Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion src/app/api/channels/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ import * as Sentry from '@sentry/nextjs';
import { authOptions, getUserEmail } from '@/lib/auth';
import { rateLimit, rateLimitResponse } from '@/lib/rate-limit';
import { getInstanceByUserId } from '@/lib/supabase';
import { getGatewayChannels, setGatewayChannel, removeGatewayChannel } from '@/lib/fly';
import {
getGatewayChannels,
isFlyMachineNotRunningError,
removeGatewayChannel,
setGatewayChannel,
} from '@/lib/fly';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
Expand Down Expand Up @@ -50,6 +55,9 @@ export async function GET() {

return NextResponse.json({ channels: safe, available: Object.keys(CHANNEL_SCHEMA) });
} catch (error) {
if (isFlyMachineNotRunningError(error)) {
return NextResponse.json({ channels: {}, available: Object.keys(CHANNEL_SCHEMA) });
}
Sentry.captureException(error);
return NextResponse.json({ error: 'Failed to fetch channels' }, { status: 500 });
}
Expand Down Expand Up @@ -118,6 +126,9 @@ export async function POST(req: Request) {

return NextResponse.json({ success: true, channel: channelName });
} catch (error) {
if (isFlyMachineNotRunningError(error)) {
return NextResponse.json({ error: 'Gateway must be running to configure channels' }, { status: 409 });
}
Sentry.captureException(error);
return NextResponse.json({ error: 'Failed to configure channel' }, { status: 500 });
}
Expand Down Expand Up @@ -157,6 +168,9 @@ export async function DELETE(req: Request) {

return NextResponse.json({ success: true });
} catch (error) {
if (isFlyMachineNotRunningError(error)) {
return NextResponse.json({ error: 'Gateway must be running to configure channels' }, { status: 409 });
}
Sentry.captureException(error);
return NextResponse.json({ error: 'Failed to remove channel' }, { status: 500 });
}
Expand Down
3 changes: 3 additions & 0 deletions src/app/api/gateway/approve-pairing/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ export async function POST() {

if (!execRes.ok) {
const errText = await execRes.text().catch(() => '');
if (execRes.status === 412) {
return NextResponse.json({ error: 'Gateway is not running' }, { status: 409 });
}
Sentry.captureMessage('Fly exec failed for approve-pairing', {
level: 'warning',
extra: { status: execRes.status, body: errText, app: instance.fly_app_name },
Expand Down
36 changes: 34 additions & 2 deletions src/lib/fly.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,32 @@ type FlyFetchOptions = RequestInit & {
expectedStatuses?: number[];
};

export class FlyApiError extends Error {
status: number;
method: string;
path: string;
responseBody: string;
expected: boolean;

constructor(args: { status: number; method: string; path: string; responseBody: string; expected: boolean }) {
super(`Fly API ${args.status} on ${args.method} ${args.path}: ${args.responseBody}`);
this.name = 'FlyApiError';
this.status = args.status;
this.method = args.method;
this.path = args.path;
this.responseBody = args.responseBody;
this.expected = args.expected;
}
}

export function isFlyApiError(error: unknown, status?: number): error is FlyApiError {
return error instanceof FlyApiError && (status === undefined || error.status === status);
}

export function isFlyMachineNotRunningError(error: unknown): error is FlyApiError {
return isFlyApiError(error, 412) && error.path.includes('/exec');
}

async function flyFetch<T>(path: string, options: FlyFetchOptions = {}): Promise<T> {
const { expectedStatuses, ...fetchOptions } = options;
const token = getFlyToken();
Expand All @@ -109,9 +135,15 @@ async function flyFetch<T>(path: string, options: FlyFetchOptions = {}): Promise

if (!res.ok) {
const body = await res.text().catch(() => '');
const err = new Error(`Fly API ${res.status} on ${fetchOptions.method ?? 'GET'} ${path}: ${body}`);
const err = new FlyApiError({
status: res.status,
method: fetchOptions.method ?? 'GET',
path,
responseBody: body,
expected: expectedStatuses?.includes(res.status) ?? false,
});
// Only report to Sentry if this status code is NOT expected
if (!expectedStatuses?.includes(res.status)) {
if (!err.expected) {
Sentry.captureException(err, { extra: { responseBody: body, status: res.status } });
}
throw err;
Expand Down