@broberg/db-sdk 0.3.0 → 0.4.1

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.
@@ -1,3 +1,9 @@
1
+ import {
2
+ PG_OPTIONS,
3
+ toResult,
4
+ toResult2
5
+ } from "../chunk-ONXYOFVT.js";
6
+
1
7
  // src/switchable/switchable.ts
2
8
  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
9
  var isQuery = (x) => {
@@ -286,6 +292,7 @@ async function unfencedTables(db, o) {
286
292
  // src/switchable/reconcile.ts
287
293
  var RECONCILE_DEFAULTS = { schema: "dbSwitch", bypass: FENCE_DEFAULTS.bypass };
288
294
  var SEP = "";
295
+ var UPSERT_CHUNK = 500;
289
296
  var q2 = (name) => `"${name.replace(/"/g, '""')}"`;
290
297
  var lit2 = (s) => `'${s.replace(/'/g, "''")}'`;
291
298
  var UTC = `set local time zone 'UTC'`;
@@ -297,12 +304,22 @@ async function tables(db) {
297
304
  from pg_index i join pg_attribute a on a.attrelid = i.indrelid and a.attnum = any(i.indkey)
298
305
  where i.indrelid = c.oid and i.indisprimary) as pk,
299
306
  (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
307
+ where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped) as cols,
308
+ (select array_agg(a.attname::text order by a.attnum) from pg_attribute a
309
+ where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped and a.attgenerated <> '') as gen,
310
+ (select array_agg(a.attname::text order by a.attnum) from pg_attribute a
311
+ where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped and a.attidentity = 'a') as ida
301
312
  from pg_class c
302
313
  where c.relnamespace = current_schema()::regnamespace and c.relkind = 'r'
303
314
  order by 1`
304
315
  );
305
- return rows.map((r) => ({ name: String(r.name), pk: r.pk ?? [], cols: r.cols }));
316
+ return rows.map((r) => ({
317
+ name: String(r.name),
318
+ pk: r.pk ?? [],
319
+ cols: r.cols,
320
+ generated: r.gen ?? [],
321
+ identityAlways: r.ida ?? []
322
+ }));
306
323
  }
307
324
  async function fingerprints(db, tabs) {
308
325
  const out = /* @__PURE__ */ new Map();
@@ -327,8 +344,10 @@ async function fingerprints(db, tabs) {
327
344
  return out;
328
345
  }
329
346
  async function captureBaseline(reserve, o) {
347
+ return writeBaseline(reserve, await fingerprints(reserve, await tables(reserve)), o);
348
+ }
349
+ async function writeBaseline(reserve, rows, o) {
330
350
  const { schema } = { ...RECONCILE_DEFAULTS, ...o };
331
- const rows = await fingerprints(reserve, await tables(reserve));
332
351
  const keys = [...rows.keys()];
333
352
  const table = baselineTable(o);
334
353
  await reserve.batch([
@@ -350,10 +369,60 @@ async function baselineAt(reserve, o) {
350
369
  const at = rows[0]?.at;
351
370
  return at ? Number(at) : null;
352
371
  }
353
- async function readBaseline(reserve, o) {
354
- const { rows } = await reserve.execute(`select "key", "h" from ${baselineTable(o)}`);
372
+ async function readBaseline(reserve, o, only) {
373
+ const { rows } = only ? await reserve.execute({ sql: `select "key", "h" from ${baselineTable(o)} where "key" = any($1::text[])`, args: [only] }) : await reserve.execute(`select "key", "h" from ${baselineTable(o)}`);
355
374
  return new Map(rows.map((r) => [String(r.key), String(r.h)]));
356
375
  }
376
+ async function reserveHorizon(reserve) {
377
+ const { rows } = await reserve.execute(
378
+ `select (pg_snapshot_xmin(pg_current_snapshot())::text::bigint % 4294967296)::text as x,
379
+ (pg_current_xact_id()::text::bigint % 4294967296)::text as c`
380
+ );
381
+ return { xmin: String(rows[0].x), at: String(rows[0].c) };
382
+ }
383
+ var keyExpr = (t) => `jsonb_build_array(${t.pk.map((c) => `x.${q2(c)}`).join(", ")})::text`;
384
+ async function deltaFingerprints(reserve, primary, tabs, since) {
385
+ const R = /* @__PURE__ */ new Map();
386
+ const P = /* @__PURE__ */ new Map();
387
+ if (tabs.length === 0) return { R, P };
388
+ const [, ...res] = await reserve.batch([
389
+ UTC,
390
+ ...tabs.flatMap((t) => [
391
+ { sql: `select ${keyExpr(t)} as k, md5(to_jsonb(x)::text) as h from ${q2(t.name)} x where x.xmin::text::bigint >= $1::bigint`, args: [since.xmin] },
392
+ `select count(*)::bigint as n from ${q2(t.name)}`
393
+ ])
394
+ ]);
395
+ const changed = tabs.map((_, i) => res[i * 2].rows.map((r) => [String(r.k), String(r.h)]));
396
+ const countR = tabs.map((_, i) => Number(res[i * 2 + 1].rows[0].n));
397
+ const [, ...pres] = await primary.batch([
398
+ UTC,
399
+ ...tabs.flatMap((t, i) => [
400
+ { sql: `select ${keyExpr(t)} as k, md5(to_jsonb(x)::text) as h from ${q2(t.name)} x where ${keyExpr(t)} = any($1::text[])`, args: [changed[i].map(([k]) => k)] },
401
+ `select count(*)::bigint as n from ${q2(t.name)}`
402
+ ])
403
+ ]);
404
+ const needKeys = [];
405
+ tabs.forEach((t, i) => {
406
+ const onP = new Map(pres[i * 2].rows.map((r) => [String(r.k), String(r.h)]));
407
+ for (const [k, h] of changed[i]) R.set(`${t.name}${SEP}${k}`, h);
408
+ for (const [k, h] of onP) P.set(`${t.name}${SEP}${k}`, h);
409
+ const inserted = changed[i].filter(([k]) => !onP.has(k)).length;
410
+ if (Number(pres[i * 2 + 1].rows[0].n) + inserted !== countR[i]) needKeys.push(i);
411
+ });
412
+ for (const i of needKeys) {
413
+ const t = tabs[i];
414
+ const [rk, pk] = await Promise.all([
415
+ reserve.execute(`select ${keyExpr(t)} as k from ${q2(t.name)} x`),
416
+ primary.batch([UTC, `select ${keyExpr(t)} as k, md5(to_jsonb(x)::text) as h from ${q2(t.name)} x`]).then((r) => r[1])
417
+ ]);
418
+ const onR = new Set(rk.rows.map((r) => String(r.k)));
419
+ for (const r of pk.rows) {
420
+ const k = String(r.k);
421
+ if (!onR.has(k)) P.set(`${t.name}${SEP}${k}`, String(r.h));
422
+ }
423
+ }
424
+ return { R, P };
425
+ }
357
426
  async function reconcile(reserve, primary, opts2) {
358
427
  const { bypass } = { ...RECONCILE_DEFAULTS, ...opts2 };
359
428
  const [rt, pt] = await Promise.all([tables(reserve), tables(primary)]);
@@ -364,7 +433,24 @@ async function reconcile(reserve, primary, opts2) {
364
433
  ...pt.filter((t) => !rt.some((r) => r.name === t.name)).map((t) => t.name)
365
434
  ];
366
435
  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)]);
436
+ let R;
437
+ let P;
438
+ let B;
439
+ const since = opts2.since && Number(opts2.since.at) >= Number(opts2.since.xmin) ? opts2.since : void 0;
440
+ if (since && await reserveHorizon(reserve).then((h) => Number(h.at) >= Number(since.xmin))) {
441
+ const keyed = rt.filter((t) => t.pk.length);
442
+ const whole = rt.filter((t) => !t.pk.length);
443
+ const [d, wr, wp] = await Promise.all([
444
+ deltaFingerprints(reserve, primary, keyed, since),
445
+ fingerprints(reserve, whole),
446
+ fingerprints(primary, pt.filter((t) => !t.pk.length))
447
+ ]);
448
+ R = new Map([...d.R, ...wr]);
449
+ P = new Map([...d.P, ...wp]);
450
+ B = await readBaseline(reserve, opts2, [.../* @__PURE__ */ new Set([...R.keys(), ...P.keys()])]);
451
+ } else {
452
+ [R, P, B] = await Promise.all([fingerprints(reserve, rt), fingerprints(primary, pt), readBaseline(reserve, opts2)]);
453
+ }
368
454
  const conflicts = [];
369
455
  const copies = [];
370
456
  for (const k of /* @__PURE__ */ new Set([...R.keys(), ...P.keys()])) {
@@ -412,27 +498,33 @@ async function reconcile(reserve, primary, opts2) {
412
498
  sql: `delete from ${q2(table2)} where ctid = (select ctid from ${q2(table2)} x where md5(to_jsonb(x)::text) = $1 limit 1)`,
413
499
  args: [x.p]
414
500
  });
415
- meaning.push({ key: `${table2}${SEP}${x.key}`, h: null, counted: "rowcount" });
501
+ meaning.push({ items: [{ key: `${table2}${SEP}${x.key}`, h: null }], counted: "rowcount" });
416
502
  }
417
503
  }
418
504
  for (const table2 of order) {
419
505
  const t = byName.get(table2);
420
- const set = t.cols.filter((col) => !t.pk.includes(col));
506
+ const insertable = t.cols.filter((col) => !t.generated.includes(col));
507
+ const set = insertable.filter((col) => !t.pk.includes(col) && !t.identityAlways.includes(col));
508
+ const colList = insertable.map(q2).join(", ");
421
509
  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"}` : "";
510
+ const ready = [];
422
511
  for (const x of upserts.get(table2) ?? []) {
423
512
  const j = rowsByH.get(`${table2}${SEP}${x.h}`);
424
- if (j === void 0) continue;
513
+ if (j !== void 0) ready.push({ key: `${table2}${SEP}${x.key}`, h: x.h, j });
514
+ }
515
+ for (let i = 0; i < ready.length; i += UPSERT_CHUNK) {
516
+ const chunk = ready.slice(i, i + UPSERT_CHUNK);
425
517
  writes.push({
426
- sql: `insert into ${q2(table2)} select * from jsonb_populate_record(null::${q2(table2)}, $1::text::jsonb) ${onConflict}`,
427
- args: [j]
518
+ sql: `insert into ${q2(table2)} (${colList}) overriding system value select ${colList} from jsonb_populate_recordset(null::${q2(table2)}, $1::text::jsonb) ${onConflict}`,
519
+ args: [`[${chunk.map((c) => c.j).join(",")}]`]
428
520
  });
429
- meaning.push({ key: `${table2}${SEP}${x.key}`, h: x.h, counted: "always" });
521
+ meaning.push({ items: chunk.map((c) => ({ key: c.key, h: c.h })), counted: "always" });
430
522
  }
431
523
  }
432
524
  const results = await primary.batch(writes);
433
525
  const written = [];
434
526
  meaning.forEach((m, i) => {
435
- if (m && (m.counted === "always" || results[i].rowsAffected === 1)) written.push({ key: m.key, h: m.h });
527
+ if (m && (m.counted === "always" || results[i].rowsAffected === 1)) written.push(...m.items);
436
528
  });
437
529
  const table = baselineTable(opts2);
438
530
  const ins = written.filter((x) => x.h !== null);
@@ -446,6 +538,96 @@ async function reconcile(reserve, primary, opts2) {
446
538
  ]);
