import { randomUUID } from "node:crypto"; import type { IncomingMessage, ServerResponse } from "node:http"; import { createServer as createNodeServer } from "node:http"; import { bootstrapAskDbEnv, getAskDbRuntimeConfig, isAskDbRuntimeInitialized } from "@askdb/config"; import { createAiRegistry, } from "@askdb/ai"; import { createAskDb, DialectNotSupportedError, ModelNotConfiguredError, SchemaLoadError, SchemaNotConfiguredError, } from "@askdb/client"; import { ASKDB_MODES_V1, AskDbLogEvent, type AskDbModeV1, type BuiltInDialectId, type NormalizedSchemaV2, QuestionDeclinedError, SensitiveReferenceError, SqlGenerationError, SqlValidationError, SUPPORTED_DIALECT_IDS, TenantGuardrailError, TenantScopeError, createAskDbLogger, isBuiltInDialectId, loadSchemaFromJson, parseAskDbModeV1, } from "@askdb/core"; import type { AskHttpErrorResponse, AskHttpRequest, AskHttpSuccessResponse } from "./types.js"; // Batteries-included surface: every built-in provider is registered, and each // loads its @ai-sdk/* package only when first used, so env config alone // selects the provider. const ai = createAiRegistry(); export type AskDbHttpServerOptions = { /** Port to listen on. Precedence: this option → `httpApi.listen.port` config → 3000. */ port?: number; /** Bind address. Precedence: this option → `httpApi.listen.host` config → 127.0.0.1. */ host?: string; /** Server-default schema artifact path. Precedence: this option → `host.schemaJson`, then `host.schemaPath`, in config. */ schemaPath?: string; /** Default: 1 MiB */ maxBodyBytes?: number; }; const DEFAULT_MAX_BODY_BYTES = 1024 * 1024; class RequestBodyTooLargeError extends Error { constructor(readonly limitBytes: number) { super(`request body exceeds ${limitBytes} bytes`); this.name = "RequestBodyTooLargeError"; } } async function readJsonBody(req: IncomingMessage, maxBodyBytes: number): Promise { const chunks: Buffer[] = []; let total = 0; for await (const c of req) { const chunk = Buffer.isBuffer(c) ? c : Buffer.from(c); total += chunk.byteLength; if (total > maxBodyBytes) { throw new RequestBodyTooLargeError(maxBodyBytes); } chunks.push(chunk); } const raw = Buffer.concat(chunks).toString("utf8"); return JSON.parse(raw) as T; } function writeJson(res: ServerResponse, status: number, body: unknown): void { const json = JSON.stringify(body); res.statusCode = status; res.setHeader("content-type", "application/json; charset=utf-8"); res.setHeader("content-length", Buffer.byteLength(json)); res.end(json); } function writeError( res: ServerResponse, status: number, correlationId: string, error: AskHttpErrorResponse["error"], ): void { writeJson(res, status, { ok: false, correlationId, error } satisfies AskHttpErrorResponse); } function getCorrelationId(req: IncomingMessage): string { const h = req.headers["x-correlation-id"]; if (typeof h === "string" && h.trim() !== "") return h.trim(); return randomUUID(); } function getHeader(req: IncomingMessage, name: string): string | undefined { const v = req.headers[name.toLowerCase()]; if (typeof v === "string") return v; if (Array.isArray(v)) return v[0]; return undefined; } function badRequest(message: string): AskHttpErrorResponse["error"] { return { code: "bad_request", message }; } /** * Resolve the caller-requested mode. Precedence: body `mode` → `x-askdb-mode` header. * Returns `undefined` when the caller did not ask for one. The facade applies config * `modes.askdbMode` (ADR 0025): a request mode can tighten it, never loosen it. * Throws on an invalid value (→ `400`). */ function resolveRequestMode(bodyMode: unknown, headerMode: string | undefined): AskDbModeV1 | undefined { if (bodyMode !== undefined && bodyMode !== null) { if (typeof bodyMode !== "string" || bodyMode.trim() === "") { throw new Error(`Invalid mode: ${JSON.stringify(bodyMode)}. Expected one of: ${ASKDB_MODES_V1.join(", ")}.`); } return parseAskDbModeV1(bodyMode); } if (headerMode !== undefined && headerMode.trim() !== "") { return parseAskDbModeV1(headerMode); } return undefined; } type MappedError = { status: number; error: AskHttpErrorResponse["error"] }; /** `instanceof` with a `name` fallback, so duplicated package copies still classify correctly. */ function isErrorOf(e: unknown, ctor: abstract new (...args: never[]) => T): e is T { return e instanceof ctor || (e instanceof Error && e.name === ctor.name); } function causeMessage(e: unknown): string | undefined { const cause = e instanceof Error ? (e as { cause?: unknown }).cause : undefined; if (cause === undefined) return undefined; return cause instanceof Error ? cause.message : String(cause); } /** What's wrong with a schema's `provider` for SQL generation, worded once for the log and the 400. */ function providerProblem(provider: string): string { return provider ? `declares provider '${provider}', which has no AskDB dialect` : "declares no provider"; } /** * Load a request's `schemaJson` with the dialect it answers for (#809): its own `provider`, never * the config's `dialect`, which describes the server's own schema. A schema that names no * provider, or one AskDB has no dialect for, throws `DialectNotSupportedError`, which * {@link mapAskError} answers with `400 bad_request`; one that doesn't load throws * `SchemaLoadError`, as the client would. */ function loadRequestSchema(json: string): { schema: NormalizedSchemaV2; dialect: BuiltInDialectId } { let schema: NormalizedSchemaV2; try { schema = loadSchemaFromJson(json); } catch (e) { throw new SchemaLoadError("request", e); } const provider = schema.provider ?? ""; if (!isBuiltInDialectId(provider)) { throw new DialectNotSupportedError(provider, `The request's schemaJson ${providerProblem(provider)}.`); } return { schema, dialect: provider }; } /** * Map an error from `askdb.ask()` to an HTTP status + client-safe body. Classification is by * error type only. Messages from the model provider are never returned to the client (they * can echo request details or credential fragments); unknown errors get a generic message. * * @internal Exported for unit tests; not re-exported from the package entry point. */ export function mapAskError( e: unknown, ctx: { timedOut: boolean; timeoutMs: number; schemaFromRequest?: boolean }, ): MappedError { if (isErrorOf(e, SqlGenerationError)) { return { status: 502, error: { code: "sql_generation_error", message: ctx.timedOut ? `Model provider request timed out after ${ctx.timeoutMs} ms.` : "Model provider request failed. See server logs for this correlationId.", }, }; } if (isErrorOf(e, SqlValidationError)) { return { status: 400, error: { code: "sql_validation_error", message: e.message, rule: e.rule } }; } if (isErrorOf(e, SensitiveReferenceError)) { return { status: 422, error: { code: "guardrail_violation", message: e.message, rule: e.rule } }; } // #949: the model declined the question: off-topic for the schema, or asks to change data. if (isErrorOf(e, QuestionDeclinedError)) { return { status: 422, error: { code: "question_declined", message: e.message, ...(typeof e.reason === "string" ? { reason: e.reason } : {}), }, }; } if (isErrorOf(e, TenantGuardrailError)) { return { status: 422, error: { code: "guardrail_violation", message: e.message, ...(e.warnings[0] ? { rule: e.warnings[0].rule } : {}), }, }; } // No schema configured server-side is the operator's to fix, as a schema that doesn't load is // (#840): a generic 500, and the log line's errName (SchemaNotConfiguredError) names the cause // (#845). A request that sends its own schemaJson never reaches this. if (isErrorOf(e, SchemaNotConfiguredError)) { return { status: 500, error: { code: "generation_not_configured", message: "The server has no schema configured. See server logs for this correlationId.", }, }; } // A schema the request sent is the caller's to fix (400). The server's own schema is the // operator's, and its error names a server path, so the caller gets a generic 500 and the log // line keeps the full error (#840). if (isErrorOf(e, SchemaLoadError)) { if (!ctx.schemaFromRequest) { return { status: 500, error: { code: "generation_not_configured", message: "The server can't load its configured schema. See server logs for this correlationId.", }, }; } return { status: 400, error: { code: "schema_parse_error", message: `schema parse error (${e.source}): ${e.cause instanceof Error ? e.cause.message : String(e.cause)}`, }, }; } if (isErrorOf(e, ModelNotConfiguredError)) { return { status: 500, error: { code: "generation_not_configured", message: "No AI model is configured on the server. Set ai.provider / ai.providerConfig in askdb.config.* (or dev.mockSql for tests).", }, }; } // The schema's provider has no AskDB dialect (#720), or a request schema names none (#809). A // schema the request sent is the caller's to fix, so the message names the ids to send; core's // own message points at the server's config, which the caller can't edit. The server's own // schema is the operator's, so it reads as a configuration error, and the log line's errName // (DialectNotSupportedError, not ModelNotConfiguredError) names the cause. if (isErrorOf(e, DialectNotSupportedError)) { if (ctx.schemaFromRequest) { return { status: 400, error: { code: "bad_request", message: `The request's schemaJson ${providerProblem(e.provider)}. ` + `Send a schema whose provider is one of: ${SUPPORTED_DIALECT_IDS.join(", ")}.`, }, }; } return { status: 500, error: { code: "generation_not_configured", message: "The server can't generate SQL for its schema: the schema's database engine has no AskDB dialect. See server logs for this correlationId.", }, }; } // The server can't set a tenant scope (#343), so core refuses a tenant-policy schema before any // model call (#716). Only a missing scope gets this code; any other reason is unexpected here // and stays the generic 500 below. if (isErrorOf(e, TenantScopeError) && e.reason === "MISSING_SCOPE") { return { status: 500, error: { code: "tenant_scope_not_configured", message: "This schema has a tenant policy, and askdb-http can't set a tenant scope yet, so it can't serve this schema. " + "Generate its SQL with ask() and a tenantScope in your own server.", }, }; } return { status: 500, error: { code: "internal_error", message: "Internal server error. See server logs for this correlationId." }, }; } export function createAskDbHttpServer(options: AskDbHttpServerOptions = {}) { // A host that bootstrapped keeps its runtime. Otherwise load `.env` and askdb.config.* from // the working directory, as the askdb-http binary does. A broken `.env` throws here rather // than setting the host's `process.exitCode`. if (!isAskDbRuntimeInitialized()) { bootstrapAskDbEnv({ cwd: process.cwd(), dotenvNonFatal: false }); } const { listen } = getAskDbRuntimeConfig().httpApi; const host = options.host ?? listen.host; const port = options.port ?? listen.port; const optionSchemaPath = options.schemaPath; const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES; // The facade is constructed lazily on the first request so it captures the // runtime config that is active at that point. Config is stable for the // process lifetime after bootstrap; the facade's internal cache handles // subsequent requests. let askdb: ReturnType | undefined; const server = createNodeServer((req, res) => { const correlationId = getCorrelationId(req); handleRequest(req, res, correlationId).catch((e: unknown) => { // Last-resort guard: anything that escapes the handler becomes a generic 500 // instead of an unhandled rejection that would take the process down. process.stderr.write( `askdb-http: unhandled error (correlationId=${correlationId}): ${e instanceof Error ? (e.stack ?? e.message) : String(e)}\n`, ); if (!res.headersSent) { writeError(res, 500, correlationId, { code: "internal_error", message: "Internal server error. See server logs for this correlationId.", }); } else { res.end(); } }); }); async function handleRequest(req: IncomingMessage, res: ServerResponse, correlationId: string): Promise { const method = req.method ?? "GET"; const url = req.url ?? "/"; if (method === "GET" && url === "/health") { writeJson(res, 200, { ok: true }); return; } if (method !== "POST" || url !== "/ask") { writeError(res, 404, correlationId, { code: "not_found", message: "not found" }); return; } const rt = getAskDbRuntimeConfig(); const logger = createAskDbLogger({ correlationId, level: rt.logging.level ?? "info", logFile: rt.logging.logFile, logStdout: rt.logging.logStdout, }); // Every non-2xx response from `POST /ask` is logged as `askdb.run.error` with its // status and code. Requests rejected before the pipeline runs log the client message. const reject = (status: number, error: AskHttpErrorResponse["error"], errMessage = error.message): void => { logger.error( { event: AskDbLogEvent.RunError, status, code: error.code, errMessage }, "askdb http request rejected", ); writeError(res, status, correlationId, error); }; let body: AskHttpRequest; try { body = await readJsonBody(req, maxBodyBytes); } catch (e) { const errMessage = e instanceof Error ? e.message : String(e); if (e instanceof RequestBodyTooLargeError) { reject(413, { code: "payload_too_large", message: `request body exceeds ${e.limitBytes} bytes` }, errMessage); return; } reject(400, badRequest("invalid JSON body"), errMessage); return; } if (!body || typeof body !== "object") { reject(400, badRequest("request body must be an object")); return; } if (typeof body.question !== "string" || body.question.trim() === "") { reject(400, badRequest("`question` is required")); return; } if ("execute" in body || getHeader(req, "x-askdb-execute") !== undefined) { reject(400, badRequest("Execution is not supported. This endpoint returns generated SQL only.")); return; } // Validate caller-controlled inputs up front so parser failures are the only // thing that can become a 400 here — never a substring match on a downstream error. let requestedMode: AskDbModeV1 | undefined; try { requestedMode = resolveRequestMode(body.mode, getHeader(req, "x-askdb-mode")); } catch (e) { reject(400, badRequest(e instanceof Error ? e.message : String(e))); return; } // Strictly boolean (`null` counts as absent): a string or number is refused rather than // ignored, because ignoring `omitSensitiveFromPrompt` would silently send sensitive // identifiers to the model. for (const field of ["omitSensitiveFromPrompt", "explain"] as const) { const value: unknown = body[field]; if (value !== undefined && value !== null && typeof value !== "boolean") { reject(400, badRequest(`\`${field}\` must be a boolean (got ${typeof value}).`)); return; } } let requestOverride: string | undefined; if (body.schemaJson !== undefined && body.schemaJson !== null) { if (typeof body.schemaJson !== "string") { reject(400, badRequest("`schemaJson` must be a string containing a bundled AskDB schema artifact.")); return; } if (body.schemaJson.trim() !== "") { if (!rt.httpApi.allowSchemaOverride) { reject(403, { code: "schema_override_disabled", message: "Per-request `schemaJson` overrides are disabled on this server. Omit `schemaJson` to use the server-configured schema.", }); return; } requestOverride = body.schemaJson; } } if (!askdb) { askdb = createAskDb({ config: rt, registry: ai, schema: optionSchemaPath ? { path: optionSchemaPath } : undefined, }); } logger.info({ event: AskDbLogEvent.RunStart }, "askdb http run start"); const timeoutMs = rt.httpApi.requestTimeoutMs; const abortSignal = AbortSignal.timeout(timeoutMs); try { const requestSchema = requestOverride === undefined ? undefined : loadRequestSchema(requestOverride); const out = await askdb.ask(body.question, { ...(requestSchema ? { schema: requestSchema.schema, dialect: requestSchema.dialect } : {}), logger, ...(requestedMode ? { mode: requestedMode } : {}), explain: body.explain === true, // The facade treats config `modes.omitSensitiveFromPrompt` as a floor: // a request can tighten it but never loosen it. omitSensitiveIdentifiersFromNlToSqlPrompt: body.omitSensitiveFromPrompt === true, abortSignal, }); const payload: AskHttpSuccessResponse = { ok: true, correlationId, sql: out.sql, explain: out.explain, usage: out.usage ?? null, ...(out.sensitiveGuardrail ? { sensitiveGuardrail: out.sensitiveGuardrail } : {}), }; logger.info({ event: AskDbLogEvent.RunEnd, ok: true }, "askdb http run end"); writeJson(res, 200, payload); return; } catch (e) { const mapped = mapAskError(e, { timedOut: abortSignal.aborted, timeoutMs, schemaFromRequest: requestOverride !== undefined }); const cause = causeMessage(e); // Always log the full error server-side; the client only sees `mapped.error`. logger.error( { event: AskDbLogEvent.RunError, status: mapped.status, code: mapped.error.code, errName: e instanceof Error ? e.name : typeof e, errMessage: e instanceof Error ? e.message : String(e), ...(cause !== undefined ? { causeMessage: cause } : {}), ...(mapped.status >= 500 && e instanceof Error && e.stack ? { errStack: e.stack } : {}), }, "askdb http run error", ); writeError(res, mapped.status, correlationId, mapped.error); return; } } return { host, port, server, listen: () => new Promise((resolve, reject) => { server.listen(port, host, () => resolve()); server.once("error", reject); }), close: () => new Promise((resolve, reject) => { server.close((err) => (err ? reject(err) : resolve())); }), }; }