@broberg/db-sdk 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/backends/libsql.ts","../src/index.ts"],"sourcesContent":["/** libSQL / Turso backend for @broberg/db-sdk. */\nimport { createClient as createLibsqlClient } from '@libsql/client';\nimport type { Client } from '@libsql/client';\nimport type { DbConfig, ReplicaConfig } from '../types';\n\nfunction requireUrl(url: string | undefined, what: string): string {\n if (!url) {\n throw new Error(\n `@broberg/db-sdk: missing ${what} — set TURSO_DATABASE_URL or pass it explicitly`,\n );\n }\n return url;\n}\n\n/** Remote libSQL/Turso client. */\nexport function libsqlClient(cfg: DbConfig): Client {\n const url = requireUrl(cfg.url ?? process.env.TURSO_DATABASE_URL, 'database url');\n const authToken = cfg.authToken ?? process.env.TURSO_AUTH_TOKEN;\n return createLibsqlClient({ url, authToken });\n}\n\n/** Embedded replica: a local SQLite file kept in sync with the remote primary. */\nexport function libsqlReplica(cfg: ReplicaConfig): Client {\n const syncUrl = requireUrl(cfg.syncUrl ?? process.env.TURSO_DATABASE_URL, 'sync url');\n const authToken = cfg.authToken ?? process.env.TURSO_AUTH_TOKEN;\n return createLibsqlClient({\n url: `file:${cfg.path}`,\n syncUrl,\n authToken,\n syncInterval: cfg.syncIntervalSeconds,\n });\n}\n","/**\n * @broberg/db-sdk — the WebHouse fleet's shared database client.\n *\n * One thin facade, every project: instead of scattering driver calls in each\n * repo, projects depend on this package and gain a single place to evolve\n * transports, limits and observability — the same play as `@broberg/ai-sdk`.\n *\n * Turso/libSQL is the only transport implemented today (Buddy Cloud, F067, is\n * the pilot consumer); `postgres` / `supabase` are planned behind the same\n * `createClient` / `createReplica` surface (see `Backend`). Intentionally THIN:\n * a remote client, an embedded-replica client, and a health probe. ORM stays in\n * the consumer (`drizzle(createClient(), { schema })`).\n */\nimport type { Client, DbConfig, ReplicaConfig } from './types';\nimport { libsqlClient, libsqlReplica } from './backends/libsql';\n\nexport type { Client, ResultSet, DbConfig, ReplicaConfig, Backend } from './types';\n\nfunction unsupported(backend: string): Error {\n return new Error(\n `@broberg/db-sdk: backend '${backend}' is not implemented yet — only 'libsql' (Turso) ` +\n `is available. Add it under src/backends/ and widen the Backend type; the public ` +\n `API stays the same.`,\n );\n}\n\n/**\n * Create a client against a REMOTE database. With no args it reads\n * `TURSO_DATABASE_URL` + `TURSO_AUTH_TOKEN` from the env. Backend defaults to\n * `libsql` (Turso).\n */\nexport function createClient(cfg: DbConfig = {}): Client {\n const backend: string = cfg.backend ?? 'libsql';\n if (backend === 'libsql') return libsqlClient(cfg);\n throw unsupported(backend);\n}\n\n/**\n * Create an EMBEDDED REPLICA: a local SQLite file kept in sync with the remote\n * Turso primary. Reads hit the local file at SQLite speed; writes forward to the\n * primary; `client.sync()` (or `syncIntervalSeconds`) pulls the latest. This is\n * how F067 edge daemons read fleet state fast and tolerate a cloud blip.\n */\nexport function createReplica(cfg: ReplicaConfig): Client {\n const backend: string = cfg.backend ?? 'libsql';\n if (backend === 'libsql') return libsqlReplica(cfg);\n throw unsupported(backend);\n}\n\n/** Liveness + SQLite version probe — handy for health endpoints. */\nexport async function health(client: Client): Promise<{ ok: boolean; version: string }> {\n const res = await client.execute('select sqlite_version() as v');\n const version = String(res.rows[0]?.v ?? 'unknown');\n return { ok: true, version };\n}\n"],"mappings":";AACA,SAAS,gBAAgB,0BAA0B;AAInD,SAAS,WAAW,KAAyB,MAAsB;AACjE,MAAI,CAAC,KAAK;AACR,UAAM,IAAI;AAAA,MACR,4BAA4B,IAAI;AAAA,IAClC;AAAA,EACF;AACA,SAAO;AACT;AAGO,SAAS,aAAa,KAAuB;AAClD,QAAM,MAAM,WAAW,IAAI,OAAO,QAAQ,IAAI,oBAAoB,cAAc;AAChF,QAAM,YAAY,IAAI,aAAa,QAAQ,IAAI;AAC/C,SAAO,mBAAmB,EAAE,KAAK,UAAU,CAAC;AAC9C;AAGO,SAAS,cAAc,KAA4B;AACxD,QAAM,UAAU,WAAW,IAAI,WAAW,QAAQ,IAAI,oBAAoB,UAAU;AACpF,QAAM,YAAY,IAAI,aAAa,QAAQ,IAAI;AAC/C,SAAO,mBAAmB;AAAA,IACxB,KAAK,QAAQ,IAAI,IAAI;AAAA,IACrB;AAAA,IACA;AAAA,IACA,cAAc,IAAI;AAAA,EACpB,CAAC;AACH;;;ACbA,SAAS,YAAY,SAAwB;AAC3C,SAAO,IAAI;AAAA,IACT,6BAA6B,OAAO;AAAA,EAGtC;AACF;AAOO,SAAS,aAAa,MAAgB,CAAC,GAAW;AACvD,QAAM,UAAkB,IAAI,WAAW;AACvC,MAAI,YAAY,SAAU,QAAO,aAAa,GAAG;AACjD,QAAM,YAAY,OAAO;AAC3B;AAQO,SAAS,cAAc,KAA4B;AACxD,QAAM,UAAkB,IAAI,WAAW;AACvC,MAAI,YAAY,SAAU,QAAO,cAAc,GAAG;AAClD,QAAM,YAAY,OAAO;AAC3B;AAGA,eAAsB,OAAO,QAA2D;AACtF,QAAM,MAAM,MAAM,OAAO,QAAQ,8BAA8B;AAC/D,QAAM,UAAU,OAAO,IAAI,KAAK,CAAC,GAAG,KAAK,SAAS;AAClD,SAAO,EAAE,IAAI,MAAM,QAAQ;AAC7B;","names":[]}
1
+ {"version":3,"sources":["../src/backends/pg.ts","../src/backends/libsql.ts","../src/backends/postgres.ts","../src/index.ts"],"sourcesContent":["/**\n * node-postgres (`pg`) transport for @broberg/db-sdk (components-F085.6).\n *\n * Why a second Postgres driver: some apps cannot move — BID runs Better Auth,\n * whose kysely dialect takes a `pg.Pool` (it recognises one by `connect`). The\n * facade is the same as the postgres.js transport: same SQL dialect ($1), same\n * DbResult shape, `transport: 'postgres'`. `pg` is an OPTIONAL peer dependency:\n * it is loaded only when `backend: 'pg'` is asked for with a `url` — pass your\n * own `pool` and this file never imports it.\n */\nimport { createRequire } from 'node:module';\nimport type { Pool, PoolClient, QueryResult } from 'pg';\nimport type { DbClient, DbResult, PgConfig, Row, Statement } from '../types';\n\nfunction parts(stmt: Statement): [string, unknown[]] {\n if (typeof stmt === 'string') return [stmt, []];\n return [stmt.sql, [...(stmt.args ?? [])]];\n}\n\nfunction toResult(res: QueryResult | QueryResult[]): DbResult {\n // A multi-statement string answers an array; the facade reports the last, like a single statement.\n const r = Array.isArray(res) ? res[res.length - 1]! : res;\n const columns = (r.fields ?? []).map((f) => f.name);\n const rows = (r.rows ?? []).map((x) => ({ ...(x as Row) }));\n const isRead = r.command === 'SELECT';\n return { rows, columns, rowsAffected: isRead ? 0 : (r.rowCount ?? 0) };\n}\n\nfunction loadPool(url: string, max?: number): Pool {\n let pg: { Pool: new (cfg: { connectionString: string; max?: number }) => Pool };\n try {\n pg = createRequire(import.meta.url)('pg');\n } catch {\n throw new Error(\"@broberg/db-sdk: backend 'pg' needs the 'pg' package — npm i pg (or pass your own `pool`)\");\n }\n return new pg.Pool({ connectionString: url, max });\n}\n\nexport function pgClient(cfg: PgConfig): DbClient<Pool> {\n let pool: Pool;\n if (cfg.pool) pool = cfg.pool;\n else {\n const url = cfg.url ?? process.env.DATABASE_URL;\n if (!url) throw new Error('@broberg/db-sdk: missing database url — set DATABASE_URL, pass url, or pass your own pool');\n pool = loadPool(url, cfg.max);\n }\n return {\n transport: 'postgres',\n raw: pool,\n async execute(stmt) {\n const [text, args] = parts(stmt);\n return toResult(await pool.query(text, args));\n },\n async batch(stmts) {\n const client: PoolClient = await pool.connect();\n try {\n await client.query('begin');\n const out: DbResult[] = [];\n for (const s of stmts) {\n const [text, args] = parts(s);\n out.push(toResult(await client.query(text, args)));\n }\n await client.query('commit');\n return out;\n } catch (e) {\n // The original error is what the caller needs; a failed rollback is\n // reported alongside it rather than replacing it.\n try {\n await client.query('rollback');\n } catch (rb) {\n (e as Error & { rollbackError?: unknown }).rollbackError = rb;\n }\n throw e;\n } finally {\n client.release();\n }\n },\n async close() {\n if (!(pool as Pool & { ended?: boolean }).ended) await pool.end();\n },\n };\n}\n","/** libSQL / Turso transport for @broberg/db-sdk. */\nimport { createClient as createLibsqlClient } from '@libsql/client';\nimport type { Client as LibsqlClient, InStatement, InValue, ResultSet } from '@libsql/client';\nimport type { BatchMode, DbClient, DbResult, LibsqlConfig, ReplicaClient, ReplicaConfig, Row, Statement } from '../types';\n\nfunction requireUrl(url: string | undefined, what: string): string {\n if (!url) {\n throw new Error(`@broberg/db-sdk: missing ${what} — set TURSO_DATABASE_URL or pass it explicitly`);\n }\n return url;\n}\n\nfunction toLibsql(stmt: Statement): InStatement {\n if (typeof stmt === 'string') return stmt;\n return { sql: stmt.sql, args: (stmt.args ?? []) as InValue[] };\n}\n\n/** libSQL rows are array-like objects; the facade hands out plain objects. */\nfunction toResult(rs: ResultSet): DbResult {\n const rows: Row[] = rs.rows.map((r) => {\n const row: Row = {};\n rs.columns.forEach((c, i) => {\n row[c] = r[i];\n });\n return row;\n });\n return { rows, columns: [...rs.columns], rowsAffected: rs.rowsAffected };\n}\n\nfunction wrap(raw: LibsqlClient): DbClient<LibsqlClient> {\n return {\n transport: 'libsql',\n raw,\n async execute(stmt) {\n return toResult(await raw.execute(toLibsql(stmt)));\n },\n async batch(stmts, mode: BatchMode = 'deferred') {\n const results = await raw.batch(stmts.map(toLibsql), mode);\n return results.map(toResult);\n },\n async close() {\n raw.close();\n },\n };\n}\n\n/** Remote libSQL/Turso client. */\nexport function libsqlClient(cfg: LibsqlConfig): DbClient<LibsqlClient> {\n const url = requireUrl(cfg.url ?? process.env.TURSO_DATABASE_URL, 'database url');\n const authToken = cfg.authToken ?? process.env.TURSO_AUTH_TOKEN;\n return wrap(createLibsqlClient({ url, authToken }));\n}\n\n/** Embedded replica: a local SQLite file kept in sync with the remote primary. */\nexport function libsqlReplica(cfg: ReplicaConfig): ReplicaClient {\n const syncUrl = requireUrl(cfg.syncUrl ?? process.env.TURSO_DATABASE_URL, 'sync url');\n const authToken = cfg.authToken ?? process.env.TURSO_AUTH_TOKEN;\n const raw = createLibsqlClient({\n url: `file:${cfg.path}`,\n syncUrl,\n authToken,\n syncInterval: cfg.syncIntervalSeconds,\n });\n return {\n ...wrap(raw),\n async sync() {\n await raw.sync();\n },\n };\n}\n\nexport async function libsqlVersion(raw: LibsqlClient): Promise<string> {\n const res = await raw.execute('select sqlite_version() as v');\n return String(res.rows[0]?.v ?? 'unknown');\n}\n","/** PostgreSQL transport for @broberg/db-sdk — Supabase included. */\nimport postgres from 'postgres';\nimport type { Sql, TransactionSql } from 'postgres';\nimport type { DbClient, DbResult, PostgresConfig, Row, Statement } from '../types';\n\n/**\n * Prepared statements are OFF, deliberately, and a test fails if they come back.\n *\n * Supabase's connection pooler in transaction mode (port 6543) hands each\n * transaction to whichever server connection is free, so a statement prepared\n * on one is missing on the next. postgres.js prepares by default. With it on,\n * everything passes against a local Postgres and fails against Supabase —\n * green until production.\n */\nexport const PG_OPTIONS = { prepare: false } as const;\n\ntype PgResult = Awaited<ReturnType<Sql['unsafe']>>;\n\nfunction toResult(res: PgResult): DbResult {\n const columns = (res.columns ?? []).map((c) => c.name);\n const rows = Array.from(res, (r) => ({ ...(r as Row) }));\n // count is the command's row count; for a SELECT that is rows returned, which\n // the facade does not call \"affected\".\n const isRead = res.command === 'SELECT';\n return { rows, columns, rowsAffected: isRead ? 0 : (res.count ?? 0) };\n}\n\nfunction parts(stmt: Statement): [string, unknown[]] {\n if (typeof stmt === 'string') return [stmt, []];\n return [stmt.sql, [...(stmt.args ?? [])]];\n}\n\nfunction run(sql: Sql | TransactionSql, stmt: Statement): Promise<PgResult> {\n const [text, args] = parts(stmt);\n return sql.unsafe(text, args as never[], PG_OPTIONS);\n}\n\nexport function postgresClient(cfg: PostgresConfig): DbClient<Sql> {\n const url = cfg.url ?? process.env.DATABASE_URL;\n if (!url) {\n throw new Error('@broberg/db-sdk: missing database url — set DATABASE_URL or pass it explicitly');\n }\n const raw = postgres(url, { ...PG_OPTIONS, max: cfg.max, onnotice: () => {} });\n return {\n transport: 'postgres',\n raw,\n async execute(stmt) {\n return toResult(await run(raw, stmt));\n },\n // Postgres has no write-lock-up-front mode, so both BatchModes begin a\n // plain transaction and the mode argument is not read.\n async batch(stmts) {\n const results = await raw.begin(async (tx) => {\n const out: DbResult[] = [];\n for (const s of stmts) out.push(toResult(await run(tx, s)));\n return out;\n });\n return results as DbResult[];\n },\n async close() {\n await raw.end();\n },\n };\n}\n\nexport async function postgresVersion(raw: Sql): Promise<string> {\n const [row] = await raw.unsafe('show server_version', [], PG_OPTIONS);\n return String((row as Row | undefined)?.server_version ?? 'unknown');\n}\n","/**\n * @broberg/db-sdk — the broberg.ai fleet's shared database client.\n *\n * One facade over two transports: libSQL/Turso and PostgreSQL (Supabase\n * included). `createClient` returns the same `DbClient` from both, so switching\n * transport is a config change at the call to `createClient` — for the\n * CONNECTION. The SQL itself is passed through untouched: libSQL takes `?`,\n * Postgres takes `$1`, and the facade does not translate between them.\n *\n * Intentionally THIN: a client, an embedded-replica client (libSQL only), and a\n * health probe. ORM, schema and migrations stay in the consumer.\n */\nimport type { LibsqlClient, Sql } from './types';\nimport type { DbClient, Health, LibsqlConfig, PgConfig, PostgresConfig, ReplicaClient, ReplicaConfig } from './types';\nimport type { Pool as PgPool } from 'pg';\nimport { pgClient } from './backends/pg';\nimport { libsqlClient, libsqlReplica, libsqlVersion } from './backends/libsql';\nimport { postgresClient, postgresVersion } from './backends/postgres';\n\nexport type {\n BatchMode,\n Client,\n DbClient,\n DbConfig,\n DbResult,\n Health,\n LibsqlClient,\n LibsqlConfig,\n PgConfig,\n PostgresConfig,\n ReplicaClient,\n ReplicaConfig,\n Row,\n Sql,\n Statement,\n Transport,\n} from './types';\n\n/**\n * Create a client against a REMOTE database.\n *\n * - libSQL/Turso (default): reads `TURSO_DATABASE_URL` + `TURSO_AUTH_TOKEN`.\n * - `{ backend: 'postgres' }`: reads `DATABASE_URL`.\n */\nexport function createClient(cfg?: LibsqlConfig): DbClient<LibsqlClient>;\nexport function createClient(cfg: PostgresConfig): DbClient<Sql>;\nexport function createClient(cfg: PgConfig): DbClient<PgPool>;\nexport function createClient(cfg: LibsqlConfig | PostgresConfig | PgConfig = {}): DbClient<LibsqlClient> | DbClient<Sql> | DbClient<PgPool> {\n const backend: string = cfg.backend ?? 'libsql';\n if (cfg.backend === 'postgres') return postgresClient(cfg);\n if (cfg.backend === 'pg') return pgClient(cfg);\n if (cfg.backend === undefined || cfg.backend === 'libsql') return libsqlClient(cfg);\n throw new Error(`@broberg/db-sdk: unknown backend '${backend}' — expected 'libsql', 'postgres' or 'pg'`);\n}\n\n/**\n * Create an EMBEDDED REPLICA: a local SQLite file kept in sync with a remote\n * Turso primary. Reads hit the local file; writes forward to the primary;\n * `sync()` (or `syncIntervalSeconds`) pulls the latest. libSQL only — there is\n * no Postgres counterpart, and the config type says so.\n */\nexport function createReplica(cfg: ReplicaConfig): ReplicaClient {\n const backend: string = cfg.backend ?? 'libsql';\n if (backend !== 'libsql') {\n throw new Error(`@broberg/db-sdk: embedded replicas are libSQL-only, got backend '${backend}'`);\n }\n return libsqlReplica(cfg);\n}\n\n/**\n * Liveness + version probe. Asks the transport itself and reports which one\n * answered — read `transport` here rather than inferring it from your config.\n * Throws if the database cannot be reached.\n */\nexport async function health(client: DbClient): Promise<Health> {\n if (client.transport === 'postgres') {\n if (typeof client.raw !== 'function') {\n // pg.Pool (an object) rather than postgres.js (a tagged-template function).\n const r = await client.execute('show server_version');\n return { ok: true, transport: 'postgres', version: String(r.rows[0]?.server_version ?? 'unknown') };\n }\n return { ok: true, transport: 'postgres', version: await postgresVersion(client.raw as Sql) };\n }\n return { ok: true, transport: 'libsql', version: await libsqlVersion(client.raw as LibsqlClient) };\n}\n"],"mappings":";AAUA,SAAS,qBAAqB;AAI9B,SAAS,MAAM,MAAsC;AACnD,MAAI,OAAO,SAAS,SAAU,QAAO,CAAC,MAAM,CAAC,CAAC;AAC9C,SAAO,CAAC,KAAK,KAAK,CAAC,GAAI,KAAK,QAAQ,CAAC,CAAE,CAAC;AAC1C;AAEA,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AY,QAAO,eAAe,GAAG;AACzD,MAAI,IAAI,YAAY,KAAM,QAAO,SAAS,GAAG;AAC7C,MAAI,IAAI,YAAY,UAAa,IAAI,YAAY,SAAU,QAAO,aAAa,GAAG;AAClF,QAAM,IAAI,MAAM,qCAAqC,OAAO,gDAA2C;AACzG;AAQO,SAAS,cAAc,KAAmC;AAC/D,QAAM,UAAkB,IAAI,WAAW;AACvC,MAAI,YAAY,UAAU;AACxB,UAAM,IAAI,MAAM,oEAAoE,OAAO,GAAG;AAAA,EAChG;AACA,SAAO,cAAc,GAAG;AAC1B;AAOA,eAAsB,OAAO,QAAmC;AAC9D,MAAI,OAAO,cAAc,YAAY;AACnC,QAAI,OAAO,OAAO,QAAQ,YAAY;AAEpC,YAAM,IAAI,MAAM,OAAO,QAAQ,qBAAqB;AACpD,aAAO,EAAE,IAAI,MAAM,WAAW,YAAY,SAAS,OAAO,EAAE,KAAK,CAAC,GAAG,kBAAkB,SAAS,EAAE;AAAA,IACpG;AACA,WAAO,EAAE,IAAI,MAAM,WAAW,YAAY,SAAS,MAAM,gBAAgB,OAAO,GAAU,EAAE;AAAA,EAC9F;AACA,SAAO,EAAE,IAAI,MAAM,WAAW,UAAU,SAAS,MAAM,cAAc,OAAO,GAAmB,EAAE;AACnG;","names":["toResult","toResult","parts"]}
@@ -0,0 +1,506 @@
1
+ import { Sql } from 'postgres';
2
+ import { Pool } from 'pg';
3
+ import { D as DbClient } from '../types-9Y21zZWt.js';
4
+ import '@libsql/client';
5
+
6
+ /**
7
+ * THE INSTANT SWITCH (components-F085.5, ported from broberg-id F084.149) — a
8
+ * Postgres client that can move to another database while the process runs.
9
+ *
10
+ * The problem it solves: switching a dual-DB app to its reserve by changing a
11
+ * secret and restarting gives a minute where machine A writes to one database
12
+ * and machine B to the other. Here, every query goes through THIS object, which
13
+ * forwards to the active side. A switch is a pointer change:
14
+ *
15
+ * hold(ms) new queries wait; resolves when none are running (or at `ms`)
16
+ * point() points at the new side WITHOUT letting the waiters go — so a
17
+ * switch can be confirmed on every machine before any query
18
+ * reaches the new database
19
+ * switchTo() point() + release()
20
+ * release() lets the waiters go, onto whatever side is pointed at
21
+ *
22
+ * How long a query may wait is the orchestrator's call (whoever holds); this
23
+ * file is only the mechanism.
24
+ *
25
+ * ── `.raw` FOLLOWS THE SWITCH TOO ───────────────────────────────────────
26
+ *
27
+ * Consumers use `db().raw` (postgres.js) as much as `execute()` — vnlekerv2 has
28
+ * ~220 `sql.unsafe` and 19 `sql.begin` calls (counted 27/11 2026). A switch that
29
+ * only moved `execute()` would leave all of those on the old database. So `raw`
30
+ * is a stand-in `Sql`:
31
+ *
32
+ * sql`…`, sql.unsafe(), sql.file() a real postgres.js Query, built lazily as
33
+ * always; it is sent to the side that is
34
+ * active WHEN IT RUNS, after any hold. Its
35
+ * modifiers (.values(), .cursor(), …) and
36
+ * its use as a fragment inside another
37
+ * sql`…` are unchanged.
38
+ * sql.begin(), sql.reserve() wait out a hold, then count as one
39
+ * running query until they finish
40
+ * sql(obj), sql.json(), … helpers — passed to the active side
41
+ * sql.notify(), sql.largeObject() wait out a hold, then run on the active side
42
+ * sql.listen() passed to the side active at the call;
43
+ * a listener does NOT move with a switch
44
+ *
45
+ * A query counts as running until postgres.js settles it through
46
+ * `query.resolve` / `query.reject` — NOT until its promise settles: the
47
+ * iterator form of `.cursor()` swaps those two out, and its promise never
48
+ * settles (bid review #56236; counted on the promise, one cursor made every
49
+ * later hold() fail).
50
+ *
51
+ * Running a Query on another side uses postgres.js internals (3.4.x: the
52
+ * Query's `handler`, `canceller`, `resolve`, `reject`, `executed`), which are
53
+ * not public API. So it FAILS CLOSED: if they are missing, creating the client
54
+ * or building a query throws — it never quietly runs on the build side. The
55
+ * dependency is pinned to ~3.4.9 for the same reason.
56
+ */
57
+
58
+ interface HoldResult {
59
+ /** true = nothing was running when the hold resolved. */
60
+ ok: boolean;
61
+ /** Queries still running (a transaction that did not finish in time). */
62
+ inFlight: number;
63
+ }
64
+ /** A Postgres DbClient that can move to another database while the process runs.
65
+ * `Raw` is the driver behind `.raw`: postgres.js (`Sql`) or node-postgres (`pg.Pool`, components-F085.6). */
66
+ interface SwitchableClient<Raw = Sql> extends DbClient<Raw> {
67
+ /** The name of the side currently pointed at. */
68
+ readonly label: string;
69
+ readonly holding: boolean;
70
+ readonly inFlight: number;
71
+ /** The side currently pointed at — for code that must talk to it directly. */
72
+ readonly current: DbClient<Raw>;
73
+ hold(ms: number): Promise<HoldResult>;
74
+ /** Point at another side without releasing waiters. Returns the old side; it is NOT closed. */
75
+ point(client: DbClient<Raw>, label: string): DbClient<Raw>;
76
+ /** point() + release(). Returns the old side; it is NOT closed. */
77
+ switchTo(client: DbClient<Raw>, label: string): DbClient<Raw>;
78
+ /** Release the waiters onto the side that is pointed at. */
79
+ release(): void;
80
+ }
81
+ declare function createSwitchable(initial: DbClient<Sql>, label: string): SwitchableClient<Sql>;
82
+ declare function createSwitchable(initial: DbClient<Pool>, label: string): SwitchableClient<Pool>;
83
+
84
+ /**
85
+ * THE FENCE IN THE DATABASE (components-F085.5, ported from broberg-id
86
+ * F084.153) — the database the app is NOT running on refuses the app's writes.
87
+ *
88
+ * The switch makes every machine write to one place. But it is the APP that
89
+ * does that. A machine that missed the switch, or a restart on a stale secret,
90
+ * would write to the old database in silence — two databases each believing
91
+ * they are the real one. With the fence that write fails loudly instead
92
+ * (`25006`, read_only_sql_transaction). It covers every path into the
93
+ * database — `execute()`, `.raw`, a migration, a psql session — because it
94
+ * lives in the database, not in the client.
95
+ *
96
+ * ── WHY A TRIGGER AND NOT `default_transaction_read_only` ───────────────
97
+ *
98
+ * Measured by BID 7/10 2026 (Postgres 17, a real publisher → subscriber):
99
+ *
100
+ * default_transaction_read_only on the role the client turns it off with
101
+ * SET TRANSACTION READ WRITE,
102
+ * and it only applies to NEW
103
+ * connections
104
+ * a per-statement trigger (this file) app writes refused, READ
105
+ * WRITE included; the initial
106
+ * copy AND ongoing replication
107
+ * pass
108
+ *
109
+ * Replication passes because subscription workers run with
110
+ * `session_replication_role = replica`, where ordinary triggers do not fire.
111
+ * The app's role cannot set that itself (superuser only), and neither
112
+ * Supabase's `postgres` nor UpCloud's `upadmin` is a superuser.
113
+ *
114
+ * ── WHAT IT IS, AND WHAT IT IS NOT ─────────────────────────────────────
115
+ *
116
+ * A guard against a MISTAKE — a machine standing in the wrong place. Not a
117
+ * guard against an attacker: the role owns the tables and can drop the trigger
118
+ * with DDL. Whoever has the database password already has everything.
119
+ *
120
+ * The state lives in the FUNCTION BODY, not in a table: a table in `public`
121
+ * would be replicated from the primary and overwrite the reserve's fence. DDL
122
+ * is not replicated. Replacing the body takes effect at once, also for
123
+ * connections already open (plpgsql looks the function up on every call).
124
+ *
125
+ * INSERT/UPDATE/DELETE only. TRUNCATE is left to rebuild tooling.
126
+ */
127
+
128
+ type FenceState = 'open' | 'locked';
129
+ interface FenceOptions {
130
+ /** Name of the trigger function AND of the trigger on every table. Default `dbFence`. BID: `bidFence`. */
131
+ name?: string;
132
+ /**
133
+ * The session setting that lets the switch's own copy-home write through a
134
+ * locked database (see reconcile). A machine that missed the switch never
135
+ * sets it, so the fence still holds against the mistake it exists for.
136
+ * Default `db_sdk.fence_bypass`. BID: `bid.fence_bypass`.
137
+ */
138
+ bypass?: string;
139
+ }
140
+ declare const FENCE_DEFAULTS: {
141
+ readonly name: "dbFence";
142
+ readonly bypass: "db_sdk.fence_bypass";
143
+ };
144
+ /** read_only_sql_transaction — what a fenced write fails with. */
145
+ declare const FENCE_ERRCODE = "25006";
146
+ type Pg$1 = Pick<DbClient<Sql>, 'execute'>;
147
+ /** Locked or open — or `missing` if the fence was never installed in this database. */
148
+ declare function fenceState(db: Pg$1, o?: FenceOptions): Promise<FenceState | 'missing'>;
149
+ declare function setFence(db: Pg$1, state: FenceState, o?: FenceOptions): Promise<void>;
150
+ /**
151
+ * Install the fence: the function if missing (in `initial`), and the trigger
152
+ * on every table in the schema that lacks it. Idempotent, and it NEVER changes
153
+ * an existing state — only the switch may. The tables are ASKED of the
154
+ * database, so a table an upgrade adds gets fenced too: call it after every
155
+ * migration.
156
+ */
157
+ declare function installFence(db: Pg$1, initial: FenceState, o?: FenceOptions): Promise<{
158
+ created: boolean;
159
+ triggered: string[];
160
+ }>;
161
+ /** Tables without the trigger — an empty list means the whole schema is covered. */
162
+ declare function unfencedTables(db: Pg$1, o?: FenceOptions): Promise<string[]>;
163
+
164
+ /**
165
+ * THE WAY BACK WITHOUT LOSS (components-F085.5, ported from broberg-id
166
+ * F084.154) — what was written in the reserve after the switch is brought over
167
+ * to the primary BEFORE switching back.
168
+ *
169
+ * ── THE WALL ─────────────────────────────────────────────────────────────
170
+ *
171
+ * The obvious tool — a reverse subscription, the primary subscribing to the
172
+ * reserve — is not always possible (Supabase cannot subscribe outward). A
173
+ * publication on the reserve plus a WAL player of our own would be a new,
174
+ * heavy component running from the switch onwards. The databases this is for
175
+ * are small (BID 7/10: ~3,000 rows, 28 tables), so COMPARING the rows takes
176
+ * milliseconds and needs nothing running in between.
177
+ *
178
+ * ── THREE STATES PER ROW ─────────────────────────────────────────────────
179
+ *
180
+ * B the baseline at the switch to the reserve — taken while every machine
181
+ * held, just after the subscription was disabled (`captureBaseline`)
182
+ * R the reserve now
183
+ * P the primary now
184
+ *
185
+ * R = P nothing to do
186
+ * P = B only the reserve changed the row → copy (a DELETE too —
187
+ * otherwise a logged-out session wakes up again)
188
+ * otherwise the primary has a change the reserve never saw: CONFLICT.
189
+ * Reported, never overwritten in silence.
190
+ *
191
+ * After a planned switch there can be no conflicts: the primary is fenced and
192
+ * stood still from the baseline. After an EMERGENCY switch the primary may hold
193
+ * the last seconds of writes that never reached the reserve — those are what
194
+ * the conflicts catch.
195
+ *
196
+ * What was copied is written into the baseline, so a run that is interrupted
197
+ * and re-run sees its own copies as "P = B", not as conflicts.
198
+ *
199
+ * A row is compared as `md5(to_jsonb(row))` in UTC: jsonb keys are sorted, so
200
+ * column order in the two databases does not matter.
201
+ *
202
+ * Only the CURRENT schema (search_path) is compared; the baseline lives in a
203
+ * schema of its own, so it is never part of the comparison.
204
+ */
205
+
206
+ type Pg = Pick<DbClient<Sql>, 'execute' | 'batch'>;
207
+ interface ReconcileOptions {
208
+ /** Schema that holds the baseline. Default `dbSwitch`. BID: `bidSwitch`. */
209
+ schema?: string;
210
+ /** The fence's bypass setting (see FenceOptions.bypass). Default `db_sdk.fence_bypass`. */
211
+ bypass?: string;
212
+ }
213
+ declare const RECONCILE_DEFAULTS: {
214
+ readonly schema: "dbSwitch";
215
+ readonly bypass: "db_sdk.fence_bypass";
216
+ };
217
+ /** Take the baseline B on the reserve. Call it while every machine holds. Returns the row count. */
218
+ declare function captureBaseline(reserve: Pg, o?: ReconcileOptions): Promise<number>;
219
+ /** Is there a baseline — and when was it taken (epoch ms)? */
220
+ declare function baselineAt(reserve: Pg, o?: ReconcileOptions): Promise<number | null>;
221
+ interface Conflict {
222
+ table: string;
223
+ key: string;
224
+ /** What the reserve holds now (null = deleted). */
225
+ reserve: string | null;
226
+ /** What the primary holds now (null = does not exist). */
227
+ primary: string | null;
228
+ /** The baseline at the switch (null = did not exist). */
229
+ baseline: string | null;
230
+ }
231
+ interface Plan {
232
+ upserts: number;
233
+ deletes: number;
234
+ conflicts: Conflict[];
235
+ /** Tables whose columns differ between the two databases — then nothing can be compared. */
236
+ schemaMismatch: string[];
237
+ /** Rows actually written in the primary (0 when only planned). */
238
+ written: number;
239
+ }
240
+ /**
241
+ * Compare, and copy if `apply` and there are neither conflicts nor schema
242
+ * differences — OR `skipConflicts`, in which case the rest is copied and the
243
+ * conflicting rows stay as the primary has them.
244
+ *
245
+ * Everything is written in the primary in ONE transaction through the fence's
246
+ * door (the bypass setting): the primary is fenced while the app runs on the
247
+ * reserve.
248
+ */
249
+ declare function reconcile(reserve: Pg, primary: Pg, opts: {
250
+ apply: boolean;
251
+ skipConflicts?: boolean;
252
+ } & ReconcileOptions): Promise<Plan>;
253
+
254
+ /** A Postgres client from either driver (postgres.js or pg, components-F085.6). */
255
+ type AnyPg = DbClient<any>;
256
+ type Target = 'primary' | 'reserve';
257
+ interface TargetSpec {
258
+ /** The name the side answers to (BID: "supabase" / "upcloud"). Known without opening. */
259
+ label: string;
260
+ /** Open a client for it. Called once, on the first prepare. */
261
+ open: () => AnyPg;
262
+ }
263
+ interface SwitchControlOptions {
264
+ switchable: SwitchableClient<any>;
265
+ targets: Record<Target, TargetSpec>;
266
+ /** The machines' shared secret; the Bearer is HMAC-SHA256(secret, context). */
267
+ secret: string;
268
+ /** HMAC context. Default "db-switch". BID: "bid-db-switch". */
269
+ context?: string;
270
+ /** Logged on a switch and on the safety net. Default console. */
271
+ log?: {
272
+ info(msg: string): void;
273
+ error(msg: string): void;
274
+ };
275
+ }
276
+ declare const HOLD_MIN_MS = 100;
277
+ declare const HOLD_MAX_MS = 10000;
278
+ /** The Bearer an orchestrator sends — derived, so it never travels or is stored on its own. */
279
+ declare function switchToken(secret: string, context?: string): string;
280
+ declare function createSwitchControl(o: SwitchControlOptions): (req: Request) => Promise<Response>;
281
+ /**
282
+ * THE EMERGENCY SWITCH'S GUARD (BID F084.152) — may a switch without the primary
283
+ * run? The emergency switch skips the marker, so whatever had not replicated is
284
+ * lost. It may ONLY run when the primary really does not answer — otherwise the
285
+ * planned switch (lossless) is the right one — and whoever presses must have
286
+ * said the loss is accepted. `fault: "primary-down"` is a test's way past the
287
+ * first condition, against a primary that is alive.
288
+ */
289
+ type EmergencyDecision = 'proceed' | 'need-accept' | 'refuse-primary-alive';
290
+ declare function emergencyGate(o: {
291
+ primaryResponds: boolean;
292
+ acceptDataLoss: boolean;
293
+ fault?: string;
294
+ }): EmergencyDecision;
295
+
296
+ type MachineAnswer = {
297
+ status: number;
298
+ ok?: boolean;
299
+ label?: string;
300
+ error?: string;
301
+ [k: string]: unknown;
302
+ };
303
+ interface Machine {
304
+ id: string;
305
+ call(path: string, body?: unknown, timeoutMs?: number): Promise<MachineAnswer>;
306
+ }
307
+ /** A machine reached over HTTP at `baseUrl` (e.g. "http://<id>.vm.<app>.internal:8081"). */
308
+ declare function httpMachine(id: string, baseUrl: string, token: string): Machine;
309
+ interface OrchestrateOptions {
310
+ to: Target;
311
+ machines: Machine[];
312
+ /** DIRECT clients to both sides (not through a pooler) — only the orchestration uses them. */
313
+ primary: DbClient<any>;
314
+ reserve: DbClient<any>;
315
+ /** The labels the machines report for each side (same as the control's targets). */
316
+ labels: Record<Target, string>;
317
+ /** The reserve's subscription to the primary (to the reserve only). */
318
+ subscription: string;
319
+ /** Hold ceiling per machine, 100–10 000. Default 3000. */
320
+ holdMs?: number;
321
+ /** To the primary: copy home but keep the primary's version of conflicting rows. */
322
+ skipConflicts?: boolean;
323
+ /** To the primary: drop what was written in the reserve (the emergency exit). */
324
+ discardReserveWrites?: boolean;
325
+ /** Emergency switch to the reserve: the primary is down. No probe, no marker —
326
+ * so what had not replicated is LOST. Needs `acceptDataLoss`, and is refused
327
+ * while the primary answers (emergencyGate). */
328
+ primaryDown?: boolean;
329
+ acceptDataLoss?: boolean;
330
+ /** Fault injection for tests in production (BID AC1). "primary-down" treats a
331
+ * live primary as dead, to test the emergency path. */
332
+ fault?: 'replication' | 'point' | 'primary-down';
333
+ /** Marker table (id text pk, at bigint). Default "dbSwitchMarker" (BID's). */
334
+ markerTable?: string;
335
+ fence?: FenceOptions;
336
+ reconcile?: ReconcileOptions;
337
+ log?: (line: string) => void;
338
+ }
339
+ type Outcome = {
340
+ outcome: 'done';
341
+ label: string;
342
+ heldMs: number;
343
+ } | {
344
+ outcome: 'refused';
345
+ reason: string;
346
+ } | {
347
+ outcome: 'aborted';
348
+ reason: string;
349
+ restored: string[];
350
+ } | {
351
+ outcome: 'unconfirmed';
352
+ reason: string;
353
+ label: string;
354
+ };
355
+ declare function orchestrateSwitch(o: OrchestrateOptions): Promise<Outcome>;
356
+
357
+ /**
358
+ * IS THE RESERVE ALIVE? — and who gets woken when it is not (components-F085.5,
359
+ * ported from broberg-id reserve-health.ts F084.114 + reserve-watch.ts F084.204).
360
+ *
361
+ * A reserve can die without anyone seeing it: a dead reserve is nothing in the
362
+ * app's logs, and a failed reserve migration is one log line. A reserve you
363
+ * believe is alive is MORE dangerous than none, because you count on it the day
364
+ * the primary falls. fd-sundhed 28/10 2026: two new columns in production
365
+ * without the reserve, replication stood still for 5 hours, the slot was 128 MB
366
+ * from being dropped.
367
+ *
368
+ * The reading comes from the PRIMARY (its replication slot and the walsender),
369
+ * not from the reserve: if the reserve is down, that is exactly what the answer
370
+ * must say. Serve it on its own route — BID: /health/reserve, NOT /health/ready:
371
+ * a dead reserve must never take logins down.
372
+ *
373
+ * The alarm half is PURE: the app keeps the episode state where it wants (BID:
374
+ * a table, because it runs on two machines) and sends the incidents its own way.
375
+ */
376
+
377
+ interface ReserveThresholds {
378
+ /** No reply from the reserve for this long = stale. BID: 300 (it replies every ~10 s). */
379
+ staleSeconds: number;
380
+ /** This far behind = not catching up. BID: 64 MB (Supabase drops the slot at 512 MB). */
381
+ lagBytes: number;
382
+ }
383
+ declare const RESERVE_DEFAULTS: ReserveThresholds;
384
+ interface SlotReading {
385
+ active: boolean;
386
+ walStatus: string | null;
387
+ lagBytes: number | null;
388
+ /** Seconds since the reserve last replied; null = no live connection. */
389
+ replyAgeSeconds: number | null;
390
+ }
391
+ type ReserveReason = 'missing' | 'inactive' | 'lost' | 'stale' | 'lagging' | 'unreadable';
392
+ type ReserveVerdict = {
393
+ ok: true;
394
+ } | {
395
+ ok: false;
396
+ reason: ReserveReason | (string & {});
397
+ };
398
+ declare function judgeReserve(r: SlotReading | null, t?: ReserveThresholds): ReserveVerdict;
399
+ /** Read the reserve's slot ON THE PRIMARY. The slot name is the subscription's (BID: bid_reserve). */
400
+ declare function readReserveSlot(primary: Pick<DbClient<Sql>, 'execute'>, slot: string): Promise<SlotReading | null>;
401
+ /** Read + judge in one call; a reading that fails — or does not answer within
402
+ * `timeoutMs` (default 5 s; a hung primary must not hang the health route) —
403
+ * is `unreadable`, never «ok». */
404
+ declare function reserveHealth(primary: Pick<DbClient<Sql>, 'execute'>, slot: string, t?: ReserveThresholds, timeoutMs?: number): Promise<ReserveVerdict>;
405
+ /** Unhealthy this long in a row → one incident per episode. A blink sends nothing. BID: 10 min. */
406
+ declare const RESERVE_ALARM_AFTER_MS: number;
407
+ declare const MIGRATION_FAILED = "migration_failed";
408
+ /** The app persists this between rounds (BID: rows in its reserveWatch table). */
409
+ interface ReserveWatchState {
410
+ slot?: {
411
+ reason: string;
412
+ firstSeenAt: number;
413
+ };
414
+ migrationFailed?: {
415
+ firstSeenAt: number;
416
+ detail: string;
417
+ };
418
+ }
419
+ interface ReserveIncident {
420
+ /** Carries the episode's start, so «sent once per id» gives one alarm per episode and a new one for a new episode. */
421
+ id: string;
422
+ reason: string;
423
+ severity: 'critical' | 'high';
424
+ openedAt: string;
425
+ detail: string | null;
426
+ }
427
+ /** The reserve migration's outcome on a deploy → state. Failure alarms at once
428
+ * (it does not fix itself). `skipped` (no reserve configured on this deploy)
429
+ * leaves the state untouched — it must never clear a pending migration_failed. */
430
+ declare function noteReserveMigration(state: ReserveWatchState, outcome: {
431
+ ok: true;
432
+ } | {
433
+ ok: false;
434
+ reason: string;
435
+ } | {
436
+ skipped: true;
437
+ }, now?: number): ReserveWatchState;
438
+ /** One alarm round: the next state from `verdict`, and the incidents to send. */
439
+ declare function watchReserve(state: ReserveWatchState, verdict: ReserveVerdict, now?: number, alarmAfterMs?: number): {
440
+ state: ReserveWatchState;
441
+ incidents: ReserveIncident[];
442
+ };
443
+
444
+ type Restrictions = {
445
+ dbAllowedCidrs: string[];
446
+ dbAllowedCidrsV6: string[];
447
+ };
448
+ interface GuardDeps {
449
+ reserveHealth(): Promise<{
450
+ ok: boolean;
451
+ reason?: string;
452
+ }>;
453
+ upcloudPublicHost(): Promise<string>;
454
+ resolve(host: string): Promise<string>;
455
+ getRestrictions(): Promise<Restrictions & {
456
+ status: string;
457
+ }>;
458
+ applyRestrictions(r: Restrictions): Promise<void>;
459
+ sleep(ms: number): Promise<void>;
460
+ log(line: string): void;
461
+ }
462
+ interface GuardOptions {
463
+ /** Known fixed v4 addresses (e.g. Fly egress, office) — only for the clean-up note. */
464
+ fixedV4: string[];
465
+ /** How long to wait for an active slot after a fix. */
466
+ waitMs: number;
467
+ pollMs: number;
468
+ /** How long to read back before a list that did not take effect is an error (BID F084.174). */
469
+ readBackMs: number;
470
+ /** BID F084.197 — an unhealthy slot is measured again after this long before acting. A blink is not a state. */
471
+ confirmMs: number;
472
+ }
473
+ type GuardResult = {
474
+ outcome: "healthy";
475
+ } | {
476
+ outcome: "not-network";
477
+ reason: string;
478
+ } | {
479
+ outcome: "already-allowed";
480
+ ip: string;
481
+ } | {
482
+ outcome: "fixed";
483
+ ip: string;
484
+ } | {
485
+ outcome: "still-down";
486
+ ip: string;
487
+ reason: string;
488
+ }
489
+ /** BID F084.238 — the slot is lost. The address is fixed (or was fine); the reserve must be rebuilt. */
490
+ | {
491
+ outcome: "needs-rebuild";
492
+ ip: string;
493
+ added: boolean;
494
+ };
495
+ declare function runGuard(d: GuardDeps, o: GuardOptions): Promise<GuardResult>;
496
+ /** The real APIs (UpCloud Managed Postgres as the reserve, Supabase as the primary).
497
+ * The keys come from the environment and are never logged. */
498
+ declare function liveDeps(env: {
499
+ healthUrl: string;
500
+ upcloudToken: string;
501
+ upcloudDbUuid: string;
502
+ supabaseToken: string;
503
+ supabaseRef: string;
504
+ }): GuardDeps;
505
+
506
+ export { type Conflict, type EmergencyDecision, FENCE_DEFAULTS, FENCE_ERRCODE, type FenceOptions, type FenceState, type GuardDeps, type GuardOptions, type GuardResult, HOLD_MAX_MS, HOLD_MIN_MS, type HoldResult, MIGRATION_FAILED, type Machine, type MachineAnswer, type OrchestrateOptions, type Outcome, type Plan, RECONCILE_DEFAULTS, RESERVE_ALARM_AFTER_MS, RESERVE_DEFAULTS, type ReconcileOptions, type ReserveIncident, type ReserveReason, type ReserveThresholds, type ReserveVerdict, type ReserveWatchState, type Restrictions, type SlotReading, type SwitchControlOptions, type SwitchableClient, type Target, type TargetSpec, baselineAt, captureBaseline, createSwitchControl, createSwitchable, emergencyGate, fenceState, httpMachine, installFence, judgeReserve, liveDeps, noteReserveMigration, orchestrateSwitch, readReserveSlot, reconcile, reserveHealth, runGuard, setFence, switchToken, unfencedTables, watchReserve };