447
539
  return { ...plan, written: written.length };
448
540
  }
541
+ async function syncSequences(db) {
542
+ const { rows } = await db.execute(
543
+ `select c.relname as t, a.attname as col, pg_get_serial_sequence(format('%I.%I', n.nspname, c.relname), a.attname) as seq
544
+ from pg_class c join pg_namespace n on n.oid = c.relnamespace join pg_attribute a on a.attrelid = c.oid
545
+ where c.relnamespace = current_schema()::regnamespace and c.relkind = 'r' and a.attnum > 0 and not a.attisdropped
546
+ and pg_get_serial_sequence(format('%I.%I', n.nspname, c.relname), a.attname) is not null
547
+ order by 1, 2`
548
+ );
549
+ if (rows.length === 0) return [];
550
+ await db.batch(
551
+ rows.map((r) => ({
552
+ sql: `select setval($1::regclass, x.m) from (select max(${q2(String(r.col))}) as m from ${q2(String(r.t))}) x
553
+ 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)})`,
554
+ args: [String(r.seq)]
555
+ }))
556
+ );
557
+ return rows.map((r) => `${String(r.t)}.${String(r.col)}`);
558
+ }
559
+ async function freezeBaseline(reserve, o) {
560
+ await reserve.execute(`drop table if exists ${baselineTable(o)}`);
561
+ const s = await openSession(reserve.raw);
562
+ try {
563
+ await s.execute("begin isolation level repeatable read read only");
564
+ await s.execute("select 1");
565
+ } catch (e) {
566
+ s.release();
567
+ throw e;
568
+ }
569
+ let settled = false;
570
+ return {
571
+ async finish() {
572
+ if (settled) throw new Error("freezeBaseline: already finished or cancelled");
573
+ settled = true;
574
+ let rows;
575
+ try {
576
+ rows = await fingerprints(s, await tables(s));
577
+ await s.execute("commit");
578
+ } catch (e) {
579
+ await s.execute("rollback").catch((rb) => {
580
+ e.rollbackError = rb;
581
+ });
582
+ throw e;
583
+ } finally {
584
+ s.release();
585
+ }
586
+ return writeBaseline(reserve, rows, o);
587
+ },
588
+ async cancel() {
589
+ if (settled) return;
590
+ settled = true;
591
+ try {
592
+ await s.execute("rollback");
593
+ } finally {
594
+ s.release();
595
+ }
596
+ }
597
+ };
598
+ }
599
+ async function openSession(raw) {
600
+ let exec;
601
+ let release;
602
+ if (raw && typeof raw.reserve === "function") {
603
+ const max = raw.options?.max;
604
+ if (typeof max === "number" && max < 2) throw new Error(`freezeBaseline needs a pool of at least 2 connections (this one has ${max})`);
605
+ const c = await raw.reserve();
606
+ exec = async (stmt) => {
607
+ const [text, args] = typeof stmt === "string" ? [stmt, []] : [stmt.sql, [...stmt.args ?? []]];
608
+ return toResult2(await c.unsafe(text, args, PG_OPTIONS));
609
+ };
610
+ release = () => c.release();
611
+ } else if (raw && typeof raw.connect === "function") {
612
+ const c = await raw.connect();
613
+ exec = async (stmt) => {
614
+ const [text, args] = typeof stmt === "string" ? [stmt, []] : [stmt.sql, [...stmt.args ?? []]];
615
+ return toResult(await c.query(text, args));
616
+ };
617
+ release = () => c.release();
618
+ } else {
619
+ throw new Error("freezeBaseline needs a postgres.js or pg client (its raw driver gives the dedicated connection)");
620
+ }
621
+ return {
622
+ execute: exec,
623
+ async batch(stmts) {
624
+ const out = [];
625
+ for (const st of stmts) out.push(await exec(st));
626
+ return out;
627
+ },
628
+ release
629
+ };
630
+ }
449
631
  function group(xs) {
450
632
  const m = /* @__PURE__ */ new Map();
451
633
  for (const x of xs) m.set(x.table, [...m.get(x.table) ?? [], x]);
@@ -641,9 +823,11 @@ async function orchestrateSwitch(o) {
641
823
  }
642
824
  let targetOpened = false;
643
825
  let subscriptionOff = false;
826
+ let frozen = null;
644
827
  const restored = [];
645
828
  const abort = async (reason) => {
646
829
  log(`ABORTING: ${reason} \u2014 releasing everyone on the old side`);
830
+ if (frozen) await frozen.cancel().catch((e) => log(`WARNING: the frozen baseline could not be released: ${e}`));
647
831
  log(`aborted: ${JSON.stringify(await all(o.machines, (m) => m.call("/db/abort", {})))}`);
648
832
  if (targetOpened) {
649
833
  try {
@@ -690,12 +874,22 @@ async function orchestrateSwitch(o) {
690
874
  log("TEST: subscription disabled before the hold");
691
875
  }
692
876
  }
877
+ let horizon;
693
878
  if (copyHome) {
694
879
  if (await baselineAt(o.reserve, o.reconcile) === null) {
695
880
  return { outcome: "refused", reason: "no baseline from the switch to the reserve \u2014 the only way back is discardReserveWrites" };
696
881
  }
882
+ horizon = await reserveHorizon(o.reserve);
697
883
  const stop = planStopper(await reconcile(o.reserve, o.primary, { apply: true, skipConflicts: o.skipConflicts, ...o.reconcile }), Boolean(o.skipConflicts), log);
698
884
  if (stop) return { outcome: "refused", reason: stop };
885
+ for (let i = 0; i < 3; i++) {
886
+ const next = await reserveHorizon(o.reserve);
887
+ const p = await reconcile(o.reserve, o.primary, { apply: true, skipConflicts: o.skipConflicts, since: horizon, ...o.reconcile });
888
+ horizon = next;
889
+ const again = planStopper(p, Boolean(o.skipConflicts), log);
890
+ if (again) return { outcome: "refused", reason: again };
891
+ if (p.upserts + p.deletes < 100) break;
892
+ }
699
893
  }
700
894
  const prep = await all(o.machines, (m) => m.call("/db/prepare", { target: o.to }));
701
895
  log(`prepare: ${JSON.stringify(prep)}`);
@@ -720,20 +914,27 @@ async function orchestrateSwitch(o) {
720
914
  }
721
915
  log("subscription disabled");
722
916
  try {
723
- log(`baseline: ${await captureBaseline(o.reserve, o.reconcile)} rows`);
917
+ frozen = await freezeBaseline(o.reserve, o.reconcile);
918
+ log("baseline frozen (read after release)");
724
919
  } catch (e) {
725
- if (!emergency) return abort(`the baseline could not be taken: ${e}`);
920
+ if (!emergency) return abort(`the baseline could not be frozen: ${e}`);
726
921
  log(`WARNING: no baseline (${e}) \u2014 the way back will be discardReserveWrites`);
727
922
  }
728
923
  }
729
924
  if (copyHome) {
730
925
  try {
731
- const stop = planStopper(await reconcile(o.reserve, o.primary, { apply: true, skipConflicts: o.skipConflicts, ...o.reconcile }), Boolean(o.skipConflicts), log);
926
+ const stop = planStopper(await reconcile(o.reserve, o.primary, { apply: true, skipConflicts: o.skipConflicts, since: horizon, ...o.reconcile }), Boolean(o.skipConflicts), log);
732
927
  if (stop) return abort(stop);
733
928
  } catch (e) {
734
929
  return abort(`copying home failed: ${e}`);
735
930
  }
736
931
  }
932
+ try {
933
+ const seqs = await syncSequences(target);
934
+ if (seqs.length) log(`sequences on ${targetLabel}: ${seqs.length} checked`);
935
+ } catch (e) {
936
+ return abort(`the sequences on ${targetLabel} could not be moved up: ${e}`);
937
+ }
737
938
  try {
738
939
  await setFence(target, "open", o.fence);
739
940
  targetOpened = true;
@@ -762,6 +963,15 @@ async function orchestrateSwitch(o) {
762
963
  } catch (e) {
763
964
  log(`WARNING: ${oldLabel} is NOT fenced (${e}) \u2014 fence it when it answers`);
764
965
  }
966
+ if (frozen) {
967
+ const f = frozen;
968
+ frozen = null;
969
+ try {
970
+ log(`baseline: ${await f.finish()} rows (read after release)`);
971
+ } catch (e) {
972
+ log(`WARNING: the baseline could not be read (${e}) \u2014 the way home will refuse; only discardReserveWrites can bring the app back`);
973
+ }
974
+ }
765
975
  if (release.some((r) => !ready(r))) {
766
976
  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
977
  }
@@ -947,6 +1157,7 @@ export {
947
1157
  createSwitchable,
948
1158
  emergencyGate,
949
1159
  fenceState,
1160
+ freezeBaseline,
950
1161
  httpMachine,
951
1162
  installFence,
952
1163
  judgeReserve,
@@ -956,9 +1167,11 @@ export {
956
1167
  readReserveSlot,
957
1168
  reconcile,
958
1169
  reserveHealth,
1170
+ reserveHorizon,
959
1171
  runGuard,
960
1172
  setFence,
961
1173
  switchToken,
1174
+ syncSequences,
962
1175
  unfencedTables,
963
1176
  watchReserve
964
1177
  };