MotorSignal-App/website/app/api/ops/actions/route.ts

178 lines
5.4 KiB
TypeScript

import { cookies } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import { hasValidOrigin } from '../../../../lib/request-origin';
export async function GET(request: NextRequest) {
const cookieStore = await cookies();
const isProduction =
process.env.NODE_ENV === 'production' &&
process.env.NEXT_PUBLIC_APP_ENV === 'production';
const opsToken = isProduction
? cookieStore.get('__Host-motorsignal_ops')?.value
: cookieStore.get('__Host-motorsignal_ops')?.value ??
cookieStore.get('motorsignal_ops')?.value;
if (!opsToken) {
return NextResponse.json(
{ detail: 'Authentication required.' },
{ status: 401 }
);
}
const searchParams = request.nextUrl.searchParams;
const cursor = searchParams.get('cursor');
const limit = searchParams.get('limit');
const actionType = searchParams.get('action_type');
const state = searchParams.get('state');
const baseUrl =
process.env.MOTORSIGNAL_API_BASE_URL ?? 'https://api.motorsignal.app';
const targetUrl = new URL(`${baseUrl}/api/v1/ops/actions`);
if (cursor) targetUrl.searchParams.set('cursor', cursor);
if (limit) targetUrl.searchParams.set('limit', limit);
if (actionType) targetUrl.searchParams.set('action_type', actionType);
if (state) targetUrl.searchParams.set('state', state);
try {
const response = await fetch(targetUrl.toString(), {
method: 'GET',
headers: {
authorization: `Bearer ${opsToken}`,
accept: 'application/json',
},
cache: 'no-store',
});
if (response.status === 401) {
return NextResponse.json(
{ detail: 'Your Operations session has expired.' },
{ status: 401 }
);
}
if (response.status === 403) {
return NextResponse.json(
{ detail: 'You do not have authority to view actions history.' },
{ status: 403 }
);
}
if (!response.ok) {
return NextResponse.json(
{ detail: 'Operations actions platform is temporarily unavailable.' },
{ status: response.status >= 500 ? response.status : 503 }
);
}
const data = await response.json();
return NextResponse.json(data);
} catch {
return NextResponse.json(
{ detail: 'Unable to connect to Operations platform.' },
{ status: 503 }
);
}
}
export async function POST(request: NextRequest) {
if (!hasValidOrigin(request)) {
return NextResponse.json({ detail: 'Invalid request origin.' }, { status: 403 });
}
const cookieStore = await cookies();
const isProduction =
process.env.NODE_ENV === 'production' &&
process.env.NEXT_PUBLIC_APP_ENV === 'production';
const opsToken = isProduction
? cookieStore.get('__Host-motorsignal_ops')?.value
: cookieStore.get('__Host-motorsignal_ops')?.value ??
cookieStore.get('motorsignal_ops')?.value;
if (!opsToken) {
return NextResponse.json(
{ detail: 'Authentication required.' },
{ status: 401 }
);
}
let body: unknown;
try {
body = await request.json();
} catch {
return NextResponse.json(
{ detail: 'Invalid request body.' },
{ status: 422 }
);
}
const baseUrl =
process.env.MOTORSIGNAL_API_BASE_URL ?? 'https://api.motorsignal.app';
try {
const response = await fetch(`${baseUrl}/api/v1/ops/actions`, {
method: 'POST',
headers: {
authorization: `Bearer ${opsToken}`,
'content-type': 'application/json',
accept: 'application/json',
},
body: JSON.stringify(body),
cache: 'no-store',
});
const data = await response.json().catch(() => null);
if (response.status === 401) {
return NextResponse.json(
{ detail: data?.detail ?? 'Your Operations session has expired.' },
{ status: 401 }
);
}
if (response.status === 403) {
return NextResponse.json(
{ detail: data?.detail ?? 'Only owners may trigger infrastructure operations actions.' },
{ status: 403 }
);
}
if (response.status === 409) {
return NextResponse.json(
{ detail: data?.detail ?? 'Another operations action is currently active.' },
{ status: 409 }
);
}
if (response.status === 422) {
const errorMsg =
typeof data?.detail === 'string'
? data.detail
: Array.isArray(data?.detail)
? data.detail.map((d: any) => d.msg || JSON.stringify(d)).join(', ')
: 'Invalid action payload.';
return NextResponse.json(
{ detail: errorMsg },
{ status: 422 }
);
}
if (!response.ok) {
const errorDetail =
typeof data?.detail === 'string'
? data.detail
: response.status === 503
? 'Operations action control plane is currently unconfigured or unavailable.'
: response.status === 502
? 'Backend API service is temporarily unreachable (502 Bad Gateway).'
: response.status === 504
? 'Operation timed out across gateway (504 Gateway Timeout).'
: 'Operations platform is temporarily unavailable.';
return NextResponse.json(
{ detail: errorDetail },
{ status: response.status >= 500 ? response.status : 503 }
);
}
return NextResponse.json(data, { status: response.status });
} catch {
return NextResponse.json(
{ detail: 'Unable to connect to Operations platform.' },
{ status: 503 }
);
}
}