@broberg/db-sdk 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,965 @@
1
+ // src/switchable/switchable.ts
2
+ var UNSUPPORTED = "@broberg/db-sdk/switchable: this postgres.js version does not have the Query internals the switch routes .raw by (3.4.x) \u2014 refusing rather than running on the wrong database";
3
+ var isQuery = (x) => {
4
+ const q4 = x;
5
+ return x instanceof Promise && typeof q4.handler === "function" && typeof q4.canceller === "function" && typeof q4.resolve === "function" && typeof q4.reject === "function" && typeof q4.handle === "function" && q4.executed === false;
6
+ };
7
+ var sides = /* @__PURE__ */ new WeakMap();
8
+ function sideOf(sql) {
9
+ let side = sides.get(sql);
10
+ if (!side) {
11
+ const probe = sql.unsafe("");
12
+ if (!isQuery(probe)) throw new Error(UNSUPPORTED);
13
+ side = { handler: probe.handler, canceller: probe.canceller };
14
+ sides.set(sql, side);
15
+ }
16
+ return side;
17
+ }
18
+ var UNSUPPORTED_RAW = "@broberg/db-sdk/switchable: .raw is neither postgres.js nor a pg.Pool \u2014 refusing rather than running unrouted";
19
+ function kindOf(raw) {
20
+ if (typeof raw === "function") {
21
+ sideOf(raw);
22
+ return "postgresjs";
23
+ }
24
+ const pool = raw;
25
+ if (pool && typeof pool.connect === "function" && typeof pool.query === "function" && typeof pool.on === "function") return "pg";
26
+ throw new Error(UNSUPPORTED_RAW);
27
+ }
28
+ function createSwitchable(initial, label) {
29
+ if (initial.transport !== "postgres") throw new Error("@broberg/db-sdk/switchable: Postgres only");
30
+ const kind = kindOf(initial.raw);
31
+ let active = initial;
32
+ let name = label;
33
+ let gate = null;
34
+ let open = null;
35
+ let running = 0;
36
+ let idle = [];
37
+ const enter = async () => {
38
+ while (gate) await gate;
39
+ running++;
40
+ };
41
+ const exit = () => {
42
+ running--;
43
+ if (running === 0) for (const f of idle.splice(0)) f();
44
+ };
45
+ const guarded = async (fn) => {
46
+ await enter();
47
+ try {
48
+ return await fn();
49
+ } finally {
50
+ exit();
51
+ }
52
+ };
53
+ const route = (q4) => {
54
+ if (!(q4 instanceof Promise)) return q4;
55
+ if (!isQuery(q4)) throw new Error(UNSUPPORTED);
56
+ q4.handle = async function() {
57
+ if (this.executed) return;
58
+ this.executed = true;
59
+ await enter();
60
+ let done = false;
61
+ const finish = () => {
62
+ if (!done) {
63
+ done = true;
64
+ exit();
65
+ }
66
+ };
67
+ for (const key of ["resolve", "reject"]) {
68
+ let fn = this[key];
69
+ Object.defineProperty(this, key, {
70
+ configurable: true,
71
+ get: () => (x) => {
72
+ finish();
73
+ return fn(x);
74
+ },
75
+ set: (v) => {
76
+ fn = v;
77
+ }
78
+ });
79
+ }
80
+ const side = sideOf(active.raw);
81
+ this.handler = side.handler;
82
+ if (this.canceller) this.canceller = side.canceller;
83
+ this.handler(this);
84
+ };
85
+ return q4;
86
+ };
87
+ const listeners = [];
88
+ const withListeners = /* @__PURE__ */ new WeakSet();
89
+ if (kind === "pg") withListeners.add(initial.raw);
90
+ const attach = (pool) => {
91
+ if (withListeners.has(pool)) return;
92
+ for (const [ev, fn] of listeners) pool.on(ev, fn);
93
+ withListeners.add(pool);
94
+ };
95
+ const callbackStyle = (a) => typeof a[a.length - 1] === "function";
96
+ const pgRaw = new Proxy({}, {
97
+ get(_t, prop) {
98
+ const pool = active.raw;
99
+ if (prop === "query") {
100
+ return (...a) => {
101
+ if (callbackStyle(a)) throw new Error("@broberg/db-sdk/switchable: callback-style pool.query is not routed \u2014 use the promise form");
102
+ return guarded(() => active.raw.query(...a));
103
+ };
104
+ }
105
+ if (prop === "connect") {
106
+ return async (...a) => {
107
+ if (callbackStyle(a)) throw new Error("@broberg/db-sdk/switchable: callback-style pool.connect is not routed \u2014 use the promise form");
108
+ await enter();
109
+ let client;
110
+ try {
111
+ client = await active.raw.connect();
112
+ } catch (err) {
113
+ exit();
114
+ throw err;
115
+ }
116
+ const release = client.release.bind(client);
117
+ let released = false;
118
+ client.release = ((err) => {
119
+ if (!released) {
120
+ released = true;
121
+ exit();
122
+ }
123
+ return release(err);
124
+ });
125
+ return client;
126
+ };
127
+ }
128
+ if (prop === "on") {
129
+ return (ev, fn) => {
130
+ listeners.push([ev, fn]);
131
+ active.raw.on(ev, fn);
132
+ return pgRaw;
133
+ };
134
+ }
135
+ if (prop === "end") return () => active.raw.ended ? Promise.resolve() : active.raw.end();
136
+ const v = pool[prop];
137
+ return typeof v === "function" ? v.bind(pool) : v;
138
+ }
139
+ });
140
+ const pjsRaw = new Proxy(function() {
141
+ }, {
142
+ apply(_t, _this, args) {
143
+ return route(active.raw(...args));
144
+ },
145
+ get(_t, prop) {
146
+ const sql = active.raw;
147
+ if (prop === "unsafe" || prop === "file") {
148
+ return (...a) => route(active.raw[prop](...a));
149
+ }
150
+ if (prop === "begin" || prop === "notify" || prop === "largeObject") {
151
+ return (...a) => guarded(() => {
152
+ const side = active.raw;
153
+ return side[prop].apply(active.raw, a);
154
+ });
155
+ }
156
+ if (prop === "reserve") {
157
+ return async () => {
158
+ await enter();
159
+ let reserved;
160
+ try {
161
+ reserved = await active.raw.reserve();
162
+ } catch (err) {
163
+ exit();
164
+ throw err;
165
+ }
166
+ const release = reserved.release.bind(reserved);
167
+ let released = false;
168
+ reserved.release = () => {
169
+ if (!released) {
170
+ released = true;
171
+ exit();
172
+ }
173
+ release();
174
+ };
175
+ return reserved;
176
+ };
177
+ }
178
+ const v = sql[prop];
179
+ return typeof v === "function" ? v.bind(active.raw) : v;
180
+ }
181
+ });
182
+ const self = {
183
+ transport: "postgres",
184
+ raw: kind === "pg" ? pgRaw : pjsRaw,
185
+ get label() {
186
+ return name;
187
+ },
188
+ get holding() {
189
+ return gate !== null;
190
+ },
191
+ get inFlight() {
192
+ return running;
193
+ },
194
+ get current() {
195
+ return active;
196
+ },
197
+ execute(stmt) {
198
+ return guarded(() => active.execute(stmt));
199
+ },
200
+ batch(stmts, mode) {
201
+ return guarded(() => active.batch(stmts, mode));
202
+ },
203
+ /** Closes the side pointed at. Sides switched away from are the caller's to close. */
204
+ close() {
205
+ return active.close();
206
+ },
207
+ async hold(ms) {
208
+ if (!gate) gate = new Promise((r) => open = r);
209
+ if (running === 0) return { ok: true, inFlight: 0 };
210
+ const empty = new Promise((r) => idle.push(() => r("empty")));
211
+ let timer;
212
+ const late = new Promise((r) => timer = setTimeout(() => r("late"), ms));
213
+ const outcome = await Promise.race([empty, late]);
214
+ clearTimeout(timer);
215
+ return { ok: outcome === "empty", inFlight: running };
216
+ },
217
+ point(client, label2) {
218
+ if (client.transport !== "postgres") throw new Error("@broberg/db-sdk/switchable: Postgres only");
219
+ if (kindOf(client.raw) !== kind) throw new Error(`@broberg/db-sdk/switchable: cannot point a ${kind} client at a ${kindOf(client.raw)} one`);
220
+ if (kind === "pg") attach(client.raw);
221
+ const old = active;
222
+ active = client;
223
+ name = label2;
224
+ return old;
225
+ },
226
+ switchTo(client, label2) {
227
+ const old = self.point(client, label2);
228
+ self.release();
229
+ return old;
230
+ },
231
+ release() {
232
+ const f = open;
233
+ gate = null;
234
+ open = null;
235
+ f?.();
236
+ }
237
+ };
238
+ return self;
239
+ }
240
+
241
+ // src/switchable/fence.ts
242
+ var FENCE_DEFAULTS = { name: "dbFence", bypass: "db_sdk.fence_bypass" };
243
+ var FENCE_ERRCODE = "25006";
244
+ var q = (name) => `"${name.replace(/"/g, '""')}"`;
245
+ var lit = (s) => `'${s.replace(/'/g, "''")}'`;
246
+ var opts = (o) => ({ ...FENCE_DEFAULTS, ...o });
247
+ var body = (state, bypass) => state === "open" ? `begin return null; end` : `begin
248
+ if current_setting(${lit(bypass)}, true) = 'on' then return null; end if;
249
+ raise exception 'db-sdk fence: this database is not the active one \u2014 the write is refused' using errcode = '${FENCE_ERRCODE}';
250
+ end`;
251
+ async function fenceState(db, o) {
252
+ const { name } = opts(o);
253
+ const { rows } = await db.execute({
254
+ sql: `select p.prosrc as src from pg_proc p where p.proname = $1 and p.pronamespace = current_schema()::regnamespace`,
255
+ args: [name]
256
+ });
257
+ if (rows.length === 0) return "missing";
258
+ return String(rows[0].src).includes("raise exception") ? "locked" : "open";
259
+ }
260
+ async function setFence(db, state, o) {
261
+ const { name, bypass } = opts(o);
262
+ await db.execute(`create or replace function ${q(name)}() returns trigger language plpgsql as $fence$ ${body(state, bypass)} $fence$`);
263
+ }
264
+ async function installFence(db, initial, o) {
265
+ const { name } = opts(o);
266
+ const created = await fenceState(db, o) === "missing";
267
+ if (created) await setFence(db, initial, o);
268
+ const missing = await unfencedTables(db, o);
269
+ for (const table of missing) {
270
+ await db.execute(`create trigger ${q(name)} before insert or update or delete on ${q(table)} for each statement execute function ${q(name)}()`);
271
+ }
272
+ return { created, triggered: missing };
273
+ }
274
+ async function unfencedTables(db, o) {
275
+ const { name } = opts(o);
276
+ const { rows } = await db.execute({
277
+ sql: `select c.relname as name from pg_class c
278
+ where c.relnamespace = current_schema()::regnamespace and c.relkind = 'r'
279
+ and not exists (select 1 from pg_trigger t where t.tgrelid = c.oid and t.tgname = $1)
280
+ order by 1`,
281
+ args: [name]
282
+ });
283
+ return rows.map((r) => String(r.name));
284
+ }
285
+
286
+ // src/switchable/reconcile.ts
287
+ var RECONCILE_DEFAULTS = { schema: "dbSwitch", bypass: FENCE_DEFAULTS.bypass };
288
+ var SEP = "";
289
+ var q2 = (name) => `"${name.replace(/"/g, '""')}"`;
290
+ var lit2 = (s) => `'${s.replace(/'/g, "''")}'`;
291
+ var UTC = `set local time zone 'UTC'`;
292
+ var baselineTable = (o) => `${q2({ ...RECONCILE_DEFAULTS, ...o }.schema)}."baseline"`;
293
+ async function tables(db) {
294
+ const { rows } = await db.execute(
295
+ `select c.relname as name,
296
+ (select array_agg(a.attname::text order by array_position(i.indkey::int2[], a.attnum))
297
+ from pg_index i join pg_attribute a on a.attrelid = i.indrelid and a.attnum = any(i.indkey)
298
+ where i.indrelid = c.oid and i.indisprimary) as pk,
299
+ (select array_agg(a.attname::text order by a.attnum) from pg_attribute a
300
+ where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped) as cols
301
+ from pg_class c
302
+ where c.relnamespace = current_schema()::regnamespace and c.relkind = 'r'
303
+ order by 1`
304
+ );
305
+ return rows.map((r) => ({ name: String(r.name), pk: r.pk ?? [], cols: r.cols }));
306
+ }
307
+ async function fingerprints(db, tabs) {
308
+ const out = /* @__PURE__ */ new Map();
309
+ if (tabs.length === 0) return out;
310
+ const parts = tabs.map((t) => {
311
+ const key = t.pk.length ? `jsonb_build_array(${t.pk.map((c) => `x.${q2(c)}`).join(", ")})::text` : `md5(to_jsonb(x)::text)`;
312
+ return `select ${lit2(t.name)} as t, ${key} as k, md5(to_jsonb(x)::text) as h from ${q2(t.name)} x`;
313
+ });
314
+ const [, res] = await db.batch([UTC, parts.join(" union all ") + " order by 1, 2"]);
315
+ const seen = /* @__PURE__ */ new Map();
316
+ const noPk = new Set(tabs.filter((t) => !t.pk.length).map((t) => t.name));
317
+ for (const r of res.rows) {
318
+ const t = String(r.t);
319
+ let k = String(r.k);
320
+ if (noPk.has(t)) {
321
+ const n = (seen.get(`${t}${SEP}${k}`) ?? 0) + 1;
322
+ seen.set(`${t}${SEP}${k}`, n);
323
+ k = `${k}#${n}`;
324
+ }
325
+ out.set(`${t}${SEP}${k}`, String(r.h));
326
+ }
327
+ return out;
328
+ }
329
+ async function captureBaseline(reserve, o) {
330
+ const { schema } = { ...RECONCILE_DEFAULTS, ...o };
331
+ const rows = await fingerprints(reserve, await tables(reserve));
332
+ const keys = [...rows.keys()];
333
+ const table = baselineTable(o);
334
+ await reserve.batch([
335
+ `create schema if not exists ${q2(schema)}`,
336
+ `drop table if exists ${table}`,
337
+ `create table ${table} ("key" text primary key, "h" text not null, "at" bigint not null)`,
338
+ {
339
+ sql: `insert into ${table} ("key", "h", "at") select k, h, $3 from unnest($1::text[], $2::text[]) as u(k, h)`,
340
+ args: [keys, keys.map((k) => rows.get(k)), Date.now()]
341
+ }
342
+ ]);
343
+ return rows.size;
344
+ }
345
+ async function baselineAt(reserve, o) {
346
+ const table = baselineTable(o);
347
+ const exists = await reserve.execute({ sql: `select to_regclass($1) is not null as e`, args: [table] });
348
+ if (exists.rows[0]?.e !== true) return null;
349
+ const { rows } = await reserve.execute(`select max("at")::text as at from ${table}`);
350
+ const at = rows[0]?.at;
351
+ return at ? Number(at) : null;
352
+ }
353
+ async function readBaseline(reserve, o) {
354
+ const { rows } = await reserve.execute(`select "key", "h" from ${baselineTable(o)}`);
355
+ return new Map(rows.map((r) => [String(r.key), String(r.h)]));
356
+ }
357
+ async function reconcile(reserve, primary, opts2) {
358
+ const { bypass } = { ...RECONCILE_DEFAULTS, ...opts2 };
359
+ const [rt, pt] = await Promise.all([tables(reserve), tables(primary)]);
360
+ const pByName = new Map(pt.map((t) => [t.name, t]));
361
+ const sameCols = (a, b) => a.cols.slice().sort().join() === b.cols.slice().sort().join();
362
+ const schemaMismatch = [
363
+ ...rt.filter((t) => !pByName.has(t.name) || !sameCols(pByName.get(t.name), t)).map((t) => t.name),
364
+ ...pt.filter((t) => !rt.some((r) => r.name === t.name)).map((t) => t.name)
365
+ ];
366
+ if (schemaMismatch.length) return { upserts: 0, deletes: 0, conflicts: [], schemaMismatch, written: 0 };
367
+ const [R, P, B] = await Promise.all([fingerprints(reserve, rt), fingerprints(primary, pt), readBaseline(reserve, opts2)]);
368
+ const conflicts = [];
369
+ const copies = [];
370
+ for (const k of /* @__PURE__ */ new Set([...R.keys(), ...P.keys()])) {
371
+ const r = R.get(k) ?? null;
372
+ const p = P.get(k) ?? null;
373
+ if (r === p) continue;
374
+ const b = B.get(k) ?? null;
375
+ const [table2, key] = k.split(SEP);
376
+ if (p === b) copies.push({ table: table2, key, h: r, p });
377
+ else conflicts.push({ table: table2, key, reserve: r, primary: p, baseline: b });
378
+ }
379
+ const plan = {
380
+ upserts: copies.filter((x) => x.h !== null).length,
381
+ deletes: copies.filter((x) => x.h === null).length,
382
+ conflicts,
383
+ schemaMismatch,
384
+ written: 0
385
+ };
386
+ if (!opts2.apply || copies.length === 0 || conflicts.length && !opts2.skipConflicts) return plan;
387
+ const order = await fkOrder(primary, rt.map((t) => t.name));
388
+ const byName = new Map(rt.map((t) => [t.name, t]));
389
+ const rowsByH = /* @__PURE__ */ new Map();
390
+ const upserts = group(copies.filter((x) => x.h !== null));
391
+ const reads = [UTC];
392
+ const readTables = [];
393
+ for (const [table2, grp] of upserts) {
394
+ reads.push({
395
+ sql: `select md5(to_jsonb(x)::text) as h, to_jsonb(x)::text as j from ${q2(table2)} x where md5(to_jsonb(x)::text) = any($1::text[])`,
396
+ args: [grp.map((x) => x.h)]
397
+ });
398
+ readTables.push(table2);
399
+ }
400
+ if (readTables.length) {
401
+ const res = await reserve.batch(reads);
402
+ readTables.forEach((table2, i) => {
403
+ for (const r of res[i + 1].rows) rowsByH.set(`${table2}${SEP}${String(r.h)}`, String(r.j));
404
+ });
405
+ }
406
+ const writes = [UTC, { sql: `select set_config($1, 'on', true)`, args: [bypass] }];
407
+ const meaning = [null, null];
408
+ const deletes = group(copies.filter((x) => x.h === null));
409
+ for (const table2 of [...order].reverse()) {
410
+ for (const x of deletes.get(table2) ?? []) {
411
+ writes.push({
412
+ sql: `delete from ${q2(table2)} where ctid = (select ctid from ${q2(table2)} x where md5(to_jsonb(x)::text) = $1 limit 1)`,
413
+ args: [x.p]
414
+ });
415
+ meaning.push({ key: `${table2}${SEP}${x.key}`, h: null, counted: "rowcount" });
416
+ }
417
+ }
418
+ for (const table2 of order) {
419
+ const t = byName.get(table2);
420
+ const set = t.cols.filter((col) => !t.pk.includes(col));
421
+ const onConflict = t.pk.length ? `on conflict (${t.pk.map(q2).join(", ")}) do ${set.length ? `update set ${set.map((col) => `${q2(col)} = excluded.${q2(col)}`).join(", ")}` : "nothing"}` : "";
422
+ for (const x of upserts.get(table2) ?? []) {
423
+ const j = rowsByH.get(`${table2}${SEP}${x.h}`);
424
+ if (j === void 0) continue;
425
+ writes.push({
426
+ sql: `insert into ${q2(table2)} select * from jsonb_populate_record(null::${q2(table2)}, $1::text::jsonb) ${onConflict}`,
427
+ args: [j]
428
+ });
429
+ meaning.push({ key: `${table2}${SEP}${x.key}`, h: x.h, counted: "always" });
430
+ }
431
+ }
432
+ const results = await primary.batch(writes);
433
+ const written = [];
434
+ meaning.forEach((m, i) => {
435
+ if (m && (m.counted === "always" || results[i].rowsAffected === 1)) written.push({ key: m.key, h: m.h });
436
+ });
437
+ const table = baselineTable(opts2);
438
+ const ins = written.filter((x) => x.h !== null);
439
+ await reserve.batch([
440
+ {
441
+ sql: `insert into ${table} ("key", "h", "at") select k, h, $3 from unnest($1::text[], $2::text[]) as u(k, h)
442
+ on conflict ("key") do update set "h" = excluded."h"`,
443
+ args: [ins.map((x) => x.key), ins.map((x) => x.h), Date.now()]
444
+ },
445
+ { sql: `delete from ${table} where "key" = any($1::text[])`, args: [written.filter((x) => x.h === null).map((x) => x.key)] }
446
+ ]);
447
+ return { ...plan, written: written.length };
448
+ }
449
+ function group(xs) {
450
+ const m = /* @__PURE__ */ new Map();
451
+ for (const x of xs) m.set(x.table, [...m.get(x.table) ?? [], x]);
452
+ return m;
453
+ }
454
+ async function fkOrder(db, names) {
455
+ const { rows } = await db.execute(
456
+ `select c.relname as child, p.relname as parent from pg_constraint k
457
+ join pg_class c on c.oid = k.conrelid join pg_class p on p.oid = k.confrelid
458
+ where k.contype = 'f' and k.connamespace = current_schema()::regnamespace and c.oid <> p.oid`
459
+ );
460
+ const out = [];
461
+ const done = /* @__PURE__ */ new Set();
462
+ const visit = (n, path) => {
463
+ if (done.has(n) || path.has(n)) return;
464
+ path.add(n);
465
+ for (const r of rows) if (r.child === n) visit(String(r.parent), path);
466
+ done.add(n);
467
+ out.push(n);
468
+ };
469
+ for (const n of names) visit(n, /* @__PURE__ */ new Set());
470
+ return out.filter((n) => names.includes(n));
471
+ }
472
+
473
+ // src/switchable/control.ts
474
+ import { createHmac, timingSafeEqual } from "crypto";
475
+ var HOLD_MIN_MS = 100;
476
+ var HOLD_MAX_MS = 1e4;
477
+ var HOLD_DEFAULT_MS = 3e3;
478
+ function switchToken(secret, context = "db-switch") {
479
+ return createHmac("sha256", secret).update(context).digest("hex");
480
+ }
481
+ function createSwitchControl(o) {
482
+ const { switchable } = o;
483
+ const log = o.log ?? { info: (m) => console.log(m), error: (m) => console.error(m) };
484
+ const token = Buffer.from(switchToken(o.secret, o.context));
485
+ const sides2 = /* @__PURE__ */ new Map([[switchable.label, switchable.current]]);
486
+ let safetyNet = null;
487
+ let beforeHold = null;
488
+ const authorized = (req) => {
489
+ const h = req.headers.get("authorization") ?? "";
490
+ const b = Buffer.from(h.startsWith("Bearer ") ? h.slice(7) : "");
491
+ return b.length === token.length && timingSafeEqual(b, token);
492
+ };
493
+ const json = (data, status = 200) => Response.json(data, { status });
494
+ const disarm = () => {
495
+ if (safetyNet) clearTimeout(safetyNet);
496
+ safetyNet = null;
497
+ };
498
+ const abort = () => {
499
+ disarm();
500
+ if (beforeHold) switchable.point(beforeHold.client, beforeHold.label);
501
+ beforeHold = null;
502
+ switchable.release();
503
+ };
504
+ const isTarget = (t) => t === "primary" || t === "reserve";
505
+ return async (req) => {
506
+ if (!authorized(req)) return json({ error: "unauthorized" }, 401);
507
+ const path = new URL(req.url).pathname;
508
+ const body2 = req.method === "POST" ? await req.json().catch(() => ({})) : {};
509
+ try {
510
+ if (path === "/db/status") return json({ label: switchable.label, holding: switchable.holding, inFlight: switchable.inFlight });
511
+ if (path === "/db/prepare") {
512
+ if (!isTarget(body2.target)) return json({ error: "target" }, 400);
513
+ const spec = o.targets[body2.target];
514
+ const client = sides2.get(spec.label) ?? spec.open();
515
+ await client.execute("select 1");
516
+ sides2.set(spec.label, client);
517
+ return json({ ok: true, label: spec.label });
518
+ }
519
+ if (path === "/db/hold") {
520
+ const ms = Math.min(Math.max(Number(body2.ms) || HOLD_DEFAULT_MS, HOLD_MIN_MS), HOLD_MAX_MS);
521
+ if (!switchable.holding) beforeHold = { client: switchable.current, label: switchable.label };
522
+ const r = await switchable.hold(ms);
523
+ disarm();
524
+ safetyNet = setTimeout(() => {
525
+ abort();
526
+ log.error(`[db-switch] safety net: the orchestrator did not answer \u2014 continuing on ${switchable.label}`);
527
+ }, ms * 2);
528
+ return json({ ...r, label: switchable.label });
529
+ }
530
+ if (path === "/db/point") {
531
+ if (!isTarget(body2.target)) return json({ error: "target" }, 400);
532
+ if (!switchable.holding) return json({ error: "not_holding" }, 409);
533
+ const label = o.targets[body2.target].label;
534
+ const client = sides2.get(label);
535
+ if (!client) return json({ error: "not_prepared", label }, 409);
536
+ switchable.point(client, label);
537
+ return json({ ok: true, label });
538
+ }
539
+ if (path === "/db/release") {
540
+ disarm();
541
+ const moved = beforeHold !== null && beforeHold.label !== switchable.label;
542
+ beforeHold = null;
543
+ switchable.release();
544
+ if (moved) log.info(`[db-switch] now on ${switchable.label}`);
545
+ return json({ ok: true, label: switchable.label });
546
+ }
547
+ if (path === "/db/abort") {
548
+ abort();
549
+ return json({ ok: true, label: switchable.label });
550
+ }
551
+ return json({ error: "not_found" }, 404);
552
+ } catch (err) {
553
+ return json({ error: err instanceof Error ? err.message : String(err) }, 500);
554
+ }
555
+ };
556
+ }
557
+ function emergencyGate(o) {
558
+ if (!o.acceptDataLoss) return "need-accept";
559
+ if (o.primaryResponds && o.fault !== "primary-down") return "refuse-primary-alive";
560
+ return "proceed";
561
+ }
562
+
563
+ // src/switchable/orchestrate.ts
564
+ import { randomBytes } from "crypto";
565
+ function httpMachine(id, baseUrl, token) {
566
+ return {
567
+ id,
568
+ async call(path, body2, timeoutMs = 15e3) {
569
+ const res = await fetch(`${baseUrl}${path}`, {
570
+ method: body2 === void 0 ? "GET" : "POST",
571
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
572
+ body: body2 === void 0 ? void 0 : JSON.stringify(body2),
573
+ signal: AbortSignal.timeout(timeoutMs)
574
+ });
575
+ const text = await res.text();
576
+ let json = {};
577
+ try {
578
+ json = text ? JSON.parse(text) : {};
579
+ } catch {
580
+ json = { error: `not JSON: ${text.slice(0, 120)}` };
581
+ }
582
+ return { status: res.status, ...json };
583
+ }
584
+ };
585
+ }
586
+ var q3 = (name) => `"${name.replace(/"/g, '""')}"`;
587
+ async function within(p, ms, what) {
588
+ let t;
589
+ try {
590
+ return await Promise.race([p, new Promise((_, j) => t = setTimeout(() => j(new Error(`${what}: no answer in ${ms} ms`)), ms))]);
591
+ } finally {
592
+ clearTimeout(t);
593
+ }
594
+ }
595
+ async function all(machines, f) {
596
+ return Promise.all(
597
+ machines.map(async (m) => {
598
+ try {
599
+ return { id: m.id, ...await f(m) };
600
+ } catch (e) {
601
+ return { id: m.id, status: 0, error: e instanceof Error ? e.message : String(e) };
602
+ }
603
+ })
604
+ );
605
+ }
606
+ function planStopper(p, skip, log) {
607
+ log(`copy home: ${p.upserts} new/changed, ${p.deletes} deleted, ${p.conflicts.length} conflicts, ${p.written} written`);
608
+ if (p.schemaMismatch.length) return `the schema differs between the two databases (${p.schemaMismatch.join(", ")}) \u2014 migrate first`;
609
+ if (p.conflicts.length) {
610
+ for (const k of p.conflicts.slice(0, 50)) log(` CONFLICT ${k.table} ${k.key}`);
611
+ if (!skip) return `${p.conflicts.length} conflict(s) \u2014 the primary has changes the reserve never saw; skipConflicts copies the rest and keeps the primary's version`;
612
+ }
613
+ return null;
614
+ }
615
+ async function orchestrateSwitch(o) {
616
+ const t0 = performance.now();
617
+ const log = (s) => (o.log ?? console.log)(`[switch +${Math.round(performance.now() - t0)}ms] ${s}`);
618
+ const holdMs = Math.min(Math.max(o.holdMs ?? 3e3, 100), 1e4);
619
+ const toReserve = o.to === "reserve";
620
+ const emergency = Boolean(o.primaryDown);
621
+ const copyHome = !toReserve && !o.discardReserveWrites;
622
+ const marker = q3(o.markerTable ?? "dbSwitchMarker");
623
+ const target = toReserve ? o.reserve : o.primary;
624
+ const old = toReserve ? o.primary : o.reserve;
625
+ const [targetLabel, oldLabel] = toReserve ? [o.labels.reserve, o.labels.primary] : [o.labels.primary, o.labels.reserve];
626
+ if (emergency && !toReserve) return { outcome: "refused", reason: "primaryDown only makes sense to the reserve" };
627
+ if (o.fault === "replication" && (!toReserve || emergency)) return { outcome: "refused", reason: "fault replication needs a planned switch to the reserve" };
628
+ if (o.fault !== void 0 && !["replication", "point", "primary-down"].includes(o.fault)) return { outcome: "refused", reason: `unknown fault \xAB${String(o.fault)}\xBB` };
629
+ if (o.fault === "primary-down" && !emergency) return { outcome: "refused", reason: "fault primary-down needs primaryDown" };
630
+ if (emergency) {
631
+ const responds = await within(o.primary.execute("select 1"), 5e3, "primary").then(() => true, () => false);
632
+ const decision = emergencyGate({ primaryResponds: responds, acceptDataLoss: Boolean(o.acceptDataLoss), fault: o.fault });
633
+ const lag = await within(
634
+ 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] }),
635
+ 5e3,
636
+ "reserve"
637
+ ).then((r) => r.rows[0]?.s ?? null, () => null);
638
+ log(`EMERGENCY: the primary ${responds ? "ANSWERS" : "does not answer"}; the reserve last heard from it ${lag ?? "?"} s ago \u2014 what the primary wrote after that is LOST \u2192 ${decision}`);
639
+ if (decision === "need-accept") return { outcome: "refused", reason: "an emergency switch loses what had not replicated \u2014 pass acceptDataLoss if that is meant" };
640
+ if (decision === "refuse-primary-alive") return { outcome: "refused", reason: "the primary ANSWERS \u2014 use the planned switch (lossless)" };
641
+ }
642
+ let targetOpened = false;
643
+ let subscriptionOff = false;
644
+ const restored = [];
645
+ const abort = async (reason) => {
646
+ log(`ABORTING: ${reason} \u2014 releasing everyone on the old side`);
647
+ log(`aborted: ${JSON.stringify(await all(o.machines, (m) => m.call("/db/abort", {})))}`);
648
+ if (targetOpened) {
649
+ try {
650
+ await setFence(target, "locked", o.fence);
651
+ restored.push(`${targetLabel} fenced again`);
652
+ } catch (e) {
653
+ log(`WARNING: ${targetLabel} could NOT be fenced again: ${e} \u2014 fence it by hand`);
654
+ }
655
+ }
656
+ if (subscriptionOff) {
657
+ try {
658
+ await o.reserve.execute(`alter subscription ${q3(o.subscription)} enable`);
659
+ restored.push("subscription enabled again");
660
+ } catch (e) {
661
+ log(`WARNING: the subscription could not be enabled again: ${e}`);
662
+ }
663
+ }
664
+ return { outcome: "aborted", reason, restored };
665
+ };
666
+ for (const [side, label, want] of emergency ? [[target, targetLabel, "locked"]] : [[target, targetLabel, "locked"], [old, oldLabel, "open"]]) {
667
+ const [state, missing] = await Promise.all([fenceState(side, o.fence), unfencedTables(side, o.fence)]);
668
+ if (state !== want || missing.length) {
669
+ return { outcome: "refused", reason: `${label}: fence is \xAB${state}\xBB (expected \xAB${want}\xBB)${missing.length ? `, ${missing.length} table(s) without it: ${missing.join(", ")}` : ""} \u2014 nothing switched` };
670
+ }
671
+ }
672
+ if (toReserve && !emergency) {
673
+ const fn = q3(o.fence?.name ?? FENCE_DEFAULTS.name);
674
+ for (const side of [o.primary, o.reserve]) {
675
+ const exists = (await side.execute({ sql: `select to_regclass($1) is not null as e`, args: [marker] })).rows[0]?.e === true;
676
+ if (exists) continue;
677
+ await side.execute(`create table ${marker} ("id" text primary key, "at" bigint not null)`);
678
+ await side.execute(`create trigger ${fn} before insert or update or delete on ${marker} for each statement execute function ${fn}()`);
679
+ }
680
+ await o.reserve.execute(`alter subscription ${q3(o.subscription)} refresh publication`);
681
+ const probe = `probe-${randomBytes(6).toString("hex")}`;
682
+ await o.primary.execute({ sql: `insert into ${marker} ("id", "at") values ($1, $2)`, args: [probe, Date.now()] });
683
+ if (!await arrived(o.reserve, marker, probe, 3e4, 100)) {
684
+ return { outcome: "refused", reason: "the probe did not reach the reserve in 30 s \u2014 is the replica alive?" };
685
+ }
686
+ log("probe: the stream carries the marker");
687
+ if (o.fault === "replication") {
688
+ await o.reserve.execute(`alter subscription ${q3(o.subscription)} disable`);
689
+ subscriptionOff = true;
690
+ log("TEST: subscription disabled before the hold");
691
+ }
692
+ }
693
+ if (copyHome) {
694
+ if (await baselineAt(o.reserve, o.reconcile) === null) {
695
+ return { outcome: "refused", reason: "no baseline from the switch to the reserve \u2014 the only way back is discardReserveWrites" };
696
+ }
697
+ const stop = planStopper(await reconcile(o.reserve, o.primary, { apply: true, skipConflicts: o.skipConflicts, ...o.reconcile }), Boolean(o.skipConflicts), log);
698
+ if (stop) return { outcome: "refused", reason: stop };
699
+ }
700
+ const prep = await all(o.machines, (m) => m.call("/db/prepare", { target: o.to }));
701
+ log(`prepare: ${JSON.stringify(prep)}`);
702
+ if (prep.some((r) => r.ok !== true)) return abort("a machine could not open the target");
703
+ const holdStart = performance.now();
704
+ const hold = await all(o.machines, (m) => m.call("/db/hold", { ms: holdMs }, holdMs + 2e3));
705
+ log(`hold: ${JSON.stringify(hold)}`);
706
+ if (hold.some((r) => r.ok !== true)) {
707
+ if (emergency && hold.every((r) => r.status === 200 && r.label !== void 0)) log("hold not drained within the ceiling \u2014 continuing (emergency)");
708
+ else return abort("a machine did not drain within the ceiling");
709
+ }
710
+ if (toReserve && !emergency) {
711
+ const id = `switch-${randomBytes(6).toString("hex")}`;
712
+ await o.primary.execute({ sql: `insert into ${marker} ("id", "at") values ($1, $2)`, args: [id, Date.now()] });
713
+ if (!await arrived(o.reserve, marker, id, holdMs, 20)) return abort("the marker did not reach the reserve within the hold");
714
+ log("marker in the reserve: everything written before the hold is there");
715
+ }
716
+ if (toReserve) {
717
+ if (!subscriptionOff) {
718
+ await o.reserve.execute(`alter subscription ${q3(o.subscription)} disable`);
719
+ subscriptionOff = true;
720
+ }
721
+ log("subscription disabled");
722
+ try {
723
+ log(`baseline: ${await captureBaseline(o.reserve, o.reconcile)} rows`);
724
+ } catch (e) {
725
+ if (!emergency) return abort(`the baseline could not be taken: ${e}`);
726
+ log(`WARNING: no baseline (${e}) \u2014 the way back will be discardReserveWrites`);
727
+ }
728
+ }
729
+ if (copyHome) {
730
+ try {
731
+ const stop = planStopper(await reconcile(o.reserve, o.primary, { apply: true, skipConflicts: o.skipConflicts, ...o.reconcile }), Boolean(o.skipConflicts), log);
732
+ if (stop) return abort(stop);
733
+ } catch (e) {
734
+ return abort(`copying home failed: ${e}`);
735
+ }
736
+ }
737
+ try {
738
+ await setFence(target, "open", o.fence);
739
+ targetOpened = true;
740
+ } catch (e) {
741
+ return abort(`${targetLabel} could not be unfenced: ${e}`);
742
+ }
743
+ const point = await all(o.machines, (m) => m.call("/db/point", { target: o.fault === "point" && m === o.machines[0] ? "nowhere" : o.to }));
744
+ log(`point: ${JSON.stringify(point)}`);
745
+ if (point.some((r) => r.ok !== true)) return abort("a machine could not point");
746
+ const pointed = [...new Set(point.map((r) => r.label))];
747
+ if (pointed.length !== 1 || typeof pointed[0] !== "string") return abort(`the machines pointed at different sides: ${JSON.stringify(pointed)}`);
748
+ const newLabel = pointed[0];
749
+ const ready = (r) => r.ok === true && r.label === newLabel;
750
+ let release = await all(o.machines, (m) => m.call("/db/release", {}));
751
+ for (let i = 0; i < 5 && release.some((r) => !ready(r)); i++) {
752
+ await new Promise((r) => setTimeout(r, 200));
753
+ const again = o.machines.filter((m) => !ready(release.find((r) => r.id === m.id)));
754
+ const answers = await all(again, (m) => m.call("/db/release", {}));
755
+ release = release.map((r) => answers.find((x) => x.id === r.id) ?? r);
756
+ }
757
+ log(`release: ${JSON.stringify(release)}`);
758
+ const heldMs = Math.round(performance.now() - holdStart);
759
+ try {
760
+ await within(setFence(old, "locked", o.fence), 5e3, `fence ${oldLabel}`);
761
+ log(`${oldLabel} fenced`);
762
+ } catch (e) {
763
+ log(`WARNING: ${oldLabel} is NOT fenced (${e}) \u2014 fence it when it answers`);
764
+ }
765
+ if (release.some((r) => !ready(r))) {
766
+ return { outcome: "unconfirmed", reason: "a machine did not confirm release on the new side \u2014 its safety net sends it back; run status NOW", label: newLabel };
767
+ }
768
+ log(`DONE: every machine on ${newLabel}; queries held for ${heldMs} ms`);
769
+ return { outcome: "done", label: newLabel, heldMs };
770
+ }
771
+ async function arrived(reserve, marker, id, ms, every) {
772
+ const end = Date.now() + ms;
773
+ while (Date.now() < end) {
774
+ if ((await reserve.execute({ sql: `select 1 from ${marker} where "id" = $1`, args: [id] })).rows.length === 1) return true;
775
+ await new Promise((r) => setTimeout(r, every));
776
+ }
777
+ return false;
778
+ }
779
+
780
+ // src/switchable/reserve.ts
781
+ var RESERVE_DEFAULTS = { staleSeconds: 300, lagBytes: 64 * 1024 * 1024 };
782
+ function judgeReserve(r, t = RESERVE_DEFAULTS) {
783
+ if (!r) return { ok: false, reason: "missing" };
784
+ if (r.walStatus === "lost") return { ok: false, reason: "lost" };
785
+ if (!r.active) return { ok: false, reason: "inactive" };
786
+ if (r.replyAgeSeconds === null || r.replyAgeSeconds > t.staleSeconds) return { ok: false, reason: "stale" };
787
+ if (r.lagBytes !== null && r.lagBytes > t.lagBytes) return { ok: false, reason: "lagging" };
788
+ return { ok: true };
789
+ }
790
+ async function readReserveSlot(primary, slot) {
791
+ const { rows } = await primary.execute({
792
+ sql: `select s.active, s.wal_status,
793
+ pg_wal_lsn_diff(pg_current_wal_lsn(), s.confirmed_flush_lsn)::bigint as lag,
794
+ extract(epoch from now() - r.reply_time)::int as reply_age
795
+ from pg_replication_slots s
796
+ left join pg_stat_replication r on r.application_name = s.slot_name
797
+ where s.slot_name = $1`,
798
+ args: [slot]
799
+ });
800
+ const row = rows[0];
801
+ if (!row) return null;
802
+ const num = (v) => v === null || v === void 0 ? null : Number(v);
803
+ return { active: row.active === true, walStatus: row.wal_status ?? null, lagBytes: num(row.lag), replyAgeSeconds: num(row.reply_age) };
804
+ }
805
+ async function reserveHealth(primary, slot, t, timeoutMs = 5e3) {
806
+ let timer;
807
+ try {
808
+ const reading = await Promise.race([
809
+ readReserveSlot(primary, slot),
810
+ new Promise((_, j) => timer = setTimeout(() => j(new Error("timeout")), timeoutMs))
811
+ ]);
812
+ return judgeReserve(reading, t);
813
+ } catch {
814
+ return { ok: false, reason: "unreadable" };
815
+ } finally {
816
+ clearTimeout(timer);
817
+ }
818
+ }
819
+ var RESERVE_ALARM_AFTER_MS = 10 * 60 * 1e3;
820
+ var MIGRATION_FAILED = "migration_failed";
821
+ function noteReserveMigration(state, outcome, now = Date.now()) {
822
+ if ("skipped" in outcome) return state;
823
+ if (outcome.ok) {
824
+ const { migrationFailed: _, ...rest } = state;
825
+ return rest;
826
+ }
827
+ return { ...state, migrationFailed: { firstSeenAt: now, detail: outcome.reason.slice(0, 500) } };
828
+ }
829
+ function watchReserve(state, verdict, now = Date.now(), alarmAfterMs = RESERVE_ALARM_AFTER_MS) {
830
+ const next = { ...state };
831
+ const incidents = [];
832
+ if (verdict.ok) delete next.slot;
833
+ else {
834
+ if (next.slot?.reason !== verdict.reason) next.slot = { reason: verdict.reason, firstSeenAt: now };
835
+ if (now - next.slot.firstSeenAt >= alarmAfterMs) incidents.push(incident(next.slot.reason, next.slot.firstSeenAt, null));
836
+ }
837
+ if (next.migrationFailed) incidents.push(incident(MIGRATION_FAILED, next.migrationFailed.firstSeenAt, next.migrationFailed.detail));
838
+ return { state: next, incidents };
839
+ }
840
+ var incident = (reason, first, detail) => ({
841
+ id: `reserve:${reason}:${first}`,
842
+ reason,
843
+ severity: reason === "lost" || reason === MIGRATION_FAILED ? "critical" : "high",
844
+ openedAt: new Date(first).toISOString(),
845
+ detail
846
+ });
847
+
848
+ // src/switchable/ip-guard.ts
849
+ import { lookup } from "dns/promises";
850
+ var NETWORK_REASONS = /* @__PURE__ */ new Set(["inactive", "stale"]);
851
+ var LOST = "lost";
852
+ async function runGuard(d, o) {
853
+ let health = await d.reserveHealth();
854
+ if (!health.ok) {
855
+ await d.sleep(o.confirmMs);
856
+ health = await d.reserveHealth();
857
+ }
858
+ if (health.ok) return { outcome: "healthy" };
859
+ const reason = health.reason ?? "unknown";
860
+ if (!NETWORK_REASONS.has(reason) && reason !== LOST) return { outcome: "not-network", reason };
861
+ const ip = await d.resolve(await d.upcloudPublicHost());
862
+ const cidr = `${ip}/32`;
863
+ const before = await d.getRestrictions();
864
+ const unknown = before.dbAllowedCidrs.filter((c) => c !== cidr && !o.fixedV4.includes(c));
865
+ if (unknown.length) d.log(`to clean up (neither fixed nor the reserve's current): ${unknown.join(", ")}`);
866
+ if (before.dbAllowedCidrs.includes(cidr)) {
867
+ return reason === LOST ? { outcome: "needs-rebuild", ip, added: false } : { outcome: "already-allowed", ip };
868
+ }
869
+ const next = { dbAllowedCidrs: [...before.dbAllowedCidrs, cidr], dbAllowedCidrsV6: before.dbAllowedCidrsV6 };
870
+ await d.applyRestrictions(next);
871
+ const expected = JSON.stringify(next);
872
+ let read = "";
873
+ for (let t = 0; ; t += o.pollMs) {
874
+ const after = await d.getRestrictions();
875
+ read = JSON.stringify({ dbAllowedCidrs: after.dbAllowedCidrs, dbAllowedCidrsV6: after.dbAllowedCidrsV6 });
876
+ if (read === expected) break;
877
+ if (t >= o.readBackMs) throw new Error(`the list did not become what was sent: expected ${expected}, read ${read}`);
878
+ await d.sleep(o.pollMs);
879
+ }
880
+ d.log(`added ${cidr}`);
881
+ if (reason === LOST) return { outcome: "needs-rebuild", ip, added: true };
882
+ let last = reason;
883
+ for (let t = 0; t < o.waitMs; t += o.pollMs) {
884
+ await d.sleep(o.pollMs);
885
+ const h = await d.reserveHealth();
886
+ if (h.ok) return { outcome: "fixed", ip };
887
+ last = h.reason ?? "unknown";
888
+ }
889
+ return { outcome: "still-down", ip, reason: last };
890
+ }
891
+ function liveDeps(env) {
892
+ const sb = `https://api.supabase.com/v1/projects/${env.supabaseRef}/network-restrictions`;
893
+ const sbHeaders = { authorization: `Bearer ${env.supabaseToken}`, "content-type": "application/json" };
894
+ const ok = async (res, what) => {
895
+ if (!res.ok) throw new Error(`${what}: HTTP ${res.status} ${(await res.text()).slice(0, 200)}`);
896
+ return res;
897
+ };
898
+ return {
899
+ async reserveHealth() {
900
+ try {
901
+ const res = await fetch(env.healthUrl);
902
+ const body2 = await res.json();
903
+ return { ok: res.status === 200 && body2.ok === true, reason: body2.reason };
904
+ } catch {
905
+ return { ok: false, reason: "unreachable" };
906
+ }
907
+ },
908
+ async upcloudPublicHost() {
909
+ const res = await ok(
910
+ await fetch(`https://api.upcloud.com/1.3/database/${env.upcloudDbUuid}`, {
911
+ headers: { authorization: `Bearer ${env.upcloudToken}` }
912
+ }),
913
+ "UpCloud"
914
+ );
915
+ const db = await res.json();
916
+ const host = db.components?.find((c) => c.component === "pg" && c.route === "public")?.host;
917
+ if (!host) throw new Error("UpCloud: no public pg host");
918
+ return host;
919
+ },
920
+ async resolve(host) {
921
+ return (await lookup(host, { family: 4 })).address;
922
+ },
923
+ async getRestrictions() {
924
+ const res = await ok(await fetch(sb, { headers: sbHeaders }), "Supabase GET");
925
+ const b = await res.json();
926
+ return { status: b.status, dbAllowedCidrs: b.config.dbAllowedCidrs ?? [], dbAllowedCidrsV6: b.config.dbAllowedCidrsV6 ?? [] };
927
+ },
928
+ async applyRestrictions(r) {
929
+ await ok(await fetch(`${sb}/apply`, { method: "POST", headers: sbHeaders, body: JSON.stringify(r) }), "Supabase apply");
930
+ },
931
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
932
+ log: (l) => console.log(l)
933
+ };
934
+ }
935
+ export {
936
+ FENCE_DEFAULTS,
937
+ FENCE_ERRCODE,
938
+ HOLD_MAX_MS,
939
+ HOLD_MIN_MS,
940
+ MIGRATION_FAILED,
941
+ RECONCILE_DEFAULTS,
942
+ RESERVE_ALARM_AFTER_MS,
943
+ RESERVE_DEFAULTS,
944
+ baselineAt,
945
+ captureBaseline,
946
+ createSwitchControl,
947
+ createSwitchable,
948
+ emergencyGate,
949
+ fenceState,
950
+ httpMachine,
951
+ installFence,
952
+ judgeReserve,
953
+ liveDeps,
954
+ noteReserveMigration,
955
+ orchestrateSwitch,
956
+ readReserveSlot,
957
+ reconcile,
958
+ reserveHealth,
959
+ runGuard,
960
+ setFence,
961
+ switchToken,
962
+ unfencedTables,
963
+ watchReserve
964
+ };
965
+ //# sourceMappingURL=index.js.map