// THE WORLD'S MANAGED DATABASE, as a pack reaches it (architecture.md, "The engine slot" and managed infrastructure): a // vendor whose data plane is a server in front of Postgres (Supabase's PostgREST, Storage and Auth; a Neon or a // PlanetScale) serves it over the World's own Postgres, whose URL the runtime hands the pack (the descriptor's // `managedDatabase`: `serve --database `, or the colocated host's `database` option). A protocol-3 handler reaches // it as `ctx.engine`; a pack's own server in front of it (a PostgREST) through `managedDatabase(url)`. Its terms: // // - Nothing here reads the environment, and the tree references none of the rows it writes. // - Each batch is ONE transaction sent as ONE extended-protocol pipeline ending in ONE Sync: `BEGIN`, the role // (`SET LOCAL ROLE`), the transaction-local settings (`set_config(…, true)`), the statements and `COMMIT`, every value a // bind parameter. The PGlite host holds one connection's whole transaction under one lock, readers included, and // native PostgreSQL gives each connection its own session; either way the batch's role and settings reach no other // connection. // - The role, which Postgres takes only as SQL text, is quoted as an identifier; which roles a caller may take is the // pack's rule (Supabase's three API roles), checked before a batch is made. // - A batch that fails leaves its transaction aborted (the backend skips to the Sync); it is ended with `ROLLBACK` before // the connection is released, and a connection that cannot be rolled back is destroyed, never reused. // // The Postgres driver is node-postgres (`pg`), loaded the first time a database is bound and installed by the package that // declares a managed database (its package.json): the kernel's dependency is ws alone (architecture B1), and a // browser bundle imports the kernel without a database. A host may register another (`useDatabaseDriver`). /** One statement of a batch; `values` travel as bind parameters (text, or null), never in the SQL text. */ export type Statement = { text: string; values?: ReadonlyArray }; /** What one statement answered: its columns and rows in Postgres's text format, and its command tag. */ export type StatementResult = { fields: string[]; rows: Array>; command: string }; /** A Postgres error as the backend reported it (SQLSTATE and its fields), what a vendor's server passes through. */ export class EngineDatabaseError extends Error { readonly code: string; readonly detail: string | null; readonly hint: string | null; constructor(message: string, fields: { code?: string; detail?: string; hint?: string }) { super(message); this.name = 'EngineDatabaseError'; this.code = fields.code ?? 'XX000'; this.detail = fields.detail ?? null; this.hint = fields.hint ?? null; } } /** The World's database cannot be reached: none is bound, or it does not answer. */ export class EngineUnavailableError extends Error { constructor(message: string) { super(message); this.name = 'EngineUnavailableError'; } } /** One transaction: as `role` (none: the twin's own login role, the vendor's servers' own work), with transaction-local * `settings` (`request.jwt.claims`, `search_path`), READ ONLY when `readOnly` (a write is refused by Postgres itself, * 25006), ended with ROLLBACK when `rollback` (a permission probe asked of Postgres and undone). */ export type Batch = { role?: string; settings?: Record; readOnly?: boolean; rollback?: boolean; statements: Statement[] }; export interface ManagedDatabase { /** Whether the World binds a database at all (a World with none refuses every batch). */ readonly bound: boolean; /** The URL the World binds it at, what an application connects to (a credential door's database URL); none when * unbound. */ readonly url?: string; /** One transaction as one pipeline and one Sync; the answer is the batch's own statements', in order. */ batch(batch: Batch): Promise; /** A whole SQL script as one simple Query (a vendor's migrations, several statements to a file). */ script(text: string): Promise; } /** Quote an identifier the way Postgres's quote_ident does for a name that needs it. */ export function quoteIdent(name: string): string { return `"${name.replace(/"/g, '""')}"`; } type BackendMessage = { fields?: unknown; text?: string }; type PgConnection = { parse(query: { text: string; types: number[] }): void; bind(config: { values: ReadonlyArray }): void; describe(message: { type: 'P' }): void; execute(config: { rows: number }): void; sync(): void; sendCopyFail(message: string): void; }; /** pg's Submittable (the extension point pg-cursor and pg-query-stream use): the client hands it the connection once * it is its turn, it writes every statement's Parse/Bind/Describe/Execute and ONE Sync, and the client hands it each * backend message until ReadyForQuery. */ class Pipeline { private readonly results: StatementResult[] = []; private current: { fields: string[]; rows: Array> } | null = null; private error: Error | null = null; private settled = false; constructor(private readonly statements: Statement[], private readonly done: (error: Error | null, results: StatementResult[]) => void) {} submit(connection: PgConnection): void { for (const statement of this.statements) { connection.parse({ text: statement.text, types: [] }); connection.bind({ values: statement.values ?? [] }); connection.describe({ type: 'P' }); connection.execute({ rows: 0 }); } connection.sync(); } handleRowDescription(message: { fields: Array<{ name: string }> }): void { this.current = { fields: message.fields.map((field) => field.name), rows: [] }; } handleDataRow(message: { fields: Array }): void { (this.current ??= { fields: [], rows: [] }).rows.push(message.fields); } handleCommandComplete(message: BackendMessage): void { this.results.push({ ...(this.current ?? { fields: [], rows: [] }), command: String(message.text ?? '') }); this.current = null; } handleEmptyQuery(): void { this.results.push({ fields: [], rows: [], command: '' }); } handlePortalSuspended(): void { /* every Execute asks for all rows */ } handleCopyInResponse(connection: PgConnection): void { connection.sendCopyFail('COPY FROM STDIN is not served by a managed database batch'); } handleCopyData(): void { /* no COPY is ever sent */ } handleError(error: Error): void { // An ErrorResponse (the backend's, with a SQLSTATE) or a failed connection. pg ends the submittable's turn here: // it drops it as the active query, so the ReadyForQuery the backend sends after skipping to the Sync goes to no // one, and the next query this client is given (the ROLLBACK) is sent once that ReadyForQuery arrives. this.error ??= error; this.finish(); } handleReadyForQuery(): void { this.finish(); } private finish(): void { if (this.settled) return; this.settled = true; this.done(this.error, this.results); } } function asDatabaseError(error: Error): Error { const fields = error as { code?: string; detail?: string; hint?: string; severity?: string }; if (fields.severity === undefined) return new EngineUnavailableError(`the World's Postgres failed: ${error.message}`); return new EngineDatabaseError(error.message, fields); } /** The part of a Postgres driver the kernel uses: node-postgres's (`pg`) Pool and its clients. */ type PgClient = { query(query: unknown): unknown; release(error?: Error): void }; type PgPool = { connect(): Promise; end(): Promise; on(event: 'error', listener: (error: Error) => void): unknown }; export type DatabaseDriver = { Pool: new (config: { connectionString: string; max: number; idleTimeoutMillis: number; connectionTimeoutMillis: number }) => PgPool }; let driver: DatabaseDriver | undefined; /** A Postgres driver a host registers in place of node-postgres. */ export function useDatabaseDriver(given: DatabaseDriver): void { driver = given; } /** The driver: the registered one, else node-postgres, loaded on first use (a name the bundler does not resolve). */ async function loadDriver(): Promise { if (driver !== undefined) return driver; const name = 'pg'; try { const mod = (await import(name)) as { default?: DatabaseDriver } & DatabaseDriver; driver = mod.default ?? mod; } catch (error) { throw new EngineUnavailableError(`no Postgres driver: node-postgres (pg) is not installed beside the pack that declares a managed database (${(error as Error).message})`); } return driver; } const pools = new Map(); // cache: one pool per bound database URL — the connections this process holds to the World's Postgres, never state async function poolFor(url: string): Promise { let pool = pools.get(url); if (pool === undefined) { const { Pool } = await loadDriver(); // another request may have made it while the driver loaded const made = pools.get(url); if (made !== undefined) return made; // a few connections: the PGlite host serializes them anyway, and a container Postgres needs no more for a twin pool = new Pool({ connectionString: url, max: 4, idleTimeoutMillis: 10_000, connectionTimeoutMillis: 10_000 }); // an idle connection that the database ends (a World's Postgres restarting) is dropped from the pool, not thrown pool.on('error', () => {}); pools.set(url, pool); } return pool; } async function checkout(url: string): Promise { const pool = await poolFor(url); try { return await pool.connect(); } catch (error) { throw new EngineUnavailableError(`the World's Postgres is not answering: ${(error as Error).message}`); } } function pipeline(client: PgClient, statements: Statement[]): Promise<{ error: Error | null; results: StatementResult[] }> { return new Promise((resolve) => { (client as unknown as { query: (submittable: Pipeline) => void }).query(new Pipeline(statements, (error, results) => resolve({ error, results }))); }); } /** Run one transaction as one pipeline with one Sync; on failure, ROLLBACK before the connection goes back. */ async function transaction(url: string, statements: Statement[], lead: number): Promise { const client = await checkout(url); let broken: Error | undefined; try { const { error, results } = await pipeline(client, statements); if (error !== null) { if ((error as { severity?: unknown }).severity !== undefined) { try { await (client.query('ROLLBACK') as Promise); } catch (rollback) { broken = rollback as Error; } } else broken = error; throw asDatabaseError(error); } // the answer is the batch's own statements: not BEGIN, the role, the settings, or its end return results.slice(lead, statements.length - 1); } finally { client.release(broken); } } function settingsStatement(settings: Record): Statement | null { const names = Object.keys(settings); if (names.length === 0) return null; const values: string[] = []; const calls = names.map((name) => { values.push(name, settings[name]!); return `set_config($${values.length - 1}, $${values.length}, true)`; }); return { text: `SELECT ${calls.join(', ')}`, values }; } /** The World's Postgres at `url` (the runtime's binding, never the environment); with `readOnly`, every transaction is * READ ONLY whatever the batch asks (a read-only twin or request: Postgres itself refuses a write, 25006). */ export function managedDatabase(url: string, options: { readOnly?: boolean } = {}): ManagedDatabase { return { bound: true, url, async batch(batch) { const set = settingsStatement(batch.settings ?? {}); const head: Statement[] = [ { text: batch.readOnly || options.readOnly ? 'BEGIN READ ONLY' : 'BEGIN' }, ...(batch.role === undefined ? [] : [{ text: `SET LOCAL ROLE ${quoteIdent(batch.role)}` }]), ...(set === null ? [] : [set]), ]; return transaction(url, [...head, ...batch.statements, { text: batch.rollback ? 'ROLLBACK' : 'COMMIT' }], head.length); }, async script(text) { const client = await checkout(url); let broken: Error | undefined; try { await (client.query(text) as Promise); } catch (error) { if ((error as { severity?: unknown }).severity === undefined) broken = error as Error; else { try { await (client.query('ROLLBACK') as Promise); } catch (rollback) { broken = rollback as Error; } } throw asDatabaseError(error as Error); } finally { client.release(broken); } }, }; } /** One connection of an application's own to the World's Postgres (a journey's SQL steps: twin-standard * walk/journey-kit.ts), its statements sent as its client sends them: a text alone as one simple Query (a migration * file, a `BEGIN`), a text with values as one extended-protocol statement, the values bind parameters. A transaction it * opens stays open across its statements until it ends it, as on the application's own connection. Each statement's * answer is its results in Postgres's text format, with native column type OIDs retained beside the values. */ export type DatabaseSession = { query(text: string, values?: ReadonlyArray): Promise>; end(): Promise }; type PgResult = { command?: string | null; rowCount?: number | null; fields?: Array<{ name: string; dataTypeID: number }>; rows?: Array> }; /** The World's Postgres at `url` as one connection held until `end()`. */ export async function databaseSession(url: string): Promise { const { Pool } = await loadDriver(); const pool = new Pool({ connectionString: url, max: 1, idleTimeoutMillis: 0, connectionTimeoutMillis: 10_000 }); pool.on('error', () => {}); let client: PgClient; try { client = await pool.connect(); } catch (error) { await pool.end().catch(() => {}); throw new EngineUnavailableError(`the World's Postgres is not answering: ${(error as Error).message}`); } // every value as the wire carries it: a row an array of texts, no type parsed const raw = { getTypeParser: () => (value: string) => value }; return { async query(text, values) { try { const answer = (await (client.query({ text, ...(values === undefined ? {} : { values }), rowMode: 'array', types: raw }) as Promise)); return (Array.isArray(answer) ? answer : [answer]).map((r) => ({ fields: (r.fields ?? []).map((f) => f.name), fieldTypes: (r.fields ?? []).map((f) => f.dataTypeID), rows: r.rows ?? [], command: [r.command ?? '', r.command === 'INSERT' ? '0' : '', r.rowCount ?? ''].filter((part) => part !== '').join(' '), })); } catch (error) { throw asDatabaseError(error as Error); } }, async end() { client.release(); await pool.end().catch(() => {}); }, }; } /** A handler's database when the World binds none: every use is the refusal naming what to add. */ export function unboundDatabase(service: string): ManagedDatabase { const refuse = (): never => { throw new EngineUnavailableError(`This World binds no managed Postgres to the ${service} twin, so what it serves over one is refused, not served: add a postgres service to the World's managed infrastructure (architecture: managed infrastructure)`); }; return { bound: false, batch: async () => refuse(), script: async () => refuse() }; }