@broberg/db-sdk 0.3.0 → 0.4.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/README.md +30 -0
- package/dist/chunk-ONXYOFVT.js +124 -0
- package/dist/chunk-ONXYOFVT.js.map +1 -0
- package/dist/index.js +8 -117
- package/dist/index.js.map +1 -1
- package/dist/switchable/index.d.ts +59 -4
- package/dist/switchable/index.js +211 -11
- package/dist/switchable/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/switchable/switchable.ts","../../src/switchable/fence.ts","../../src/switchable/reconcile.ts","../../src/switchable/control.ts","../../src/switchable/orchestrate.ts","../../src/switchable/reserve.ts","../../src/switchable/ip-guard.ts"],"sourcesContent":["/**\n * THE INSTANT SWITCH (components-F085.5, ported from broberg-id F084.149) — a\n * Postgres client that can move to another database while the process runs.\n *\n * The problem it solves: switching a dual-DB app to its reserve by changing a\n * secret and restarting gives a minute where machine A writes to one database\n * and machine B to the other. Here, every query goes through THIS object, which\n * forwards to the active side. A switch is a pointer change:\n *\n * hold(ms) new queries wait; resolves when none are running (or at `ms`)\n * point() points at the new side WITHOUT letting the waiters go — so a\n * switch can be confirmed on every machine before any query\n * reaches the new database\n * switchTo() point() + release()\n * release() lets the waiters go, onto whatever side is pointed at\n *\n * How long a query may wait is the orchestrator's call (whoever holds); this\n * file is only the mechanism.\n *\n * ── `.raw` FOLLOWS THE SWITCH TOO ───────────────────────────────────────\n *\n * Consumers use `db().raw` (postgres.js) as much as `execute()` — vnlekerv2 has\n * ~220 `sql.unsafe` and 19 `sql.begin` calls (counted 27/11 2026). A switch that\n * only moved `execute()` would leave all of those on the old database. So `raw`\n * is a stand-in `Sql`:\n *\n * sql`…`, sql.unsafe(), sql.file() a real postgres.js Query, built lazily as\n * always; it is sent to the side that is\n * active WHEN IT RUNS, after any hold. Its\n * modifiers (.values(), .cursor(), …) and\n * its use as a fragment inside another\n * sql`…` are unchanged.\n * sql.begin(), sql.reserve() wait out a hold, then count as one\n * running query until they finish\n * sql(obj), sql.json(), … helpers — passed to the active side\n * sql.notify(), sql.largeObject() wait out a hold, then run on the active side\n * sql.listen() passed to the side active at the call;\n * a listener does NOT move with a switch\n *\n * A query counts as running until postgres.js settles it through\n * `query.resolve` / `query.reject` — NOT until its promise settles: the\n * iterator form of `.cursor()` swaps those two out, and its promise never\n * settles (bid review #56236; counted on the promise, one cursor made every\n * later hold() fail).\n *\n * Running a Query on another side uses postgres.js internals (3.4.x: the\n * Query's `handler`, `canceller`, `resolve`, `reject`, `executed`), which are\n * not public API. So it FAILS CLOSED: if they are missing, creating the client\n * or building a query throws — it never quietly runs on the build side. The\n * dependency is pinned to ~3.4.9 for the same reason.\n */\nimport type { Sql } from 'postgres';\nimport type { Pool as PgPool, PoolClient } from 'pg';\nimport type { BatchMode, DbClient, DbResult, Statement } from '../types';\n\nexport interface HoldResult {\n /** true = nothing was running when the hold resolved. */\n ok: boolean;\n /** Queries still running (a transaction that did not finish in time). */\n inFlight: number;\n}\n\n/** A Postgres DbClient that can move to another database while the process runs.\n * `Raw` is the driver behind `.raw`: postgres.js (`Sql`) or node-postgres (`pg.Pool`, components-F085.6). */\nexport interface SwitchableClient<Raw = Sql> extends DbClient<Raw> {\n /** The name of the side currently pointed at. */\n readonly label: string;\n readonly holding: boolean;\n readonly inFlight: number;\n /** The side currently pointed at — for code that must talk to it directly. */\n readonly current: DbClient<Raw>;\n hold(ms: number): Promise<HoldResult>;\n /** Point at another side without releasing waiters. Returns the old side; it is NOT closed. */\n point(client: DbClient<Raw>, label: string): DbClient<Raw>;\n /** point() + release(). Returns the old side; it is NOT closed. */\n switchTo(client: DbClient<Raw>, label: string): DbClient<Raw>;\n /** Release the waiters onto the side that is pointed at. */\n release(): void;\n}\n\n/** The postgres.js Query internals this file relies on (3.4.x). */\ninterface QueryInternals {\n executed: boolean;\n handler: (q: unknown) => unknown;\n canceller: ((q: unknown) => unknown) | null;\n handle: () => Promise<void>;\n resolve: (x: unknown) => unknown;\n reject: (x: unknown) => unknown;\n}\ntype Side = Pick<QueryInternals, 'handler' | 'canceller'>;\n\nconst UNSUPPORTED = '@broberg/db-sdk/switchable: this postgres.js version does not have the Query internals the switch routes .raw by (3.4.x) — refusing rather than running on the wrong database';\n\nconst isQuery = (x: unknown): x is QueryInternals => {\n const q = x as Partial<QueryInternals>;\n return (\n x instanceof Promise &&\n typeof q.handler === 'function' &&\n typeof q.canceller === 'function' &&\n typeof q.resolve === 'function' &&\n typeof q.reject === 'function' &&\n typeof q.handle === 'function' &&\n q.executed === false\n );\n};\n\n// Each postgres.js instance's private handler + canceller, read once off a\n// query that is built and never run (postgres.js queries are lazy).\nconst sides = new WeakMap<Sql, Side>();\nfunction sideOf(sql: Sql): Side {\n let side = sides.get(sql);\n if (!side) {\n const probe: unknown = sql.unsafe('');\n if (!isQuery(probe)) throw new Error(UNSUPPORTED);\n side = { handler: probe.handler, canceller: probe.canceller };\n sides.set(sql, side);\n }\n return side;\n}\n\n/** Which driver a Postgres client's `.raw` is. Anything else is refused. */\ntype Kind = 'postgresjs' | 'pg';\nconst UNSUPPORTED_RAW = '@broberg/db-sdk/switchable: .raw is neither postgres.js nor a pg.Pool — refusing rather than running unrouted';\nfunction kindOf(raw: unknown): Kind {\n if (typeof raw === 'function') {\n sideOf(raw as Sql); // postgres.js: throws if its Query internals moved\n return 'postgresjs';\n }\n const pool = raw as Partial<PgPool> | null;\n if (pool && typeof pool.connect === 'function' && typeof pool.query === 'function' && typeof pool.on === 'function') return 'pg';\n throw new Error(UNSUPPORTED_RAW);\n}\n\nexport function createSwitchable(initial: DbClient<Sql>, label: string): SwitchableClient<Sql>;\nexport function createSwitchable(initial: DbClient<PgPool>, label: string): SwitchableClient<PgPool>;\nexport function createSwitchable(initial: DbClient<Sql> | DbClient<PgPool>, label: string): SwitchableClient<Sql> | SwitchableClient<PgPool> {\n if (initial.transport !== 'postgres') throw new Error('@broberg/db-sdk/switchable: Postgres only');\n const kind = kindOf(initial.raw); // fail closed at creation, not at the first query\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- one of two drivers, checked by kind\n let active: DbClient<any> = initial;\n let name = label;\n let gate: Promise<void> | null = null;\n let open: (() => void) | null = null;\n let running = 0;\n let idle: Array<() => void> = [];\n\n const enter = async () => {\n while (gate) await gate;\n running++;\n };\n const exit = () => {\n running--;\n if (running === 0) for (const f of idle.splice(0)) f();\n };\n const guarded = async <T>(fn: () => Promise<T>): Promise<T> => {\n await enter();\n try {\n return await fn();\n } finally {\n exit();\n }\n };\n\n /** Make a lazily-built Query run on the side that is active when it runs. */\n const route = <Q>(q: Q): Q => {\n // A helper (sql(obj), sql.json()) is no promise and passes as is. A promise\n // that is not a Query we can route is refused — never run unrouted.\n if (!(q instanceof Promise)) return q;\n if (!isQuery(q)) throw new Error(UNSUPPORTED);\n q.handle = async function (this: QueryInternals) {\n if (this.executed) return;\n this.executed = true;\n await enter();\n // Count out when postgres.js settles the query — whichever resolve or\n // reject is in place by then (the cursor iterator assigns its own).\n let done = false;\n const finish = () => {\n if (!done) {\n done = true;\n exit();\n }\n };\n for (const key of ['resolve', 'reject'] as const) {\n let fn = this[key];\n Object.defineProperty(this, key, {\n configurable: true,\n get: () => (x: unknown) => {\n finish();\n return fn(x);\n },\n set: (v: (x: unknown) => unknown) => {\n fn = v;\n },\n });\n }\n const side = sideOf(active.raw);\n this.handler = side.handler;\n // cancel() before this point has nothing to cancel; after it, it must\n // reach the side the query was sent to.\n if (this.canceller) this.canceller = side.canceller;\n this.handler(this);\n };\n return q;\n };\n\n // ── node-postgres: a stand-in pg.Pool (BID's SwitchablePool, F084.149) ──\n // query/connect wait out a hold and count as running — a client until its\n // release(), counted once. Listeners are re-attached to each new pool once.\n const listeners: Array<[string, (...a: unknown[]) => void]> = [];\n const withListeners = new WeakSet<object>();\n if (kind === 'pg') withListeners.add(initial.raw as object);\n const attach = (pool: PgPool) => {\n if (withListeners.has(pool)) return;\n for (const [ev, fn] of listeners) pool.on(ev as 'error', fn as () => void);\n withListeners.add(pool);\n };\n const callbackStyle = (a: unknown[]) => typeof a[a.length - 1] === 'function';\n const pgRaw: PgPool = new Proxy({} as PgPool, {\n get(_t, prop) {\n const pool = active.raw as PgPool;\n if (prop === 'query') {\n return (...a: unknown[]) => {\n if (callbackStyle(a)) throw new Error('@broberg/db-sdk/switchable: callback-style pool.query is not routed — use the promise form');\n return guarded(() => (active.raw as PgPool).query(...(a as [string])));\n };\n }\n if (prop === 'connect') {\n return async (...a: unknown[]) => {\n if (callbackStyle(a)) throw new Error('@broberg/db-sdk/switchable: callback-style pool.connect is not routed — use the promise form');\n await enter();\n let client: PoolClient;\n try {\n client = await (active.raw as PgPool).connect();\n } catch (err) {\n exit();\n throw err;\n }\n const release = client.release.bind(client);\n let released = false;\n client.release = ((err?: Error | boolean) => {\n if (!released) {\n released = true;\n exit();\n }\n return release(err as Error);\n }) as PoolClient['release'];\n return client;\n };\n }\n if (prop === 'on') {\n return (ev: string, fn: (...x: unknown[]) => void) => {\n listeners.push([ev, fn]);\n (active.raw as PgPool).on(ev as 'error', fn as () => void);\n return pgRaw;\n };\n }\n if (prop === 'end') return () => ((active.raw as PgPool & { ended?: boolean }).ended ? Promise.resolve() : (active.raw as PgPool).end());\n const v = (pool as unknown as Record<PropertyKey, unknown>)[prop];\n return typeof v === 'function' ? (v as (...x: unknown[]) => unknown).bind(pool) : v;\n },\n });\n\n // ── postgres.js: a stand-in Sql ──\n const pjsRaw = new Proxy(function () {} as unknown as Sql, {\n apply(_t, _this, args: unknown[]) {\n return route((active.raw as unknown as (...a: unknown[]) => unknown)(...args));\n },\n get(_t, prop) {\n const sql = active.raw as unknown as Record<PropertyKey, unknown>;\n if (prop === 'unsafe' || prop === 'file') {\n return (...a: unknown[]) => route((active.raw as unknown as Record<string, (...x: unknown[]) => unknown>)[prop]!(...a));\n }\n if (prop === 'begin' || prop === 'notify' || prop === 'largeObject') {\n return (...a: unknown[]) => guarded(() => {\n // Looked up when it RUNS, after any hold — not on the side of the call.\n const side = active.raw as unknown as Record<PropertyKey, (...x: unknown[]) => Promise<unknown>>;\n return side[prop]!.apply(active.raw, a);\n });\n }\n if (prop === 'reserve') {\n return async () => {\n await enter();\n let reserved: Awaited<ReturnType<Sql['reserve']>>;\n try {\n reserved = await active.raw.reserve();\n } catch (err) {\n exit();\n throw err;\n }\n const release = reserved.release.bind(reserved);\n let released = false;\n reserved.release = () => {\n if (!released) {\n released = true;\n exit();\n }\n release();\n };\n return reserved;\n };\n }\n const v = sql[prop];\n return typeof v === 'function' ? (v as (...a: unknown[]) => unknown).bind(active.raw) : v;\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- the two overloads share one implementation\n const self: SwitchableClient<any> = {\n transport: 'postgres',\n raw: kind === 'pg' ? pgRaw : pjsRaw,\n get label() {\n return name;\n },\n get holding() {\n return gate !== null;\n },\n get inFlight() {\n return running;\n },\n get current() {\n return active;\n },\n execute(stmt: Statement): Promise<DbResult> {\n return guarded(() => active.execute(stmt));\n },\n batch(stmts: readonly Statement[], mode?: BatchMode): Promise<DbResult[]> {\n return guarded(() => active.batch(stmts, mode));\n },\n /** Closes the side pointed at. Sides switched away from are the caller's to close. */\n close() {\n return active.close();\n },\n async hold(ms) {\n if (!gate) gate = new Promise<void>((r) => (open = r));\n if (running === 0) return { ok: true, inFlight: 0 };\n const empty = new Promise<'empty'>((r) => idle.push(() => r('empty')));\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<'late'>((r) => (timer = setTimeout(() => r('late'), ms)));\n const outcome = await Promise.race([empty, late]);\n clearTimeout(timer);\n return { ok: outcome === 'empty', inFlight: running };\n },\n point(client, label) {\n if (client.transport !== 'postgres') throw new Error('@broberg/db-sdk/switchable: Postgres only');\n // Both sides must speak the same driver: .raw callers hold one driver's API.\n if (kindOf(client.raw) !== kind) throw new Error(`@broberg/db-sdk/switchable: cannot point a ${kind} client at a ${kindOf(client.raw)} one`);\n if (kind === 'pg') attach(client.raw as PgPool);\n const old = active;\n active = client;\n name = label;\n return old;\n },\n switchTo(client: DbClient<any>, label: string) {\n const old = self.point(client, label);\n self.release();\n return old;\n },\n release() {\n const f = open;\n gate = null;\n open = null;\n f?.();\n },\n };\n return self;\n}\n","/**\n * THE FENCE IN THE DATABASE (components-F085.5, ported from broberg-id\n * F084.153) — the database the app is NOT running on refuses the app's writes.\n *\n * The switch makes every machine write to one place. But it is the APP that\n * does that. A machine that missed the switch, or a restart on a stale secret,\n * would write to the old database in silence — two databases each believing\n * they are the real one. With the fence that write fails loudly instead\n * (`25006`, read_only_sql_transaction). It covers every path into the\n * database — `execute()`, `.raw`, a migration, a psql session — because it\n * lives in the database, not in the client.\n *\n * ── WHY A TRIGGER AND NOT `default_transaction_read_only` ───────────────\n *\n * Measured by BID 7/10 2026 (Postgres 17, a real publisher → subscriber):\n *\n * default_transaction_read_only on the role the client turns it off with\n * SET TRANSACTION READ WRITE,\n * and it only applies to NEW\n * connections\n * a per-statement trigger (this file) app writes refused, READ\n * WRITE included; the initial\n * copy AND ongoing replication\n * pass\n *\n * Replication passes because subscription workers run with\n * `session_replication_role = replica`, where ordinary triggers do not fire.\n * The app's role cannot set that itself (superuser only), and neither\n * Supabase's `postgres` nor UpCloud's `upadmin` is a superuser.\n *\n * ── WHAT IT IS, AND WHAT IT IS NOT ─────────────────────────────────────\n *\n * A guard against a MISTAKE — a machine standing in the wrong place. Not a\n * guard against an attacker: the role owns the tables and can drop the trigger\n * with DDL. Whoever has the database password already has everything.\n *\n * The state lives in the FUNCTION BODY, not in a table: a table in `public`\n * would be replicated from the primary and overwrite the reserve's fence. DDL\n * is not replicated. Replacing the body takes effect at once, also for\n * connections already open (plpgsql looks the function up on every call).\n *\n * INSERT/UPDATE/DELETE only. TRUNCATE is left to rebuild tooling.\n */\nimport type { Sql } from 'postgres';\nimport type { DbClient } from '../types';\n\nexport type FenceState = 'open' | 'locked';\n\nexport interface FenceOptions {\n /** Name of the trigger function AND of the trigger on every table. Default `dbFence`. BID: `bidFence`. */\n name?: string;\n /**\n * The session setting that lets the switch's own copy-home write through a\n * locked database (see reconcile). A machine that missed the switch never\n * sets it, so the fence still holds against the mistake it exists for.\n * Default `db_sdk.fence_bypass`. BID: `bid.fence_bypass`.\n */\n bypass?: string;\n}\n\nexport const FENCE_DEFAULTS = { name: 'dbFence', bypass: 'db_sdk.fence_bypass' } as const;\n/** read_only_sql_transaction — what a fenced write fails with. */\nexport const FENCE_ERRCODE = '25006';\n\ntype Pg = Pick<DbClient<Sql>, 'execute'>;\n\nconst q = (name: string) => `\"${name.replace(/\"/g, '\"\"')}\"`;\nconst lit = (s: string) => `'${s.replace(/'/g, \"''\")}'`;\nconst opts = (o?: FenceOptions) => ({ ...FENCE_DEFAULTS, ...o });\n\nconst body = (state: FenceState, bypass: string) =>\n state === 'open'\n ? `begin return null; end`\n : `begin\n if current_setting(${lit(bypass)}, true) = 'on' then return null; end if;\n raise exception 'db-sdk fence: this database is not the active one — the write is refused' using errcode = '${FENCE_ERRCODE}';\n end`;\n\n/** Locked or open — or `missing` if the fence was never installed in this database. */\nexport async function fenceState(db: Pg, o?: FenceOptions): Promise<FenceState | 'missing'> {\n const { name } = opts(o);\n const { rows } = await db.execute({\n sql: `select p.prosrc as src from pg_proc p where p.proname = $1 and p.pronamespace = current_schema()::regnamespace`,\n args: [name],\n });\n if (rows.length === 0) return 'missing';\n return String(rows[0]!.src).includes('raise exception') ? 'locked' : 'open';\n}\n\nexport async function setFence(db: Pg, state: FenceState, o?: FenceOptions): Promise<void> {\n const { name, bypass } = opts(o);\n await db.execute(`create or replace function ${q(name)}() returns trigger language plpgsql as $fence$ ${body(state, bypass)} $fence$`);\n}\n\n/**\n * Install the fence: the function if missing (in `initial`), and the trigger\n * on every table in the schema that lacks it. Idempotent, and it NEVER changes\n * an existing state — only the switch may. The tables are ASKED of the\n * database, so a table an upgrade adds gets fenced too: call it after every\n * migration.\n */\nexport async function installFence(\n db: Pg,\n initial: FenceState,\n o?: FenceOptions,\n): Promise<{ created: boolean; triggered: string[] }> {\n const { name } = opts(o);\n const created = (await fenceState(db, o)) === 'missing';\n if (created) await setFence(db, initial, o);\n const missing = await unfencedTables(db, o);\n for (const table of missing) {\n await db.execute(`create trigger ${q(name)} before insert or update or delete on ${q(table)} for each statement execute function ${q(name)}()`);\n }\n return { created, triggered: missing };\n}\n\n/** Tables without the trigger — an empty list means the whole schema is covered. */\nexport async function unfencedTables(db: Pg, o?: FenceOptions): Promise<string[]> {\n const { name } = opts(o);\n const { rows } = await db.execute({\n sql: `select c.relname as name from pg_class c\n where c.relnamespace = current_schema()::regnamespace and c.relkind = 'r'\n and not exists (select 1 from pg_trigger t where t.tgrelid = c.oid and t.tgname = $1)\n order by 1`,\n args: [name],\n });\n return rows.map((r) => String(r.name));\n}\n","/**\n * THE WAY BACK WITHOUT LOSS (components-F085.5, ported from broberg-id\n * F084.154) — what was written in the reserve after the switch is brought over\n * to the primary BEFORE switching back.\n *\n * ── THE WALL ─────────────────────────────────────────────────────────────\n *\n * The obvious tool — a reverse subscription, the primary subscribing to the\n * reserve — is not always possible (Supabase cannot subscribe outward). A\n * publication on the reserve plus a WAL player of our own would be a new,\n * heavy component running from the switch onwards. The databases this is for\n * are small (BID 7/10: ~3,000 rows, 28 tables), so COMPARING the rows takes\n * milliseconds and needs nothing running in between.\n *\n * ── THREE STATES PER ROW ─────────────────────────────────────────────────\n *\n * B the baseline at the switch to the reserve — taken while every machine\n * held, just after the subscription was disabled (`captureBaseline`)\n * R the reserve now\n * P the primary now\n *\n * R = P nothing to do\n * P = B only the reserve changed the row → copy (a DELETE too —\n * otherwise a logged-out session wakes up again)\n * otherwise the primary has a change the reserve never saw: CONFLICT.\n * Reported, never overwritten in silence.\n *\n * After a planned switch there can be no conflicts: the primary is fenced and\n * stood still from the baseline. After an EMERGENCY switch the primary may hold\n * the last seconds of writes that never reached the reserve — those are what\n * the conflicts catch.\n *\n * What was copied is written into the baseline, so a run that is interrupted\n * and re-run sees its own copies as \"P = B\", not as conflicts.\n *\n * A row is compared as `md5(to_jsonb(row))` in UTC: jsonb keys are sorted, so\n * column order in the two databases does not matter.\n *\n * Only the CURRENT schema (search_path) is compared; the baseline lives in a\n * schema of its own, so it is never part of the comparison.\n */\nimport type { Sql } from 'postgres';\nimport type { DbClient, Statement } from '../types';\nimport { FENCE_DEFAULTS } from './fence';\n\ntype Pg = Pick<DbClient<Sql>, 'execute' | 'batch'>;\n\nexport interface ReconcileOptions {\n /** Schema that holds the baseline. Default `dbSwitch`. BID: `bidSwitch`. */\n schema?: string;\n /** The fence's bypass setting (see FenceOptions.bypass). Default `db_sdk.fence_bypass`. */\n bypass?: string;\n}\n\nexport const RECONCILE_DEFAULTS = { schema: 'dbSwitch', bypass: FENCE_DEFAULTS.bypass } as const;\n\n/** Table and key in ONE text — separated by a unit separator, not NUL, which Postgres text cannot hold. */\nconst SEP = '\\u001f';\nconst q = (name: string) => `\"${name.replace(/\"/g, '\"\"')}\"`;\nconst lit = (s: string) => `'${s.replace(/'/g, \"''\")}'`;\nconst UTC = `set local time zone 'UTC'`;\nconst baselineTable = (o?: ReconcileOptions) => `${q({ ...RECONCILE_DEFAULTS, ...o }.schema)}.\"baseline\"`;\n\ninterface Table {\n name: string;\n pk: string[];\n cols: string[];\n}\n\nasync function tables(db: Pg): Promise<Table[]> {\n const { rows } = await db.execute(\n `select c.relname as name,\n (select array_agg(a.attname::text order by array_position(i.indkey::int2[], a.attnum))\n from pg_index i join pg_attribute a on a.attrelid = i.indrelid and a.attnum = any(i.indkey)\n where i.indrelid = c.oid and i.indisprimary) as pk,\n (select array_agg(a.attname::text order by a.attnum) from pg_attribute a\n where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped) as cols\n from pg_class c\n where c.relnamespace = current_schema()::regnamespace and c.relkind = 'r'\n order by 1`,\n );\n return rows.map((r) => ({ name: String(r.name), pk: (r.pk as string[] | null) ?? [], cols: r.cols as string[] }));\n}\n\n/**\n * Every row as key → fingerprint, in one call. The key is table + primary key;\n * a table WITHOUT a primary key is a multiset, so its key is the fingerprint\n * itself + a running number.\n */\nasync function fingerprints(db: Pg, tabs: Table[]): Promise<Map<string, string>> {\n const out = new Map<string, string>();\n if (tabs.length === 0) return out;\n const parts = tabs.map((t) => {\n const key = t.pk.length ? `jsonb_build_array(${t.pk.map((c) => `x.${q(c)}`).join(', ')})::text` : `md5(to_jsonb(x)::text)`;\n return `select ${lit(t.name)} as t, ${key} as k, md5(to_jsonb(x)::text) as h from ${q(t.name)} x`;\n });\n const [, res] = await db.batch([UTC, parts.join(' union all ') + ' order by 1, 2']);\n const seen = new Map<string, number>();\n const noPk = new Set(tabs.filter((t) => !t.pk.length).map((t) => t.name));\n for (const r of res!.rows) {\n const t = String(r.t);\n let k = String(r.k);\n if (noPk.has(t)) {\n const n = (seen.get(`${t}${SEP}${k}`) ?? 0) + 1;\n seen.set(`${t}${SEP}${k}`, n);\n k = `${k}#${n}`;\n }\n out.set(`${t}${SEP}${k}`, String(r.h));\n }\n return out;\n}\n\n/** Take the baseline B on the reserve. Call it while every machine holds. Returns the row count. */\nexport async function captureBaseline(reserve: Pg, o?: ReconcileOptions): Promise<number> {\n const { schema } = { ...RECONCILE_DEFAULTS, ...o };\n const rows = await fingerprints(reserve, await tables(reserve));\n const keys = [...rows.keys()];\n const table = baselineTable(o);\n await reserve.batch([\n `create schema if not exists ${q(schema)}`,\n `drop table if exists ${table}`,\n `create table ${table} (\"key\" text primary key, \"h\" text not null, \"at\" bigint not null)`,\n {\n sql: `insert into ${table} (\"key\", \"h\", \"at\") select k, h, $3 from unnest($1::text[], $2::text[]) as u(k, h)`,\n args: [keys, keys.map((k) => rows.get(k)!), Date.now()],\n },\n ]);\n return rows.size;\n}\n\n/** Is there a baseline — and when was it taken (epoch ms)? */\nexport async function baselineAt(reserve: Pg, o?: ReconcileOptions): Promise<number | null> {\n const table = baselineTable(o);\n // Two statements, not one CASE: Postgres resolves every relation a statement\n // names before it runs, so a CASE that never reads a missing table still\n // fails on it (42P01). broberg-id's one-statement version throws for the\n // same reason when no baseline was ever taken.\n const exists = await reserve.execute({ sql: `select to_regclass($1) is not null as e`, args: [table] });\n if (exists.rows[0]?.e !== true) return null;\n const { rows } = await reserve.execute(`select max(\"at\")::text as at from ${table}`);\n const at = rows[0]?.at;\n return at ? Number(at) : null;\n}\n\nasync function readBaseline(reserve: Pg, o?: ReconcileOptions): Promise<Map<string, string>> {\n const { rows } = await reserve.execute(`select \"key\", \"h\" from ${baselineTable(o)}`);\n return new Map(rows.map((r) => [String(r.key), String(r.h)]));\n}\n\nexport interface Conflict {\n table: string;\n key: string;\n /** What the reserve holds now (null = deleted). */\n reserve: string | null;\n /** What the primary holds now (null = does not exist). */\n primary: string | null;\n /** The baseline at the switch (null = did not exist). */\n baseline: string | null;\n}\n\nexport interface Plan {\n upserts: number;\n deletes: number;\n conflicts: Conflict[];\n /** Tables whose columns differ between the two databases — then nothing can be compared. */\n schemaMismatch: string[];\n /** Rows actually written in the primary (0 when only planned). */\n written: number;\n}\n\n/**\n * Compare, and copy if `apply` and there are neither conflicts nor schema\n * differences — OR `skipConflicts`, in which case the rest is copied and the\n * conflicting rows stay as the primary has them.\n *\n * Everything is written in the primary in ONE transaction through the fence's\n * door (the bypass setting): the primary is fenced while the app runs on the\n * reserve.\n */\nexport async function reconcile(\n reserve: Pg,\n primary: Pg,\n opts: { apply: boolean; skipConflicts?: boolean } & ReconcileOptions,\n): Promise<Plan> {\n const { bypass } = { ...RECONCILE_DEFAULTS, ...opts };\n const [rt, pt] = await Promise.all([tables(reserve), tables(primary)]);\n const pByName = new Map(pt.map((t) => [t.name, t]));\n const sameCols = (a: Table, b: Table) => a.cols.slice().sort().join() === b.cols.slice().sort().join();\n const schemaMismatch = [\n ...rt.filter((t) => !pByName.has(t.name) || !sameCols(pByName.get(t.name)!, t)).map((t) => t.name),\n ...pt.filter((t) => !rt.some((r) => r.name === t.name)).map((t) => t.name),\n ];\n if (schemaMismatch.length) return { upserts: 0, deletes: 0, conflicts: [], schemaMismatch, written: 0 };\n\n const [R, P, B] = await Promise.all([fingerprints(reserve, rt), fingerprints(primary, pt), readBaseline(reserve, opts)]);\n const conflicts: Conflict[] = [];\n const copies: { table: string; key: string; h: string | null; p: string | null }[] = [];\n for (const k of new Set([...R.keys(), ...P.keys()])) {\n const r = R.get(k) ?? null;\n const p = P.get(k) ?? null;\n if (r === p) continue;\n const b = B.get(k) ?? null;\n const [table, key] = k.split(SEP) as [string, string];\n if (p === b) copies.push({ table, key, h: r, p });\n else conflicts.push({ table, key, reserve: r, primary: p, baseline: b });\n }\n const plan: Plan = {\n upserts: copies.filter((x) => x.h !== null).length,\n deletes: copies.filter((x) => x.h === null).length,\n conflicts,\n schemaMismatch,\n written: 0,\n };\n if (!opts.apply || copies.length === 0 || (conflicts.length && !opts.skipConflicts)) return plan;\n\n // Order: parents before children on insert, children before parents on\n // delete — the foreign keys are ASKED of the database.\n const order = await fkOrder(primary, rt.map((t) => t.name));\n const byName = new Map(rt.map((t) => [t.name, t]));\n\n // The rows to copy, read from the reserve by fingerprint — in UTC like the\n // fingerprint, or a timestamp column gives a different one. Read as jsonb\n // TEXT and written back as that same text: no round trip through a JS\n // object, whose number and date handling is not Postgres'. The parameter is\n // `$1::text::jsonb`: typed as jsonb directly, postgres.js JSON.stringify's\n // the text once more and Postgres gets a JSON string, not a row (measured).\n const rowsByH = new Map<string, string>();\n const upserts = group(copies.filter((x) => x.h !== null));\n const reads: Statement[] = [UTC];\n const readTables: string[] = [];\n for (const [table, grp] of upserts) {\n reads.push({\n sql: `select md5(to_jsonb(x)::text) as h, to_jsonb(x)::text as j from ${q(table)} x where md5(to_jsonb(x)::text) = any($1::text[])`,\n args: [grp.map((x) => x.h)],\n });\n readTables.push(table);\n }\n if (readTables.length) {\n const res = await reserve.batch(reads);\n readTables.forEach((table, i) => {\n for (const r of res[i + 1]!.rows) rowsByH.set(`${table}${SEP}${String(r.h)}`, String(r.j));\n });\n }\n\n // One transaction on the primary. Each write remembers which key it is, so\n // only what was actually written goes into the baseline.\n const writes: Statement[] = [UTC, { sql: `select set_config($1, 'on', true)`, args: [bypass] }];\n const meaning: ({ key: string; h: string | null; counted: 'rowcount' | 'always' } | null)[] = [null, null];\n // Delete by the primary's OWN row (p = b): one copy at a time, so a table\n // without a primary key loses exactly the row the reserve lost.\n const deletes = group(copies.filter((x) => x.h === null));\n for (const table of [...order].reverse()) {\n for (const x of deletes.get(table) ?? []) {\n writes.push({\n sql: `delete from ${q(table)} where ctid = (select ctid from ${q(table)} x where md5(to_jsonb(x)::text) = $1 limit 1)`,\n args: [x.p],\n });\n meaning.push({ key: `${table}${SEP}${x.key}`, h: null, counted: 'rowcount' });\n }\n }\n for (const table of order) {\n const t = byName.get(table)!;\n const set = t.cols.filter((col) => !t.pk.includes(col));\n const onConflict = t.pk.length\n ? `on conflict (${t.pk.map(q).join(', ')}) do ${set.length ? `update set ${set.map((col) => `${q(col)} = excluded.${q(col)}`).join(', ')}` : 'nothing'}`\n : '';\n for (const x of upserts.get(table) ?? []) {\n // Changed in the reserve since its fingerprint (only possible without a\n // hold): skipped here and taken on the next pass — under the hold.\n const j = rowsByH.get(`${table}${SEP}${x.h}`);\n if (j === undefined) continue;\n writes.push({\n sql: `insert into ${q(table)} select * from jsonb_populate_record(null::${q(table)}, $1::text::jsonb) ${onConflict}`,\n args: [j],\n });\n meaning.push({ key: `${table}${SEP}${x.key}`, h: x.h, counted: 'always' });\n }\n }\n const results = await primary.batch(writes);\n const written: { key: string; h: string | null }[] = [];\n meaning.forEach((m, i) => {\n if (m && (m.counted === 'always' || results[i]!.rowsAffected === 1)) written.push({ key: m.key, h: m.h });\n });\n\n // What was copied is now the primary's state: write it into the baseline,\n // so a new run does not see our own copies as conflicts.\n const table = baselineTable(opts);\n const ins = written.filter((x) => x.h !== null);\n await reserve.batch([\n {\n sql: `insert into ${table} (\"key\", \"h\", \"at\") select k, h, $3 from unnest($1::text[], $2::text[]) as u(k, h)\n on conflict (\"key\") do update set \"h\" = excluded.\"h\"`,\n args: [ins.map((x) => x.key), ins.map((x) => x.h), Date.now()],\n },\n { sql: `delete from ${table} where \"key\" = any($1::text[])`, args: [written.filter((x) => x.h === null).map((x) => x.key)] },\n ]);\n return { ...plan, written: written.length };\n}\n\nfunction group<T extends { table: string }>(xs: T[]): Map<string, T[]> {\n const m = new Map<string, T[]>();\n for (const x of xs) m.set(x.table, [...(m.get(x.table) ?? []), x]);\n return m;\n}\n\n/** The tables ordered so a parent stands before its children. */\nasync function fkOrder(db: Pg, names: string[]): Promise<string[]> {\n const { rows } = await db.execute(\n `select c.relname as child, p.relname as parent from pg_constraint k\n join pg_class c on c.oid = k.conrelid join pg_class p on p.oid = k.confrelid\n where k.contype = 'f' and k.connamespace = current_schema()::regnamespace and c.oid <> p.oid`,\n );\n const out: string[] = [];\n const done = new Set<string>();\n const visit = (n: string, path: Set<string>) => {\n if (done.has(n) || path.has(n)) return;\n path.add(n);\n for (const r of rows) if (r.child === n) visit(String(r.parent), path);\n done.add(n);\n out.push(n);\n };\n for (const n of names) visit(n, new Set());\n return out.filter((n) => names.includes(n));\n}\n","/**\n * THE PER-MACHINE CONTROL (components-F085.5, ported from broberg-id\n * db-switch-control.ts, F084.149) — the HTTP door an orchestrator uses to move\n * ONE process's SwitchableClient.\n *\n * The orchestrator calls every machine in turn: prepare → hold → point — and\n * only when ALL have pointed: release. If one fails, abort is called on all,\n * and the waiters go onto the side from before the hold. No query reaches the\n * new database before every machine is ready.\n *\n * SAFETY NET: a machine that holds ABORTS BY ITSELF after `holdMs × 2` if the\n * orchestrator disappears — back to the side from before the hold, also if it\n * had already pointed. A login must never hang because a script died, and a\n * machine must never end up alone on the new database.\n *\n * What stays in the app (it is the app's own environment): which URLs, which\n * TLS, where the handler listens. BID serves it on Fly's private network only\n * (fly-local-6pn:8081); serve it where only your own machines can reach it.\n * The Bearer is an HMAC of a secret the machines already share.\n *\n * POST /db/prepare { target } open the target (once) and run `select 1`\n * POST /db/hold { ms } hold (100–10 000 ms); arms the safety net\n * POST /db/point { target } point while holding; 409 unless prepared + holding\n * POST /db/release release onto the side pointed at\n * POST /db/abort back to the side from before the hold, release\n * GET /db/status { label, holding, inFlight }\n */\nimport { createHmac, timingSafeEqual } from 'node:crypto';\nimport type { DbClient } from '../types';\nimport type { SwitchableClient } from './switchable';\n\n/** A Postgres client from either driver (postgres.js or pg, components-F085.6). */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- driver-agnostic: only execute/batch and the switchable API are used\ntype AnyPg = DbClient<any>;\n\nexport type Target = 'primary' | 'reserve';\n\nexport interface TargetSpec {\n /** The name the side answers to (BID: \"supabase\" / \"upcloud\"). Known without opening. */\n label: string;\n /** Open a client for it. Called once, on the first prepare. */\n open: () => AnyPg;\n}\n\nexport interface SwitchControlOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- either driver\n switchable: SwitchableClient<any>;\n targets: Record<Target, TargetSpec>;\n /** The machines' shared secret; the Bearer is HMAC-SHA256(secret, context). */\n secret: string;\n /** HMAC context. Default \"db-switch\". BID: \"bid-db-switch\". */\n context?: string;\n /** Logged on a switch and on the safety net. Default console. */\n log?: { info(msg: string): void; error(msg: string): void };\n}\n\nexport const HOLD_MIN_MS = 100;\nexport const HOLD_MAX_MS = 10_000;\nconst HOLD_DEFAULT_MS = 3_000;\n\n/** The Bearer an orchestrator sends — derived, so it never travels or is stored on its own. */\nexport function switchToken(secret: string, context = 'db-switch'): string {\n return createHmac('sha256', secret).update(context).digest('hex');\n}\n\nexport function createSwitchControl(o: SwitchControlOptions): (req: Request) => Promise<Response> {\n const { switchable } = o;\n const log = o.log ?? { info: (m: string) => console.log(m), error: (m: string) => console.error(m) };\n const token = Buffer.from(switchToken(o.secret, o.context));\n // The side the machine started on, under its own name — the way back.\n const sides = new Map<string, AnyPg>([[switchable.label, switchable.current]]);\n let safetyNet: ReturnType<typeof setTimeout> | null = null;\n // The side from before the hold — the way back if the switch is aborted.\n let beforeHold: { client: AnyPg; label: string } | null = null;\n\n const authorized = (req: Request) => {\n const h = req.headers.get('authorization') ?? '';\n const b = Buffer.from(h.startsWith('Bearer ') ? h.slice(7) : '');\n return b.length === token.length && timingSafeEqual(b, token);\n };\n const json = (data: unknown, status = 200) => Response.json(data, { status });\n const disarm = () => {\n if (safetyNet) clearTimeout(safetyNet);\n safetyNet = null;\n };\n /** Back to the side from before the hold, and release. */\n const abort = () => {\n disarm();\n if (beforeHold) switchable.point(beforeHold.client, beforeHold.label);\n beforeHold = null;\n switchable.release();\n };\n const isTarget = (t: unknown): t is Target => t === 'primary' || t === 'reserve';\n\n return async (req) => {\n if (!authorized(req)) return json({ error: 'unauthorized' }, 401);\n const path = new URL(req.url).pathname;\n const body = req.method === 'POST' ? ((await req.json().catch(() => ({}))) as { target?: unknown; ms?: unknown }) : {};\n try {\n if (path === '/db/status') return json({ label: switchable.label, holding: switchable.holding, inFlight: switchable.inFlight });\n\n if (path === '/db/prepare') {\n if (!isTarget(body.target)) return json({ error: 'target' }, 400);\n const spec = o.targets[body.target];\n const client = sides.get(spec.label) ?? spec.open();\n await client.execute('select 1');\n sides.set(spec.label, client);\n return json({ ok: true, label: spec.label });\n }\n\n if (path === '/db/hold') {\n const ms = Math.min(Math.max(Number(body.ms) || HOLD_DEFAULT_MS, HOLD_MIN_MS), HOLD_MAX_MS);\n if (!switchable.holding) beforeHold = { client: switchable.current, label: switchable.label };\n const r = await switchable.hold(ms);\n disarm();\n safetyNet = setTimeout(() => {\n abort();\n log.error(`[db-switch] safety net: the orchestrator did not answer — continuing on ${switchable.label}`);\n }, ms * 2);\n return json({ ...r, label: switchable.label });\n }\n\n // Point WITHOUT releasing. Only during a hold — otherwise queries would\n // reach the new side before the other machines are ready.\n if (path === '/db/point') {\n if (!isTarget(body.target)) return json({ error: 'target' }, 400);\n if (!switchable.holding) return json({ error: 'not_holding' }, 409);\n const label = o.targets[body.target].label;\n const client = sides.get(label);\n if (!client) return json({ error: 'not_prepared', label }, 409);\n switchable.point(client, label);\n return json({ ok: true, label });\n }\n\n if (path === '/db/release') {\n disarm();\n const moved = beforeHold !== null && beforeHold.label !== switchable.label;\n beforeHold = null;\n switchable.release();\n if (moved) log.info(`[db-switch] now on ${switchable.label}`);\n return json({ ok: true, label: switchable.label });\n }\n\n if (path === '/db/abort') {\n abort();\n return json({ ok: true, label: switchable.label });\n }\n return json({ error: 'not_found' }, 404);\n } catch (err) {\n return json({ error: err instanceof Error ? err.message : String(err) }, 500);\n }\n };\n}\n\n/**\n * THE EMERGENCY SWITCH'S GUARD (BID F084.152) — may a switch without the primary\n * run? The emergency switch skips the marker, so whatever had not replicated is\n * lost. It may ONLY run when the primary really does not answer — otherwise the\n * planned switch (lossless) is the right one — and whoever presses must have\n * said the loss is accepted. `fault: \"primary-down\"` is a test's way past the\n * first condition, against a primary that is alive.\n */\nexport type EmergencyDecision = 'proceed' | 'need-accept' | 'refuse-primary-alive';\nexport function emergencyGate(o: { primaryResponds: boolean; acceptDataLoss: boolean; fault?: string }): EmergencyDecision {\n if (!o.acceptDataLoss) return 'need-accept';\n if (o.primaryResponds && o.fault !== 'primary-down') return 'refuse-primary-alive';\n return 'proceed';\n}\n","/**\n * THE ORCHESTRATION (components-F085.5, ported from broberg-id\n * db-switch-cli.ts, F084.149/.152/.153/.154) — moves EVERY machine of an app\n * from one database to the other, so no minute exists where two machines\n * write to two places.\n *\n * to the reserve, in this order:\n * 0. the fence is in place on both sides (target locked, current open), the\n * marker table exists in both and the stream carries a probe row\n * 1. prepare: every machine opens the target and tries it\n * 2. hold: every machine lets new queries wait and drains the running ones —\n * a machine not drained in time ABORTS the switch\n * 3. marker: one row written in the primary; the switch waits until it is in\n * the reserve — then EVERYTHING written before the hold is there\n * 4. the subscription is disabled, then the baseline for the way back is taken\n * 5. the target is unfenced (everyone holds, nothing writes), every machine\n * points at it — and still holds\n * 6. release: only when ALL have pointed; then the old side is fenced\n * A failure in 1–5: abort on all — back to the old side, the target re-fenced,\n * the subscription re-enabled. No query has reached the new side.\n *\n * to the primary: the reserve's writes are copied home first (reconcile) —\n * once without a hold, the rest under it — unless `discardReserveWrites`.\n * Conflicts stop the switch unless `skipConflicts`.\n *\n * What stays in the app: finding the machines (BID: Fly's vms.<app>.internal),\n * the URLs/TLS, and setting the secrets afterwards so a restart lands on the\n * same side (BID: stage-env). Machines are given as `call` functions —\n * `httpMachine()` is the plain HTTP one.\n */\nimport { randomBytes } from 'node:crypto';\nimport type { Sql } from 'postgres';\nimport type { DbClient } from '../types';\nimport { emergencyGate, type Target } from './control';\nimport { FENCE_DEFAULTS, fenceState, setFence, unfencedTables, type FenceOptions, type FenceState } from './fence';\nimport { baselineAt, captureBaseline, reconcile, type Plan, type ReconcileOptions } from './reconcile';\n\nexport type MachineAnswer = { status: number; ok?: boolean; label?: string; error?: string; [k: string]: unknown };\nexport interface Machine {\n id: string;\n call(path: string, body?: unknown, timeoutMs?: number): Promise<MachineAnswer>;\n}\n\n/** A machine reached over HTTP at `baseUrl` (e.g. \"http://<id>.vm.<app>.internal:8081\"). */\nexport function httpMachine(id: string, baseUrl: string, token: string): Machine {\n return {\n id,\n async call(path, body, timeoutMs = 15_000) {\n const res = await fetch(`${baseUrl}${path}`, {\n method: body === undefined ? 'GET' : 'POST',\n headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: AbortSignal.timeout(timeoutMs),\n });\n const text = await res.text();\n let json: Record<string, unknown> = {};\n try {\n json = text ? (JSON.parse(text) as Record<string, unknown>) : {};\n } catch {\n json = { error: `not JSON: ${text.slice(0, 120)}` };\n }\n return { status: res.status, ...json };\n },\n };\n}\n\nexport interface OrchestrateOptions {\n to: Target;\n machines: Machine[];\n /** DIRECT clients to both sides (not through a pooler) — only the orchestration uses them. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- either driver (postgres.js or pg)\n primary: DbClient<any>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- either driver\n reserve: DbClient<any>;\n /** The labels the machines report for each side (same as the control's targets). */\n labels: Record<Target, string>;\n /** The reserve's subscription to the primary (to the reserve only). */\n subscription: string;\n /** Hold ceiling per machine, 100–10 000. Default 3000. */\n holdMs?: number;\n /** To the primary: copy home but keep the primary's version of conflicting rows. */\n skipConflicts?: boolean;\n /** To the primary: drop what was written in the reserve (the emergency exit). */\n discardReserveWrites?: boolean;\n /** Emergency switch to the reserve: the primary is down. No probe, no marker —\n * so what had not replicated is LOST. Needs `acceptDataLoss`, and is refused\n * while the primary answers (emergencyGate). */\n primaryDown?: boolean;\n acceptDataLoss?: boolean;\n /** Fault injection for tests in production (BID AC1). \"primary-down\" treats a\n * live primary as dead, to test the emergency path. */\n fault?: 'replication' | 'point' | 'primary-down';\n /** Marker table (id text pk, at bigint). Default \"dbSwitchMarker\" (BID's). */\n markerTable?: string;\n fence?: FenceOptions;\n reconcile?: ReconcileOptions;\n log?: (line: string) => void;\n}\n\nexport type Outcome =\n | { outcome: 'done'; label: string; heldMs: number }\n | { outcome: 'refused'; reason: string } // nothing was held; nothing changed\n | { outcome: 'aborted'; reason: string; restored: string[] } // held, then rolled back\n | { outcome: 'unconfirmed'; reason: string; label: string }; // released, but a machine did not confirm — run status NOW\n\nconst q = (name: string) => `\"${name.replace(/\"/g, '\"\"')}\"`;\n\nasync function within<T>(p: Promise<T>, ms: number, what: string): Promise<T> {\n let t: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([p, new Promise<never>((_, j) => (t = setTimeout(() => j(new Error(`${what}: no answer in ${ms} ms`)), ms)))]);\n } finally {\n clearTimeout(t);\n }\n}\n\nasync function all(machines: Machine[], f: (m: Machine) => Promise<MachineAnswer>): Promise<(MachineAnswer & { id: string })[]> {\n return Promise.all(\n machines.map(async (m) => {\n try {\n return { id: m.id, ...(await f(m)) };\n } catch (e) {\n return { id: m.id, status: 0, error: e instanceof Error ? e.message : String(e) };\n }\n }),\n );\n}\n\n/** The plan in plain words — and whether it stops the switch. */\nfunction planStopper(p: Plan, skip: boolean, log: (s: string) => void): string | null {\n log(`copy home: ${p.upserts} new/changed, ${p.deletes} deleted, ${p.conflicts.length} conflicts, ${p.written} written`);\n if (p.schemaMismatch.length) return `the schema differs between the two databases (${p.schemaMismatch.join(', ')}) — migrate first`;\n if (p.conflicts.length) {\n for (const k of p.conflicts.slice(0, 50)) log(` CONFLICT ${k.table} ${k.key}`);\n if (!skip) return `${p.conflicts.length} conflict(s) — the primary has changes the reserve never saw; skipConflicts copies the rest and keeps the primary's version`;\n }\n return null;\n}\n\nexport async function orchestrateSwitch(o: OrchestrateOptions): Promise<Outcome> {\n const t0 = performance.now();\n const log = (s: string) => (o.log ?? console.log)(`[switch +${Math.round(performance.now() - t0)}ms] ${s}`);\n const holdMs = Math.min(Math.max(o.holdMs ?? 3000, 100), 10_000);\n const toReserve = o.to === 'reserve';\n const emergency = Boolean(o.primaryDown);\n const copyHome = !toReserve && !o.discardReserveWrites;\n const marker = q(o.markerTable ?? 'dbSwitchMarker');\n const target = toReserve ? o.reserve : o.primary;\n const old = toReserve ? o.primary : o.reserve;\n const [targetLabel, oldLabel] = toReserve ? [o.labels.reserve, o.labels.primary] : [o.labels.primary, o.labels.reserve];\n if (emergency && !toReserve) return { outcome: 'refused', reason: 'primaryDown only makes sense to the reserve' };\n if (o.fault === 'replication' && (!toReserve || emergency)) return { outcome: 'refused', reason: 'fault replication needs a planned switch to the reserve' };\n if (o.fault !== undefined && !['replication', 'point', 'primary-down'].includes(o.fault)) return { outcome: 'refused', reason: `unknown fault «${String(o.fault)}»` };\n if (o.fault === 'primary-down' && !emergency) return { outcome: 'refused', reason: 'fault primary-down needs primaryDown' };\n if (emergency) {\n const responds = await within(o.primary.execute('select 1'), 5000, 'primary').then(() => true, () => false);\n const decision = emergencyGate({ primaryResponds: responds, acceptDataLoss: Boolean(o.acceptDataLoss), fault: o.fault });\n // What is lost: everything written on the primary after the reserve's last message.\n const lag = await within(\n o.reserve.execute({ sql: `select extract(epoch from now() - last_msg_receipt_time)::int as s from pg_stat_subscription where subname = $1 and relid is null`, args: [o.subscription] }),\n 5000,\n 'reserve',\n ).then((r) => (r.rows[0]?.s ?? null) as number | null, () => null);\n log(`EMERGENCY: the primary ${responds ? 'ANSWERS' : 'does not answer'}; the reserve last heard from it ${lag ?? '?'} s ago — what the primary wrote after that is LOST → ${decision}`);\n if (decision === 'need-accept') return { outcome: 'refused', reason: 'an emergency switch loses what had not replicated — pass acceptDataLoss if that is meant' };\n if (decision === 'refuse-primary-alive') return { outcome: 'refused', reason: 'the primary ANSWERS — use the planned switch (lossless)' };\n }\n\n let targetOpened = false;\n let subscriptionOff = false;\n const restored: string[] = [];\n const abort = async (reason: string): Promise<Outcome> => {\n log(`ABORTING: ${reason} — releasing everyone on the old side`);\n log(`aborted: ${JSON.stringify(await all(o.machines, (m) => m.call('/db/abort', {})))}`);\n if (targetOpened) {\n try {\n await setFence(target, 'locked', o.fence);\n restored.push(`${targetLabel} fenced again`);\n } catch (e) {\n log(`WARNING: ${targetLabel} could NOT be fenced again: ${e} — fence it by hand`);\n }\n }\n if (subscriptionOff) {\n try {\n await o.reserve.execute(`alter subscription ${q(o.subscription)} enable`);\n restored.push('subscription enabled again');\n } catch (e) {\n log(`WARNING: the subscription could not be enabled again: ${e}`);\n }\n }\n return { outcome: 'aborted', reason, restored };\n };\n\n // Preconditions: the fence installed by the app's migration, not here — DDL\n // against a live database does not belong in the middle of a switch. The old\n // side cannot be asked in an emergency.\n for (const [side, label, want] of (emergency ? [[target, targetLabel, 'locked']] : [[target, targetLabel, 'locked'], [old, oldLabel, 'open']]) as [Pick<DbClient<Sql>, 'execute'>, string, FenceState][]) {\n const [state, missing] = await Promise.all([fenceState(side, o.fence), unfencedTables(side, o.fence)]);\n if (state !== want || missing.length) {\n return { outcome: 'refused', reason: `${label}: fence is «${state}» (expected «${want}»)${missing.length ? `, ${missing.length} table(s) without it: ${missing.join(', ')}` : ''} — nothing switched` };\n }\n }\n\n // 0. The marker table and a probe through the stream, before anything holds.\n if (toReserve && !emergency) {\n // The marker table normally comes from the app's migration (BID's does).\n // Created here only if missing — and then it, and ONLY it, gets the fence\n // trigger: the preconditions above already proved every other table fenced.\n const fn = q(o.fence?.name ?? FENCE_DEFAULTS.name);\n for (const side of [o.primary, o.reserve]) {\n const exists = (await side.execute({ sql: `select to_regclass($1) is not null as e`, args: [marker] })).rows[0]?.e === true; // quoted: unquoted, to_regclass folds it to lower case\n if (exists) continue;\n await side.execute(`create table ${marker} (\"id\" text primary key, \"at\" bigint not null)`);\n await side.execute(`create trigger ${fn} before insert or update or delete on ${marker} for each statement execute function ${fn}()`);\n }\n await o.reserve.execute(`alter subscription ${q(o.subscription)} refresh publication`);\n const probe = `probe-${randomBytes(6).toString('hex')}`;\n await o.primary.execute({ sql: `insert into ${marker} (\"id\", \"at\") values ($1, $2)`, args: [probe, Date.now()] });\n if (!(await arrived(o.reserve, marker, probe, 30_000, 100))) {\n // Refused, not aborted: the probe runs before prepare, so no machine holds anything.\n return { outcome: 'refused', reason: 'the probe did not reach the reserve in 30 s — is the replica alive?' };\n }\n log('probe: the stream carries the marker');\n if (o.fault === 'replication') {\n await o.reserve.execute(`alter subscription ${q(o.subscription)} disable`);\n subscriptionOff = true;\n log('TEST: subscription disabled before the hold');\n }\n }\n\n // The reserve's writes home: one pass WITHOUT a hold, so the hold only carries the last seconds.\n if (copyHome) {\n if ((await baselineAt(o.reserve, o.reconcile)) === null) {\n return { outcome: 'refused', reason: 'no baseline from the switch to the reserve — the only way back is discardReserveWrites' };\n }\n const stop = planStopper(await reconcile(o.reserve, o.primary, { apply: true, skipConflicts: o.skipConflicts, ...o.reconcile }), Boolean(o.skipConflicts), log);\n if (stop) return { outcome: 'refused', reason: stop };\n }\n\n // 1. Prepare.\n const prep = await all(o.machines, (m) => m.call('/db/prepare', { target: o.to }));\n log(`prepare: ${JSON.stringify(prep)}`);\n if (prep.some((r) => r.ok !== true)) return abort('a machine could not open the target');\n\n // 2. Hold — a machine not drained in time aborts (an emergency tolerates it:\n // queries against a dead database hang, and they fail on the old side anyway).\n const holdStart = performance.now();\n const hold = await all(o.machines, (m) => m.call('/db/hold', { ms: holdMs }, holdMs + 2000));\n log(`hold: ${JSON.stringify(hold)}`);\n if (hold.some((r) => r.ok !== true)) {\n if (emergency && hold.every((r) => r.status === 200 && r.label !== undefined)) log('hold not drained within the ceiling — continuing (emergency)');\n else return abort('a machine did not drain within the ceiling');\n }\n\n // 3. Marker (not in an emergency) + 4. subscription off + baseline.\n if (toReserve && !emergency) {\n const id = `switch-${randomBytes(6).toString('hex')}`;\n await o.primary.execute({ sql: `insert into ${marker} (\"id\", \"at\") values ($1, $2)`, args: [id, Date.now()] });\n if (!(await arrived(o.reserve, marker, id, holdMs, 20))) return abort('the marker did not reach the reserve within the hold');\n log('marker in the reserve: everything written before the hold is there');\n }\n if (toReserve) {\n if (!subscriptionOff) {\n await o.reserve.execute(`alter subscription ${q(o.subscription)} disable`);\n subscriptionOff = true;\n }\n log('subscription disabled');\n try {\n log(`baseline: ${await captureBaseline(o.reserve, o.reconcile)} rows`);\n } catch (e) {\n if (!emergency) return abort(`the baseline could not be taken: ${e}`);\n log(`WARNING: no baseline (${e}) — the way back will be discardReserveWrites`);\n }\n }\n if (copyHome) {\n try {\n const stop = planStopper(await reconcile(o.reserve, o.primary, { apply: true, skipConflicts: o.skipConflicts, ...o.reconcile }), Boolean(o.skipConflicts), log);\n if (stop) return abort(stop);\n } catch (e) {\n return abort(`copying home failed: ${e}`);\n }\n }\n\n // 4½. Unfence the target — everyone holds, nothing writes yet.\n try {\n await setFence(target, 'open', o.fence);\n targetOpened = true;\n } catch (e) {\n return abort(`${targetLabel} could not be unfenced: ${e}`);\n }\n\n // 5. Point — still holding.\n const point = await all(o.machines, (m) => m.call('/db/point', { target: o.fault === 'point' && m === o.machines[0] ? 'nowhere' : o.to }));\n log(`point: ${JSON.stringify(point)}`);\n if (point.some((r) => r.ok !== true)) return abort('a machine could not point');\n // The new side is what the machines REPORTED at point (all must agree) —\n // not the caller's labels, which could be wrong and turn every switch «unconfirmed».\n const pointed = [...new Set(point.map((r) => r.label))];\n if (pointed.length !== 1 || typeof pointed[0] !== 'string') return abort(`the machines pointed at different sides: ${JSON.stringify(pointed)}`);\n const newLabel = pointed[0];\n\n // 6. Release — retried for a machine that does not answer (its safety net\n // would otherwise send it back while the others are on the new side). A\n // release counts only if the machine answers from the NEW side.\n const ready = (r: MachineAnswer) => r.ok === true && r.label === newLabel;\n let release = await all(o.machines, (m) => m.call('/db/release', {}));\n for (let i = 0; i < 5 && release.some((r) => !ready(r)); i++) {\n await new Promise((r) => setTimeout(r, 200));\n const again = o.machines.filter((m) => !ready(release.find((r) => r.id === m.id)!));\n const answers = await all(again, (m) => m.call('/db/release', {}));\n release = release.map((r) => answers.find((x) => x.id === r.id) ?? r);\n }\n log(`release: ${JSON.stringify(release)}`);\n const heldMs = Math.round(performance.now() - holdStart);\n // Fence the old side — ALSO if a machine did not confirm: one left on the old\n // side is exactly the one that must fail loudly.\n try {\n await within(setFence(old, 'locked', o.fence), 5000, `fence ${oldLabel}`);\n log(`${oldLabel} fenced`);\n } catch (e) {\n log(`WARNING: ${oldLabel} is NOT fenced (${e}) — fence it when it answers`);\n }\n if (release.some((r) => !ready(r))) {\n return { outcome: 'unconfirmed', reason: 'a machine did not confirm release on the new side — its safety net sends it back; run status NOW', label: newLabel };\n }\n log(`DONE: every machine on ${newLabel}; queries held for ${heldMs} ms`);\n return { outcome: 'done', label: newLabel, heldMs };\n}\n\nasync function arrived(reserve: Pick<DbClient<Sql>, 'execute'>, marker: string, id: string, ms: number, every: number): Promise<boolean> {\n const end = Date.now() + ms;\n while (Date.now() < end) {\n if ((await reserve.execute({ sql: `select 1 from ${marker} where \"id\" = $1`, args: [id] })).rows.length === 1) return true;\n await new Promise((r) => setTimeout(r, every));\n }\n return false;\n}\n","/**\n * IS THE RESERVE ALIVE? — and who gets woken when it is not (components-F085.5,\n * ported from broberg-id reserve-health.ts F084.114 + reserve-watch.ts F084.204).\n *\n * A reserve can die without anyone seeing it: a dead reserve is nothing in the\n * app's logs, and a failed reserve migration is one log line. A reserve you\n * believe is alive is MORE dangerous than none, because you count on it the day\n * the primary falls. fd-sundhed 28/10 2026: two new columns in production\n * without the reserve, replication stood still for 5 hours, the slot was 128 MB\n * from being dropped.\n *\n * The reading comes from the PRIMARY (its replication slot and the walsender),\n * not from the reserve: if the reserve is down, that is exactly what the answer\n * must say. Serve it on its own route — BID: /health/reserve, NOT /health/ready:\n * a dead reserve must never take logins down.\n *\n * The alarm half is PURE: the app keeps the episode state where it wants (BID:\n * a table, because it runs on two machines) and sends the incidents its own way.\n */\nimport type { Sql } from 'postgres';\nimport type { DbClient } from '../types';\n\nexport interface ReserveThresholds {\n /** No reply from the reserve for this long = stale. BID: 300 (it replies every ~10 s). */\n staleSeconds: number;\n /** This far behind = not catching up. BID: 64 MB (Supabase drops the slot at 512 MB). */\n lagBytes: number;\n}\nexport const RESERVE_DEFAULTS: ReserveThresholds = { staleSeconds: 300, lagBytes: 64 * 1024 * 1024 };\n\nexport interface SlotReading {\n active: boolean;\n walStatus: string | null;\n lagBytes: number | null;\n /** Seconds since the reserve last replied; null = no live connection. */\n replyAgeSeconds: number | null;\n}\n\nexport type ReserveReason = 'missing' | 'inactive' | 'lost' | 'stale' | 'lagging' | 'unreadable';\nexport type ReserveVerdict = { ok: true } | { ok: false; reason: ReserveReason | (string & {}) };\n\nexport function judgeReserve(r: SlotReading | null, t: ReserveThresholds = RESERVE_DEFAULTS): ReserveVerdict {\n if (!r) return { ok: false, reason: 'missing' };\n if (r.walStatus === 'lost') return { ok: false, reason: 'lost' };\n if (!r.active) return { ok: false, reason: 'inactive' };\n if (r.replyAgeSeconds === null || r.replyAgeSeconds > t.staleSeconds) return { ok: false, reason: 'stale' };\n if (r.lagBytes !== null && r.lagBytes > t.lagBytes) return { ok: false, reason: 'lagging' };\n return { ok: true };\n}\n\n/** Read the reserve's slot ON THE PRIMARY. The slot name is the subscription's (BID: bid_reserve). */\nexport async function readReserveSlot(primary: Pick<DbClient<Sql>, 'execute'>, slot: string): Promise<SlotReading | null> {\n const { rows } = await primary.execute({\n sql: `select s.active, s.wal_status,\n pg_wal_lsn_diff(pg_current_wal_lsn(), s.confirmed_flush_lsn)::bigint as lag,\n extract(epoch from now() - r.reply_time)::int as reply_age\n from pg_replication_slots s\n left join pg_stat_replication r on r.application_name = s.slot_name\n where s.slot_name = $1`,\n args: [slot],\n });\n const row = rows[0];\n if (!row) return null;\n const num = (v: unknown) => (v === null || v === undefined ? null : Number(v));\n return { active: row.active === true, walStatus: (row.wal_status as string | null) ?? null, lagBytes: num(row.lag), replyAgeSeconds: num(row.reply_age) };\n}\n\n/** Read + judge in one call; a reading that fails — or does not answer within\n * `timeoutMs` (default 5 s; a hung primary must not hang the health route) —\n * is `unreadable`, never «ok». */\nexport async function reserveHealth(primary: Pick<DbClient<Sql>, 'execute'>, slot: string, t?: ReserveThresholds, timeoutMs = 5000): Promise<ReserveVerdict> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const reading = await Promise.race([\n readReserveSlot(primary, slot),\n new Promise<never>((_, j) => (timer = setTimeout(() => j(new Error('timeout')), timeoutMs))),\n ]);\n return judgeReserve(reading, t);\n } catch {\n return { ok: false, reason: 'unreadable' };\n } finally {\n clearTimeout(timer);\n }\n}\n\n// ── THE ALARM HOOK ──────────────────────────────────────────────────────────\n\n/** Unhealthy this long in a row → one incident per episode. A blink sends nothing. BID: 10 min. */\nexport const RESERVE_ALARM_AFTER_MS = 10 * 60 * 1000;\nexport const MIGRATION_FAILED = 'migration_failed';\n\n/** The app persists this between rounds (BID: rows in its reserveWatch table). */\nexport interface ReserveWatchState {\n slot?: { reason: string; firstSeenAt: number };\n migrationFailed?: { firstSeenAt: number; detail: string };\n}\n\nexport interface ReserveIncident {\n /** Carries the episode's start, so «sent once per id» gives one alarm per episode and a new one for a new episode. */\n id: string;\n reason: string;\n severity: 'critical' | 'high';\n openedAt: string;\n detail: string | null;\n}\n\n/** The reserve migration's outcome on a deploy → state. Failure alarms at once\n * (it does not fix itself). `skipped` (no reserve configured on this deploy)\n * leaves the state untouched — it must never clear a pending migration_failed. */\nexport function noteReserveMigration(\n state: ReserveWatchState,\n outcome: { ok: true } | { ok: false; reason: string } | { skipped: true },\n now = Date.now(),\n): ReserveWatchState {\n if ('skipped' in outcome) return state;\n if (outcome.ok) {\n const { migrationFailed: _, ...rest } = state;\n return rest;\n }\n return { ...state, migrationFailed: { firstSeenAt: now, detail: outcome.reason.slice(0, 500) } };\n}\n\n/** One alarm round: the next state from `verdict`, and the incidents to send. */\nexport function watchReserve(\n state: ReserveWatchState,\n verdict: ReserveVerdict,\n now = Date.now(),\n alarmAfterMs = RESERVE_ALARM_AFTER_MS,\n): { state: ReserveWatchState; incidents: ReserveIncident[] } {\n const next: ReserveWatchState = { ...state };\n const incidents: ReserveIncident[] = [];\n if (verdict.ok) delete next.slot;\n else {\n // The same reason continues the episode; a different reason starts a new one.\n if (next.slot?.reason !== verdict.reason) next.slot = { reason: verdict.reason, firstSeenAt: now };\n if (now - next.slot.firstSeenAt >= alarmAfterMs) incidents.push(incident(next.slot.reason, next.slot.firstSeenAt, null));\n }\n if (next.migrationFailed) incidents.push(incident(MIGRATION_FAILED, next.migrationFailed.firstSeenAt, next.migrationFailed.detail));\n return { state: next, incidents };\n}\n\nconst incident = (reason: string, first: number, detail: string | null): ReserveIncident => ({\n id: `reserve:${reason}:${first}`,\n reason,\n severity: reason === 'lost' || reason === MIGRATION_FAILED ? 'critical' : 'high',\n openedAt: new Date(first).toISOString(),\n detail,\n});\n","/**\n * THE RESERVE RECONNECTS ITSELF (components-F085.5, ported from broberg-id\n * reserve-ip-guard.ts, F084.172/.174/.197/.238).\n *\n * 18/10 2026 UpCloud's Sunday maintenance replaced the reserve node and it got\n * a new public address. Supabase only lets known addresses in, so the slot sat\n * inactive for ~6 hours until a human fixed the list. At ~512 MB behind,\n * Supabase drops the slot and the reserve must be copied from scratch.\n *\n * Run it from CI (BID: .github/workflows/reserve-ip-guard.yml — the workflow is\n * in the Discovery playbook), NOT in the app: the Supabase token is account-wide.\n *\n * 1. reserve healthy → stop. No call to Supabase.\n * 2. inactive/stale/lost → the reserve's public host from UpCloud's API; its\n * address from DNS (BID measured: = the address the reserve calls from).\n * 3. Missing from dbAllowedCidrs → ADD it. The guard never removes anything:\n * an address it believes is old may be another machine's. Addresses that\n * are neither fixed nor the reserve's are logged for clean-up.\n * 4. Wait for the slot to become active. If it does not → a red run.\n *\n * `runGuard` is pure (its world comes in as `GuardDeps`); `liveDeps` is the\n * UpCloud + Supabase implementation. Another pair of providers is another deps.\n */\nimport { lookup } from \"node:dns/promises\";\n\nexport type Restrictions = { dbAllowedCidrs: string[]; dbAllowedCidrsV6: string[] };\n\nexport interface GuardDeps {\n reserveHealth(): Promise<{ ok: boolean; reason?: string }>;\n upcloudPublicHost(): Promise<string>;\n resolve(host: string): Promise<string>;\n getRestrictions(): Promise<Restrictions & { status: string }>;\n applyRestrictions(r: Restrictions): Promise<void>;\n sleep(ms: number): Promise<void>;\n log(line: string): void;\n}\n\nexport interface GuardOptions {\n /** Known fixed v4 addresses (e.g. Fly egress, office) — only for the clean-up note. */\n fixedV4: string[];\n /** How long to wait for an active slot after a fix. */\n waitMs: number;\n pollMs: number;\n /** How long to read back before a list that did not take effect is an error (BID F084.174). */\n readBackMs: number;\n /** BID F084.197 — an unhealthy slot is measured again after this long before acting. A blink is not a state. */\n confirmMs: number;\n}\n\nexport type GuardResult =\n | { outcome: \"healthy\" }\n | { outcome: \"not-network\"; reason: string }\n | { outcome: \"already-allowed\"; ip: string }\n | { outcome: \"fixed\"; ip: string }\n | { outcome: \"still-down\"; ip: string; reason: string }\n /** BID F084.238 — the slot is lost. The address is fixed (or was fine); the reserve must be rebuilt. */\n | { outcome: \"needs-rebuild\"; ip: string; added: boolean };\n\n/** Reasons an unknown address can cause. `lagging` is not the network. */\nconst NETWORK_REASONS = new Set([\"inactive\", \"stale\"]);\n/**\n * BID F084.238 — a LOST slot can also come from a new address: 15/11 2026\n * UpCloud's maintenance gave the reserve a new address at ~05:20, the guard ran\n * at 11:38, and by then the slot was «lost». The network was still closed, so a\n * rebuild failed until the address was on the list. So the address is fixed\n * here too — but a lost slot does not come back by itself, so the outcome is\n * «needs-rebuild», not «fixed».\n */\nconst LOST = \"lost\";\n\nexport async function runGuard(d: GuardDeps, o: GuardOptions): Promise<GuardResult> {\n let health = await d.reserveHealth();\n // BID F084.197 — fd-sundhed measured a slot unhealthy for a moment and healthy\n // 40 s later. Without a second reading it became a red run and an alarm.\n if (!health.ok) {\n await d.sleep(o.confirmMs);\n health = await d.reserveHealth();\n }\n if (health.ok) return { outcome: \"healthy\" };\n const reason = health.reason ?? \"unknown\";\n if (!NETWORK_REASONS.has(reason) && reason !== LOST) return { outcome: \"not-network\", reason };\n\n const ip = await d.resolve(await d.upcloudPublicHost());\n const cidr = `${ip}/32`;\n const before = await d.getRestrictions();\n const unknown = before.dbAllowedCidrs.filter((c) => c !== cidr && !o.fixedV4.includes(c));\n if (unknown.length) d.log(`to clean up (neither fixed nor the reserve's current): ${unknown.join(\", \")}`);\n if (before.dbAllowedCidrs.includes(cidr)) {\n return reason === LOST ? { outcome: \"needs-rebuild\", ip, added: false } : { outcome: \"already-allowed\", ip };\n }\n\n const next: Restrictions = { dbAllowedCidrs: [...before.dbAllowedCidrs, cidr], dbAllowedCidrsV6: before.dbAllowedCidrsV6 };\n await d.applyRestrictions(next);\n // Supabase shows the new list only after a while (BID measured 19/10: old\n // after 5 s, new within 20 s) — so read back, and throw only when the window is spent.\n const expected = JSON.stringify(next);\n let read = \"\";\n for (let t = 0; ; t += o.pollMs) {\n const after = await d.getRestrictions();\n read = JSON.stringify({ dbAllowedCidrs: after.dbAllowedCidrs, dbAllowedCidrsV6: after.dbAllowedCidrsV6 });\n if (read === expected) break;\n if (t >= o.readBackMs) throw new Error(`the list did not become what was sent: expected ${expected}, read ${read}`);\n await d.sleep(o.pollMs);\n }\n d.log(`added ${cidr}`);\n if (reason === LOST) return { outcome: \"needs-rebuild\", ip, added: true };\n\n let last = reason;\n for (let t = 0; t < o.waitMs; t += o.pollMs) {\n await d.sleep(o.pollMs);\n const h = await d.reserveHealth();\n if (h.ok) return { outcome: \"fixed\", ip };\n last = h.reason ?? \"unknown\";\n }\n return { outcome: \"still-down\", ip, reason: last };\n}\n\n/** The real APIs (UpCloud Managed Postgres as the reserve, Supabase as the primary).\n * The keys come from the environment and are never logged. */\nexport function liveDeps(env: {\n healthUrl: string;\n upcloudToken: string;\n upcloudDbUuid: string;\n supabaseToken: string;\n supabaseRef: string;\n}): GuardDeps {\n const sb = `https://api.supabase.com/v1/projects/${env.supabaseRef}/network-restrictions`;\n const sbHeaders = { authorization: `Bearer ${env.supabaseToken}`, \"content-type\": \"application/json\" };\n const ok = async (res: Response, what: string) => {\n if (!res.ok) throw new Error(`${what}: HTTP ${res.status} ${(await res.text()).slice(0, 200)}`);\n return res;\n };\n return {\n async reserveHealth() {\n // BID F084.197 — a 502 or a page that is not JSON (e.g. mid-deploy) is an\n // answer, not a crash: «unreachable» is confirmed like anything else.\n try {\n const res = await fetch(env.healthUrl);\n const body = (await res.json()) as { ok?: boolean; reason?: string };\n return { ok: res.status === 200 && body.ok === true, reason: body.reason };\n } catch {\n return { ok: false, reason: \"unreachable\" };\n }\n },\n async upcloudPublicHost() {\n const res = await ok(\n await fetch(`https://api.upcloud.com/1.3/database/${env.upcloudDbUuid}`, {\n headers: { authorization: `Bearer ${env.upcloudToken}` },\n }),\n \"UpCloud\",\n );\n const db = (await res.json()) as { components?: { component: string; route: string; host: string }[] };\n const host = db.components?.find((c) => c.component === \"pg\" && c.route === \"public\")?.host;\n if (!host) throw new Error(\"UpCloud: no public pg host\");\n return host;\n },\n async resolve(host) {\n return (await lookup(host, { family: 4 })).address;\n },\n async getRestrictions() {\n const res = await ok(await fetch(sb, { headers: sbHeaders }), \"Supabase GET\");\n const b = (await res.json()) as { status: string; config: Restrictions };\n return { status: b.status, dbAllowedCidrs: b.config.dbAllowedCidrs ?? [], dbAllowedCidrsV6: b.config.dbAllowedCidrsV6 ?? [] };\n },\n async applyRestrictions(r) {\n await ok(await fetch(`${sb}/apply`, { method: \"POST\", headers: sbHeaders, body: JSON.stringify(r) }), \"Supabase apply\");\n },\n sleep: (ms) => new Promise((r) => setTimeout(r, ms)),\n log: (l) => console.log(l),\n };\n}\n"],"mappings":";AA2FA,IAAM,cAAc;AAEpB,IAAM,UAAU,CAAC,MAAoC;AACnD,QAAMA,KAAI;AACV,SACE,aAAa,WACb,OAAOA,GAAE,YAAY,cACrB,OAAOA,GAAE,cAAc,cACvB,OAAOA,GAAE,YAAY,cACrB,OAAOA,GAAE,WAAW,cACpB,OAAOA,GAAE,WAAW,cACpBA,GAAE,aAAa;AAEnB;AAIA,IAAM,QAAQ,oBAAI,QAAmB;AACrC,SAAS,OAAO,KAAgB;AAC9B,MAAI,OAAO,MAAM,IAAI,GAAG;AACxB,MAAI,CAAC,MAAM;AACT,UAAM,QAAiB,IAAI,OAAO,EAAE;AACpC,QAAI,CAAC,QAAQ,KAAK,EAAG,OAAM,IAAI,MAAM,WAAW;AAChD,WAAO,EAAE,SAAS,MAAM,SAAS,WAAW,MAAM,UAAU;AAC5D,UAAM,IAAI,KAAK,IAAI;AAAA,EACrB;AACA,SAAO;AACT;AAIA,IAAM,kBAAkB;AACxB,SAAS,OAAO,KAAoB;AAClC,MAAI,OAAO,QAAQ,YAAY;AAC7B,WAAO,GAAU;AACjB,WAAO;AAAA,EACT;AACA,QAAM,OAAO;AACb,MAAI,QAAQ,OAAO,KAAK,YAAY,cAAc,OAAO,KAAK,UAAU,cAAc,OAAO,KAAK,OAAO,WAAY,QAAO;AAC5H,QAAM,IAAI,MAAM,eAAe;AACjC;AAIO,SAAS,iBAAiB,SAA2C,OAAiE;AAC3I,MAAI,QAAQ,cAAc,WAAY,OAAM,IAAI,MAAM,2CAA2C;AACjG,QAAM,OAAO,OAAO,QAAQ,GAAG;AAE/B,MAAI,SAAwB;AAC5B,MAAI,OAA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,EAAE;AAAA,IAC9H;AAAA,IACA,MAAM,kBAAkB,GAAG;AACzB,YAAM,GAAG,MAAM,MAAM,GAAG,EAAE,UAAU,EAAE,QAAQ,QAAQ,SAAS,WAAW,MAAM,KAAK,UAAU,CAAC,EAAE,CAAC,GAAG,gBAAgB;AAAA,IACxH;AAAA,IACA,OAAO,CAAC,OAAO,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,EAAE,CAAC;AAAA,IACnD,KAAK,CAAC,MAAM,QAAQ,IAAI,CAAC;AAAA,EAC3B;AACF;","names":["q","label","q","lit","opts","table","sides","body","body","q","body"]}
|
|
1
|
+
{"version":3,"sources":["../../src/switchable/switchable.ts","../../src/switchable/fence.ts","../../src/switchable/reconcile.ts","../../src/switchable/control.ts","../../src/switchable/orchestrate.ts","../../src/switchable/reserve.ts","../../src/switchable/ip-guard.ts"],"sourcesContent":["/**\n * THE INSTANT SWITCH (components-F085.5, ported from broberg-id F084.149) — a\n * Postgres client that can move to another database while the process runs.\n *\n * The problem it solves: switching a dual-DB app to its reserve by changing a\n * secret and restarting gives a minute where machine A writes to one database\n * and machine B to the other. Here, every query goes through THIS object, which\n * forwards to the active side. A switch is a pointer change:\n *\n * hold(ms) new queries wait; resolves when none are running (or at `ms`)\n * point() points at the new side WITHOUT letting the waiters go — so a\n * switch can be confirmed on every machine before any query\n * reaches the new database\n * switchTo() point() + release()\n * release() lets the waiters go, onto whatever side is pointed at\n *\n * How long a query may wait is the orchestrator's call (whoever holds); this\n * file is only the mechanism.\n *\n * ── `.raw` FOLLOWS THE SWITCH TOO ───────────────────────────────────────\n *\n * Consumers use `db().raw` (postgres.js) as much as `execute()` — vnlekerv2 has\n * ~220 `sql.unsafe` and 19 `sql.begin` calls (counted 27/11 2026). A switch that\n * only moved `execute()` would leave all of those on the old database. So `raw`\n * is a stand-in `Sql`:\n *\n * sql`…`, sql.unsafe(), sql.file() a real postgres.js Query, built lazily as\n * always; it is sent to the side that is\n * active WHEN IT RUNS, after any hold. Its\n * modifiers (.values(), .cursor(), …) and\n * its use as a fragment inside another\n * sql`…` are unchanged.\n * sql.begin(), sql.reserve() wait out a hold, then count as one\n * running query until they finish\n * sql(obj), sql.json(), … helpers — passed to the active side\n * sql.notify(), sql.largeObject() wait out a hold, then run on the active side\n * sql.listen() passed to the side active at the call;\n * a listener does NOT move with a switch\n *\n * A query counts as running until postgres.js settles it through\n * `query.resolve` / `query.reject` — NOT until its promise settles: the\n * iterator form of `.cursor()` swaps those two out, and its promise never\n * settles (bid review #56236; counted on the promise, one cursor made every\n * later hold() fail).\n *\n * Running a Query on another side uses postgres.js internals (3.4.x: the\n * Query's `handler`, `canceller`, `resolve`, `reject`, `executed`), which are\n * not public API. So it FAILS CLOSED: if they are missing, creating the client\n * or building a query throws — it never quietly runs on the build side. The\n * dependency is pinned to ~3.4.9 for the same reason.\n */\nimport type { Sql } from 'postgres';\nimport type { Pool as PgPool, PoolClient } from 'pg';\nimport type { BatchMode, DbClient, DbResult, Statement } from '../types';\n\nexport interface HoldResult {\n /** true = nothing was running when the hold resolved. */\n ok: boolean;\n /** Queries still running (a transaction that did not finish in time). */\n inFlight: number;\n}\n\n/** A Postgres DbClient that can move to another database while the process runs.\n * `Raw` is the driver behind `.raw`: postgres.js (`Sql`) or node-postgres (`pg.Pool`, components-F085.6). */\nexport interface SwitchableClient<Raw = Sql> extends DbClient<Raw> {\n /** The name of the side currently pointed at. */\n readonly label: string;\n readonly holding: boolean;\n readonly inFlight: number;\n /** The side currently pointed at — for code that must talk to it directly. */\n readonly current: DbClient<Raw>;\n hold(ms: number): Promise<HoldResult>;\n /** Point at another side without releasing waiters. Returns the old side; it is NOT closed. */\n point(client: DbClient<Raw>, label: string): DbClient<Raw>;\n /** point() + release(). Returns the old side; it is NOT closed. */\n switchTo(client: DbClient<Raw>, label: string): DbClient<Raw>;\n /** Release the waiters onto the side that is pointed at. */\n release(): void;\n}\n\n/** The postgres.js Query internals this file relies on (3.4.x). */\ninterface QueryInternals {\n executed: boolean;\n handler: (q: unknown) => unknown;\n canceller: ((q: unknown) => unknown) | null;\n handle: () => Promise<void>;\n resolve: (x: unknown) => unknown;\n reject: (x: unknown) => unknown;\n}\ntype Side = Pick<QueryInternals, 'handler' | 'canceller'>;\n\nconst UNSUPPORTED = '@broberg/db-sdk/switchable: this postgres.js version does not have the Query internals the switch routes .raw by (3.4.x) — refusing rather than running on the wrong database';\n\nconst isQuery = (x: unknown): x is QueryInternals => {\n const q = x as Partial<QueryInternals>;\n return (\n x instanceof Promise &&\n typeof q.handler === 'function' &&\n typeof q.canceller === 'function' &&\n typeof q.resolve === 'function' &&\n typeof q.reject === 'function' &&\n typeof q.handle === 'function' &&\n q.executed === false\n );\n};\n\n// Each postgres.js instance's private handler + canceller, read once off a\n// query that is built and never run (postgres.js queries are lazy).\nconst sides = new WeakMap<Sql, Side>();\nfunction sideOf(sql: Sql): Side {\n let side = sides.get(sql);\n if (!side) {\n const probe: unknown = sql.unsafe('');\n if (!isQuery(probe)) throw new Error(UNSUPPORTED);\n side = { handler: probe.handler, canceller: probe.canceller };\n sides.set(sql, side);\n }\n return side;\n}\n\n/** Which driver a Postgres client's `.raw` is. Anything else is refused. */\ntype Kind = 'postgresjs' | 'pg';\nconst UNSUPPORTED_RAW = '@broberg/db-sdk/switchable: .raw is neither postgres.js nor a pg.Pool — refusing rather than running unrouted';\nfunction kindOf(raw: unknown): Kind {\n if (typeof raw === 'function') {\n sideOf(raw as Sql); // postgres.js: throws if its Query internals moved\n return 'postgresjs';\n }\n const pool = raw as Partial<PgPool> | null;\n if (pool && typeof pool.connect === 'function' && typeof pool.query === 'function' && typeof pool.on === 'function') return 'pg';\n throw new Error(UNSUPPORTED_RAW);\n}\n\nexport function createSwitchable(initial: DbClient<Sql>, label: string): SwitchableClient<Sql>;\nexport function createSwitchable(initial: DbClient<PgPool>, label: string): SwitchableClient<PgPool>;\nexport function createSwitchable(initial: DbClient<Sql> | DbClient<PgPool>, label: string): SwitchableClient<Sql> | SwitchableClient<PgPool> {\n if (initial.transport !== 'postgres') throw new Error('@broberg/db-sdk/switchable: Postgres only');\n const kind = kindOf(initial.raw); // fail closed at creation, not at the first query\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- one of two drivers, checked by kind\n let active: DbClient<any> = initial;\n let name = label;\n let gate: Promise<void> | null = null;\n let open: (() => void) | null = null;\n let running = 0;\n let idle: Array<() => void> = [];\n\n const enter = async () => {\n while (gate) await gate;\n running++;\n };\n const exit = () => {\n running--;\n if (running === 0) for (const f of idle.splice(0)) f();\n };\n const guarded = async <T>(fn: () => Promise<T>): Promise<T> => {\n await enter();\n try {\n return await fn();\n } finally {\n exit();\n }\n };\n\n /** Make a lazily-built Query run on the side that is active when it runs. */\n const route = <Q>(q: Q): Q => {\n // A helper (sql(obj), sql.json()) is no promise and passes as is. A promise\n // that is not a Query we can route is refused — never run unrouted.\n if (!(q instanceof Promise)) return q;\n if (!isQuery(q)) throw new Error(UNSUPPORTED);\n q.handle = async function (this: QueryInternals) {\n if (this.executed) return;\n this.executed = true;\n await enter();\n // Count out when postgres.js settles the query — whichever resolve or\n // reject is in place by then (the cursor iterator assigns its own).\n let done = false;\n const finish = () => {\n if (!done) {\n done = true;\n exit();\n }\n };\n for (const key of ['resolve', 'reject'] as const) {\n let fn = this[key];\n Object.defineProperty(this, key, {\n configurable: true,\n get: () => (x: unknown) => {\n finish();\n return fn(x);\n },\n set: (v: (x: unknown) => unknown) => {\n fn = v;\n },\n });\n }\n const side = sideOf(active.raw);\n this.handler = side.handler;\n // cancel() before this point has nothing to cancel; after it, it must\n // reach the side the query was sent to.\n if (this.canceller) this.canceller = side.canceller;\n this.handler(this);\n };\n return q;\n };\n\n // ── node-postgres: a stand-in pg.Pool (BID's SwitchablePool, F084.149) ──\n // query/connect wait out a hold and count as running — a client until its\n // release(), counted once. Listeners are re-attached to each new pool once.\n const listeners: Array<[string, (...a: unknown[]) => void]> = [];\n const withListeners = new WeakSet<object>();\n if (kind === 'pg') withListeners.add(initial.raw as object);\n const attach = (pool: PgPool) => {\n if (withListeners.has(pool)) return;\n for (const [ev, fn] of listeners) pool.on(ev as 'error', fn as () => void);\n withListeners.add(pool);\n };\n const callbackStyle = (a: unknown[]) => typeof a[a.length - 1] === 'function';\n const pgRaw: PgPool = new Proxy({} as PgPool, {\n get(_t, prop) {\n const pool = active.raw as PgPool;\n if (prop === 'query') {\n return (...a: unknown[]) => {\n if (callbackStyle(a)) throw new Error('@broberg/db-sdk/switchable: callback-style pool.query is not routed — use the promise form');\n return guarded(() => (active.raw as PgPool).query(...(a as [string])));\n };\n }\n if (prop === 'connect') {\n return async (...a: unknown[]) => {\n if (callbackStyle(a)) throw new Error('@broberg/db-sdk/switchable: callback-style pool.connect is not routed — use the promise form');\n await enter();\n let client: PoolClient;\n try {\n client = await (active.raw as PgPool).connect();\n } catch (err) {\n exit();\n throw err;\n }\n const release = client.release.bind(client);\n let released = false;\n client.release = ((err?: Error | boolean) => {\n if (!released) {\n released = true;\n exit();\n }\n return release(err as Error);\n }) as PoolClient['release'];\n return client;\n };\n }\n if (prop === 'on') {\n return (ev: string, fn: (...x: unknown[]) => void) => {\n listeners.push([ev, fn]);\n (active.raw as PgPool).on(ev as 'error', fn as () => void);\n return pgRaw;\n };\n }\n if (prop === 'end') return () => ((active.raw as PgPool & { ended?: boolean }).ended ? Promise.resolve() : (active.raw as PgPool).end());\n const v = (pool as unknown as Record<PropertyKey, unknown>)[prop];\n return typeof v === 'function' ? (v as (...x: unknown[]) => unknown).bind(pool) : v;\n },\n });\n\n // ── postgres.js: a stand-in Sql ──\n const pjsRaw = new Proxy(function () {} as unknown as Sql, {\n apply(_t, _this, args: unknown[]) {\n return route((active.raw as unknown as (...a: unknown[]) => unknown)(...args));\n },\n get(_t, prop) {\n const sql = active.raw as unknown as Record<PropertyKey, unknown>;\n if (prop === 'unsafe' || prop === 'file') {\n return (...a: unknown[]) => route((active.raw as unknown as Record<string, (...x: unknown[]) => unknown>)[prop]!(...a));\n }\n if (prop === 'begin' || prop === 'notify' || prop === 'largeObject') {\n return (...a: unknown[]) => guarded(() => {\n // Looked up when it RUNS, after any hold — not on the side of the call.\n const side = active.raw as unknown as Record<PropertyKey, (...x: unknown[]) => Promise<unknown>>;\n return side[prop]!.apply(active.raw, a);\n });\n }\n if (prop === 'reserve') {\n return async () => {\n await enter();\n let reserved: Awaited<ReturnType<Sql['reserve']>>;\n try {\n reserved = await active.raw.reserve();\n } catch (err) {\n exit();\n throw err;\n }\n const release = reserved.release.bind(reserved);\n let released = false;\n reserved.release = () => {\n if (!released) {\n released = true;\n exit();\n }\n release();\n };\n return reserved;\n };\n }\n const v = sql[prop];\n return typeof v === 'function' ? (v as (...a: unknown[]) => unknown).bind(active.raw) : v;\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- the two overloads share one implementation\n const self: SwitchableClient<any> = {\n transport: 'postgres',\n raw: kind === 'pg' ? pgRaw : pjsRaw,\n get label() {\n return name;\n },\n get holding() {\n return gate !== null;\n },\n get inFlight() {\n return running;\n },\n get current() {\n return active;\n },\n execute(stmt: Statement): Promise<DbResult> {\n return guarded(() => active.execute(stmt));\n },\n batch(stmts: readonly Statement[], mode?: BatchMode): Promise<DbResult[]> {\n return guarded(() => active.batch(stmts, mode));\n },\n /** Closes the side pointed at. Sides switched away from are the caller's to close. */\n close() {\n return active.close();\n },\n async hold(ms) {\n if (!gate) gate = new Promise<void>((r) => (open = r));\n if (running === 0) return { ok: true, inFlight: 0 };\n const empty = new Promise<'empty'>((r) => idle.push(() => r('empty')));\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<'late'>((r) => (timer = setTimeout(() => r('late'), ms)));\n const outcome = await Promise.race([empty, late]);\n clearTimeout(timer);\n return { ok: outcome === 'empty', inFlight: running };\n },\n point(client, label) {\n if (client.transport !== 'postgres') throw new Error('@broberg/db-sdk/switchable: Postgres only');\n // Both sides must speak the same driver: .raw callers hold one driver's API.\n if (kindOf(client.raw) !== kind) throw new Error(`@broberg/db-sdk/switchable: cannot point a ${kind} client at a ${kindOf(client.raw)} one`);\n if (kind === 'pg') attach(client.raw as PgPool);\n const old = active;\n active = client;\n name = label;\n return old;\n },\n switchTo(client: DbClient<any>, label: string) {\n const old = self.point(client, label);\n self.release();\n return old;\n },\n release() {\n const f = open;\n gate = null;\n open = null;\n f?.();\n },\n };\n return self;\n}\n","/**\n * THE FENCE IN THE DATABASE (components-F085.5, ported from broberg-id\n * F084.153) — the database the app is NOT running on refuses the app's writes.\n *\n * The switch makes every machine write to one place. But it is the APP that\n * does that. A machine that missed the switch, or a restart on a stale secret,\n * would write to the old database in silence — two databases each believing\n * they are the real one. With the fence that write fails loudly instead\n * (`25006`, read_only_sql_transaction). It covers every path into the\n * database — `execute()`, `.raw`, a migration, a psql session — because it\n * lives in the database, not in the client.\n *\n * ── WHY A TRIGGER AND NOT `default_transaction_read_only` ───────────────\n *\n * Measured by BID 7/10 2026 (Postgres 17, a real publisher → subscriber):\n *\n * default_transaction_read_only on the role the client turns it off with\n * SET TRANSACTION READ WRITE,\n * and it only applies to NEW\n * connections\n * a per-statement trigger (this file) app writes refused, READ\n * WRITE included; the initial\n * copy AND ongoing replication\n * pass\n *\n * Replication passes because subscription workers run with\n * `session_replication_role = replica`, where ordinary triggers do not fire.\n * The app's role cannot set that itself (superuser only), and neither\n * Supabase's `postgres` nor UpCloud's `upadmin` is a superuser.\n *\n * ── WHAT IT IS, AND WHAT IT IS NOT ─────────────────────────────────────\n *\n * A guard against a MISTAKE — a machine standing in the wrong place. Not a\n * guard against an attacker: the role owns the tables and can drop the trigger\n * with DDL. Whoever has the database password already has everything.\n *\n * The state lives in the FUNCTION BODY, not in a table: a table in `public`\n * would be replicated from the primary and overwrite the reserve's fence. DDL\n * is not replicated. Replacing the body takes effect at once, also for\n * connections already open (plpgsql looks the function up on every call).\n *\n * INSERT/UPDATE/DELETE only. TRUNCATE is left to rebuild tooling.\n */\nimport type { Sql } from 'postgres';\nimport type { DbClient } from '../types';\n\nexport type FenceState = 'open' | 'locked';\n\nexport interface FenceOptions {\n /** Name of the trigger function AND of the trigger on every table. Default `dbFence`. BID: `bidFence`. */\n name?: string;\n /**\n * The session setting that lets the switch's own copy-home write through a\n * locked database (see reconcile). A machine that missed the switch never\n * sets it, so the fence still holds against the mistake it exists for.\n * Default `db_sdk.fence_bypass`. BID: `bid.fence_bypass`.\n */\n bypass?: string;\n}\n\nexport const FENCE_DEFAULTS = { name: 'dbFence', bypass: 'db_sdk.fence_bypass' } as const;\n/** read_only_sql_transaction — what a fenced write fails with. */\nexport const FENCE_ERRCODE = '25006';\n\ntype Pg = Pick<DbClient<Sql>, 'execute'>;\n\nconst q = (name: string) => `\"${name.replace(/\"/g, '\"\"')}\"`;\nconst lit = (s: string) => `'${s.replace(/'/g, \"''\")}'`;\nconst opts = (o?: FenceOptions) => ({ ...FENCE_DEFAULTS, ...o });\n\nconst body = (state: FenceState, bypass: string) =>\n state === 'open'\n ? `begin return null; end`\n : `begin\n if current_setting(${lit(bypass)}, true) = 'on' then return null; end if;\n raise exception 'db-sdk fence: this database is not the active one — the write is refused' using errcode = '${FENCE_ERRCODE}';\n end`;\n\n/** Locked or open — or `missing` if the fence was never installed in this database. */\nexport async function fenceState(db: Pg, o?: FenceOptions): Promise<FenceState | 'missing'> {\n const { name } = opts(o);\n const { rows } = await db.execute({\n sql: `select p.prosrc as src from pg_proc p where p.proname = $1 and p.pronamespace = current_schema()::regnamespace`,\n args: [name],\n });\n if (rows.length === 0) return 'missing';\n return String(rows[0]!.src).includes('raise exception') ? 'locked' : 'open';\n}\n\nexport async function setFence(db: Pg, state: FenceState, o?: FenceOptions): Promise<void> {\n const { name, bypass } = opts(o);\n await db.execute(`create or replace function ${q(name)}() returns trigger language plpgsql as $fence$ ${body(state, bypass)} $fence$`);\n}\n\n/**\n * Install the fence: the function if missing (in `initial`), and the trigger\n * on every table in the schema that lacks it. Idempotent, and it NEVER changes\n * an existing state — only the switch may. The tables are ASKED of the\n * database, so a table an upgrade adds gets fenced too: call it after every\n * migration.\n */\nexport async function installFence(\n db: Pg,\n initial: FenceState,\n o?: FenceOptions,\n): Promise<{ created: boolean; triggered: string[] }> {\n const { name } = opts(o);\n const created = (await fenceState(db, o)) === 'missing';\n if (created) await setFence(db, initial, o);\n const missing = await unfencedTables(db, o);\n for (const table of missing) {\n await db.execute(`create trigger ${q(name)} before insert or update or delete on ${q(table)} for each statement execute function ${q(name)}()`);\n }\n return { created, triggered: missing };\n}\n\n/** Tables without the trigger — an empty list means the whole schema is covered. */\nexport async function unfencedTables(db: Pg, o?: FenceOptions): Promise<string[]> {\n const { name } = opts(o);\n const { rows } = await db.execute({\n sql: `select c.relname as name from pg_class c\n where c.relnamespace = current_schema()::regnamespace and c.relkind = 'r'\n and not exists (select 1 from pg_trigger t where t.tgrelid = c.oid and t.tgname = $1)\n order by 1`,\n args: [name],\n });\n return rows.map((r) => String(r.name));\n}\n","/**\n * THE WAY BACK WITHOUT LOSS (components-F085.5, ported from broberg-id\n * F084.154) — what was written in the reserve after the switch is brought over\n * to the primary BEFORE switching back.\n *\n * ── THE WALL ─────────────────────────────────────────────────────────────\n *\n * The obvious tool — a reverse subscription, the primary subscribing to the\n * reserve — is not always possible (Supabase cannot subscribe outward). A\n * publication on the reserve plus a WAL player of our own would be a new,\n * heavy component running from the switch onwards. The databases this is for\n * are small (BID 7/10: ~3,000 rows, 28 tables), so COMPARING the rows takes\n * milliseconds and needs nothing running in between.\n *\n * ── THREE STATES PER ROW ─────────────────────────────────────────────────\n *\n * B the baseline at the switch to the reserve — its INSTANT fixed while\n * every machine held, just after the subscription was disabled, and its\n * rows read after release through that snapshot (`freezeBaseline`, F085.7)\n * R the reserve now\n * P the primary now\n *\n * R = P nothing to do\n * P = B only the reserve changed the row → copy (a DELETE too —\n * otherwise a logged-out session wakes up again)\n * otherwise the primary has a change the reserve never saw: CONFLICT.\n * Reported, never overwritten in silence.\n *\n * After a planned switch there can be no conflicts: the primary is fenced and\n * stood still from the baseline. After an EMERGENCY switch the primary may hold\n * the last seconds of writes that never reached the reserve — those are what\n * the conflicts catch.\n *\n * What was copied is written into the baseline, so a run that is interrupted\n * and re-run sees its own copies as \"P = B\", not as conflicts.\n *\n * A row is compared as `md5(to_jsonb(row))` in UTC: jsonb keys are sorted, so\n * column order in the two databases does not matter.\n *\n * Only the CURRENT schema (search_path) is compared; the baseline lives in a\n * schema of its own, so it is never part of the comparison.\n */\nimport type { Sql } from 'postgres';\nimport type { DbClient, DbResult, Statement } from '../types';\nimport { PG_OPTIONS, toResult as postgresResult } from '../backends/postgres';\nimport { toResult as pgResult } from '../backends/pg';\nimport { FENCE_DEFAULTS } from './fence';\n\ntype Pg = Pick<DbClient<Sql>, 'execute' | 'batch'>;\n\nexport interface ReconcileOptions {\n /** Schema that holds the baseline. Default `dbSwitch`. BID: `bidSwitch`. */\n schema?: string;\n /** The fence's bypass setting (see FenceOptions.bypass). Default `db_sdk.fence_bypass`. */\n bypass?: string;\n}\n\nexport const RECONCILE_DEFAULTS = { schema: 'dbSwitch', bypass: FENCE_DEFAULTS.bypass } as const;\n\n/** Table and key in ONE text — separated by a unit separator, not NUL, which Postgres text cannot hold. */\nconst SEP = '\\u001f';\nconst q = (name: string) => `\"${name.replace(/\"/g, '\"\"')}\"`;\nconst lit = (s: string) => `'${s.replace(/'/g, \"''\")}'`;\nconst UTC = `set local time zone 'UTC'`;\nconst baselineTable = (o?: ReconcileOptions) => `${q({ ...RECONCILE_DEFAULTS, ...o }.schema)}.\"baseline\"`;\n\ninterface Table {\n name: string;\n pk: string[];\n cols: string[];\n /** Stored generated columns — Postgres computes them; an insert may not name them. */\n generated: string[];\n /** GENERATED ALWAYS identity columns — written only with OVERRIDING SYSTEM VALUE, never updated. */\n identityAlways: string[];\n}\n\nasync function tables(db: Pg): Promise<Table[]> {\n const { rows } = await db.execute(\n `select c.relname as name,\n (select array_agg(a.attname::text order by array_position(i.indkey::int2[], a.attnum))\n from pg_index i join pg_attribute a on a.attrelid = i.indrelid and a.attnum = any(i.indkey)\n where i.indrelid = c.oid and i.indisprimary) as pk,\n (select array_agg(a.attname::text order by a.attnum) from pg_attribute a\n where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped) as cols,\n (select array_agg(a.attname::text order by a.attnum) from pg_attribute a\n where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped and a.attgenerated <> '') as gen,\n (select array_agg(a.attname::text order by a.attnum) from pg_attribute a\n where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped and a.attidentity = 'a') as ida\n from pg_class c\n where c.relnamespace = current_schema()::regnamespace and c.relkind = 'r'\n order by 1`,\n );\n return rows.map((r) => ({\n name: String(r.name),\n pk: (r.pk as string[] | null) ?? [],\n cols: r.cols as string[],\n generated: (r.gen as string[] | null) ?? [],\n identityAlways: (r.ida as string[] | null) ?? [],\n }));\n}\n\n/**\n * Every row as key → fingerprint, in one call. The key is table + primary key;\n * a table WITHOUT a primary key is a multiset, so its key is the fingerprint\n * itself + a running number.\n */\nasync function fingerprints(db: Pg, tabs: Table[]): Promise<Map<string, string>> {\n const out = new Map<string, string>();\n if (tabs.length === 0) return out;\n const parts = tabs.map((t) => {\n const key = t.pk.length ? `jsonb_build_array(${t.pk.map((c) => `x.${q(c)}`).join(', ')})::text` : `md5(to_jsonb(x)::text)`;\n return `select ${lit(t.name)} as t, ${key} as k, md5(to_jsonb(x)::text) as h from ${q(t.name)} x`;\n });\n const [, res] = await db.batch([UTC, parts.join(' union all ') + ' order by 1, 2']);\n const seen = new Map<string, number>();\n const noPk = new Set(tabs.filter((t) => !t.pk.length).map((t) => t.name));\n for (const r of res!.rows) {\n const t = String(r.t);\n let k = String(r.k);\n if (noPk.has(t)) {\n const n = (seen.get(`${t}${SEP}${k}`) ?? 0) + 1;\n seen.set(`${t}${SEP}${k}`, n);\n k = `${k}#${n}`;\n }\n out.set(`${t}${SEP}${k}`, String(r.h));\n }\n return out;\n}\n\n/**\n * Take the baseline B on the reserve, reading every row NOW. Kept for callers\n * of 0.3.0; the switch itself uses `freezeBaseline`, which does not read the\n * rows while customers wait (F085.7). Returns the row count.\n */\nexport async function captureBaseline(reserve: Pg, o?: ReconcileOptions): Promise<number> {\n return writeBaseline(reserve, await fingerprints(reserve, await tables(reserve)), o);\n}\n\nasync function writeBaseline(reserve: Pg, rows: Map<string, string>, o?: ReconcileOptions): Promise<number> {\n const { schema } = { ...RECONCILE_DEFAULTS, ...o };\n const keys = [...rows.keys()];\n const table = baselineTable(o);\n await reserve.batch([\n `create schema if not exists ${q(schema)}`,\n `drop table if exists ${table}`,\n `create table ${table} (\"key\" text primary key, \"h\" text not null, \"at\" bigint not null)`,\n {\n sql: `insert into ${table} (\"key\", \"h\", \"at\") select k, h, $3 from unnest($1::text[], $2::text[]) as u(k, h)`,\n args: [keys, keys.map((k) => rows.get(k)!), Date.now()],\n },\n ]);\n return rows.size;\n}\n\n/** Is there a baseline — and when was it taken (epoch ms)? */\nexport async function baselineAt(reserve: Pg, o?: ReconcileOptions): Promise<number | null> {\n const table = baselineTable(o);\n // Two statements, not one CASE: Postgres resolves every relation a statement\n // names before it runs, so a CASE that never reads a missing table still\n // fails on it (42P01). broberg-id's one-statement version throws for the\n // same reason when no baseline was ever taken.\n const exists = await reserve.execute({ sql: `select to_regclass($1) is not null as e`, args: [table] });\n if (exists.rows[0]?.e !== true) return null;\n const { rows } = await reserve.execute(`select max(\"at\")::text as at from ${table}`);\n const at = rows[0]?.at;\n return at ? Number(at) : null;\n}\n\nasync function readBaseline(reserve: Pg, o?: ReconcileOptions, only?: string[]): Promise<Map<string, string>> {\n const { rows } = only\n ? await reserve.execute({ sql: `select \"key\", \"h\" from ${baselineTable(o)} where \"key\" = any($1::text[])`, args: [only] })\n : await reserve.execute(`select \"key\", \"h\" from ${baselineTable(o)}`);\n return new Map(rows.map((r) => [String(r.key), String(r.h)]));\n}\n\n/** Where the reserve's transactions stood when a pass started — see `reconcile`'s `since`. */\nexport interface Horizon {\n /** The oldest transaction the pass could not see, as a 32-bit xid (what a row's `xmin` holds). */\n xmin: string;\n /** The current xid at the same moment, 32-bit — to notice a wraparound in between. */\n at: string;\n}\n\n/** Read the reserve's horizon. Take it BEFORE a pass: every row written after it has an xmin at or above it. */\nexport async function reserveHorizon(reserve: Pg): Promise<Horizon> {\n const { rows } = await reserve.execute(\n `select (pg_snapshot_xmin(pg_current_snapshot())::text::bigint % 4294967296)::text as x,\n (pg_current_xact_id()::text::bigint % 4294967296)::text as c`,\n );\n return { xmin: String(rows[0]!.x), at: String(rows[0]!.c) };\n}\n\nconst keyExpr = (t: Table) => `jsonb_build_array(${t.pk.map((c) => `x.${q(c)}`).join(', ')})::text`;\n\n/**\n * F085.7 — the rows that can differ since `since`, read WITHOUT fingerprinting\n * every row. Under the hold the primary only takes our own copies, so after a\n * first pass the two sides can only differ where the reserve wrote since:\n * rows whose xmin is at or above the horizon (inserted or updated), and rows\n * deleted — found by counting, and compared key by key only in a table whose\n * count says something was deleted. Tables without a primary key are not\n * handled here (the caller compares them in full).\n */\nasync function deltaFingerprints(reserve: Pg, primary: Pg, tabs: Table[], since: Horizon): Promise<{ R: Map<string, string>; P: Map<string, string> }> {\n const R = new Map<string, string>();\n const P = new Map<string, string>();\n if (tabs.length === 0) return { R, P };\n // Changed on the reserve since the horizon, and the row counts — in one transaction.\n const [, ...res] = await reserve.batch([\n UTC,\n ...tabs.flatMap((t) => [\n { sql: `select ${keyExpr(t)} as k, md5(to_jsonb(x)::text) as h from ${q(t.name)} x where x.xmin::text::bigint >= $1::bigint`, args: [since.xmin] },\n `select count(*)::bigint as n from ${q(t.name)}`,\n ]),\n ]);\n const changed = tabs.map((_, i) => res[i * 2]!.rows.map((r) => [String(r.k), String(r.h)] as const));\n const countR = tabs.map((_, i) => Number(res[i * 2 + 1]!.rows[0]!.n));\n const [, ...pres] = await primary.batch([\n UTC,\n ...tabs.flatMap((t, i) => [\n { sql: `select ${keyExpr(t)} as k, md5(to_jsonb(x)::text) as h from ${q(t.name)} x where ${keyExpr(t)} = any($1::text[])`, args: [changed[i]!.map(([k]) => k)] },\n `select count(*)::bigint as n from ${q(t.name)}`,\n ]),\n ]);\n const needKeys: number[] = [];\n tabs.forEach((t, i) => {\n const onP = new Map(pres[i * 2]!.rows.map((r) => [String(r.k), String(r.h)]));\n for (const [k, h] of changed[i]!) R.set(`${t.name}${SEP}${k}`, h);\n for (const [k, h] of onP) P.set(`${t.name}${SEP}${k}`, h);\n const inserted = changed[i]!.filter(([k]) => !onP.has(k)).length;\n // |R| = |P| + inserted − deleted, so anything else means rows went away.\n if (Number(pres[i * 2 + 1]!.rows[0]!.n) + inserted !== countR[i]) needKeys.push(i);\n });\n for (const i of needKeys) {\n const t = tabs[i]!;\n const [rk, pk] = await Promise.all([\n reserve.execute(`select ${keyExpr(t)} as k from ${q(t.name)} x`),\n primary.batch([UTC, `select ${keyExpr(t)} as k, md5(to_jsonb(x)::text) as h from ${q(t.name)} x`]).then((r) => r[1]!),\n ]);\n const onR = new Set(rk.rows.map((r) => String(r.k)));\n for (const r of pk.rows) {\n const k = String(r.k);\n if (!onR.has(k)) P.set(`${t.name}${SEP}${k}`, String(r.h));\n }\n }\n return { R, P };\n}\n\nexport interface Conflict {\n table: string;\n key: string;\n /** What the reserve holds now (null = deleted). */\n reserve: string | null;\n /** What the primary holds now (null = does not exist). */\n primary: string | null;\n /** The baseline at the switch (null = did not exist). */\n baseline: string | null;\n}\n\nexport interface Plan {\n upserts: number;\n deletes: number;\n conflicts: Conflict[];\n /** Tables whose columns differ between the two databases — then nothing can be compared. */\n schemaMismatch: string[];\n /** Rows actually written in the primary (0 when only planned). */\n written: number;\n}\n\n/**\n * Compare, and copy if `apply` and there are neither conflicts nor schema\n * differences — OR `skipConflicts`, in which case the rest is copied and the\n * conflicting rows stay as the primary has them.\n *\n * Everything is written in the primary in ONE transaction through the fence's\n * door (the bypass setting): the primary is fenced while the app runs on the\n * reserve.\n */\nexport async function reconcile(\n reserve: Pg,\n primary: Pg,\n opts: {\n apply: boolean;\n skipConflicts?: boolean;\n /**\n * F085.7 — compare only what the reserve changed since this horizon\n * (`reserveHorizon`, taken before an earlier full pass). For the second\n * pass under the hold: at VN's size a full compare took 19.5 s there.\n * Tables without a primary key are still compared in full. Falls back to\n * a full compare if the transaction counter wrapped in between.\n */\n since?: Horizon;\n } & ReconcileOptions,\n): Promise<Plan> {\n const { bypass } = { ...RECONCILE_DEFAULTS, ...opts };\n const [rt, pt] = await Promise.all([tables(reserve), tables(primary)]);\n const pByName = new Map(pt.map((t) => [t.name, t]));\n const sameCols = (a: Table, b: Table) => a.cols.slice().sort().join() === b.cols.slice().sort().join();\n const schemaMismatch = [\n ...rt.filter((t) => !pByName.has(t.name) || !sameCols(pByName.get(t.name)!, t)).map((t) => t.name),\n ...pt.filter((t) => !rt.some((r) => r.name === t.name)).map((t) => t.name),\n ];\n if (schemaMismatch.length) return { upserts: 0, deletes: 0, conflicts: [], schemaMismatch, written: 0 };\n\n let R: Map<string, string>;\n let P: Map<string, string>;\n let B: Map<string, string>;\n const since = opts.since && Number(opts.since.at) >= Number(opts.since.xmin) ? opts.since : undefined;\n if (since && (await reserveHorizon(reserve).then((h) => Number(h.at) >= Number(since.xmin)))) {\n const keyed = rt.filter((t) => t.pk.length);\n const whole = rt.filter((t) => !t.pk.length);\n const [d, wr, wp] = await Promise.all([\n deltaFingerprints(reserve, primary, keyed, since),\n fingerprints(reserve, whole),\n fingerprints(primary, pt.filter((t) => !t.pk.length)),\n ]);\n R = new Map([...d.R, ...wr]);\n P = new Map([...d.P, ...wp]);\n B = await readBaseline(reserve, opts, [...new Set([...R.keys(), ...P.keys()])]);\n } else {\n [R, P, B] = await Promise.all([fingerprints(reserve, rt), fingerprints(primary, pt), readBaseline(reserve, opts)]);\n }\n const conflicts: Conflict[] = [];\n const copies: { table: string; key: string; h: string | null; p: string | null }[] = [];\n for (const k of new Set([...R.keys(), ...P.keys()])) {\n const r = R.get(k) ?? null;\n const p = P.get(k) ?? null;\n if (r === p) continue;\n const b = B.get(k) ?? null;\n const [table, key] = k.split(SEP) as [string, string];\n if (p === b) copies.push({ table, key, h: r, p });\n else conflicts.push({ table, key, reserve: r, primary: p, baseline: b });\n }\n const plan: Plan = {\n upserts: copies.filter((x) => x.h !== null).length,\n deletes: copies.filter((x) => x.h === null).length,\n conflicts,\n schemaMismatch,\n written: 0,\n };\n if (!opts.apply || copies.length === 0 || (conflicts.length && !opts.skipConflicts)) return plan;\n\n // Order: parents before children on insert, children before parents on\n // delete — the foreign keys are ASKED of the database.\n const order = await fkOrder(primary, rt.map((t) => t.name));\n const byName = new Map(rt.map((t) => [t.name, t]));\n\n // The rows to copy, read from the reserve by fingerprint — in UTC like the\n // fingerprint, or a timestamp column gives a different one. Read as jsonb\n // TEXT and written back as that same text: no round trip through a JS\n // object, whose number and date handling is not Postgres'. The parameter is\n // `$1::text::jsonb`: typed as jsonb directly, postgres.js JSON.stringify's\n // the text once more and Postgres gets a JSON string, not a row (measured).\n const rowsByH = new Map<string, string>();\n const upserts = group(copies.filter((x) => x.h !== null));\n const reads: Statement[] = [UTC];\n const readTables: string[] = [];\n for (const [table, grp] of upserts) {\n reads.push({\n sql: `select md5(to_jsonb(x)::text) as h, to_jsonb(x)::text as j from ${q(table)} x where md5(to_jsonb(x)::text) = any($1::text[])`,\n args: [grp.map((x) => x.h)],\n });\n readTables.push(table);\n }\n if (readTables.length) {\n const res = await reserve.batch(reads);\n readTables.forEach((table, i) => {\n for (const r of res[i + 1]!.rows) rowsByH.set(`${table}${SEP}${String(r.h)}`, String(r.j));\n });\n }\n\n // One transaction on the primary. Each write remembers which key it is, so\n // only what was actually written goes into the baseline.\n const writes: Statement[] = [UTC, { sql: `select set_config($1, 'on', true)`, args: [bypass] }];\n const meaning: ({ key: string; h: string | null; counted: 'rowcount' | 'always' } | null)[] = [null, null];\n // Delete by the primary's OWN row (p = b): one copy at a time, so a table\n // without a primary key loses exactly the row the reserve lost.\n const deletes = group(copies.filter((x) => x.h === null));\n for (const table of [...order].reverse()) {\n for (const x of deletes.get(table) ?? []) {\n writes.push({\n sql: `delete from ${q(table)} where ctid = (select ctid from ${q(table)} x where md5(to_jsonb(x)::text) = $1 limit 1)`,\n args: [x.p],\n });\n meaning.push({ key: `${table}${SEP}${x.key}`, h: null, counted: 'rowcount' });\n }\n }\n for (const table of order) {\n const t = byName.get(table)!;\n // F085.7 (VN): a GENERATED ALWAYS identity column refuses a value (428C9)\n // unless the insert says OVERRIDING SYSTEM VALUE — harmless on a table\n // without one. A stored generated column may not be named at all; Postgres\n // computes it. An identity-always column is never in the SET list: it can\n // only be updated to DEFAULT.\n const insertable = t.cols.filter((col) => !t.generated.includes(col));\n const set = insertable.filter((col) => !t.pk.includes(col) && !t.identityAlways.includes(col));\n const colList = insertable.map(q).join(', ');\n const onConflict = t.pk.length\n ? `on conflict (${t.pk.map(q).join(', ')}) do ${set.length ? `update set ${set.map((col) => `${q(col)} = excluded.${q(col)}`).join(', ')}` : 'nothing'}`\n : '';\n for (const x of upserts.get(table) ?? []) {\n // Changed in the reserve since its fingerprint (only possible without a\n // hold): skipped here and taken on the next pass — under the hold.\n const j = rowsByH.get(`${table}${SEP}${x.h}`);\n if (j === undefined) continue;\n writes.push({\n sql: `insert into ${q(table)} (${colList}) overriding system value select ${colList} from jsonb_populate_record(null::${q(table)}, $1::text::jsonb) ${onConflict}`,\n args: [j],\n });\n meaning.push({ key: `${table}${SEP}${x.key}`, h: x.h, counted: 'always' });\n }\n }\n const results = await primary.batch(writes);\n const written: { key: string; h: string | null }[] = [];\n meaning.forEach((m, i) => {\n if (m && (m.counted === 'always' || results[i]!.rowsAffected === 1)) written.push({ key: m.key, h: m.h });\n });\n\n // What was copied is now the primary's state: write it into the baseline,\n // so a new run does not see our own copies as conflicts.\n const table = baselineTable(opts);\n const ins = written.filter((x) => x.h !== null);\n await reserve.batch([\n {\n sql: `insert into ${table} (\"key\", \"h\", \"at\") select k, h, $3 from unnest($1::text[], $2::text[]) as u(k, h)\n on conflict (\"key\") do update set \"h\" = excluded.\"h\"`,\n args: [ins.map((x) => x.key), ins.map((x) => x.h), Date.now()],\n },\n { sql: `delete from ${table} where \"key\" = any($1::text[])`, args: [written.filter((x) => x.h === null).map((x) => x.key)] },\n ]);\n return { ...plan, written: written.length };\n}\n\n/**\n * Move every identity/serial sequence in the current schema up to the column's\n * max (F085.7). Logical replication copies ROWS, not sequences: the reserve's\n * sequences stand where they stood when it was created, and after the way home\n * the primary's stand behind the ids the reserve handed out. The side that\n * starts taking writes must not hand out an id that is already used — call\n * this on it while every machine still holds. Never moves a sequence back.\n * Returns the columns it checked, as `table.column`.\n */\nexport async function syncSequences(db: Pg): Promise<string[]> {\n const { rows } = await db.execute(\n `select c.relname as t, a.attname as col, pg_get_serial_sequence(format('%I.%I', n.nspname, c.relname), a.attname) as seq\n from pg_class c join pg_namespace n on n.oid = c.relnamespace join pg_attribute a on a.attrelid = c.oid\n where c.relnamespace = current_schema()::regnamespace and c.relkind = 'r' and a.attnum > 0 and not a.attisdropped\n and pg_get_serial_sequence(format('%I.%I', n.nspname, c.relname), a.attname) is not null\n order by 1, 2`,\n );\n if (rows.length === 0) return [];\n // The sequence name comes back from Postgres already quoted where it must be.\n await db.batch(\n rows.map((r) => ({\n sql: `select setval($1::regclass, x.m) from (select max(${q(String(r.col))}) as m from ${q(String(r.t))}) x\n where x.m is not null and x.m > (select case when is_called then last_value else last_value - 1 end from ${String(r.seq)})`,\n args: [String(r.seq)],\n })),\n );\n return rows.map((r) => `${String(r.t)}.${String(r.col)}`);\n}\n\n/** A baseline whose instant is fixed, and whose rows are read later. */\nexport interface FrozenBaseline {\n /** Read the rows as they were at the freeze, write the baseline, release the connection. Returns the row count. */\n finish(): Promise<number>;\n /** Give up: roll back, release the connection, leave no baseline. */\n cancel(): Promise<void>;\n}\n\n/**\n * Fix the baseline's INSTANT without reading it (F085.7). At VN's size\n * (308,176 rows) reading the baseline under the hold kept customers waiting\n * 3.5–5.8 s. The baseline only has to be the reserve as it was at the switch:\n * a REPEATABLE READ transaction on a connection of its own takes its snapshot\n * at its first statement — milliseconds — and keeps seeing exactly that while\n * the app writes. `finish()` reads the fingerprints through it after release.\n *\n * The old baseline is dropped here, so until `finish()` has written the new\n * one `baselineAt` is null and the way home refuses rather than compare\n * against a baseline from an earlier switch.\n *\n * Needs the client's raw driver (postgres.js or a pg.Pool) for the dedicated\n * connection; both transports of this package qualify.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- either driver\nexport async function freezeBaseline(reserve: Pick<DbClient<any>, 'execute' | 'batch' | 'raw'>, o?: ReconcileOptions): Promise<FrozenBaseline> {\n await reserve.execute(`drop table if exists ${baselineTable(o)}`);\n const s = await openSession(reserve.raw);\n try {\n await s.execute('begin isolation level repeatable read read only');\n await s.execute('select 1'); // the snapshot is taken here\n } catch (e) {\n s.release();\n throw e;\n }\n let settled = false;\n return {\n async finish() {\n if (settled) throw new Error('freezeBaseline: already finished or cancelled');\n settled = true;\n let rows: Map<string, string>;\n try {\n rows = await fingerprints(s, await tables(s));\n await s.execute('commit');\n } catch (e) {\n await s.execute('rollback').catch((rb: unknown) => {\n (e as Error & { rollbackError?: unknown }).rollbackError = rb;\n });\n throw e;\n } finally {\n s.release();\n }\n return writeBaseline(reserve, rows, o);\n },\n async cancel() {\n if (settled) return;\n settled = true;\n try {\n await s.execute('rollback');\n } finally {\n s.release();\n }\n },\n };\n}\n\n/** One connection of its own, for a transaction that must outlive a call. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- either driver\nasync function openSession(raw: any): Promise<Pg & { release(): void }> {\n let exec: (stmt: Statement) => Promise<DbResult>;\n let release: () => void;\n if (raw && typeof raw.reserve === 'function') {\n // A reserved connection is taken OUT of the pool: with a pool of one,\n // every other query would wait for it forever. Refuse instead of hanging.\n const max = (raw as Sql).options?.max;\n if (typeof max === 'number' && max < 2) throw new Error(`freezeBaseline needs a pool of at least 2 connections (this one has ${max})`);\n const c = await (raw as Sql).reserve();\n exec = async (stmt) => {\n const [text, args] = typeof stmt === 'string' ? [stmt, []] : [stmt.sql, [...(stmt.args ?? [])]];\n return postgresResult(await c.unsafe(text, args as never[], PG_OPTIONS));\n };\n release = () => c.release();\n } else if (raw && typeof raw.connect === 'function') {\n const c = await (raw as import('pg').Pool).connect();\n exec = async (stmt) => {\n const [text, args] = typeof stmt === 'string' ? [stmt, []] : [stmt.sql, [...(stmt.args ?? [])]];\n return pgResult(await c.query(text, args));\n };\n release = () => c.release();\n } else {\n throw new Error('freezeBaseline needs a postgres.js or pg client (its raw driver gives the dedicated connection)');\n }\n return {\n execute: exec,\n async batch(stmts) {\n const out: DbResult[] = [];\n for (const st of stmts) out.push(await exec(st));\n return out;\n },\n release,\n };\n}\n\nfunction group<T extends { table: string }>(xs: T[]): Map<string, T[]> {\n const m = new Map<string, T[]>();\n for (const x of xs) m.set(x.table, [...(m.get(x.table) ?? []), x]);\n return m;\n}\n\n/** The tables ordered so a parent stands before its children. */\nasync function fkOrder(db: Pg, names: string[]): Promise<string[]> {\n const { rows } = await db.execute(\n `select c.relname as child, p.relname as parent from pg_constraint k\n join pg_class c on c.oid = k.conrelid join pg_class p on p.oid = k.confrelid\n where k.contype = 'f' and k.connamespace = current_schema()::regnamespace and c.oid <> p.oid`,\n );\n const out: string[] = [];\n const done = new Set<string>();\n const visit = (n: string, path: Set<string>) => {\n if (done.has(n) || path.has(n)) return;\n path.add(n);\n for (const r of rows) if (r.child === n) visit(String(r.parent), path);\n done.add(n);\n out.push(n);\n };\n for (const n of names) visit(n, new Set());\n return out.filter((n) => names.includes(n));\n}\n","/**\n * THE PER-MACHINE CONTROL (components-F085.5, ported from broberg-id\n * db-switch-control.ts, F084.149) — the HTTP door an orchestrator uses to move\n * ONE process's SwitchableClient.\n *\n * The orchestrator calls every machine in turn: prepare → hold → point — and\n * only when ALL have pointed: release. If one fails, abort is called on all,\n * and the waiters go onto the side from before the hold. No query reaches the\n * new database before every machine is ready.\n *\n * SAFETY NET: a machine that holds ABORTS BY ITSELF after `holdMs × 2` if the\n * orchestrator disappears — back to the side from before the hold, also if it\n * had already pointed. A login must never hang because a script died, and a\n * machine must never end up alone on the new database.\n *\n * What stays in the app (it is the app's own environment): which URLs, which\n * TLS, where the handler listens. BID serves it on Fly's private network only\n * (fly-local-6pn:8081); serve it where only your own machines can reach it.\n * The Bearer is an HMAC of a secret the machines already share.\n *\n * POST /db/prepare { target } open the target (once) and run `select 1`\n * POST /db/hold { ms } hold (100–10 000 ms); arms the safety net\n * POST /db/point { target } point while holding; 409 unless prepared + holding\n * POST /db/release release onto the side pointed at\n * POST /db/abort back to the side from before the hold, release\n * GET /db/status { label, holding, inFlight }\n */\nimport { createHmac, timingSafeEqual } from 'node:crypto';\nimport type { DbClient } from '../types';\nimport type { SwitchableClient } from './switchable';\n\n/** A Postgres client from either driver (postgres.js or pg, components-F085.6). */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- driver-agnostic: only execute/batch and the switchable API are used\ntype AnyPg = DbClient<any>;\n\nexport type Target = 'primary' | 'reserve';\n\nexport interface TargetSpec {\n /** The name the side answers to (BID: \"supabase\" / \"upcloud\"). Known without opening. */\n label: string;\n /** Open a client for it. Called once, on the first prepare. */\n open: () => AnyPg;\n}\n\nexport interface SwitchControlOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- either driver\n switchable: SwitchableClient<any>;\n targets: Record<Target, TargetSpec>;\n /** The machines' shared secret; the Bearer is HMAC-SHA256(secret, context). */\n secret: string;\n /** HMAC context. Default \"db-switch\". BID: \"bid-db-switch\". */\n context?: string;\n /** Logged on a switch and on the safety net. Default console. */\n log?: { info(msg: string): void; error(msg: string): void };\n}\n\nexport const HOLD_MIN_MS = 100;\nexport const HOLD_MAX_MS = 10_000;\nconst HOLD_DEFAULT_MS = 3_000;\n\n/** The Bearer an orchestrator sends — derived, so it never travels or is stored on its own. */\nexport function switchToken(secret: string, context = 'db-switch'): string {\n return createHmac('sha256', secret).update(context).digest('hex');\n}\n\nexport function createSwitchControl(o: SwitchControlOptions): (req: Request) => Promise<Response> {\n const { switchable } = o;\n const log = o.log ?? { info: (m: string) => console.log(m), error: (m: string) => console.error(m) };\n const token = Buffer.from(switchToken(o.secret, o.context));\n // The side the machine started on, under its own name — the way back.\n const sides = new Map<string, AnyPg>([[switchable.label, switchable.current]]);\n let safetyNet: ReturnType<typeof setTimeout> | null = null;\n // The side from before the hold — the way back if the switch is aborted.\n let beforeHold: { client: AnyPg; label: string } | null = null;\n\n const authorized = (req: Request) => {\n const h = req.headers.get('authorization') ?? '';\n const b = Buffer.from(h.startsWith('Bearer ') ? h.slice(7) : '');\n return b.length === token.length && timingSafeEqual(b, token);\n };\n const json = (data: unknown, status = 200) => Response.json(data, { status });\n const disarm = () => {\n if (safetyNet) clearTimeout(safetyNet);\n safetyNet = null;\n };\n /** Back to the side from before the hold, and release. */\n const abort = () => {\n disarm();\n if (beforeHold) switchable.point(beforeHold.client, beforeHold.label);\n beforeHold = null;\n switchable.release();\n };\n const isTarget = (t: unknown): t is Target => t === 'primary' || t === 'reserve';\n\n return async (req) => {\n if (!authorized(req)) return json({ error: 'unauthorized' }, 401);\n const path = new URL(req.url).pathname;\n const body = req.method === 'POST' ? ((await req.json().catch(() => ({}))) as { target?: unknown; ms?: unknown }) : {};\n try {\n if (path === '/db/status') return json({ label: switchable.label, holding: switchable.holding, inFlight: switchable.inFlight });\n\n if (path === '/db/prepare') {\n if (!isTarget(body.target)) return json({ error: 'target' }, 400);\n const spec = o.targets[body.target];\n const client = sides.get(spec.label) ?? spec.open();\n await client.execute('select 1');\n sides.set(spec.label, client);\n return json({ ok: true, label: spec.label });\n }\n\n if (path === '/db/hold') {\n const ms = Math.min(Math.max(Number(body.ms) || HOLD_DEFAULT_MS, HOLD_MIN_MS), HOLD_MAX_MS);\n if (!switchable.holding) beforeHold = { client: switchable.current, label: switchable.label };\n const r = await switchable.hold(ms);\n disarm();\n safetyNet = setTimeout(() => {\n abort();\n log.error(`[db-switch] safety net: the orchestrator did not answer — continuing on ${switchable.label}`);\n }, ms * 2);\n return json({ ...r, label: switchable.label });\n }\n\n // Point WITHOUT releasing. Only during a hold — otherwise queries would\n // reach the new side before the other machines are ready.\n if (path === '/db/point') {\n if (!isTarget(body.target)) return json({ error: 'target' }, 400);\n if (!switchable.holding) return json({ error: 'not_holding' }, 409);\n const label = o.targets[body.target].label;\n const client = sides.get(label);\n if (!client) return json({ error: 'not_prepared', label }, 409);\n switchable.point(client, label);\n return json({ ok: true, label });\n }\n\n if (path === '/db/release') {\n disarm();\n const moved = beforeHold !== null && beforeHold.label !== switchable.label;\n beforeHold = null;\n switchable.release();\n if (moved) log.info(`[db-switch] now on ${switchable.label}`);\n return json({ ok: true, label: switchable.label });\n }\n\n if (path === '/db/abort') {\n abort();\n return json({ ok: true, label: switchable.label });\n }\n return json({ error: 'not_found' }, 404);\n } catch (err) {\n return json({ error: err instanceof Error ? err.message : String(err) }, 500);\n }\n };\n}\n\n/**\n * THE EMERGENCY SWITCH'S GUARD (BID F084.152) — may a switch without the primary\n * run? The emergency switch skips the marker, so whatever had not replicated is\n * lost. It may ONLY run when the primary really does not answer — otherwise the\n * planned switch (lossless) is the right one — and whoever presses must have\n * said the loss is accepted. `fault: \"primary-down\"` is a test's way past the\n * first condition, against a primary that is alive.\n */\nexport type EmergencyDecision = 'proceed' | 'need-accept' | 'refuse-primary-alive';\nexport function emergencyGate(o: { primaryResponds: boolean; acceptDataLoss: boolean; fault?: string }): EmergencyDecision {\n if (!o.acceptDataLoss) return 'need-accept';\n if (o.primaryResponds && o.fault !== 'primary-down') return 'refuse-primary-alive';\n return 'proceed';\n}\n","/**\n * THE ORCHESTRATION (components-F085.5, ported from broberg-id\n * db-switch-cli.ts, F084.149/.152/.153/.154) — moves EVERY machine of an app\n * from one database to the other, so no minute exists where two machines\n * write to two places.\n *\n * to the reserve, in this order:\n * 0. the fence is in place on both sides (target locked, current open), the\n * marker table exists in both and the stream carries a probe row\n * 1. prepare: every machine opens the target and tries it\n * 2. hold: every machine lets new queries wait and drains the running ones —\n * a machine not drained in time ABORTS the switch\n * 3. marker: one row written in the primary; the switch waits until it is in\n * the reserve — then EVERYTHING written before the hold is there\n * 4. the subscription is disabled, then the baseline for the way back is taken\n * 5. the target is unfenced (everyone holds, nothing writes), every machine\n * points at it — and still holds\n * 6. release: only when ALL have pointed; then the old side is fenced\n * A failure in 1–5: abort on all — back to the old side, the target re-fenced,\n * the subscription re-enabled. No query has reached the new side.\n *\n * to the primary: the reserve's writes are copied home first (reconcile) —\n * once without a hold, the rest under it — unless `discardReserveWrites`.\n * Conflicts stop the switch unless `skipConflicts`.\n *\n * What stays in the app: finding the machines (BID: Fly's vms.<app>.internal),\n * the URLs/TLS, and setting the secrets afterwards so a restart lands on the\n * same side (BID: stage-env). Machines are given as `call` functions —\n * `httpMachine()` is the plain HTTP one.\n */\nimport { randomBytes } from 'node:crypto';\nimport type { Sql } from 'postgres';\nimport type { DbClient } from '../types';\nimport { emergencyGate, type Target } from './control';\nimport { FENCE_DEFAULTS, fenceState, setFence, unfencedTables, type FenceOptions, type FenceState } from './fence';\nimport { baselineAt, freezeBaseline, reconcile, reserveHorizon, syncSequences, type FrozenBaseline, type Horizon, type Plan, type ReconcileOptions } from './reconcile';\n\nexport type MachineAnswer = { status: number; ok?: boolean; label?: string; error?: string; [k: string]: unknown };\nexport interface Machine {\n id: string;\n call(path: string, body?: unknown, timeoutMs?: number): Promise<MachineAnswer>;\n}\n\n/** A machine reached over HTTP at `baseUrl` (e.g. \"http://<id>.vm.<app>.internal:8081\"). */\nexport function httpMachine(id: string, baseUrl: string, token: string): Machine {\n return {\n id,\n async call(path, body, timeoutMs = 15_000) {\n const res = await fetch(`${baseUrl}${path}`, {\n method: body === undefined ? 'GET' : 'POST',\n headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: AbortSignal.timeout(timeoutMs),\n });\n const text = await res.text();\n let json: Record<string, unknown> = {};\n try {\n json = text ? (JSON.parse(text) as Record<string, unknown>) : {};\n } catch {\n json = { error: `not JSON: ${text.slice(0, 120)}` };\n }\n return { status: res.status, ...json };\n },\n };\n}\n\nexport interface OrchestrateOptions {\n to: Target;\n machines: Machine[];\n /** DIRECT clients to both sides (not through a pooler) — only the orchestration uses them. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- either driver (postgres.js or pg)\n primary: DbClient<any>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- either driver\n reserve: DbClient<any>;\n /** The labels the machines report for each side (same as the control's targets). */\n labels: Record<Target, string>;\n /** The reserve's subscription to the primary (to the reserve only). */\n subscription: string;\n /** Hold ceiling per machine, 100–10 000. Default 3000. */\n holdMs?: number;\n /** To the primary: copy home but keep the primary's version of conflicting rows. */\n skipConflicts?: boolean;\n /** To the primary: drop what was written in the reserve (the emergency exit). */\n discardReserveWrites?: boolean;\n /** Emergency switch to the reserve: the primary is down. No probe, no marker —\n * so what had not replicated is LOST. Needs `acceptDataLoss`, and is refused\n * while the primary answers (emergencyGate). */\n primaryDown?: boolean;\n acceptDataLoss?: boolean;\n /** Fault injection for tests in production (BID AC1). \"primary-down\" treats a\n * live primary as dead, to test the emergency path. */\n fault?: 'replication' | 'point' | 'primary-down';\n /** Marker table (id text pk, at bigint). Default \"dbSwitchMarker\" (BID's). */\n markerTable?: string;\n fence?: FenceOptions;\n reconcile?: ReconcileOptions;\n log?: (line: string) => void;\n}\n\nexport type Outcome =\n | { outcome: 'done'; label: string; heldMs: number }\n | { outcome: 'refused'; reason: string } // nothing was held; nothing changed\n | { outcome: 'aborted'; reason: string; restored: string[] } // held, then rolled back\n | { outcome: 'unconfirmed'; reason: string; label: string }; // released, but a machine did not confirm — run status NOW\n\nconst q = (name: string) => `\"${name.replace(/\"/g, '\"\"')}\"`;\n\nasync function within<T>(p: Promise<T>, ms: number, what: string): Promise<T> {\n let t: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([p, new Promise<never>((_, j) => (t = setTimeout(() => j(new Error(`${what}: no answer in ${ms} ms`)), ms)))]);\n } finally {\n clearTimeout(t);\n }\n}\n\nasync function all(machines: Machine[], f: (m: Machine) => Promise<MachineAnswer>): Promise<(MachineAnswer & { id: string })[]> {\n return Promise.all(\n machines.map(async (m) => {\n try {\n return { id: m.id, ...(await f(m)) };\n } catch (e) {\n return { id: m.id, status: 0, error: e instanceof Error ? e.message : String(e) };\n }\n }),\n );\n}\n\n/** The plan in plain words — and whether it stops the switch. */\nfunction planStopper(p: Plan, skip: boolean, log: (s: string) => void): string | null {\n log(`copy home: ${p.upserts} new/changed, ${p.deletes} deleted, ${p.conflicts.length} conflicts, ${p.written} written`);\n if (p.schemaMismatch.length) return `the schema differs between the two databases (${p.schemaMismatch.join(', ')}) — migrate first`;\n if (p.conflicts.length) {\n for (const k of p.conflicts.slice(0, 50)) log(` CONFLICT ${k.table} ${k.key}`);\n if (!skip) return `${p.conflicts.length} conflict(s) — the primary has changes the reserve never saw; skipConflicts copies the rest and keeps the primary's version`;\n }\n return null;\n}\n\nexport async function orchestrateSwitch(o: OrchestrateOptions): Promise<Outcome> {\n const t0 = performance.now();\n const log = (s: string) => (o.log ?? console.log)(`[switch +${Math.round(performance.now() - t0)}ms] ${s}`);\n const holdMs = Math.min(Math.max(o.holdMs ?? 3000, 100), 10_000);\n const toReserve = o.to === 'reserve';\n const emergency = Boolean(o.primaryDown);\n const copyHome = !toReserve && !o.discardReserveWrites;\n const marker = q(o.markerTable ?? 'dbSwitchMarker');\n const target = toReserve ? o.reserve : o.primary;\n const old = toReserve ? o.primary : o.reserve;\n const [targetLabel, oldLabel] = toReserve ? [o.labels.reserve, o.labels.primary] : [o.labels.primary, o.labels.reserve];\n if (emergency && !toReserve) return { outcome: 'refused', reason: 'primaryDown only makes sense to the reserve' };\n if (o.fault === 'replication' && (!toReserve || emergency)) return { outcome: 'refused', reason: 'fault replication needs a planned switch to the reserve' };\n if (o.fault !== undefined && !['replication', 'point', 'primary-down'].includes(o.fault)) return { outcome: 'refused', reason: `unknown fault «${String(o.fault)}»` };\n if (o.fault === 'primary-down' && !emergency) return { outcome: 'refused', reason: 'fault primary-down needs primaryDown' };\n if (emergency) {\n const responds = await within(o.primary.execute('select 1'), 5000, 'primary').then(() => true, () => false);\n const decision = emergencyGate({ primaryResponds: responds, acceptDataLoss: Boolean(o.acceptDataLoss), fault: o.fault });\n // What is lost: everything written on the primary after the reserve's last message.\n const lag = await within(\n o.reserve.execute({ sql: `select extract(epoch from now() - last_msg_receipt_time)::int as s from pg_stat_subscription where subname = $1 and relid is null`, args: [o.subscription] }),\n 5000,\n 'reserve',\n ).then((r) => (r.rows[0]?.s ?? null) as number | null, () => null);\n log(`EMERGENCY: the primary ${responds ? 'ANSWERS' : 'does not answer'}; the reserve last heard from it ${lag ?? '?'} s ago — what the primary wrote after that is LOST → ${decision}`);\n if (decision === 'need-accept') return { outcome: 'refused', reason: 'an emergency switch loses what had not replicated — pass acceptDataLoss if that is meant' };\n if (decision === 'refuse-primary-alive') return { outcome: 'refused', reason: 'the primary ANSWERS — use the planned switch (lossless)' };\n }\n\n let targetOpened = false;\n let subscriptionOff = false;\n let frozen: FrozenBaseline | null = null;\n const restored: string[] = [];\n const abort = async (reason: string): Promise<Outcome> => {\n log(`ABORTING: ${reason} — releasing everyone on the old side`);\n if (frozen) await frozen.cancel().catch((e) => log(`WARNING: the frozen baseline could not be released: ${e}`));\n log(`aborted: ${JSON.stringify(await all(o.machines, (m) => m.call('/db/abort', {})))}`);\n if (targetOpened) {\n try {\n await setFence(target, 'locked', o.fence);\n restored.push(`${targetLabel} fenced again`);\n } catch (e) {\n log(`WARNING: ${targetLabel} could NOT be fenced again: ${e} — fence it by hand`);\n }\n }\n if (subscriptionOff) {\n try {\n await o.reserve.execute(`alter subscription ${q(o.subscription)} enable`);\n restored.push('subscription enabled again');\n } catch (e) {\n log(`WARNING: the subscription could not be enabled again: ${e}`);\n }\n }\n return { outcome: 'aborted', reason, restored };\n };\n\n // Preconditions: the fence installed by the app's migration, not here — DDL\n // against a live database does not belong in the middle of a switch. The old\n // side cannot be asked in an emergency.\n for (const [side, label, want] of (emergency ? [[target, targetLabel, 'locked']] : [[target, targetLabel, 'locked'], [old, oldLabel, 'open']]) as [Pick<DbClient<Sql>, 'execute'>, string, FenceState][]) {\n const [state, missing] = await Promise.all([fenceState(side, o.fence), unfencedTables(side, o.fence)]);\n if (state !== want || missing.length) {\n return { outcome: 'refused', reason: `${label}: fence is «${state}» (expected «${want}»)${missing.length ? `, ${missing.length} table(s) without it: ${missing.join(', ')}` : ''} — nothing switched` };\n }\n }\n\n // 0. The marker table and a probe through the stream, before anything holds.\n if (toReserve && !emergency) {\n // The marker table normally comes from the app's migration (BID's does).\n // Created here only if missing — and then it, and ONLY it, gets the fence\n // trigger: the preconditions above already proved every other table fenced.\n const fn = q(o.fence?.name ?? FENCE_DEFAULTS.name);\n for (const side of [o.primary, o.reserve]) {\n const exists = (await side.execute({ sql: `select to_regclass($1) is not null as e`, args: [marker] })).rows[0]?.e === true; // quoted: unquoted, to_regclass folds it to lower case\n if (exists) continue;\n await side.execute(`create table ${marker} (\"id\" text primary key, \"at\" bigint not null)`);\n await side.execute(`create trigger ${fn} before insert or update or delete on ${marker} for each statement execute function ${fn}()`);\n }\n await o.reserve.execute(`alter subscription ${q(o.subscription)} refresh publication`);\n const probe = `probe-${randomBytes(6).toString('hex')}`;\n await o.primary.execute({ sql: `insert into ${marker} (\"id\", \"at\") values ($1, $2)`, args: [probe, Date.now()] });\n if (!(await arrived(o.reserve, marker, probe, 30_000, 100))) {\n // Refused, not aborted: the probe runs before prepare, so no machine holds anything.\n return { outcome: 'refused', reason: 'the probe did not reach the reserve in 30 s — is the replica alive?' };\n }\n log('probe: the stream carries the marker');\n if (o.fault === 'replication') {\n await o.reserve.execute(`alter subscription ${q(o.subscription)} disable`);\n subscriptionOff = true;\n log('TEST: subscription disabled before the hold');\n }\n }\n\n // The reserve's writes home: one pass WITHOUT a hold, so the hold only carries the last seconds.\n // F085.7: the pass under the hold compares only what changed since this one began.\n let horizon: Horizon | undefined;\n if (copyHome) {\n if ((await baselineAt(o.reserve, o.reconcile)) === null) {\n return { outcome: 'refused', reason: 'no baseline from the switch to the reserve — the only way back is discardReserveWrites' };\n }\n horizon = await reserveHorizon(o.reserve);\n const stop = planStopper(await reconcile(o.reserve, o.primary, { apply: true, skipConflicts: o.skipConflicts, ...o.reconcile }), Boolean(o.skipConflicts), log);\n if (stop) return { outcome: 'refused', reason: stop };\n }\n\n // 1. Prepare.\n const prep = await all(o.machines, (m) => m.call('/db/prepare', { target: o.to }));\n log(`prepare: ${JSON.stringify(prep)}`);\n if (prep.some((r) => r.ok !== true)) return abort('a machine could not open the target');\n\n // 2. Hold — a machine not drained in time aborts (an emergency tolerates it:\n // queries against a dead database hang, and they fail on the old side anyway).\n const holdStart = performance.now();\n const hold = await all(o.machines, (m) => m.call('/db/hold', { ms: holdMs }, holdMs + 2000));\n log(`hold: ${JSON.stringify(hold)}`);\n if (hold.some((r) => r.ok !== true)) {\n if (emergency && hold.every((r) => r.status === 200 && r.label !== undefined)) log('hold not drained within the ceiling — continuing (emergency)');\n else return abort('a machine did not drain within the ceiling');\n }\n\n // 3. Marker (not in an emergency) + 4. subscription off + baseline.\n if (toReserve && !emergency) {\n const id = `switch-${randomBytes(6).toString('hex')}`;\n await o.primary.execute({ sql: `insert into ${marker} (\"id\", \"at\") values ($1, $2)`, args: [id, Date.now()] });\n if (!(await arrived(o.reserve, marker, id, holdMs, 20))) return abort('the marker did not reach the reserve within the hold');\n log('marker in the reserve: everything written before the hold is there');\n }\n if (toReserve) {\n if (!subscriptionOff) {\n await o.reserve.execute(`alter subscription ${q(o.subscription)} disable`);\n subscriptionOff = true;\n }\n log('subscription disabled');\n // F085.7: only the INSTANT is fixed under the hold; the rows are read after release.\n try {\n frozen = await freezeBaseline(o.reserve, o.reconcile);\n log('baseline frozen (read after release)');\n } catch (e) {\n if (!emergency) return abort(`the baseline could not be frozen: ${e}`);\n log(`WARNING: no baseline (${e}) — the way back will be discardReserveWrites`);\n }\n }\n if (copyHome) {\n try {\n const stop = planStopper(await reconcile(o.reserve, o.primary, { apply: true, skipConflicts: o.skipConflicts, since: horizon, ...o.reconcile }), Boolean(o.skipConflicts), log);\n if (stop) return abort(stop);\n } catch (e) {\n return abort(`copying home failed: ${e}`);\n }\n }\n\n // 4¼. F085.7: logical replication copies rows, not sequences. The target must\n // not hand out an id it already holds — on the reserve after the switch to it,\n // on the primary after the way home.\n try {\n const seqs = await syncSequences(target);\n if (seqs.length) log(`sequences on ${targetLabel}: ${seqs.length} checked`);\n } catch (e) {\n return abort(`the sequences on ${targetLabel} could not be moved up: ${e}`);\n }\n\n // 4½. Unfence the target — everyone holds, nothing writes yet.\n try {\n await setFence(target, 'open', o.fence);\n targetOpened = true;\n } catch (e) {\n return abort(`${targetLabel} could not be unfenced: ${e}`);\n }\n\n // 5. Point — still holding.\n const point = await all(o.machines, (m) => m.call('/db/point', { target: o.fault === 'point' && m === o.machines[0] ? 'nowhere' : o.to }));\n log(`point: ${JSON.stringify(point)}`);\n if (point.some((r) => r.ok !== true)) return abort('a machine could not point');\n // The new side is what the machines REPORTED at point (all must agree) —\n // not the caller's labels, which could be wrong and turn every switch «unconfirmed».\n const pointed = [...new Set(point.map((r) => r.label))];\n if (pointed.length !== 1 || typeof pointed[0] !== 'string') return abort(`the machines pointed at different sides: ${JSON.stringify(pointed)}`);\n const newLabel = pointed[0];\n\n // 6. Release — retried for a machine that does not answer (its safety net\n // would otherwise send it back while the others are on the new side). A\n // release counts only if the machine answers from the NEW side.\n const ready = (r: MachineAnswer) => r.ok === true && r.label === newLabel;\n let release = await all(o.machines, (m) => m.call('/db/release', {}));\n for (let i = 0; i < 5 && release.some((r) => !ready(r)); i++) {\n await new Promise((r) => setTimeout(r, 200));\n const again = o.machines.filter((m) => !ready(release.find((r) => r.id === m.id)!));\n const answers = await all(again, (m) => m.call('/db/release', {}));\n release = release.map((r) => answers.find((x) => x.id === r.id) ?? r);\n }\n log(`release: ${JSON.stringify(release)}`);\n const heldMs = Math.round(performance.now() - holdStart);\n // Fence the old side — ALSO if a machine did not confirm: one left on the old\n // side is exactly the one that must fail loudly.\n try {\n await within(setFence(old, 'locked', o.fence), 5000, `fence ${oldLabel}`);\n log(`${oldLabel} fenced`);\n } catch (e) {\n log(`WARNING: ${oldLabel} is NOT fenced (${e}) — fence it when it answers`);\n }\n // F085.7: the baseline's rows, read through the snapshot frozen under the hold.\n if (frozen) {\n const f = frozen;\n frozen = null;\n try {\n log(`baseline: ${await f.finish()} rows (read after release)`);\n } catch (e) {\n log(`WARNING: the baseline could not be read (${e}) — the way home will refuse; only discardReserveWrites can bring the app back`);\n }\n }\n if (release.some((r) => !ready(r))) {\n return { outcome: 'unconfirmed', reason: 'a machine did not confirm release on the new side — its safety net sends it back; run status NOW', label: newLabel };\n }\n log(`DONE: every machine on ${newLabel}; queries held for ${heldMs} ms`);\n return { outcome: 'done', label: newLabel, heldMs };\n}\n\nasync function arrived(reserve: Pick<DbClient<Sql>, 'execute'>, marker: string, id: string, ms: number, every: number): Promise<boolean> {\n const end = Date.now() + ms;\n while (Date.now() < end) {\n if ((await reserve.execute({ sql: `select 1 from ${marker} where \"id\" = $1`, args: [id] })).rows.length === 1) return true;\n await new Promise((r) => setTimeout(r, every));\n }\n return false;\n}\n","/**\n * IS THE RESERVE ALIVE? — and who gets woken when it is not (components-F085.5,\n * ported from broberg-id reserve-health.ts F084.114 + reserve-watch.ts F084.204).\n *\n * A reserve can die without anyone seeing it: a dead reserve is nothing in the\n * app's logs, and a failed reserve migration is one log line. A reserve you\n * believe is alive is MORE dangerous than none, because you count on it the day\n * the primary falls. fd-sundhed 28/10 2026: two new columns in production\n * without the reserve, replication stood still for 5 hours, the slot was 128 MB\n * from being dropped.\n *\n * The reading comes from the PRIMARY (its replication slot and the walsender),\n * not from the reserve: if the reserve is down, that is exactly what the answer\n * must say. Serve it on its own route — BID: /health/reserve, NOT /health/ready:\n * a dead reserve must never take logins down.\n *\n * The alarm half is PURE: the app keeps the episode state where it wants (BID:\n * a table, because it runs on two machines) and sends the incidents its own way.\n */\nimport type { Sql } from 'postgres';\nimport type { DbClient } from '../types';\n\nexport interface ReserveThresholds {\n /** No reply from the reserve for this long = stale. BID: 300 (it replies every ~10 s). */\n staleSeconds: number;\n /** This far behind = not catching up. BID: 64 MB (Supabase drops the slot at 512 MB). */\n lagBytes: number;\n}\nexport const RESERVE_DEFAULTS: ReserveThresholds = { staleSeconds: 300, lagBytes: 64 * 1024 * 1024 };\n\nexport interface SlotReading {\n active: boolean;\n walStatus: string | null;\n lagBytes: number | null;\n /** Seconds since the reserve last replied; null = no live connection. */\n replyAgeSeconds: number | null;\n}\n\nexport type ReserveReason = 'missing' | 'inactive' | 'lost' | 'stale' | 'lagging' | 'unreadable';\nexport type ReserveVerdict = { ok: true } | { ok: false; reason: ReserveReason | (string & {}) };\n\nexport function judgeReserve(r: SlotReading | null, t: ReserveThresholds = RESERVE_DEFAULTS): ReserveVerdict {\n if (!r) return { ok: false, reason: 'missing' };\n if (r.walStatus === 'lost') return { ok: false, reason: 'lost' };\n if (!r.active) return { ok: false, reason: 'inactive' };\n if (r.replyAgeSeconds === null || r.replyAgeSeconds > t.staleSeconds) return { ok: false, reason: 'stale' };\n if (r.lagBytes !== null && r.lagBytes > t.lagBytes) return { ok: false, reason: 'lagging' };\n return { ok: true };\n}\n\n/** Read the reserve's slot ON THE PRIMARY. The slot name is the subscription's (BID: bid_reserve). */\nexport async function readReserveSlot(primary: Pick<DbClient<Sql>, 'execute'>, slot: string): Promise<SlotReading | null> {\n const { rows } = await primary.execute({\n sql: `select s.active, s.wal_status,\n pg_wal_lsn_diff(pg_current_wal_lsn(), s.confirmed_flush_lsn)::bigint as lag,\n extract(epoch from now() - r.reply_time)::int as reply_age\n from pg_replication_slots s\n left join pg_stat_replication r on r.application_name = s.slot_name\n where s.slot_name = $1`,\n args: [slot],\n });\n const row = rows[0];\n if (!row) return null;\n const num = (v: unknown) => (v === null || v === undefined ? null : Number(v));\n return { active: row.active === true, walStatus: (row.wal_status as string | null) ?? null, lagBytes: num(row.lag), replyAgeSeconds: num(row.reply_age) };\n}\n\n/** Read + judge in one call; a reading that fails — or does not answer within\n * `timeoutMs` (default 5 s; a hung primary must not hang the health route) —\n * is `unreadable`, never «ok». */\nexport async function reserveHealth(primary: Pick<DbClient<Sql>, 'execute'>, slot: string, t?: ReserveThresholds, timeoutMs = 5000): Promise<ReserveVerdict> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const reading = await Promise.race([\n readReserveSlot(primary, slot),\n new Promise<never>((_, j) => (timer = setTimeout(() => j(new Error('timeout')), timeoutMs))),\n ]);\n return judgeReserve(reading, t);\n } catch {\n return { ok: false, reason: 'unreadable' };\n } finally {\n clearTimeout(timer);\n }\n}\n\n// ── THE ALARM HOOK ──────────────────────────────────────────────────────────\n\n/** Unhealthy this long in a row → one incident per episode. A blink sends nothing. BID: 10 min. */\nexport const RESERVE_ALARM_AFTER_MS = 10 * 60 * 1000;\nexport const MIGRATION_FAILED = 'migration_failed';\n\n/** The app persists this between rounds (BID: rows in its reserveWatch table). */\nexport interface ReserveWatchState {\n slot?: { reason: string; firstSeenAt: number };\n migrationFailed?: { firstSeenAt: number; detail: string };\n}\n\nexport interface ReserveIncident {\n /** Carries the episode's start, so «sent once per id» gives one alarm per episode and a new one for a new episode. */\n id: string;\n reason: string;\n severity: 'critical' | 'high';\n openedAt: string;\n detail: string | null;\n}\n\n/** The reserve migration's outcome on a deploy → state. Failure alarms at once\n * (it does not fix itself). `skipped` (no reserve configured on this deploy)\n * leaves the state untouched — it must never clear a pending migration_failed. */\nexport function noteReserveMigration(\n state: ReserveWatchState,\n outcome: { ok: true } | { ok: false; reason: string } | { skipped: true },\n now = Date.now(),\n): ReserveWatchState {\n if ('skipped' in outcome) return state;\n if (outcome.ok) {\n const { migrationFailed: _, ...rest } = state;\n return rest;\n }\n return { ...state, migrationFailed: { firstSeenAt: now, detail: outcome.reason.slice(0, 500) } };\n}\n\n/** One alarm round: the next state from `verdict`, and the incidents to send. */\nexport function watchReserve(\n state: ReserveWatchState,\n verdict: ReserveVerdict,\n now = Date.now(),\n alarmAfterMs = RESERVE_ALARM_AFTER_MS,\n): { state: ReserveWatchState; incidents: ReserveIncident[] } {\n const next: ReserveWatchState = { ...state };\n const incidents: ReserveIncident[] = [];\n if (verdict.ok) delete next.slot;\n else {\n // The same reason continues the episode; a different reason starts a new one.\n if (next.slot?.reason !== verdict.reason) next.slot = { reason: verdict.reason, firstSeenAt: now };\n if (now - next.slot.firstSeenAt >= alarmAfterMs) incidents.push(incident(next.slot.reason, next.slot.firstSeenAt, null));\n }\n if (next.migrationFailed) incidents.push(incident(MIGRATION_FAILED, next.migrationFailed.firstSeenAt, next.migrationFailed.detail));\n return { state: next, incidents };\n}\n\nconst incident = (reason: string, first: number, detail: string | null): ReserveIncident => ({\n id: `reserve:${reason}:${first}`,\n reason,\n severity: reason === 'lost' || reason === MIGRATION_FAILED ? 'critical' : 'high',\n openedAt: new Date(first).toISOString(),\n detail,\n});\n","/**\n * THE RESERVE RECONNECTS ITSELF (components-F085.5, ported from broberg-id\n * reserve-ip-guard.ts, F084.172/.174/.197/.238).\n *\n * 18/10 2026 UpCloud's Sunday maintenance replaced the reserve node and it got\n * a new public address. Supabase only lets known addresses in, so the slot sat\n * inactive for ~6 hours until a human fixed the list. At ~512 MB behind,\n * Supabase drops the slot and the reserve must be copied from scratch.\n *\n * Run it from CI (BID: .github/workflows/reserve-ip-guard.yml — the workflow is\n * in the Discovery playbook), NOT in the app: the Supabase token is account-wide.\n *\n * 1. reserve healthy → stop. No call to Supabase.\n * 2. inactive/stale/lost → the reserve's public host from UpCloud's API; its\n * address from DNS (BID measured: = the address the reserve calls from).\n * 3. Missing from dbAllowedCidrs → ADD it. The guard never removes anything:\n * an address it believes is old may be another machine's. Addresses that\n * are neither fixed nor the reserve's are logged for clean-up.\n * 4. Wait for the slot to become active. If it does not → a red run.\n *\n * `runGuard` is pure (its world comes in as `GuardDeps`); `liveDeps` is the\n * UpCloud + Supabase implementation. Another pair of providers is another deps.\n */\nimport { lookup } from \"node:dns/promises\";\n\nexport type Restrictions = { dbAllowedCidrs: string[]; dbAllowedCidrsV6: string[] };\n\nexport interface GuardDeps {\n reserveHealth(): Promise<{ ok: boolean; reason?: string }>;\n upcloudPublicHost(): Promise<string>;\n resolve(host: string): Promise<string>;\n getRestrictions(): Promise<Restrictions & { status: string }>;\n applyRestrictions(r: Restrictions): Promise<void>;\n sleep(ms: number): Promise<void>;\n log(line: string): void;\n}\n\nexport interface GuardOptions {\n /** Known fixed v4 addresses (e.g. Fly egress, office) — only for the clean-up note. */\n fixedV4: string[];\n /** How long to wait for an active slot after a fix. */\n waitMs: number;\n pollMs: number;\n /** How long to read back before a list that did not take effect is an error (BID F084.174). */\n readBackMs: number;\n /** BID F084.197 — an unhealthy slot is measured again after this long before acting. A blink is not a state. */\n confirmMs: number;\n}\n\nexport type GuardResult =\n | { outcome: \"healthy\" }\n | { outcome: \"not-network\"; reason: string }\n | { outcome: \"already-allowed\"; ip: string }\n | { outcome: \"fixed\"; ip: string }\n | { outcome: \"still-down\"; ip: string; reason: string }\n /** BID F084.238 — the slot is lost. The address is fixed (or was fine); the reserve must be rebuilt. */\n | { outcome: \"needs-rebuild\"; ip: string; added: boolean };\n\n/** Reasons an unknown address can cause. `lagging` is not the network. */\nconst NETWORK_REASONS = new Set([\"inactive\", \"stale\"]);\n/**\n * BID F084.238 — a LOST slot can also come from a new address: 15/11 2026\n * UpCloud's maintenance gave the reserve a new address at ~05:20, the guard ran\n * at 11:38, and by then the slot was «lost». The network was still closed, so a\n * rebuild failed until the address was on the list. So the address is fixed\n * here too — but a lost slot does not come back by itself, so the outcome is\n * «needs-rebuild», not «fixed».\n */\nconst LOST = \"lost\";\n\nexport async function runGuard(d: GuardDeps, o: GuardOptions): Promise<GuardResult> {\n let health = await d.reserveHealth();\n // BID F084.197 — fd-sundhed measured a slot unhealthy for a moment and healthy\n // 40 s later. Without a second reading it became a red run and an alarm.\n if (!health.ok) {\n await d.sleep(o.confirmMs);\n health = await d.reserveHealth();\n }\n if (health.ok) return { outcome: \"healthy\" };\n const reason = health.reason ?? \"unknown\";\n if (!NETWORK_REASONS.has(reason) && reason !== LOST) return { outcome: \"not-network\", reason };\n\n const ip = await d.resolve(await d.upcloudPublicHost());\n const cidr = `${ip}/32`;\n const before = await d.getRestrictions();\n const unknown = before.dbAllowedCidrs.filter((c) => c !== cidr && !o.fixedV4.includes(c));\n if (unknown.length) d.log(`to clean up (neither fixed nor the reserve's current): ${unknown.join(\", \")}`);\n if (before.dbAllowedCidrs.includes(cidr)) {\n return reason === LOST ? { outcome: \"needs-rebuild\", ip, added: false } : { outcome: \"already-allowed\", ip };\n }\n\n const next: Restrictions = { dbAllowedCidrs: [...before.dbAllowedCidrs, cidr], dbAllowedCidrsV6: before.dbAllowedCidrsV6 };\n await d.applyRestrictions(next);\n // Supabase shows the new list only after a while (BID measured 19/10: old\n // after 5 s, new within 20 s) — so read back, and throw only when the window is spent.\n const expected = JSON.stringify(next);\n let read = \"\";\n for (let t = 0; ; t += o.pollMs) {\n const after = await d.getRestrictions();\n read = JSON.stringify({ dbAllowedCidrs: after.dbAllowedCidrs, dbAllowedCidrsV6: after.dbAllowedCidrsV6 });\n if (read === expected) break;\n if (t >= o.readBackMs) throw new Error(`the list did not become what was sent: expected ${expected}, read ${read}`);\n await d.sleep(o.pollMs);\n }\n d.log(`added ${cidr}`);\n if (reason === LOST) return { outcome: \"needs-rebuild\", ip, added: true };\n\n let last = reason;\n for (let t = 0; t < o.waitMs; t += o.pollMs) {\n await d.sleep(o.pollMs);\n const h = await d.reserveHealth();\n if (h.ok) return { outcome: \"fixed\", ip };\n last = h.reason ?? \"unknown\";\n }\n return { outcome: \"still-down\", ip, reason: last };\n}\n\n/** The real APIs (UpCloud Managed Postgres as the reserve, Supabase as the primary).\n * The keys come from the environment and are never logged. */\nexport function liveDeps(env: {\n healthUrl: string;\n upcloudToken: string;\n upcloudDbUuid: string;\n supabaseToken: string;\n supabaseRef: string;\n}): GuardDeps {\n const sb = `https://api.supabase.com/v1/projects/${env.supabaseRef}/network-restrictions`;\n const sbHeaders = { authorization: `Bearer ${env.supabaseToken}`, \"content-type\": \"application/json\" };\n const ok = async (res: Response, what: string) => {\n if (!res.ok) throw new Error(`${what}: HTTP ${res.status} ${(await res.text()).slice(0, 200)}`);\n return res;\n };\n return {\n async reserveHealth() {\n // BID F084.197 — a 502 or a page that is not JSON (e.g. mid-deploy) is an\n // answer, not a crash: «unreachable» is confirmed like anything else.\n try {\n const res = await fetch(env.healthUrl);\n const body = (await res.json()) as { ok?: boolean; reason?: string };\n return { ok: res.status === 200 && body.ok === true, reason: body.reason };\n } catch {\n return { ok: false, reason: \"unreachable\" };\n }\n },\n async upcloudPublicHost() {\n const res = await ok(\n await fetch(`https://api.upcloud.com/1.3/database/${env.upcloudDbUuid}`, {\n headers: { authorization: `Bearer ${env.upcloudToken}` },\n }),\n \"UpCloud\",\n );\n const db = (await res.json()) as { components?: { component: string; route: string; host: string }[] };\n const host = db.components?.find((c) => c.component === \"pg\" && c.route === \"public\")?.host;\n if (!host) throw new Error(\"UpCloud: no public pg host\");\n return host;\n },\n async resolve(host) {\n return (await lookup(host, { family: 4 })).address;\n },\n async getRestrictions() {\n const res = await ok(await fetch(sb, { headers: sbHeaders }), \"Supabase GET\");\n const b = (await res.json()) as { status: string; config: Restrictions };\n return { status: b.status, dbAllowedCidrs: b.config.dbAllowedCidrs ?? [], dbAllowedCidrsV6: b.config.dbAllowedCidrsV6 ?? [] };\n },\n async applyRestrictions(r) {\n await ok(await fetch(`${sb}/apply`, { method: \"POST\", headers: sbHeaders, body: JSON.stringify(r) }), \"Supabase apply\");\n },\n sleep: (ms) => new Promise((r) => setTimeout(r, ms)),\n log: (l) => console.log(l),\n };\n}\n"],"mappings":";;;;;;;AA2FA,IAAM,cAAc;AAEpB,IAAM,UAAU,CAAC,MAAoC;AACnD,QAAMA,KAAI;AACV,SACE,aAAa,WACb,OAAOA,GAAE,YAAY,cACrB,OAAOA,GAAE,cAAc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,IAAI,CAAC;AAAA,EAC3B;AACF;","names":["q","label","q","lit","opts","table","toResult","sides","body","body","q","body"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@broberg/db-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Thin shared database client for the broberg.ai fleet — one DbClient facade over libSQL/Turso and PostgreSQL (postgres.js or pg), plus /switchable: BID's instant primary↔reserve switch (fence, way back, per-machine control, orchestration, reserve health, IP guard). The SQL dialect is passed through, not translated.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "FSL-1.1-Apache-2.0",
|