import { type NextRequest, NextResponse } from "next/server"; import { AsyncLocalStorage } from "node:async_hooks"; import { CLIError, EXIT_CODE_MAP, classifyErrorSource, createLogger, enterLogContext, generateTraceId, runWithLogContext, } from "@tablestore/tablestore-agent-shared"; import type { StandardResponse } from "@tablestore/tablestore-agent-sdk"; import { resolveClients, type ResolvedClients } from "./sdk-client"; interface ApiLogContext { traceId: string; dashboardSessionId?: string; method?: string; path?: string; startTime: number; } const apiContext = new AsyncLocalStorage(); const apiLogger = createLogger("dashboard.api"); const QUIET_SUCCESS_PATHS = new Set(["/api/v1/runtime/context"]); // --------------------------------------------------------------------------- // HTTP status mapping // --------------------------------------------------------------------------- /** * Map our canonical error code → HTTP status. * Mirrors packages/shared EXIT_CODE_MAP categories in HTTP terms. */ const CODE_TO_HTTP_STATUS: Record = { SUCCESS: 200, PARTIAL_SUCCESS: 207, BAD_REQUEST: 400, VALIDATION_ERROR: 400, INVALID_PARAMETER: 400, NOT_FOUND: 404, UNAUTHORIZED: 401, FORBIDDEN: 403, CONFLICT: 409, PATH_EXISTS: 409, LOCK_CONFLICT: 409, QUOTA_EXCEEDED: 409, READ_ONLY_STORE: 409, PAYLOAD_TOO_LARGE: 413, QUOTA_EXHAUSTED: 429, FLOW_CONTROL: 429, INTERNAL_SERVER_ERROR: 500, NETWORK_ERROR: 503, SERVICE_UNAVAILABLE: 503, }; function httpStatusFor(code: string, fallback = 500): number { return CODE_TO_HTTP_STATUS[code] ?? fallback; } function attachNoStoreHeader(response: NextResponse): void { response.headers.set("Cache-Control", "no-store, max-age=0"); } function shouldLogApiSuccess(path: string | undefined): boolean { return !path || !QUIET_SUCCESS_PATHS.has(path); } // --------------------------------------------------------------------------- // Response builders // --------------------------------------------------------------------------- /** * Wrap successful data into the standard envelope. * * The body shape `{ code, data, message, requestId }` matches what the CLI * emits on stdout, so the Dashboard frontend uses the same response parser. */ export function successResponse(data: T, status = 200): NextResponse { logApiResponse("api.response", "succeed", "SUCCESS", status); const response = NextResponse.json( { code: "SUCCESS", message: "succeed", data }, { status }, ); attachNoStoreHeader(response); attachTraceHeader(response); return response; } /** * Build a standard error envelope response. * * `details` is forwarded both into the response body and into the server log * record (merged under `details.*`). Use it to carry upstream diagnostics * (e.g. `upstreamCode`, `upstreamRequestId`) that the UI can prefix to the * displayed message and that support agents can grep the JSONL logs for. */ export function errorResponse( code: string, message: string, status?: number, options: { log?: boolean; errorSource?: "local" | "network" | "service" | "browser"; details?: Record; } = {}, ): NextResponse { const responseStatus = status ?? httpStatusFor(code); if (options.log !== false) { logApiResponse( "api.error_response", message, code, responseStatus, undefined, options.errorSource ?? "local", options.details, ); } const body: Record = { code, message, data: null }; if (options.details && Object.keys(options.details).length > 0) { body.details = options.details; } const response = NextResponse.json(body, { status: responseStatus }); attachNoStoreHeader(response); attachTraceHeader(response); return response; } /** * Partial envelope that callers construct locally (e.g. for a pre-flight * validation error). `requestId` is optional here because route handlers * often generate ad-hoc error envelopes that do not correspond to an SDK * call. */ export interface ForwardableEnvelope { code: string; data: unknown; message: string; requestId?: string; details?: ForwardableUpstreamErrorDetails; } type ForwardableUpstreamErrorDetails = { upstreamCode?: string; upstreamStatus?: number; upstreamRequestId?: string; }; /** * Forward a {@link StandardResponse} (or an ad-hoc envelope) produced by a * route handler as an HTTP response. Success envelopes become 200 with `data` * under `data`; error envelopes become the appropriate 4xx/5xx with the raw * code / message. */ export function forwardResponse( resp: StandardResponse | ForwardableEnvelope, ): NextResponse { // PARTIAL_SUCCESS also carries meaningful data (e.g. successful items in a // mixed-result batch), so we preserve data for both SUCCESS and // PARTIAL_SUCCESS responses. Only genuine errors get their data nulled out. const preserveData = resp.code === "SUCCESS" || resp.code === "PARTIAL_SUCCESS"; const body: Record = { code: resp.code, data: preserveData ? resp.data : null, message: resp.message, }; if (resp.requestId) body.requestId = resp.requestId; const details = normalizeUpstreamErrorDetails(resp.details); if (details) body.details = details; const upstreamStatus = details?.upstreamStatus; const status = resolveForwardedStatus(resp.code, upstreamStatus); logApiResponse( resp.code === "SUCCESS" ? "api.response" : "api.service_error", resp.code === "SUCCESS" ? "succeed" : "upstream service error", resp.code, status, resp.requestId, resp.code === "SUCCESS" ? undefined : "service", details, ); const response = NextResponse.json(body, { status }); attachNoStoreHeader(response); attachTraceHeader(response); return response; } function isForwardableHttpStatus(status: number | undefined): status is number { return ( status !== undefined && Number.isInteger(status) && status >= 400 && status <= 599 ); } function resolveForwardedStatus( code: string, upstreamStatus: number | undefined, ): number { if (code === "SUCCESS") return 200; // The SDK can recover a masked upstream 500 into an actionable canonical // client error while retaining upstreamStatus=500 for diagnostics. Keep // HTTP aligned with every explicit 2xx/4xx mapping so callers receive the // contract implied by the canonical code (for example FLOW_CONTROL=429). const canonicalStatus = CODE_TO_HTTP_STATUS[code]; if (canonicalStatus !== undefined && canonicalStatus < 500) { return canonicalStatus; } if (isForwardableHttpStatus(upstreamStatus)) return upstreamStatus; return canonicalStatus ?? httpStatusFor(code); } function normalizeUpstreamErrorDetails( details: unknown, ): ForwardableUpstreamErrorDetails | undefined { if (details === null || typeof details !== "object") return undefined; const record = details as Record; const normalized: ForwardableUpstreamErrorDetails = {}; if (typeof record.upstreamCode === "string") { normalized.upstreamCode = record.upstreamCode; } if (typeof record.upstreamStatus === "number") { normalized.upstreamStatus = record.upstreamStatus; } if (typeof record.upstreamRequestId === "string") { normalized.upstreamRequestId = record.upstreamRequestId; } return Object.keys(normalized).length > 0 ? normalized : undefined; } // --------------------------------------------------------------------------- // Error handling // --------------------------------------------------------------------------- /** * Convert any thrown exception into a structured error response. * * - {@link CLIError}: use its code + message and mapped HTTP status. * - Generic `Error`: inspect message for obvious network issues, otherwise 500. * - Unknown: 500 with stringified payload. * * Note: the shared SDK clients never throw for remote errors (they return an * error envelope). This helper only fires for config errors (UNAUTHORIZED / * BAD_REQUEST) and unexpected runtime exceptions. */ export function handleApiError(error: unknown): NextResponse { if (error instanceof CLIError) { logApiException(error, error.code, httpStatusFor(error.code)); return errorResponse(error.code, error.message, httpStatusFor(error.code), { log: false, }); } if (error instanceof Error) { const message = error.message; const lowerMessage = message.toLowerCase(); if ( lowerMessage.includes("missing required environment") || lowerMessage.includes("invalid token") || lowerMessage.includes("token missing") || lowerMessage.includes("token decode") || lowerMessage.includes("unsupported token version") ) { logApiException(error, "UNAUTHORIZED", 401); return errorResponse("UNAUTHORIZED", message, 401, { log: false }); } if ( lowerMessage.includes("timeout") || lowerMessage.includes("econnrefused") || lowerMessage.includes("econnreset") || lowerMessage.includes("enotfound") || lowerMessage.includes("network") ) { logApiException(error, "NETWORK_ERROR", 503); return errorResponse("NETWORK_ERROR", message, 503, { log: false }); } logApiException(error, "INTERNAL_SERVER_ERROR", 500); return errorResponse("INTERNAL_SERVER_ERROR", message, 500, { log: false }); } logApiException(error, "INTERNAL_SERVER_ERROR", 500); return errorResponse( "INTERNAL_SERVER_ERROR", typeof error === "string" ? error : JSON.stringify(error), 500, { log: false }, ); } // --------------------------------------------------------------------------- // Auth helpers // --------------------------------------------------------------------------- /** * Resolve the {@link ResolvedClients} for this request or respond with an * UNAUTHORIZED envelope. Usage in a route: * * ```ts * export async function GET(request: NextRequest) { * const auth = requireClients(request); * if (auth instanceof NextResponse) return auth; * const { kb } = auth; * // ... * } * ``` */ export function requireClients( request: NextRequest, ): ResolvedClients | NextResponse { ensureApiLogContext(request); try { return resolveClients(request); } catch (err) { return handleApiError(err); } } export function ensureApiLogContext(request: NextRequest): ApiLogContext { const current = apiContext.getStore(); if (current) return current; const traceId = request.headers.get("x-trace-id") || request.headers.get("x-request-id") || generateTraceId(); const path = request.nextUrl?.pathname ?? safePathname(request.url); const context: ApiLogContext = { traceId, dashboardSessionId: process.env.TABLESTORE_DASHBOARD_SESSION_ID, method: request.method, path, startTime: Date.now(), }; apiContext.enterWith(context); enterLogContext(context); if (shouldLogApiSuccess(path)) { apiLogger.info({ event: "api.request", message: `${request.method} ${path}`, dashboardSessionId: context.dashboardSessionId, traceId, details: { method: request.method, path, userAgent: request.headers.get("user-agent") ?? undefined, }, }); } return context; } export function getApiLogContext(): ApiLogContext | undefined { return apiContext.getStore(); } export async function withApiLogging( request: NextRequest, handler: () => Promise | T, ): Promise { const context = ensureApiLogContext(request); return apiContext.run(context, async () => runWithLogContext(context, async () => handler()), ); } // Re-export so routes can `import { CODE_TO_HTTP_STATUS } from` if ever needed. export { CODE_TO_HTTP_STATUS, EXIT_CODE_MAP }; function logApiResponse( event: string, message: string, code: string, status: number, requestId?: string, errorSource?: "local" | "network" | "service" | "browser", extraDetails?: Record, ): void { const context = apiContext.getStore(); if (status < 400 && !shouldLogApiSuccess(context?.path)) return; const durationMs = context ? Date.now() - context.startTime : undefined; const level = status >= 500 ? "error" : status >= 400 ? "warn" : "info"; apiLogger.log({ level, event, message, dashboardSessionId: context?.dashboardSessionId, traceId: context?.traceId, requestId, durationMs, errorSource, details: { method: context?.method, path: context?.path, status, code, errorSource, ...extraDetails, }, }); } function logApiException(error: unknown, code: string, status: number): void { const context = apiContext.getStore(); const durationMs = context ? Date.now() - context.startTime : undefined; const source = classifyErrorSource(error); apiLogger.error({ event: "api.exception", message: error instanceof Error ? error.message : String(error), dashboardSessionId: context?.dashboardSessionId, traceId: context?.traceId, durationMs, error, errorSource: source, details: { method: context?.method, path: context?.path, status, code, errorSource: source, }, }); } function attachTraceHeader(response: NextResponse): void { const context = apiContext.getStore(); if (context?.traceId) { response.headers.set("x-trace-id", context.traceId); } } function safePathname(url: string): string { try { return new URL(url).pathname; } catch { return ""; } }