@rocicorp/zero 1.11.0-canary.6 → 1.11.0-canary.8

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.
Files changed (69) hide show
  1. package/out/analyze-query/src/analyze-cli.js +2 -2
  2. package/out/analyze-query/src/analyze-cli.js.map +1 -1
  3. package/out/zero/package.js +1 -1
  4. package/out/zero/package.js.map +1 -1
  5. package/out/zero-cache/src/config/zero-config.d.ts +0 -2
  6. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  7. package/out/zero-cache/src/config/zero-config.js +5 -7
  8. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  9. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  10. package/out/zero-cache/src/server/change-streamer.js +2 -2
  11. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  12. package/out/zero-cache/src/services/change-source/common/backfill-manager.d.ts.map +1 -1
  13. package/out/zero-cache/src/services/change-source/common/backfill-manager.js +14 -1
  14. package/out/zero-cache/src/services/change-source/common/backfill-manager.js.map +1 -1
  15. package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.d.ts.map +1 -1
  16. package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.js +15 -3
  17. package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.js.map +1 -1
  18. package/out/zero-cache/src/services/change-source/custom/change-source.js +2 -2
  19. package/out/zero-cache/src/services/change-source/custom/change-source.js.map +1 -1
  20. package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts.map +1 -1
  21. package/out/zero-cache/src/services/change-streamer/backup-monitor.js +58 -7
  22. package/out/zero-cache/src/services/change-streamer/backup-monitor.js.map +1 -1
  23. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +3 -3
  24. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  25. package/out/zero-cache/src/services/change-streamer/snapshot.d.ts +3 -1
  26. package/out/zero-cache/src/services/change-streamer/snapshot.d.ts.map +1 -1
  27. package/out/zero-cache/src/services/change-streamer/snapshot.js +54 -20
  28. package/out/zero-cache/src/services/change-streamer/snapshot.js.map +1 -1
  29. package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
  30. package/out/zero-cache/src/services/change-streamer/storer.js +2 -0
  31. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  32. package/out/zero-cache/src/services/litestream/litestream-checkpointer.js +1 -1
  33. package/out/zero-cache/src/services/litestream/litestream-checkpointer.js.map +1 -1
  34. package/out/zero-cache/src/services/mutagen/mutagen.d.ts +5 -0
  35. package/out/zero-cache/src/services/mutagen/mutagen.d.ts.map +1 -1
  36. package/out/zero-cache/src/services/mutagen/mutagen.js +7 -1
  37. package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
  38. package/out/zero-cache/src/services/mutagen/pusher.js +2 -1
  39. package/out/zero-cache/src/services/mutagen/pusher.js.map +1 -1
  40. package/out/zero-cache/src/services/profz.d.ts.map +1 -1
  41. package/out/zero-cache/src/services/profz.js +15 -9
  42. package/out/zero-cache/src/services/profz.js.map +1 -1
  43. package/out/zero-cache/src/services/runner.d.ts.map +1 -1
  44. package/out/zero-cache/src/services/runner.js +1 -1
  45. package/out/zero-cache/src/services/runner.js.map +1 -1
  46. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  47. package/out/zero-cache/src/services/view-syncer/view-syncer.js +20 -0
  48. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  49. package/out/zero-cache/src/types/processes.d.ts +8 -0
  50. package/out/zero-cache/src/types/processes.d.ts.map +1 -1
  51. package/out/zero-cache/src/types/processes.js +19 -4
  52. package/out/zero-cache/src/types/processes.js.map +1 -1
  53. package/out/zero-cache/src/workers/connection.js +3 -3
  54. package/out/zero-cache/src/workers/connection.js.map +1 -1
  55. package/out/zero-cache/src/workers/syncer-ws-message-handler.d.ts.map +1 -1
  56. package/out/zero-cache/src/workers/syncer-ws-message-handler.js +21 -16
  57. package/out/zero-cache/src/workers/syncer-ws-message-handler.js.map +1 -1
  58. package/out/zero-cache/src/workers/syncer.d.ts.map +1 -1
  59. package/out/zero-cache/src/workers/syncer.js +10 -1
  60. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  61. package/out/zero-client/src/client/connection-manager.d.ts.map +1 -1
  62. package/out/zero-client/src/client/connection-manager.js +46 -0
  63. package/out/zero-client/src/client/connection-manager.js.map +1 -1
  64. package/out/zero-client/src/client/version.js +1 -1
  65. package/out/zqlite/src/db.d.ts +9 -1
  66. package/out/zqlite/src/db.d.ts.map +1 -1
  67. package/out/zqlite/src/db.js +8 -2
  68. package/out/zqlite/src/db.js.map +1 -1
  69. package/package.json +1 -1
@@ -14,6 +14,7 @@
14
14
  import type { LogContext } from '@rocicorp/logger';
15
15
  import * as v from '../../../../shared/src/valita.ts';
16
16
  import { type NormalizedZeroConfig } from '../../config/normalize.ts';
17
+ import type { Source } from '../../types/streams.ts';
17
18
  declare const statusSchema: v.ObjectType<{
18
19
  tag: v.Type<"status">;
19
20
  /**
@@ -79,6 +80,7 @@ export declare const snapshotMessageSchema: v.UnionType<[v.TupleType<[v.Type<"st
79
80
  minWatermark: v.Type<string>;
80
81
  }, undefined>]>]>;
81
82
  export type SnapshotMessage = v.Infer<typeof statusMessageSchema>;
82
- export declare function reserveAndGetSnapshotStatus(lc: LogContext, config: NormalizedZeroConfig): Promise<SnapshotStatus>;
83
+ export type ReserveSnapshot = (lc: LogContext, config: NormalizedZeroConfig) => Promise<Source<SnapshotMessage>>;
84
+ export declare function reserveAndGetSnapshotStatus(lc: LogContext, config: NormalizedZeroConfig, reserve?: ReserveSnapshot): Promise<SnapshotStatus>;
83
85
  export {};
84
86
  //# sourceMappingURL=snapshot.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"snapshot.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/change-streamer/snapshot.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,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mBAAmB;;IAxBvB;;OAEG;;IAGH;;;;;OAKG;;IAGH;;;;;OAKG;;eAMmE,CAAC;AAEzE,eAAO,MAAM,qBAAqB;;IA1BhC;;OAEG;;IAGH;;;;;OAKG;;IAGH;;;;;OAKG;;iBAQ4D,CAAC;AAElE,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAElE,MAAM,MAAM,eAAe,GAAG,CAC5B,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,oBAAoB,KACzB,OAAO,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAEtC,wBAAgB,2BAA2B,CACzC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,oBAAoB,EAC5B,OAAO,GAAE,eAAiC,GACzC,OAAO,CAAC,cAAc,CAAC,CAwEzB"}
@@ -1,3 +1,4 @@
1
+ import { AbortError } from "../../../../shared/src/abort-error.js";
1
2
  import { sleep } from "../../../../shared/src/sleep.js";
2
3
  import { valita_exports } from "../../../../shared/src/valita.js";
3
4
  import { getShardConfig } from "../../types/shards.js";
@@ -28,35 +29,68 @@ var statusSchema = valita_exports.object({
28
29
  });
29
30
  var statusMessageSchema = valita_exports.tuple([valita_exports.literal("status"), statusSchema]);
30
31
  var snapshotMessageSchema = valita_exports.union(statusMessageSchema);
31
- function reserveAndGetSnapshotStatus(lc, config) {
32
+ function reserveAndGetSnapshotStatus(lc, config, reserve = reserveSnapshot) {
32
33
  const { promise: status, resolve, reject } = resolver();
33
34
  (async function() {
34
35
  const abort = new AbortController();
35
- process.on("SIGINT", () => abort.abort());
36
- process.on("SIGTERM", () => abort.abort());
37
- for (let i = 0;; i++) {
38
- let err;
39
- try {
40
- let resolved = false;
41
- const stream = await reserveSnapshot(lc, config);
42
- for await (const msg of stream) {
43
- resolve(msg[1]);
44
- resolved = true;
36
+ const { signal } = abort;
37
+ const onSignal = () => abort.abort();
38
+ process.on("SIGINT", onSignal);
39
+ process.on("SIGTERM", onSignal);
40
+ try {
41
+ for (let i = 0;; i++) {
42
+ let err;
43
+ try {
44
+ let resolved = false;
45
+ const stream = await untilAborted(reserve(lc, config), signal);
46
+ const cancelStream = () => stream.cancel(new AbortError("Aborted"));
47
+ signal.addEventListener("abort", cancelStream, { once: true });
48
+ try {
49
+ for await (const msg of stream) {
50
+ resolve(msg[1]);
51
+ resolved = true;
52
+ }
53
+ } finally {
54
+ signal.removeEventListener("abort", cancelStream);
55
+ }
56
+ if (resolved) break;
57
+ } catch (e) {
58
+ err = e;
59
+ }
60
+ if (signal.aborted) return reject(err instanceof AbortError ? err : new AbortError("Aborted"));
61
+ lc.warn?.(`Unable to reserve snapshot (attempt ${i + 1}). Retrying in 5 seconds.`, String(err));
62
+ try {
63
+ await sleep(5e3, abort.signal);
64
+ } catch (e) {
65
+ return reject(e);
45
66
  }
46
- if (resolved) break;
47
- } catch (e) {
48
- err = e;
49
- }
50
- lc.warn?.(`Unable to reserve snapshot (attempt ${i + 1}). Retrying in 5 seconds.`, String(err));
51
- try {
52
- await sleep(5e3, abort.signal);
53
- } catch (e) {
54
- return reject(e);
55
67
  }
68
+ } finally {
69
+ process.off("SIGINT", onSignal);
70
+ process.off("SIGTERM", onSignal);
56
71
  }
57
72
  })();
58
73
  return status;
59
74
  }
75
+ /**
76
+ * Resolves with the reserved stream, or rejects with an AbortError if the
77
+ * `signal` is aborted while the reservation is pending (in which case a
78
+ * stream that arrives later is canceled rather than held open).
79
+ */
80
+ function untilAborted(reservation, signal) {
81
+ return new Promise((resolve, reject) => {
82
+ const onAbort = () => reject(new AbortError("Aborted"));
83
+ signal.addEventListener("abort", onAbort, { once: true });
84
+ reservation.then((stream) => {
85
+ signal.removeEventListener("abort", onAbort);
86
+ if (signal.aborted) stream.cancel();
87
+ else resolve(stream);
88
+ }, (e) => {
89
+ signal.removeEventListener("abort", onAbort);
90
+ reject(e);
91
+ });
92
+ });
93
+ }
60
94
  function reserveSnapshot(lc, config) {
61
95
  const { taskID, change, changeStreamer } = config;
62
96
  return new ChangeStreamerHttpClient(lc, getShardConfig(config), change.db, changeStreamer.uri).reserveSnapshot(taskID);
@@ -1 +1 @@
1
- {"version":3,"file":"snapshot.js","names":[],"sources":["../../../../../../zero-cache/src/services/change-streamer/snapshot.ts"],"sourcesContent":["/**\n * The `snapshot` API serves the purpose of:\n * - informing subscribers (i.e. view-syncers) of the (litestream)\n * backup location from which to restore a replica snapshot\n * - checking whether a restored backup or existing replica is\n * compatible with the change-streamer\n * - preventing change-log cleanup while a snapshot restore is in\n * progress\n * - tracking the approximate time it takes from the beginning of\n * snapshot \"reservation\" to the subsequent subscription, which\n * serves as the minimum interval to wait before cleaning up\n * backed up changes.\n */\n\nimport type {LogContext} from '@rocicorp/logger';\nimport {resolver} from '@rocicorp/resolver';\nimport {sleep} from '../../../../shared/src/sleep.ts';\nimport * as v from '../../../../shared/src/valita.ts';\nimport {type NormalizedZeroConfig} from '../../config/normalize.ts';\nimport {getShardConfig} from '../../types/shards.ts';\nimport type {Source} from '../../types/streams.ts';\nimport {ChangeStreamerHttpClient} from './change-streamer-http.ts';\n\nconst statusSchema = v.object({\n tag: v.literal('status'),\n\n /**\n * The location from which litestream should perform the restore.\n */\n backupURL: v.string(),\n\n /**\n * The `replicaVersion` of the backup. If a subscriber's restored or\n * existing replica is of a different version, it should delete it and\n * retry the restore from litestream (i.e. equivalent to a\n * `WrongReplicaVersion` response from a `/changes` subscription).\n */\n replicaVersion: v.string(),\n\n /**\n * The earliest watermark from which catchup is possible. If the\n * subscriber's replica is older that this watermark, it should delete it\n * and (retry the) restore from litestream (i.e. equivalent to a\n * `WatermarkTooOld` response from a `/changes` subscription).\n */\n minWatermark: v.string(),\n});\n\nexport type SnapshotStatus = v.Infer<typeof statusSchema>;\n\nconst statusMessageSchema = v.tuple([v.literal('status'), statusSchema]);\n\nexport const snapshotMessageSchema = v.union(statusMessageSchema);\n\nexport type SnapshotMessage = v.Infer<typeof statusMessageSchema>;\n\nexport function reserveAndGetSnapshotStatus(\n lc: LogContext,\n config: NormalizedZeroConfig,\n): Promise<SnapshotStatus> {\n const {promise: status, resolve, reject} = resolver<SnapshotStatus>();\n\n void (async function () {\n const abort = new AbortController();\n process.on('SIGINT', () => abort.abort());\n process.on('SIGTERM', () => abort.abort());\n\n for (let i = 0; ; i++) {\n let err: unknown;\n try {\n let resolved = false;\n const stream = await reserveSnapshot(lc, config);\n for await (const msg of stream) {\n // Capture the value of the status message that the change-streamer\n // backup monitor returns, and hold the connection open to\n // \"reserve\" the snapshot and prevent change log cleanup.\n resolve(msg[1]);\n resolved = true;\n }\n // The change-streamer itself closes the connection when the\n // subscription is started (or the reservation retried).\n if (resolved) {\n break;\n }\n } catch (e) {\n err = e;\n }\n // Retry in the view-syncer since it cannot proceed until it connects\n // to a (compatible) replication-manager. In particular, a\n // replication-manager that does not support the view-syncer's\n // change-streamer protocol will close the stream with an error; this\n // retry logic essentially delays the startup of a view-syncer until\n // a compatible replication-manager has been rolled out, allowing\n // replication-manager and view-syncer services to be updated in\n // parallel.\n lc.warn?.(\n `Unable to reserve snapshot (attempt ${i + 1}). Retrying in 5 seconds.`,\n String(err),\n );\n try {\n await sleep(5000, abort.signal);\n } catch (e) {\n return reject(e);\n }\n }\n })();\n\n return status;\n}\n\nfunction reserveSnapshot(\n lc: LogContext,\n config: NormalizedZeroConfig,\n): Promise<Source<SnapshotMessage>> {\n const {taskID, change, changeStreamer} = config;\n const shardID = getShardConfig(config);\n\n const changeStreamerClient = new ChangeStreamerHttpClient(\n lc,\n shardID,\n change.db,\n changeStreamer.uri,\n );\n\n return changeStreamerClient.reserveSnapshot(taskID);\n}\n"],"mappings":";;;;;;;AAuBA,IAAM,eAAe,eAAE,OAAO;CAC5B,KAAK,eAAE,QAAQ,QAAQ;;;;CAKvB,WAAW,eAAE,OAAO;;;;;;;CAQpB,gBAAgB,eAAE,OAAO;;;;;;;CAQzB,cAAc,eAAE,OAAO;AACzB,CAAC;AAID,IAAM,sBAAsB,eAAE,MAAM,CAAC,eAAE,QAAQ,QAAQ,GAAG,YAAY,CAAC;AAEvE,IAAa,wBAAwB,eAAE,MAAM,mBAAmB;AAIhE,SAAgB,4BACd,IACA,QACyB;CACzB,MAAM,EAAC,SAAS,QAAQ,SAAS,WAAU,SAAyB;CAEpE,CAAM,iBAAkB;EACtB,MAAM,QAAQ,IAAI,gBAAgB;EAClC,QAAQ,GAAG,gBAAgB,MAAM,MAAM,CAAC;EACxC,QAAQ,GAAG,iBAAiB,MAAM,MAAM,CAAC;EAEzC,KAAK,IAAI,IAAI,IAAK,KAAK;GACrB,IAAI;GACJ,IAAI;IACF,IAAI,WAAW;IACf,MAAM,SAAS,MAAM,gBAAgB,IAAI,MAAM;IAC/C,WAAW,MAAM,OAAO,QAAQ;KAI9B,QAAQ,IAAI,EAAE;KACd,WAAW;IACb;IAGA,IAAI,UACF;GAEJ,SAAS,GAAG;IACV,MAAM;GACR;GASA,GAAG,OACD,uCAAuC,IAAI,EAAE,4BAC7C,OAAO,GAAG,CACZ;GACA,IAAI;IACF,MAAM,MAAM,KAAM,MAAM,MAAM;GAChC,SAAS,GAAG;IACV,OAAO,OAAO,CAAC;GACjB;EACF;CACF,GAAG;CAEH,OAAO;AACT;AAEA,SAAS,gBACP,IACA,QACkC;CAClC,MAAM,EAAC,QAAQ,QAAQ,mBAAkB;CAUzC,OAAO,IAP0B,yBAC/B,IAHc,eAAe,MAI7B,GACA,OAAO,IACP,eAAe,GAGV,EAAqB,gBAAgB,MAAM;AACpD"}
1
+ {"version":3,"file":"snapshot.js","names":[],"sources":["../../../../../../zero-cache/src/services/change-streamer/snapshot.ts"],"sourcesContent":["/**\n * The `snapshot` API serves the purpose of:\n * - informing subscribers (i.e. view-syncers) of the (litestream)\n * backup location from which to restore a replica snapshot\n * - checking whether a restored backup or existing replica is\n * compatible with the change-streamer\n * - preventing change-log cleanup while a snapshot restore is in\n * progress\n * - tracking the approximate time it takes from the beginning of\n * snapshot \"reservation\" to the subsequent subscription, which\n * serves as the minimum interval to wait before cleaning up\n * backed up changes.\n */\n\nimport type {LogContext} from '@rocicorp/logger';\nimport {resolver} from '@rocicorp/resolver';\nimport {AbortError} from '../../../../shared/src/abort-error.ts';\nimport {sleep} from '../../../../shared/src/sleep.ts';\nimport * as v from '../../../../shared/src/valita.ts';\nimport {type NormalizedZeroConfig} from '../../config/normalize.ts';\nimport {getShardConfig} from '../../types/shards.ts';\nimport type {Source} from '../../types/streams.ts';\nimport {ChangeStreamerHttpClient} from './change-streamer-http.ts';\n\nconst statusSchema = v.object({\n tag: v.literal('status'),\n\n /**\n * The location from which litestream should perform the restore.\n */\n backupURL: v.string(),\n\n /**\n * The `replicaVersion` of the backup. If a subscriber's restored or\n * existing replica is of a different version, it should delete it and\n * retry the restore from litestream (i.e. equivalent to a\n * `WrongReplicaVersion` response from a `/changes` subscription).\n */\n replicaVersion: v.string(),\n\n /**\n * The earliest watermark from which catchup is possible. If the\n * subscriber's replica is older that this watermark, it should delete it\n * and (retry the) restore from litestream (i.e. equivalent to a\n * `WatermarkTooOld` response from a `/changes` subscription).\n */\n minWatermark: v.string(),\n});\n\nexport type SnapshotStatus = v.Infer<typeof statusSchema>;\n\nconst statusMessageSchema = v.tuple([v.literal('status'), statusSchema]);\n\nexport const snapshotMessageSchema = v.union(statusMessageSchema);\n\nexport type SnapshotMessage = v.Infer<typeof statusMessageSchema>;\n\nexport type ReserveSnapshot = (\n lc: LogContext,\n config: NormalizedZeroConfig,\n) => Promise<Source<SnapshotMessage>>;\n\nexport function reserveAndGetSnapshotStatus(\n lc: LogContext,\n config: NormalizedZeroConfig,\n reserve: ReserveSnapshot = reserveSnapshot, // for testing\n): Promise<SnapshotStatus> {\n const {promise: status, resolve, reject} = resolver<SnapshotStatus>();\n\n void (async function () {\n const abort = new AbortController();\n const {signal} = abort;\n const onSignal = () => abort.abort();\n process.on('SIGINT', onSignal);\n process.on('SIGTERM', onSignal);\n\n try {\n for (let i = 0; ; i++) {\n let err: unknown;\n try {\n let resolved = false;\n const stream = await untilAborted(reserve(lc, config), signal);\n // A signal while the stream is open cancels it, which ends the\n // iteration below with an AbortError.\n const cancelStream = () => stream.cancel(new AbortError('Aborted'));\n signal.addEventListener('abort', cancelStream, {once: true});\n try {\n for await (const msg of stream) {\n // Capture the value of the status message that the change-streamer\n // backup monitor returns, and hold the connection open to\n // \"reserve\" the snapshot and prevent change log cleanup.\n resolve(msg[1]);\n resolved = true;\n }\n } finally {\n signal.removeEventListener('abort', cancelStream);\n }\n // The change-streamer itself closes the connection when the\n // subscription is started (or the reservation retried).\n if (resolved) {\n break;\n }\n } catch (e) {\n err = e;\n }\n if (signal.aborted) {\n // (A no-op if the status was already resolved.)\n return reject(\n err instanceof AbortError ? err : new AbortError('Aborted'),\n );\n }\n // Retry in the view-syncer since it cannot proceed until it connects\n // to a (compatible) replication-manager. In particular, a\n // replication-manager that does not support the view-syncer's\n // change-streamer protocol will close the stream with an error; this\n // retry logic essentially delays the startup of a view-syncer until\n // a compatible replication-manager has been rolled out, allowing\n // replication-manager and view-syncer services to be updated in\n // parallel.\n lc.warn?.(\n `Unable to reserve snapshot (attempt ${i + 1}). Retrying in 5 seconds.`,\n String(err),\n );\n try {\n await sleep(5000, abort.signal);\n } catch (e) {\n return reject(e);\n }\n }\n } finally {\n // This function is called repeatedly (e.g. by the replicator's restore\n // loop), so the signal handlers must not outlive the reservation.\n process.off('SIGINT', onSignal);\n process.off('SIGTERM', onSignal);\n }\n })();\n\n return status;\n}\n\n/**\n * Resolves with the reserved stream, or rejects with an AbortError if the\n * `signal` is aborted while the reservation is pending (in which case a\n * stream that arrives later is canceled rather than held open).\n */\nfunction untilAborted<T>(\n reservation: Promise<Source<T>>,\n signal: AbortSignal,\n): Promise<Source<T>> {\n return new Promise((resolve, reject) => {\n const onAbort = () => reject(new AbortError('Aborted'));\n signal.addEventListener('abort', onAbort, {once: true});\n reservation.then(\n stream => {\n signal.removeEventListener('abort', onAbort);\n if (signal.aborted) {\n stream.cancel();\n } else {\n resolve(stream);\n }\n },\n e => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\nfunction reserveSnapshot(\n lc: LogContext,\n config: NormalizedZeroConfig,\n): Promise<Source<SnapshotMessage>> {\n const {taskID, change, changeStreamer} = config;\n const shardID = getShardConfig(config);\n\n const changeStreamerClient = new ChangeStreamerHttpClient(\n lc,\n shardID,\n change.db,\n changeStreamer.uri,\n );\n\n return changeStreamerClient.reserveSnapshot(taskID);\n}\n"],"mappings":";;;;;;;;AAwBA,IAAM,eAAe,eAAE,OAAO;CAC5B,KAAK,eAAE,QAAQ,QAAQ;;;;CAKvB,WAAW,eAAE,OAAO;;;;;;;CAQpB,gBAAgB,eAAE,OAAO;;;;;;;CAQzB,cAAc,eAAE,OAAO;AACzB,CAAC;AAID,IAAM,sBAAsB,eAAE,MAAM,CAAC,eAAE,QAAQ,QAAQ,GAAG,YAAY,CAAC;AAEvE,IAAa,wBAAwB,eAAE,MAAM,mBAAmB;AAShE,SAAgB,4BACd,IACA,QACA,UAA2B,iBACF;CACzB,MAAM,EAAC,SAAS,QAAQ,SAAS,WAAU,SAAyB;CAEpE,CAAM,iBAAkB;EACtB,MAAM,QAAQ,IAAI,gBAAgB;EAClC,MAAM,EAAC,WAAU;EACjB,MAAM,iBAAiB,MAAM,MAAM;EACnC,QAAQ,GAAG,UAAU,QAAQ;EAC7B,QAAQ,GAAG,WAAW,QAAQ;EAE9B,IAAI;GACF,KAAK,IAAI,IAAI,IAAK,KAAK;IACrB,IAAI;IACJ,IAAI;KACF,IAAI,WAAW;KACf,MAAM,SAAS,MAAM,aAAa,QAAQ,IAAI,MAAM,GAAG,MAAM;KAG7D,MAAM,qBAAqB,OAAO,OAAO,IAAI,WAAW,SAAS,CAAC;KAClE,OAAO,iBAAiB,SAAS,cAAc,EAAC,MAAM,KAAI,CAAC;KAC3D,IAAI;MACF,WAAW,MAAM,OAAO,QAAQ;OAI9B,QAAQ,IAAI,EAAE;OACd,WAAW;MACb;KACF,UAAU;MACR,OAAO,oBAAoB,SAAS,YAAY;KAClD;KAGA,IAAI,UACF;IAEJ,SAAS,GAAG;KACV,MAAM;IACR;IACA,IAAI,OAAO,SAET,OAAO,OACL,eAAe,aAAa,MAAM,IAAI,WAAW,SAAS,CAC5D;IAUF,GAAG,OACD,uCAAuC,IAAI,EAAE,4BAC7C,OAAO,GAAG,CACZ;IACA,IAAI;KACF,MAAM,MAAM,KAAM,MAAM,MAAM;IAChC,SAAS,GAAG;KACV,OAAO,OAAO,CAAC;IACjB;GACF;EACF,UAAU;GAGR,QAAQ,IAAI,UAAU,QAAQ;GAC9B,QAAQ,IAAI,WAAW,QAAQ;EACjC;CACF,GAAG;CAEH,OAAO;AACT;;;;;;AAOA,SAAS,aACP,aACA,QACoB;CACpB,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,gBAAgB,OAAO,IAAI,WAAW,SAAS,CAAC;EACtD,OAAO,iBAAiB,SAAS,SAAS,EAAC,MAAM,KAAI,CAAC;EACtD,YAAY,MACV,WAAU;GACR,OAAO,oBAAoB,SAAS,OAAO;GAC3C,IAAI,OAAO,SACT,OAAO,OAAO;QAEd,QAAQ,MAAM;EAElB,IACA,MAAK;GACH,OAAO,oBAAoB,SAAS,OAAO;GAC3C,OAAO,CAAC;EACV,CACF;CACF,CAAC;AACH;AAEA,SAAS,gBACP,IACA,QACkC;CAClC,MAAM,EAAC,QAAQ,QAAQ,mBAAkB;CAUzC,OAAO,IAP0B,yBAC/B,IAHc,eAAe,MAI7B,GACA,OAAO,IACP,eAAe,GAGV,EAAqB,gBAAgB,MAAM;AACpD"}
@@ -1 +1 @@
1
- {"version":3,"file":"storer.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/change-streamer/storer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAKjD,OAAO,EAEL,KAAK,UAAU,EAChB,MAAM,uCAAuC,CAAC;AAM/C,OAAO,EAAiB,eAAe,EAAC,MA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C,IAAI,CAAC,GAAG,SAAS,CAwBxC;IAmDD;;;OAGG;IACG,GAAG,kBA6BR;IAofD;;;OAGG;IACG,YAAY,kBAMjB;IAED;;;;OAIG;IACG,IAAI,kBAcT;CACF;AAED,qBAAa,SAAS;;IAGpB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAE9B,YACE,EAAE,EAAE,UAAU,EACd,EAAE,EAAE,eAAe,EACnB,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,MAAM,EAMlB;IAIK,OAAO,kBAUZ;CACF;AAED,qBAAa,WAAW;;IAKtB,YAAY,EAAE,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,UAAU,EAIzD;IAOK,OAAO,8BA2BZ;CACF;AAKD,KAAK,OAAO,GAAG,UAAU,CAAC;AAE1B,KAAK,UAAU,GAAG,MAAM,IAAI,CAAC;AAE7B;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,eAAe;;IAQ1B,YACE,EAAE,EAAE,UAAU,EACd,kBAAkB,EAAE,MAAM,EAC1B,SAAS,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,EAKhC;IAED,KAAK,SAMJ;IAGD,iBAAiB,CAAC,GAAG,EAAE,IAAI,QAgB1B;IAED;;;;OAIG;IACH,SAAS,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,OAAa,GAAG,UAAU,CAKrD;IAED,IAAI,SAGH;CACF"}
1
+ {"version":3,"file":"storer.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/change-streamer/storer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAKjD,OAAO,EAEL,KAAK,UAAU,EAChB,MAAM,uCAAuC,CAAC;AAM/C,OAAO,EAAiB,eAAe,EAAC,MAAM,8BAA8B,CAAC;AAC7E,OAAO,EAAC,KAAK,UAAU,EAA2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,GAAG,kBA6BR;IAyfD;;;OAGG;IACG,YAAY,kBAMjB;IAED;;;;OAIG;IACG,IAAI,kBAcT;CACF;AAED,qBAAa,SAAS;;IAGpB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAE9B,YACE,EAAE,EAAE,UAAU,EACd,EAAE,EAAE,eAAe,EACnB,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,MAAM,EAMlB;IAIK,OAAO,kBAUZ;CACF;AAED,qBAAa,WAAW;;IAKtB,YAAY,EAAE,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,UAAU,EAIzD;IAOK,OAAO,8BA2BZ;CACF;AAKD,KAAK,OAAO,GAAG,UAAU,CAAC;AAE1B,KAAK,UAAU,GAAG,MAAM,IAAI,CAAC;AAE7B;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,eAAe;;IAQ1B,YACE,EAAE,EAAE,UAAU,EACd,kBAAkB,EAAE,MAAM,EAC1B,SAAS,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,EAKhC;IAED,KAAK,SAMJ;IAGD,iBAAiB,CAAC,GAAG,EAAE,IAAI,QAgB1B;IAED;;;;OAIG;IACH,SAAS,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,OAAa,GAAG,UAAU,CAKrD;IAED,IAAI,SAGH;CACF"}
@@ -511,6 +511,8 @@ var Storer = class {
511
511
  lc.info?.(`snapshotted db at ${lastWatermark} (${await snapshotID}) to catchup ${numCatchups} subscriber(s)`);
512
512
  } catch (e) {
513
513
  subs.map(({ subscriber }) => subscriber.fail(e));
514
+ reader.abort();
515
+ catchupConns.end().catch(() => {});
514
516
  throw e;
515
517
  } finally {
516
518
  catchupSnapshotted();
@@ -1 +1 @@
1
- {"version":3,"file":"storer.js","names":["#lc","#shard","#taskID","#discoveryAddress","#discoveryProtocol","#makeConnectionPool","#db","#inserter","#purger","#replicaVersion","#onCommitted","#onFatal","#queue","#backPressureThresholdBytes","#statementTimeoutMs","#changeLogBatchSize","#drainTimeoutMs","#progressMonitor","#withTimeout","#cdc","#approximateQueuedBytes","#running","#readyForMore","#stopped","#processQueue","#cancelQueueEntries","#startCatchup","#flushChangeLog","#trackBackfillMetadata","#maybeReleaseBackPressure","#catchup","#cookieStmts","#upsertTableMetadataStmt","#upsertColumnBackfillStmt","#tx","#released","#failureThresholdMs","#onFailure","#taskUpdates","#timer"],"sources":["../../../../../../zero-cache/src/services/change-streamer/storer.ts"],"sourcesContent":["import {getHeapStatistics} from 'node:v8';\nimport type {LogContext} from '@rocicorp/logger';\nimport {resolver, type Resolver} from '@rocicorp/resolver';\nimport {type PendingQuery, type Row} from 'postgres';\nimport {AbortError} from '../../../../shared/src/abort-error.ts';\nimport {assert, unreachable} from '../../../../shared/src/asserts.ts';\nimport {\n BigIntJSON,\n type JSONObject,\n} from '../../../../shared/src/bigint-json.ts';\nimport {Queue} from '../../../../shared/src/queue.ts';\nimport {promiseVoid} from '../../../../shared/src/resolved-promises.ts';\nimport * as v from '../../../../shared/src/valita.ts';\nimport * as Mode from '../../db/mode-enum.ts';\nimport {runTx} from '../../db/run-transaction.ts';\nimport {sharedSnapshot, TransactionPool} from '../../db/transaction-pool.ts';\nimport {type PostgresDB, type PostgresTransaction} from '../../types/pg.ts';\nimport {cdcSchema, type ShardID} from '../../types/shards.ts';\nimport {orTimeout} from '../../types/timeout.ts';\nimport {\n backfillRequestSchema,\n isDataChange,\n isSchemaChange,\n type BackfillID,\n type BackfillRequest,\n type Change,\n type DataChange,\n type Identifier,\n type SchemaChange,\n type TableMetadata,\n} from '../change-source/protocol/current.ts';\nimport {\n type ChangeStreamData,\n type Commit,\n} from '../change-source/protocol/current/downstream.ts';\nimport type {UpstreamStatusMessage} from '../change-source/protocol/current/status.ts';\nimport {\n cookieOps,\n type BackfillCookie,\n type CookieOp,\n type CookieSet,\n type TableMetadataCookie,\n} from '../replicator/change-log-cookies.ts';\nimport type {ReplicatorMode} from '../replicator/replicator.ts';\nimport type {Service} from '../service.ts';\nimport {\n reconstructWatermarkedChange,\n serializeChangeStreamDataWithChange,\n type ChangeLogEntry,\n type SerializedChangeStreamData,\n} from './change-log-codec.ts';\nimport * as ErrorType from './error-type-enum.ts';\nimport {\n AutoResetSignal,\n markResetRequired,\n type BackfillingColumn,\n type TableMetadataRow,\n} from './schema/tables.ts';\nimport type {Subscriber} from './subscriber.ts';\n\n/**\n * Factory for creating dynamic connection pools used by the Storer to\n * isolate concurrent transactions into separate pg clients.\n */\nexport type PostgresDBProvider = (\n applicationName: string,\n maxConns: number,\n) => PostgresDB;\n\ntype SubscriberAndMode = {\n subscriber: Subscriber;\n mode: ReplicatorMode;\n};\n\ntype QueueEntry =\n | [\n 'change',\n watermark: string,\n json: string,\n storedChange: string,\n orig: Exclude<Change, DataChange> | null, // null for DataChanges\n ]\n | ['ready', callback: () => void]\n | ['subscriber', SubscriberAndMode]\n | ['abort']\n | 'stop';\n\ntype PendingTransaction = {\n pool: TransactionPool;\n preCommitWatermark: string;\n pos: number;\n startingReplicationState: Promise<ReplicationOwner>;\n ack: boolean;\n // changeLog rows buffered for the next multi-row INSERT flush.\n batch: ChangeLogRow[];\n // The most recently issued flush (or metadata) process, awaited to bound\n // pipeline depth and to order the commit-time replicationState update.\n lastFlush: Promise<unknown> | undefined;\n};\n\ntype ReplicationOwner = {\n owner: string | null;\n};\n\nconst backfillRequestsSchema = v.array(backfillRequestSchema);\n\nexport type TuningOptions = {\n backPressureLimitHeapProportion: number;\n statementTimeoutMs: number;\n changeLogBatchSize: number;\n drainTimeoutMs?: number | undefined;\n};\n\n/**\n * A single `changeLog` row, accumulated in {@link PendingTransaction.batch}\n * and written via `json_to_recordset()` (see `#flushChangeLog()`).\n */\ntype ChangeLogRow = {\n watermark: string;\n precommit: string | null;\n pos: number;\n change: string;\n};\n\n/**\n * Handles the storage of changes and the catchup of subscribers\n * that are behind.\n *\n * In the context of catchup and cleanup, it is the responsibility of the\n * Storer to decide whether a client can be caught up, or whether the\n * changes needed to catch a client up have been purged.\n *\n * **Maintained invariant**: The Change DB is only empty for a\n * completely new replica (i.e. initial-sync with no changes from the\n * replication stream).\n * * In this case, all new subscribers are expected start from the\n * `replicaVersion`, which is the version at which initial sync\n * was performed, and any attempts to catchup from a different\n * point fail.\n *\n * Conversely, if non-initial changes have flowed through the system\n * (i.e. via the replication stream), the ChangeDB must *not* be empty,\n * and the earliest change in the `changeLog` represents the earliest\n * \"commit\" from (after) which a subscriber can be caught up.\n * * Any attempts to catchup from an earlier point must fail with\n * a `WatermarkTooOld` error.\n * * Failure to do so could result in streaming changes to the\n * subscriber such that there is a gap in its replication history.\n *\n * Note: Subscribers (i.e. `incremental-syncer`) consider an \"error\" signal\n * an unrecoverable error and shut down in response. This allows the\n * production system to replace it with a new task and fresh copy of the\n * replica backup.\n */\nexport class Storer implements Service {\n readonly id = 'storer';\n readonly #lc: LogContext;\n readonly #shard: ShardID;\n readonly #taskID: string;\n readonly #discoveryAddress: string;\n readonly #discoveryProtocol: string;\n readonly #makeConnectionPool: PostgresDBProvider;\n\n // Isolated connection pools for steady-state, potentially concurrent\n // queries, in order to avoid a postgres.js connection-swapping bug:\n // https://github.com/porsager/postgres/issues/1204\n readonly #db: PostgresDB;\n readonly #inserter: PostgresDB;\n readonly #purger: PostgresDB;\n\n readonly #replicaVersion: string;\n readonly #onCommitted: (c: Commit) => void;\n readonly #onFatal: (err: Error) => void;\n readonly #queue = new Queue<QueueEntry>();\n readonly #backPressureThresholdBytes: number;\n readonly #statementTimeoutMs: number;\n readonly #changeLogBatchSize: number;\n readonly #drainTimeoutMs: number;\n readonly #progressMonitor: ProgressMonitor;\n\n #approximateQueuedBytes = 0;\n #running = false;\n\n constructor(\n lc: LogContext,\n shard: ShardID,\n taskID: string,\n discoveryAddress: string,\n discoveryProtocol: string,\n dbProvider: PostgresDBProvider,\n replicaVersion: string,\n onCommitted: (c: Commit | UpstreamStatusMessage) => void,\n onFatal: (err: Error) => void,\n {\n backPressureLimitHeapProportion,\n statementTimeoutMs,\n changeLogBatchSize,\n drainTimeoutMs = 30_000,\n }: TuningOptions,\n ) {\n this.#lc = lc.withContext('component', 'change-log');\n this.#shard = shard;\n this.#taskID = taskID;\n this.#discoveryAddress = discoveryAddress;\n this.#discoveryProtocol = discoveryProtocol;\n this.#makeConnectionPool = dbProvider;\n this.#db = dbProvider('change-stream-init', 3);\n this.#inserter = dbProvider('change-log-inserter', 1);\n this.#purger = dbProvider('change-log-purger', 1);\n this.#replicaVersion = replicaVersion;\n this.#onCommitted = onCommitted;\n this.#onFatal = onFatal;\n this.#statementTimeoutMs = statementTimeoutMs;\n this.#changeLogBatchSize = Math.max(1, changeLogBatchSize);\n this.#drainTimeoutMs = drainTimeoutMs;\n this.#progressMonitor = new ProgressMonitor(\n lc,\n statementTimeoutMs,\n onFatal,\n );\n\n const heapStats = getHeapStatistics();\n this.#backPressureThresholdBytes =\n (heapStats.heap_size_limit - heapStats.used_heap_size) *\n backPressureLimitHeapProportion;\n\n this.#lc.info?.(\n `Using up to ${(this.#backPressureThresholdBytes / 1024 ** 2).toFixed(2)} MB of ` +\n `--max-old-space-size (~${(heapStats.heap_size_limit / 1024 ** 2).toFixed(2)} MB) ` +\n `to absorb upstream spikes`,\n {heapStats},\n );\n }\n\n // For readability in SQL statements.\n #cdc(table: string) {\n return this.#db(`${cdcSchema(this.#shard)}.${table}`);\n }\n\n /**\n * Bounds a one-off db call (i.e. not part of the main storer loop or the\n * background catchup read, which are tracked by the ProgressMonitor\n * instead) with a plain timeout. This covers calls like\n * {@link assumeOwnership} and {@link getStartStreamInitializationParameters}\n * that are made by the caller *before* {@link run()} -- and thus before the\n * ProgressMonitor's polling starts -- as well as ones made well after,\n * where a continuously-polling watchdog would be overkill for a single\n * bounded db round trip.\n *\n * Does not cancel `promise` on timeout (there is no cancellation mechanism\n * for a postgres.js query); it just stops waiting for it, and swallows a\n * later rejection so it doesn't surface as an unhandled rejection.\n */\n async #withTimeout<T>(name: string, promise: Promise<T>): Promise<T> {\n const result = await orTimeout(promise, this.#statementTimeoutMs);\n if (result === 'timed-out') {\n void promise.catch(() => {});\n throw new AbortError(\n `${name} did not complete within ${this.#statementTimeoutMs}ms`,\n );\n }\n return result;\n }\n\n async assumeOwnership(purgeLock?: PurgeLock | null) {\n const db = this.#db;\n const owner = this.#taskID;\n const ownerAddress = this.#discoveryAddress;\n const ownerProtocol = this.#discoveryProtocol;\n // we omit `ws://` so that old view syncer versions that are not expecting the protocol continue to not get it\n const addressWithProtocol =\n ownerProtocol === 'ws'\n ? ownerAddress\n : `${ownerProtocol}://${ownerAddress}`;\n this.#lc.info?.(`assuming ownership at ${addressWithProtocol}`);\n const start = performance.now();\n await this.#withTimeout(\n 'assume-ownership',\n db`UPDATE ${this.#cdc('replicationState')} SET ${db({owner, ownerAddress: addressWithProtocol})}`,\n );\n const elapsed = (performance.now() - start).toFixed(2);\n this.#lc.info?.(\n `assumed ownership at ${addressWithProtocol} (${elapsed} ms)`,\n );\n\n if (purgeLock) {\n // Once ownership has been assumed, any initial purge-lock preventing the\n // purging of change-log records can be released, as a change-streamer\n // that was attempting to purge records will correspondingly abort on the\n // ownership check.\n void purgeLock.release();\n }\n }\n\n /**\n * The whole of what a stream connection starts from: where to resume, what to\n * ask the change source to backfill, and the raw cookie set those requests\n * were derived from.\n *\n * All four statements run in one REPEATABLE READ transaction, so they see one\n * snapshot. That is invariant 15 — the resume watermark and the cookies must\n * come from the same store, read at the same position — and it is why the\n * cookies are read here rather than by a second call: a cookie set paired\n * with a watermark it was not folded to loses every backfill that completed\n * in the interval, and those rows are not replayable from the slot.\n *\n * `cookies` is not `backfillRequests` in another shape. The request list is\n * driven off `backfilling`, so it drops the metadata of every table with no\n * in-flight backfill — correct for starting a stream, lossy as the cookie\n * snapshot that the SQLite change log continues folding onto.\n */\n async getStartStreamInitializationParameters(): Promise<{\n lastWatermark: string;\n backfillRequests: BackfillRequest[];\n cookies: CookieSet;\n }> {\n const [[{lastWatermark}], result, tableMetadata, backfilling] =\n await this.#withTimeout(\n 'get-stream-params',\n runTx(\n this.#db,\n sql => [\n sql<{lastWatermark: string}[]>`\n SELECT \"lastWatermark\" FROM ${this.#cdc('replicationState')}`,\n\n // Formats a BackfillRequest using json_object_agg() to construct the\n // `columns` object. It is LEFT JOIN'ed with the `tableMetadata` table\n // to make it optional and possibly `null`.\n sql`\n SELECT\n json_build_object(\n 'schema', b.\"schema\",\n 'name', b.\"table\",\n 'metadata', t.\"metadata\"\n ) as \"table\",\n json_object_agg(b.\"column\", b.\"backfill\")\n as \"columns\"\n FROM ${this.#cdc('backfilling')} as b\n LEFT JOIN ${this.#cdc('tableMetadata')} as t\n ON (b.\"schema\" = t.\"schema\" AND b.\"table\" = t.\"table\")\n GROUP BY b.\"schema\", b.\"table\", t.\"metadata\"\n `,\n\n // Ordered by primary key, so that this set and the SQLite change log's\n // can be compared row for row. `COLLATE \"C\"` because that comparison is\n // against a store whose TEXT columns sort by byte: a linguistic\n // collation orders `foo-bar` and `foobar` differently than SQLite's\n // BINARY does, which would read as a divergence rather than as the\n // identical set it is.\n sql<TableMetadataCookie[]>`\n SELECT \"schema\", \"table\", \"metadata\" FROM ${this.#cdc('tableMetadata')}\n ORDER BY \"schema\" COLLATE \"C\", \"table\" COLLATE \"C\"`,\n\n sql<BackfillCookie[]>`\n SELECT \"schema\", \"table\", \"column\", \"backfill\" FROM ${this.#cdc('backfilling')}\n ORDER BY \"schema\" COLLATE \"C\", \"table\" COLLATE \"C\", \"column\" COLLATE \"C\"`,\n ],\n {mode: Mode.READONLY},\n ),\n );\n\n return {\n lastWatermark,\n backfillRequests: v.parse(result, backfillRequestsSchema),\n cookies: {\n tableMetadata: [...tableMetadata],\n backfilling: [...backfilling],\n },\n };\n }\n\n async getMinWatermarkForCatchup(): Promise<string | null> {\n const [{minWatermark}] = await this.#withTimeout(\n 'get-min-watermark',\n this.#db<{minWatermark: string | null}[]> /*sql*/ `\n SELECT min(watermark) as \"minWatermark\" FROM ${this.#cdc('changeLog')}`,\n );\n return minWatermark;\n }\n\n /**\n * Returns the retained Postgres catchup bounds.\n * `minWatermark` is the oldest transaction, or `null` for a new replica.\n * `lastWatermark` is the durable head.\n */\n async getCatchupBounds(): Promise<{\n minWatermark: string | null;\n lastWatermark: string;\n }> {\n const [bounds] = await this.#withTimeout(\n 'get-catchup-bounds',\n this.#db<{minWatermark: string | null; lastWatermark: string}[]> /*sql*/ `\n SELECT\n (SELECT min(watermark) FROM ${this.#cdc('changeLog')}) as \"minWatermark\",\n (SELECT \"lastWatermark\" FROM ${this.#cdc('replicationState')}) as \"lastWatermark\"`,\n );\n return bounds;\n }\n\n /**\n * Lists at most `limit` committed transaction watermarks in\n * `(afterWatermark, throughWatermark]`, in ascending order.\n */\n async listCommitWatermarks(\n afterWatermark: string,\n throughWatermark: string,\n limit: number,\n ): Promise<string[]> {\n const rows = await this.#db<{watermark: string}[]> /*sql*/ `\n SELECT watermark FROM ${this.#cdc('changeLog')}\n WHERE precommit IS NOT NULL\n AND watermark > ${afterWatermark}\n AND watermark <= ${throughWatermark}\n ORDER BY watermark\n LIMIT ${limit}`;\n return rows.map(({watermark}) => watermark);\n }\n\n /**\n * Reads `(afterWatermark, throughWatermark]` in stream order and bounded batches.\n * This query matches the subscriber catchup query.\n *\n * Both queries fail when an escaped NUL reaches `change->'tag'`.\n * Postgres cannot convert that value to text.\n */\n readCatchupRange(\n afterWatermark: string,\n throughWatermark: string,\n batchRows = 2000,\n ): AsyncIterable<ChangeLogEntry[]> {\n assert(\n Number.isSafeInteger(batchRows) && batchRows > 0,\n 'Postgres change log batch size must be a positive safe integer',\n );\n return this.#db<ChangeLogEntry[]> /*sql*/ `\n SELECT watermark, change->'tag' as tag, change::text FROM ${this.#cdc('changeLog')}\n WHERE watermark > ${afterWatermark}\n AND watermark <= ${throughWatermark}\n ORDER BY watermark, pos`.cursor(batchRows) as AsyncIterable<\n ChangeLogEntry[]\n >;\n }\n\n // Note: These are the only db `await`s that are not tracked by the\n // ProgressMonitor, as the delete can legitimately block and/or take\n // an arbitrary amount of time. Luckily, this is a background call and\n // thus cannot cause the storer loop to hang.\n purgeRecordsBefore(watermark: string): Promise<number> {\n return runTx(this.#purger, async sql => {\n // This NOWAIT pre-check is an optimization to abort the transaction\n // (and release associated resources) early.\n await sql<{watermark: string}[]>`\n SELECT watermark FROM ${this.#cdc('changeLog')}\n ORDER BY watermark, pos LIMIT 1\n FOR UPDATE NOWAIT\n `;\n // If the row is purge-locked by an incoming replication-manager, it\n // will assume ownership of the change-log before releasing the lock.\n // This DELETE blocks until the lock is released, allowing the change\n // in ownership to be reliably detected (and the transaction aborted)\n // in the subsequent check.\n const [{deleted}] = await sql<{deleted: bigint}[]>`\n -- The backup watermark can be ahead of the durable changeLog if the\n -- storer is behind but the backup replica has consumed forwarded\n -- changes. Preserve the latest durable changeLog transaction as the\n -- catchup boundary instead of assuming the backup watermark exists.\n -- The storer inserts each changeLog transaction atomically, so any\n -- durable row for a watermark implies the full transaction is durable.\n WITH keep AS (\n SELECT max(watermark) AS watermark\n FROM ${this.#cdc('changeLog')}\n ), purged AS (\n DELETE FROM ${this.#cdc('changeLog')} WHERE watermark < ${watermark} \n AND watermark < (SELECT watermark FROM keep)\n RETURNING watermark, pos\n ) SELECT COUNT(*) as deleted FROM purged;`;\n\n const [{owner}] = await sql<ReplicationOwner[]>`\n SELECT \"owner\" FROM ${this.#cdc('replicationState')} FOR SHARE`;\n if (owner !== this.#taskID) {\n throw new AbortError(\n `aborting changeLog purge to ${watermark} because ownership has been taken by ${owner}`,\n );\n }\n return Number(deleted);\n });\n }\n\n /**\n * @returns The JSON stringified stream message to be sent downstream.\n */\n store(\n watermark: string,\n data: ChangeStreamData,\n serialized: SerializedChangeStreamData = serializeChangeStreamDataWithChange(\n data,\n ),\n ) {\n // Eagerly stringify the JSON payload to:\n // - avoid redundant stringification when fanning out to subscribers\n // - efficiently estimate the amount of memory the payload consumes\n const {json, change: storedChange} = serialized;\n this.#approximateQueuedBytes += json.length;\n\n const change = data[1];\n this.#queue.enqueue([\n 'change',\n watermark,\n json,\n storedChange,\n isDataChange(change) ? null : change, // drop DataChanges to save memory\n ]);\n\n return json;\n }\n\n abort() {\n this.#queue.enqueue(['abort']);\n }\n\n catchup(subscriber: Subscriber, mode: ReplicatorMode) {\n this.#queue.enqueue(['subscriber', {subscriber, mode}]);\n }\n\n #readyForMore: Resolver<void> | null = null;\n\n readyForMore(): Promise<void> | undefined {\n if (!this.#running) {\n return undefined;\n }\n if (\n this.#readyForMore === null &&\n this.#approximateQueuedBytes > this.#backPressureThresholdBytes\n ) {\n this.#lc.warn?.(\n `applying back pressure with ${this.#queue.size()} queued changes (~${(this.#approximateQueuedBytes / 1024 ** 2).toFixed(2)} MB)\\n` +\n `\\n` +\n `To inspect changeLog backlog in your change DB:\\n` +\n ` SELECT\\n` +\n ` (change->'relation'->>'schema') || '.' || (change->'relation'->>'name') AS table_name,\\n` +\n ` change->>'tag' AS operation,\\n` +\n ` COUNT(*) AS count\\n` +\n ` FROM \"<app_id>/cdc\".\"changeLog\"\\n` +\n ` GROUP BY 1, 2\\n` +\n ` ORDER BY 3 DESC\\n` +\n ` LIMIT 20;`,\n );\n this.#readyForMore = resolver();\n }\n return this.#readyForMore?.promise;\n }\n\n #maybeReleaseBackPressure() {\n if (this.#readyForMore !== null) {\n // Wait for at least 20% of the threshold to free up.\n if (\n this.#approximateQueuedBytes <\n this.#backPressureThresholdBytes * 0.8\n ) {\n this.#lc.info?.(\n `releasing back pressure with ${this.#queue.size()} queued changes (~${(this.#approximateQueuedBytes / 1024 ** 2).toFixed(2)} MB)`,\n );\n this.#readyForMore.resolve();\n this.#readyForMore = null;\n }\n }\n }\n\n /**\n * Flushes any buffered {@link PendingTransaction.batch} rows to the changeLog.\n *\n * Uses `json_to_recordset()` so the batch is a single JSON parameter: the\n * statement text stays constant regardless of batch size, avoiding the\n * unbounded prepared-statement variants (and Postgres memory growth) that a\n * multi-row INSERT would produce. See rocicorp/mono#3511.\n *\n * Returns (and updates) {@link PendingTransaction.lastFlush}; a no-op when the\n * batch is empty.\n */\n #flushChangeLog(tx: PendingTransaction): Promise<unknown> | undefined {\n const {batch} = tx;\n if (batch.length === 0) {\n return tx.lastFlush;\n }\n tx.batch = [];\n tx.lastFlush = tx.pool.process(sql => [\n sql`\n INSERT INTO ${this.#cdc('changeLog')} (\"watermark\", \"pos\", \"change\", \"precommit\")\n SELECT \"watermark\", \"pos\", \"change\"::json, \"precommit\"\n FROM json_to_recordset(${batch}) AS x(\n \"watermark\" TEXT,\n \"pos\" INT8,\n \"change\" TEXT,\n \"precommit\" TEXT\n )`,\n ]);\n return tx.lastFlush;\n }\n\n #stopped = promiseVoid;\n\n /**\n * Runs the storer loop until {@link stop()} is called, or an error is thrown.\n * Once {@link run()} completes, it can be called again.\n */\n async run() {\n assert(!this.#running, `storer is already running`);\n\n const {promise: stopped, resolve: signalStopped} = resolver();\n this.#running = true;\n this.#stopped = stopped;\n\n this.#lc.info?.('starting storer');\n this.#progressMonitor.start(); // Note: This is stopped in stop()\n let err: unknown;\n try {\n await this.#processQueue();\n } catch (e) {\n err = e; // used in finally\n throw e;\n } finally {\n // Release any pending backpressure so the upstream can proceed\n if (this.#readyForMore !== null) {\n this.#readyForMore.resolve();\n this.#readyForMore = null;\n }\n this.#cancelQueueEntries(\n this.#queue.drain().filter(entry => entry !== undefined),\n err,\n );\n this.#running = false;\n signalStopped();\n this.#lc.info?.('storer stopped');\n }\n }\n\n #cancelQueueEntries(queue: QueueEntry[], e: unknown) {\n if (queue.length === 0) {\n return;\n }\n this.#lc.info?.(\n `canceling ${queue.length} entries from the changeLog queue`,\n );\n const err = e instanceof Error ? e : new AbortError('server shutting down');\n for (const entry of queue) {\n if (entry === 'stop') {\n continue;\n }\n const type = entry[0];\n switch (type) {\n case 'subscriber': {\n // Disconnect subscribers waiting to be caught up so that they can\n // reconnect and try again.\n const {subscriber} = entry[1];\n this.#lc.info?.(`disconnecting ${subscriber.id}`);\n subscriber.fail(err);\n break;\n }\n }\n }\n }\n\n async #processQueue() {\n let tx: PendingTransaction | null = null;\n let msg: QueueEntry | false;\n\n // Track the progress of each (previous and next) queue entry before it is\n // processed in the loop.\n let lastTaskDone: TaskDoneFn | undefined;\n const nextMessage = async () => {\n lastTaskDone?.();\n lastTaskDone = undefined;\n const entry = await this.#queue.dequeue();\n if (entry !== 'stop') {\n lastTaskDone = this.#progressMonitor.trackTask({\n task: 'queue-entry',\n // Note: TaskKeys are logged, so only include entry[0] (the type) to\n // avoid logging application data.\n type: entry[0],\n });\n }\n return entry;\n };\n\n const catchupQueue: SubscriberAndMode[] = [];\n try {\n while ((msg = await nextMessage()) !== 'stop') {\n const [msgType] = msg;\n switch (msgType) {\n case 'ready': {\n const signalReady = msg[1];\n signalReady();\n continue;\n }\n case 'subscriber': {\n const subscriber = msg[1];\n if (tx) {\n catchupQueue.push(subscriber); // Wait for the current tx to complete.\n } else {\n await this.#startCatchup([subscriber]); // Catch up immediately.\n }\n continue;\n }\n case 'abort': {\n if (tx) {\n tx.pool.abort();\n await tx.pool.done();\n tx = null;\n }\n continue;\n }\n }\n // msgType === 'change'\n const [_, watermark, json, storedChange, change] = msg;\n const tag = change?.tag;\n this.#approximateQueuedBytes -= json.length;\n\n if (tag === 'begin') {\n assert(!tx, 'received BEGIN in the middle of a transaction');\n const {promise, resolve, reject} = resolver<ReplicationOwner>();\n void promise.catch(() => {}); // handle rejections before the await\n tx = {\n pool: new TransactionPool(\n this.#lc.withContext('watermark', watermark),\n {mode: Mode.READ_COMMITTED},\n ),\n preCommitWatermark: watermark,\n pos: 0,\n startingReplicationState: promise,\n ack: !change.skipAck,\n batch: [],\n lastFlush: undefined,\n };\n tx.pool.run(this.#inserter);\n // Acquire a lock on the replicationState row to detect and/or prevent\n // a concurrent ownership change.\n void tx.pool.process(tx => {\n tx<ReplicationOwner[]> /*sql*/ `\n SELECT \"owner\" FROM ${this.#cdc('replicationState')} FOR UPDATE`.then(\n ([result]) => resolve(result),\n reject,\n );\n return [];\n });\n } else {\n assert(tx, () => `received change outside of transaction: ${json}`);\n tx.pos++;\n }\n\n const entry: ChangeLogRow = {\n watermark: tag === 'commit' ? watermark : tx.preCommitWatermark,\n precommit: tag === 'commit' ? tx.preCommitWatermark : null,\n pos: tx.pos,\n // For backwards compatibility, only the change message is stored\n // in the cdc changeLog. It was serialized separately with the\n // downstream envelope, so no full-message scan is needed here.\n change: storedChange,\n };\n\n if (change !== null && isSchemaChange(change)) {\n // Schema changes carry backfill / table-metadata statements that\n // must be applied in stream order relative to the changeLog rows.\n // Flush any buffered rows first, then write this row together with\n // its metadata statements as a single unit (preserving the previous\n // per-change ordering for schema changes).\n await this.#flushChangeLog(tx);\n tx.lastFlush = tx.pool.process(sql => [\n sql`INSERT INTO ${this.#cdc('changeLog')} ${sql(entry)}`,\n ...this.#trackBackfillMetadata(sql, change),\n ]);\n } else {\n // Accumulate plain changeLog rows (begin, data changes, commit) and\n // write them as a single multi-row INSERT. Collapsing the per-change\n // single-row INSERTs into batches is the dominant cost reduction for\n // large transactions, where the previous one-statement-per-change\n // path dominated the upstream replication lag.\n tx.batch.push(entry);\n if (tx.batch.length >= this.#changeLogBatchSize) {\n // Bound pipeline depth (and thus memory) by awaiting the previous\n // flush before issuing the next. This is the batched analog of the\n // previous per-100-statement backpressure await, and likewise\n // guards against memory blowup on very large transactions.\n const prevFlush = tx.lastFlush;\n void this.#flushChangeLog(tx);\n await prevFlush;\n }\n }\n this.#maybeReleaseBackPressure();\n\n if (tag === 'commit') {\n // Flush any remaining buffered changeLog rows (including this commit\n // row) before updating the replication state, so the state update is\n // ordered after all changeLog inserts for this transaction.\n void this.#flushChangeLog(tx);\n\n const {owner} = await tx.startingReplicationState;\n if (owner !== this.#taskID) {\n // Ownership change reflected in the replicationState read in 'begin'.\n tx.pool.fail(\n new AbortError(\n `changeLog ownership has been assumed by ${owner}`,\n ),\n );\n } else {\n // Update the replication state.\n const lastWatermark = watermark;\n void tx.pool.process(tx => [\n tx`\n UPDATE ${this.#cdc('replicationState')} SET ${tx({lastWatermark})}`,\n ]);\n tx.pool.setDone();\n }\n\n await tx.pool.done();\n\n // ACK the LSN to the upstream Postgres.\n if (tx.ack) {\n this.#onCommitted(['commit', change, {watermark}]);\n }\n tx = null;\n\n // Before beginning the next transaction, open a READONLY snapshot to\n // concurrently catchup any queued subscribers.\n await this.#startCatchup(catchupQueue.splice(0));\n } else if (tag === 'rollback') {\n // Aborted transactions are not stored in the changeLog. Abort the current tx\n // and process catchup of subscribers that were waiting for it to end.\n tx.pool.abort();\n await tx.pool.done();\n tx = null;\n\n await this.#startCatchup(catchupQueue.splice(0));\n }\n }\n } catch (e) {\n catchupQueue.forEach(({subscriber}) => subscriber.fail(e));\n throw e;\n }\n }\n\n async #startCatchup(subs: SubscriberAndMode[]) {\n const numCatchups = subs.length;\n if (numCatchups === 0) {\n return;\n }\n\n const lc = this.#lc.withContext('pool', 'catchup');\n const {init, cleanup, snapshotID} = sharedSnapshot();\n const reader = new TransactionPool(lc, {\n mode: Mode.READONLY,\n init,\n cleanup,\n initialWorkers: subs.length,\n });\n\n // A dynamic connection pool is created for catchup, sized to the number\n // of subscribers being caught up.\n const catchupConns = this.#makeConnectionPool(\n 'subscriber-catchup',\n numCatchups,\n );\n reader.run(catchupConns);\n\n let lastWatermark: string | undefined;\n const catchupSnapshotted = this.#progressMonitor.trackTask({\n task: 'capture-catchup-snapshot',\n subscribers: subs.map(({subscriber: s}) => s.id),\n });\n try {\n // Ensure that the transaction has started (and is thus holding a snapshot\n // of the database) before continuing on to commit more changes. This is\n // done by performing a single read on the db, which determines the\n // snapshot for the REPEATABLE_READ transaction.\n [{lastWatermark}] = await reader.processReadTask(\n sql => sql<{lastWatermark: string}[]>`\n SELECT \"lastWatermark\" FROM ${this.#cdc('replicationState')}\n `,\n );\n lc.info?.(\n `snapshotted db at ${lastWatermark} (${await snapshotID}) ` +\n `to catchup ${numCatchups} subscriber(s)`,\n );\n } catch (e) {\n subs.map(({subscriber}) => subscriber.fail(e));\n throw e;\n } finally {\n catchupSnapshotted();\n }\n\n // Run the actual catchup queries in the background. Errors are handled in\n // #catchup() by disconnecting the associated subscriber.\n void Promise.allSettled(\n subs.map(sub =>\n this.#catchup(\n lc.withContext('subscriber', sub.subscriber.id),\n sub,\n lastWatermark,\n reader,\n ),\n ),\n ).finally(() => {\n reader.setDone();\n void catchupConns.end().catch(() => {});\n });\n }\n\n async #catchup(\n lc: LogContext,\n {subscriber: sub, mode}: SubscriberAndMode,\n lastWatermark: string,\n reader: TransactionPool,\n ) {\n let entriesReceived = 0;\n let catchupProgressed = this.#progressMonitor.trackTask({\n task: 'catchup',\n subscriber: sub.id,\n entriesReceived,\n });\n try {\n lc.info?.(`starting catchup`);\n await reader.processReadTask(async tx => {\n lc.info?.(`catching up`);\n const start = Date.now();\n\n // When starting from initial-sync, there won't be a change with a watermark\n // equal to the replica version. This is the empty changeLog scenario.\n let watermarkFound = sub.watermark === this.#replicaVersion;\n let count = 0;\n let lastBatchConsumed: Promise<unknown> | undefined;\n\n for await (const entries of tx<ChangeLogEntry[]> /*sql*/ `\n SELECT watermark, change->'tag' as tag, change::text FROM ${this.#cdc('changeLog')}\n WHERE watermark >= ${sub.watermark}\n AND watermark <= ${lastWatermark}\n ORDER BY watermark, pos`.cursor(2000)) {\n catchupProgressed();\n entriesReceived += entries.length;\n\n try {\n // Wait for the last batch of entries to be consumed by the\n // subscriber before sending down the current batch. This pipelining\n // allows one batch of changes to be received from the change-db\n // while the previous batch of changes are sent to the subscriber,\n // resulting in flow control that caps the number of changes\n // referenced in memory to 2 * batch-size.\n const start = performance.now();\n await lastBatchConsumed;\n const elapsed = performance.now() - start;\n if (lastBatchConsumed) {\n lc[elapsed > 100 ? 'info' : 'debug']?.(\n `waited ${elapsed.toFixed(3)} ms for ${sub.id} to consume last batch of catchup entries`,\n );\n }\n\n for (const entry of entries) {\n if (entry.watermark === sub.watermark) {\n // This should be the first entry.\n // Catchup starts from *after* the watermark.\n watermarkFound = true;\n } else if (watermarkFound) {\n lastBatchConsumed = sub.catchup(\n reconstructWatermarkedChange(entry),\n );\n count++;\n } else if (mode === 'backup') {\n throw new AutoResetSignal(\n `backup replica at watermark ${sub.watermark} is behind change db: ${entry.watermark})`,\n );\n } else {\n lc.warn?.(\n `rejecting subscriber at watermark ${sub.watermark} (earliest watermark: ${entry.watermark})`,\n );\n sub.close(\n ErrorType.WatermarkTooOld,\n `earliest supported watermark is ${entry.watermark} (requested ${sub.watermark})`,\n );\n return;\n }\n }\n } finally {\n // Track the db's read of the next chunk of changes.\n catchupProgressed = this.#progressMonitor.trackTask({\n task: 'catchup',\n subscriber: sub.id,\n entriesReceived,\n });\n }\n }\n catchupProgressed();\n\n if (watermarkFound) {\n await lastBatchConsumed;\n lc.info?.(\n `caught up ${sub.id} with ${count} changes (${\n Date.now() - start\n } ms)`,\n );\n } else {\n // The subscriber is ahead of the latest durable changeLog entry\n // (lastWatermark). This can legitimately happen: changes are\n // forwarded to subscribers (the backup replica and view-syncers)\n // concurrently with — and can outrun — the durable store, so a\n // replica may briefly lead the change DB after the storer falls\n // behind or the change-streamer restarts. No catchup is possible or\n // needed; once the change DB catches back up, forwarding resumes and\n // the subscriber dedups any watermarks it already has. Unlike the\n // AutoResetSignal / WatermarkTooOld cases above, this is not a gap in\n // replication history, so the subscriber is simply marked caught up.\n lc.warn?.(\n `subscriber ${sub.id} at watermark ${sub.watermark} is ahead of ` +\n `the latest durable watermark ${lastWatermark}; waiting for the ` +\n `change DB to catch up`,\n );\n }\n // Start draining messages buffered during catchup. The returned promise\n // is intentionally not awaited here: while the drain is in progress,\n // new sends keep appending to the subscriber backlog and inherit its\n // byte-based backpressure.\n void sub.setCaughtUp();\n });\n } catch (err) {\n lc.error?.(`error while catching up subscriber ${sub.id}`, err);\n if (err instanceof AutoResetSignal) {\n await markResetRequired(this.#db, this.#shard);\n this.#onFatal(err);\n }\n sub.fail(err);\n } finally {\n catchupProgressed();\n }\n }\n\n /**\n * Returns the db statements necessary to track backfill and table metadata\n * presented in the `change`, if any.\n *\n * This is the Postgres interpreter of {@link cookieOps}, which is also\n * interpreted against the SQLite change log by `ChangeLogCookieWriter`. The\n * two stores have to agree on every transition forever, and the failure mode\n * if they drift is a backfill that is silently never re-requested — so the\n * decision of what a schema change *means* lives in one place and only its\n * transport lives here.\n */\n #trackBackfillMetadata(sql: PostgresTransaction, change: SchemaChange) {\n return cookieOps(change).flatMap(op => this.#cookieStmts(sql, op));\n }\n\n #cookieStmts(sql: PostgresTransaction, op: CookieOp): PendingQuery<Row[]>[] {\n switch (op.op) {\n case 'upsert-metadata':\n return [this.#upsertTableMetadataStmt(sql, op.table, op.metadata)];\n\n case 'upsert-backfill':\n return [\n this.#upsertColumnBackfillStmt(sql, op.table, op.column, op.backfill),\n ];\n\n case 'rename-table': {\n const {old} = op;\n const row = {schema: op.new.schema, table: op.new.name};\n return [\n sql`UPDATE ${this.#cdc('tableMetadata')} SET ${sql(row)}\n WHERE \"schema\" = ${old.schema} AND \"table\" = ${old.name}`,\n sql`UPDATE ${this.#cdc('backfilling')} SET ${sql(row)}\n WHERE \"schema\" = ${old.schema} AND \"table\" = ${old.name}`,\n ];\n }\n\n case 'drop-table': {\n const {schema, name} = op.table;\n return [\n sql`DELETE FROM ${this.#cdc('tableMetadata')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${name}`,\n sql`DELETE FROM ${this.#cdc('backfilling')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${name}`,\n ];\n }\n\n case 'rename-column': {\n const {schema, name: table} = op.table;\n return [\n sql`UPDATE ${this.#cdc('backfilling')} SET \"column\" = ${op.new}\n WHERE \"schema\" = ${schema} AND \"table\" = ${table} AND \"column\" = ${op.old}`,\n ];\n }\n\n case 'drop-column': {\n const {schema, name} = op.table;\n return [\n sql`DELETE FROM ${this.#cdc('backfilling')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${name} AND \"column\" = ${op.column}`,\n ];\n }\n\n case 'complete-backfill': {\n const {schema, name: table} = op.table;\n return [\n sql`DELETE FROM ${this.#cdc('backfilling')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${table} AND \"column\" IN ${sql([...op.columns])}`,\n ];\n }\n\n default:\n unreachable(op);\n }\n }\n\n #upsertTableMetadataStmt(\n sql: PostgresTransaction,\n {schema, name: table}: Identifier,\n metadata: TableMetadata,\n ) {\n const row: TableMetadataRow = {schema, table, metadata};\n return sql`\n INSERT INTO ${this.#cdc('tableMetadata')} ${sql(row)}\n ON CONFLICT (\"schema\", \"table\")\n DO UPDATE SET ${sql(row)};\n `;\n }\n\n #upsertColumnBackfillStmt(\n sql: PostgresTransaction,\n {schema, name: table}: Identifier,\n column: string,\n backfill: BackfillID,\n ) {\n const row: BackfillingColumn = {schema, table, column, backfill};\n return sql`\n INSERT INTO ${this.#cdc('backfilling')} ${sql(row)}\n ON CONFLICT (\"schema\", \"table\", \"column\")\n DO UPDATE SET ${sql(row)};\n `;\n }\n\n /**\n * Waits until all currently queued entries have been processed.\n * This is only used in tests.\n */\n async allProcessed() {\n if (this.#running) {\n const {promise, resolve} = resolver();\n this.#queue.enqueue(['ready', resolve]);\n await promise;\n }\n }\n\n /**\n * Stops the storer and waits up to a drain timeout for entries to drain,\n * throwing an exception if it doesn't drain in time, in order to abort\n * the server when PG (or the connection to it) appears to be wedged.\n */\n async stop() {\n if (this.#running) {\n this.#progressMonitor.stop();\n this.#lc.info?.(`draining ${this.#queue.size()} changeLog entries`);\n this.abort(); // for cleanliness, abort any open transactions\n this.#queue.enqueue('stop');\n }\n if (\n (await orTimeout(this.#stopped, this.#drainTimeoutMs)) === 'timed-out'\n ) {\n throw new AbortError(\n `changeLog did not drain within ${this.#drainTimeoutMs}ms`,\n );\n }\n }\n}\n\nexport class PurgeLock {\n readonly #lc: LogContext;\n readonly #tx: TransactionPool;\n readonly replicaVersion: string;\n readonly minWatermark: string;\n\n constructor(\n lc: LogContext,\n tx: TransactionPool,\n replicaVersion: string,\n watermark: string,\n ) {\n this.#lc = lc;\n this.#tx = tx;\n this.replicaVersion = replicaVersion;\n this.minWatermark = watermark;\n }\n\n #released = false;\n\n async release() {\n if (this.#released) {\n return;\n }\n this.#released = true;\n this.#tx.setDone();\n await this.#tx\n .done()\n .catch(e => this.#lc.warn?.(`error from purge-lock release`, e));\n this.#lc.info?.(`released purge lock on ${this.minWatermark}`);\n }\n}\n\nexport class PurgeLocker {\n readonly #lc: LogContext;\n readonly #shard: ShardID;\n readonly #db: PostgresDB;\n\n constructor(lc: LogContext, shard: ShardID, db: PostgresDB) {\n this.#lc = lc.withContext('component', 'purge-locker');\n this.#shard = shard;\n this.#db = db;\n }\n\n // For readability in SQL statements.\n #cdc(table: string) {\n return this.#db(`${cdcSchema(this.#shard)}.${table}`);\n }\n\n async acquire() {\n const tx = new TransactionPool(this.#lc, {mode: Mode.READ_COMMITTED}).run(\n this.#db,\n );\n const row = await tx.processReadTask(\n sql => sql<{watermark: string}[]>`\n SELECT watermark FROM ${this.#cdc('changeLog')}\n ORDER BY watermark, pos LIMIT 1\n FOR SHARE \n `,\n );\n if (row.length === 0) {\n this.#lc.info?.(`changeLog is empty. No rows to purge-lock.`);\n tx.setDone();\n await tx.done();\n return null;\n }\n const [{watermark}] = row;\n const [{replicaVersion}] = await tx.processReadTask(\n sql => sql<{replicaVersion: string}[]>`\n SELECT \"replicaVersion\" FROM ${this.#cdc('replicationConfig')}\n `,\n );\n this.#lc.info?.(\n `locked watermark ${watermark} from being purged from replica@${replicaVersion}`,\n );\n return new PurgeLock(this.#lc, tx, replicaVersion, watermark);\n }\n}\n\n// A TaskKey, keyed by identity, representing an db task monitored by the\n// ProgressMonitor. The contents are stringified in error messages if the\n// task fails to make progress for more than a failure threshold interval.\ntype TaskKey = JSONObject;\n\ntype TaskDoneFn = () => void;\n\n/**\n * Periodic monitor for detecting the pathological condition in which a db\n * query hangs forever because of a connection problem, such as a half-closed\n * socket.\n *\n * Use this for db calls that recur or accumulate progress within a single\n * logical operation on the main storer loop (e.g. the queue-processing loop,\n * or a multi-batch catchup read), where \"no progress for N ms\" is the\n * meaningful signal. For a one-off db call -- including ones made before\n * {@link Storer.run} starts this monitor's polling -- use a plain timeout\n * (see `Storer.#withTimeout`) instead.\n *\n * The failure handler should stop the server. The ProgressMonitor will\n * assume this and stop itself after calling it.\n *\n * Internal to the Storer, but exported for testing.\n */\nexport class ProgressMonitor {\n readonly #lc: LogContext;\n readonly #failureThresholdMs;\n readonly #onFailure: (err: Error) => void;\n readonly #taskUpdates = new Map<TaskKey, Date>();\n\n #timer: NodeJS.Timeout | undefined;\n\n constructor(\n lc: LogContext,\n failureThresholdMs: number,\n onFailure: (err: Error) => void,\n ) {\n this.#lc = lc.withContext('component', 'storer-progress-monitor');\n this.#failureThresholdMs = failureThresholdMs;\n this.#onFailure = onFailure;\n }\n\n start() {\n clearInterval(this.#timer);\n this.#timer = setInterval(\n () => this.checkTaskProgress(new Date()),\n this.#failureThresholdMs,\n ).unref();\n }\n\n // Called by an internal periodic timer, but exported for testing.\n checkTaskProgress(now: Date) {\n for (const [task, lastUpdate] of this.#taskUpdates.entries()) {\n if (now.getTime() - lastUpdate.getTime() >= this.#failureThresholdMs) {\n this.#lc.error?.(\n `Last task update was more than ${this.#failureThresholdMs}ms ago`,\n {task, lastUpdate},\n );\n this.#onFailure(\n new Error(\n `Task failed to progress for over ${this.#failureThresholdMs}ms: ${BigIntJSON.stringify(task)}`,\n ),\n );\n this.stop();\n return;\n }\n }\n }\n\n /**\n * Starts a task to be tracked.\n *\n * @return a callback to invoke when the task is done.\n */\n trackTask(task: TaskKey, now = new Date()): TaskDoneFn {\n this.#taskUpdates.set(task, now);\n return () => {\n this.#taskUpdates.delete(task);\n };\n }\n\n stop() {\n clearInterval(this.#timer);\n this.#taskUpdates.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwGA,IAAM,yBAAyB,eAAE,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkD5D,IAAa,SAAb,MAA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B,SAAS;CAC9D;AACF;;;;;;;;;;;;;;;;;;AA0BA,IAAa,kBAAb,MAA6B;CAC3B;CACA;CACA;CACA,+BAAwB,IAAI,IAAmB;CAE/C;CAEA,YACE,IACA,oBACA,WACA;EACA,KAAKA,MAAM,GAAG,YAAY,aAAa,yBAAyB;EAChE,KAAKoC,sBAAsB;EAC3B,KAAKC,aAAa;CACpB;CAEA,QAAQ;EACN,cAAc,KAAKE,MAAM;EACzB,KAAKA,SAAS,kBACN,KAAK,kCAAkB,IAAI,KAAK,CAAC,GACvC,KAAKH,mBACP,EAAE,MAAM;CACV;CAGA,kBAAkB,KAAW;EAC3B,KAAK,MAAM,CAAC,MAAM,eAAe,KAAKE,aAAa,QAAQ,GACzD,IAAI,IAAI,QAAQ,IAAI,WAAW,QAAQ,KAAK,KAAKF,qBAAqB;GACpE,KAAKpC,IAAI,QACP,kCAAkC,KAAKoC,oBAAoB,SAC3D;IAAC;IAAM;GAAU,CACnB;GACA,KAAKC,2BACH,IAAI,MACF,oCAAoC,KAAKD,oBAAoB,MAAM,WAAW,UAAU,IAAI,GAC9F,CACF;GACA,KAAK,KAAK;GACV;EACF;CAEJ;;;;;;CAOA,UAAU,MAAe,sBAAM,IAAI,KAAK,GAAe;EACrD,KAAKE,aAAa,IAAI,MAAM,GAAG;EAC/B,aAAa;GACX,KAAKA,aAAa,OAAO,IAAI;EAC/B;CACF;CAEA,OAAO;EACL,cAAc,KAAKC,MAAM;EACzB,KAAKD,aAAa,MAAM;CAC1B;AACF"}
1
+ {"version":3,"file":"storer.js","names":["#lc","#shard","#taskID","#discoveryAddress","#discoveryProtocol","#makeConnectionPool","#db","#inserter","#purger","#replicaVersion","#onCommitted","#onFatal","#queue","#backPressureThresholdBytes","#statementTimeoutMs","#changeLogBatchSize","#drainTimeoutMs","#progressMonitor","#withTimeout","#cdc","#approximateQueuedBytes","#running","#readyForMore","#stopped","#processQueue","#cancelQueueEntries","#startCatchup","#flushChangeLog","#trackBackfillMetadata","#maybeReleaseBackPressure","#catchup","#cookieStmts","#upsertTableMetadataStmt","#upsertColumnBackfillStmt","#tx","#released","#failureThresholdMs","#onFailure","#taskUpdates","#timer"],"sources":["../../../../../../zero-cache/src/services/change-streamer/storer.ts"],"sourcesContent":["import {getHeapStatistics} from 'node:v8';\nimport type {LogContext} from '@rocicorp/logger';\nimport {resolver, type Resolver} from '@rocicorp/resolver';\nimport {type PendingQuery, type Row} from 'postgres';\nimport {AbortError} from '../../../../shared/src/abort-error.ts';\nimport {assert, unreachable} from '../../../../shared/src/asserts.ts';\nimport {\n BigIntJSON,\n type JSONObject,\n} from '../../../../shared/src/bigint-json.ts';\nimport {Queue} from '../../../../shared/src/queue.ts';\nimport {promiseVoid} from '../../../../shared/src/resolved-promises.ts';\nimport * as v from '../../../../shared/src/valita.ts';\nimport * as Mode from '../../db/mode-enum.ts';\nimport {runTx} from '../../db/run-transaction.ts';\nimport {sharedSnapshot, TransactionPool} from '../../db/transaction-pool.ts';\nimport {type PostgresDB, type PostgresTransaction} from '../../types/pg.ts';\nimport {cdcSchema, type ShardID} from '../../types/shards.ts';\nimport {orTimeout} from '../../types/timeout.ts';\nimport {\n backfillRequestSchema,\n isDataChange,\n isSchemaChange,\n type BackfillID,\n type BackfillRequest,\n type Change,\n type DataChange,\n type Identifier,\n type SchemaChange,\n type TableMetadata,\n} from '../change-source/protocol/current.ts';\nimport {\n type ChangeStreamData,\n type Commit,\n} from '../change-source/protocol/current/downstream.ts';\nimport type {UpstreamStatusMessage} from '../change-source/protocol/current/status.ts';\nimport {\n cookieOps,\n type BackfillCookie,\n type CookieOp,\n type CookieSet,\n type TableMetadataCookie,\n} from '../replicator/change-log-cookies.ts';\nimport type {ReplicatorMode} from '../replicator/replicator.ts';\nimport type {Service} from '../service.ts';\nimport {\n reconstructWatermarkedChange,\n serializeChangeStreamDataWithChange,\n type ChangeLogEntry,\n type SerializedChangeStreamData,\n} from './change-log-codec.ts';\nimport * as ErrorType from './error-type-enum.ts';\nimport {\n AutoResetSignal,\n markResetRequired,\n type BackfillingColumn,\n type TableMetadataRow,\n} from './schema/tables.ts';\nimport type {Subscriber} from './subscriber.ts';\n\n/**\n * Factory for creating dynamic connection pools used by the Storer to\n * isolate concurrent transactions into separate pg clients.\n */\nexport type PostgresDBProvider = (\n applicationName: string,\n maxConns: number,\n) => PostgresDB;\n\ntype SubscriberAndMode = {\n subscriber: Subscriber;\n mode: ReplicatorMode;\n};\n\ntype QueueEntry =\n | [\n 'change',\n watermark: string,\n json: string,\n storedChange: string,\n orig: Exclude<Change, DataChange> | null, // null for DataChanges\n ]\n | ['ready', callback: () => void]\n | ['subscriber', SubscriberAndMode]\n | ['abort']\n | 'stop';\n\ntype PendingTransaction = {\n pool: TransactionPool;\n preCommitWatermark: string;\n pos: number;\n startingReplicationState: Promise<ReplicationOwner>;\n ack: boolean;\n // changeLog rows buffered for the next multi-row INSERT flush.\n batch: ChangeLogRow[];\n // The most recently issued flush (or metadata) process, awaited to bound\n // pipeline depth and to order the commit-time replicationState update.\n lastFlush: Promise<unknown> | undefined;\n};\n\ntype ReplicationOwner = {\n owner: string | null;\n};\n\nconst backfillRequestsSchema = v.array(backfillRequestSchema);\n\nexport type TuningOptions = {\n backPressureLimitHeapProportion: number;\n statementTimeoutMs: number;\n changeLogBatchSize: number;\n drainTimeoutMs?: number | undefined;\n};\n\n/**\n * A single `changeLog` row, accumulated in {@link PendingTransaction.batch}\n * and written via `json_to_recordset()` (see `#flushChangeLog()`).\n */\ntype ChangeLogRow = {\n watermark: string;\n precommit: string | null;\n pos: number;\n change: string;\n};\n\n/**\n * Handles the storage of changes and the catchup of subscribers\n * that are behind.\n *\n * In the context of catchup and cleanup, it is the responsibility of the\n * Storer to decide whether a client can be caught up, or whether the\n * changes needed to catch a client up have been purged.\n *\n * **Maintained invariant**: The Change DB is only empty for a\n * completely new replica (i.e. initial-sync with no changes from the\n * replication stream).\n * * In this case, all new subscribers are expected start from the\n * `replicaVersion`, which is the version at which initial sync\n * was performed, and any attempts to catchup from a different\n * point fail.\n *\n * Conversely, if non-initial changes have flowed through the system\n * (i.e. via the replication stream), the ChangeDB must *not* be empty,\n * and the earliest change in the `changeLog` represents the earliest\n * \"commit\" from (after) which a subscriber can be caught up.\n * * Any attempts to catchup from an earlier point must fail with\n * a `WatermarkTooOld` error.\n * * Failure to do so could result in streaming changes to the\n * subscriber such that there is a gap in its replication history.\n *\n * Note: Subscribers (i.e. `incremental-syncer`) consider an \"error\" signal\n * an unrecoverable error and shut down in response. This allows the\n * production system to replace it with a new task and fresh copy of the\n * replica backup.\n */\nexport class Storer implements Service {\n readonly id = 'storer';\n readonly #lc: LogContext;\n readonly #shard: ShardID;\n readonly #taskID: string;\n readonly #discoveryAddress: string;\n readonly #discoveryProtocol: string;\n readonly #makeConnectionPool: PostgresDBProvider;\n\n // Isolated connection pools for steady-state, potentially concurrent\n // queries, in order to avoid a postgres.js connection-swapping bug:\n // https://github.com/porsager/postgres/issues/1204\n readonly #db: PostgresDB;\n readonly #inserter: PostgresDB;\n readonly #purger: PostgresDB;\n\n readonly #replicaVersion: string;\n readonly #onCommitted: (c: Commit) => void;\n readonly #onFatal: (err: Error) => void;\n readonly #queue = new Queue<QueueEntry>();\n readonly #backPressureThresholdBytes: number;\n readonly #statementTimeoutMs: number;\n readonly #changeLogBatchSize: number;\n readonly #drainTimeoutMs: number;\n readonly #progressMonitor: ProgressMonitor;\n\n #approximateQueuedBytes = 0;\n #running = false;\n\n constructor(\n lc: LogContext,\n shard: ShardID,\n taskID: string,\n discoveryAddress: string,\n discoveryProtocol: string,\n dbProvider: PostgresDBProvider,\n replicaVersion: string,\n onCommitted: (c: Commit | UpstreamStatusMessage) => void,\n onFatal: (err: Error) => void,\n {\n backPressureLimitHeapProportion,\n statementTimeoutMs,\n changeLogBatchSize,\n drainTimeoutMs = 30_000,\n }: TuningOptions,\n ) {\n this.#lc = lc.withContext('component', 'change-log');\n this.#shard = shard;\n this.#taskID = taskID;\n this.#discoveryAddress = discoveryAddress;\n this.#discoveryProtocol = discoveryProtocol;\n this.#makeConnectionPool = dbProvider;\n this.#db = dbProvider('change-stream-init', 3);\n this.#inserter = dbProvider('change-log-inserter', 1);\n this.#purger = dbProvider('change-log-purger', 1);\n this.#replicaVersion = replicaVersion;\n this.#onCommitted = onCommitted;\n this.#onFatal = onFatal;\n this.#statementTimeoutMs = statementTimeoutMs;\n this.#changeLogBatchSize = Math.max(1, changeLogBatchSize);\n this.#drainTimeoutMs = drainTimeoutMs;\n this.#progressMonitor = new ProgressMonitor(\n lc,\n statementTimeoutMs,\n onFatal,\n );\n\n const heapStats = getHeapStatistics();\n this.#backPressureThresholdBytes =\n (heapStats.heap_size_limit - heapStats.used_heap_size) *\n backPressureLimitHeapProportion;\n\n this.#lc.info?.(\n `Using up to ${(this.#backPressureThresholdBytes / 1024 ** 2).toFixed(2)} MB of ` +\n `--max-old-space-size (~${(heapStats.heap_size_limit / 1024 ** 2).toFixed(2)} MB) ` +\n `to absorb upstream spikes`,\n {heapStats},\n );\n }\n\n // For readability in SQL statements.\n #cdc(table: string) {\n return this.#db(`${cdcSchema(this.#shard)}.${table}`);\n }\n\n /**\n * Bounds a one-off db call (i.e. not part of the main storer loop or the\n * background catchup read, which are tracked by the ProgressMonitor\n * instead) with a plain timeout. This covers calls like\n * {@link assumeOwnership} and {@link getStartStreamInitializationParameters}\n * that are made by the caller *before* {@link run()} -- and thus before the\n * ProgressMonitor's polling starts -- as well as ones made well after,\n * where a continuously-polling watchdog would be overkill for a single\n * bounded db round trip.\n *\n * Does not cancel `promise` on timeout (there is no cancellation mechanism\n * for a postgres.js query); it just stops waiting for it, and swallows a\n * later rejection so it doesn't surface as an unhandled rejection.\n */\n async #withTimeout<T>(name: string, promise: Promise<T>): Promise<T> {\n const result = await orTimeout(promise, this.#statementTimeoutMs);\n if (result === 'timed-out') {\n void promise.catch(() => {});\n throw new AbortError(\n `${name} did not complete within ${this.#statementTimeoutMs}ms`,\n );\n }\n return result;\n }\n\n async assumeOwnership(purgeLock?: PurgeLock | null) {\n const db = this.#db;\n const owner = this.#taskID;\n const ownerAddress = this.#discoveryAddress;\n const ownerProtocol = this.#discoveryProtocol;\n // we omit `ws://` so that old view syncer versions that are not expecting the protocol continue to not get it\n const addressWithProtocol =\n ownerProtocol === 'ws'\n ? ownerAddress\n : `${ownerProtocol}://${ownerAddress}`;\n this.#lc.info?.(`assuming ownership at ${addressWithProtocol}`);\n const start = performance.now();\n await this.#withTimeout(\n 'assume-ownership',\n db`UPDATE ${this.#cdc('replicationState')} SET ${db({owner, ownerAddress: addressWithProtocol})}`,\n );\n const elapsed = (performance.now() - start).toFixed(2);\n this.#lc.info?.(\n `assumed ownership at ${addressWithProtocol} (${elapsed} ms)`,\n );\n\n if (purgeLock) {\n // Once ownership has been assumed, any initial purge-lock preventing the\n // purging of change-log records can be released, as a change-streamer\n // that was attempting to purge records will correspondingly abort on the\n // ownership check.\n void purgeLock.release();\n }\n }\n\n /**\n * The whole of what a stream connection starts from: where to resume, what to\n * ask the change source to backfill, and the raw cookie set those requests\n * were derived from.\n *\n * All four statements run in one REPEATABLE READ transaction, so they see one\n * snapshot. That is invariant 15 — the resume watermark and the cookies must\n * come from the same store, read at the same position — and it is why the\n * cookies are read here rather than by a second call: a cookie set paired\n * with a watermark it was not folded to loses every backfill that completed\n * in the interval, and those rows are not replayable from the slot.\n *\n * `cookies` is not `backfillRequests` in another shape. The request list is\n * driven off `backfilling`, so it drops the metadata of every table with no\n * in-flight backfill — correct for starting a stream, lossy as the cookie\n * snapshot that the SQLite change log continues folding onto.\n */\n async getStartStreamInitializationParameters(): Promise<{\n lastWatermark: string;\n backfillRequests: BackfillRequest[];\n cookies: CookieSet;\n }> {\n const [[{lastWatermark}], result, tableMetadata, backfilling] =\n await this.#withTimeout(\n 'get-stream-params',\n runTx(\n this.#db,\n sql => [\n sql<{lastWatermark: string}[]>`\n SELECT \"lastWatermark\" FROM ${this.#cdc('replicationState')}`,\n\n // Formats a BackfillRequest using json_object_agg() to construct the\n // `columns` object. It is LEFT JOIN'ed with the `tableMetadata` table\n // to make it optional and possibly `null`.\n sql`\n SELECT\n json_build_object(\n 'schema', b.\"schema\",\n 'name', b.\"table\",\n 'metadata', t.\"metadata\"\n ) as \"table\",\n json_object_agg(b.\"column\", b.\"backfill\")\n as \"columns\"\n FROM ${this.#cdc('backfilling')} as b\n LEFT JOIN ${this.#cdc('tableMetadata')} as t\n ON (b.\"schema\" = t.\"schema\" AND b.\"table\" = t.\"table\")\n GROUP BY b.\"schema\", b.\"table\", t.\"metadata\"\n `,\n\n // Ordered by primary key, so that this set and the SQLite change log's\n // can be compared row for row. `COLLATE \"C\"` because that comparison is\n // against a store whose TEXT columns sort by byte: a linguistic\n // collation orders `foo-bar` and `foobar` differently than SQLite's\n // BINARY does, which would read as a divergence rather than as the\n // identical set it is.\n sql<TableMetadataCookie[]>`\n SELECT \"schema\", \"table\", \"metadata\" FROM ${this.#cdc('tableMetadata')}\n ORDER BY \"schema\" COLLATE \"C\", \"table\" COLLATE \"C\"`,\n\n sql<BackfillCookie[]>`\n SELECT \"schema\", \"table\", \"column\", \"backfill\" FROM ${this.#cdc('backfilling')}\n ORDER BY \"schema\" COLLATE \"C\", \"table\" COLLATE \"C\", \"column\" COLLATE \"C\"`,\n ],\n {mode: Mode.READONLY},\n ),\n );\n\n return {\n lastWatermark,\n backfillRequests: v.parse(result, backfillRequestsSchema),\n cookies: {\n tableMetadata: [...tableMetadata],\n backfilling: [...backfilling],\n },\n };\n }\n\n async getMinWatermarkForCatchup(): Promise<string | null> {\n const [{minWatermark}] = await this.#withTimeout(\n 'get-min-watermark',\n this.#db<{minWatermark: string | null}[]> /*sql*/ `\n SELECT min(watermark) as \"minWatermark\" FROM ${this.#cdc('changeLog')}`,\n );\n return minWatermark;\n }\n\n /**\n * Returns the retained Postgres catchup bounds.\n * `minWatermark` is the oldest transaction, or `null` for a new replica.\n * `lastWatermark` is the durable head.\n */\n async getCatchupBounds(): Promise<{\n minWatermark: string | null;\n lastWatermark: string;\n }> {\n const [bounds] = await this.#withTimeout(\n 'get-catchup-bounds',\n this.#db<{minWatermark: string | null; lastWatermark: string}[]> /*sql*/ `\n SELECT\n (SELECT min(watermark) FROM ${this.#cdc('changeLog')}) as \"minWatermark\",\n (SELECT \"lastWatermark\" FROM ${this.#cdc('replicationState')}) as \"lastWatermark\"`,\n );\n return bounds;\n }\n\n /**\n * Lists at most `limit` committed transaction watermarks in\n * `(afterWatermark, throughWatermark]`, in ascending order.\n */\n async listCommitWatermarks(\n afterWatermark: string,\n throughWatermark: string,\n limit: number,\n ): Promise<string[]> {\n const rows = await this.#db<{watermark: string}[]> /*sql*/ `\n SELECT watermark FROM ${this.#cdc('changeLog')}\n WHERE precommit IS NOT NULL\n AND watermark > ${afterWatermark}\n AND watermark <= ${throughWatermark}\n ORDER BY watermark\n LIMIT ${limit}`;\n return rows.map(({watermark}) => watermark);\n }\n\n /**\n * Reads `(afterWatermark, throughWatermark]` in stream order and bounded batches.\n * This query matches the subscriber catchup query.\n *\n * Both queries fail when an escaped NUL reaches `change->'tag'`.\n * Postgres cannot convert that value to text.\n */\n readCatchupRange(\n afterWatermark: string,\n throughWatermark: string,\n batchRows = 2000,\n ): AsyncIterable<ChangeLogEntry[]> {\n assert(\n Number.isSafeInteger(batchRows) && batchRows > 0,\n 'Postgres change log batch size must be a positive safe integer',\n );\n return this.#db<ChangeLogEntry[]> /*sql*/ `\n SELECT watermark, change->'tag' as tag, change::text FROM ${this.#cdc('changeLog')}\n WHERE watermark > ${afterWatermark}\n AND watermark <= ${throughWatermark}\n ORDER BY watermark, pos`.cursor(batchRows) as AsyncIterable<\n ChangeLogEntry[]\n >;\n }\n\n // Note: These are the only db `await`s that are not tracked by the\n // ProgressMonitor, as the delete can legitimately block and/or take\n // an arbitrary amount of time. Luckily, this is a background call and\n // thus cannot cause the storer loop to hang.\n purgeRecordsBefore(watermark: string): Promise<number> {\n return runTx(this.#purger, async sql => {\n // This NOWAIT pre-check is an optimization to abort the transaction\n // (and release associated resources) early.\n await sql<{watermark: string}[]>`\n SELECT watermark FROM ${this.#cdc('changeLog')}\n ORDER BY watermark, pos LIMIT 1\n FOR UPDATE NOWAIT\n `;\n // If the row is purge-locked by an incoming replication-manager, it\n // will assume ownership of the change-log before releasing the lock.\n // This DELETE blocks until the lock is released, allowing the change\n // in ownership to be reliably detected (and the transaction aborted)\n // in the subsequent check.\n const [{deleted}] = await sql<{deleted: bigint}[]>`\n -- The backup watermark can be ahead of the durable changeLog if the\n -- storer is behind but the backup replica has consumed forwarded\n -- changes. Preserve the latest durable changeLog transaction as the\n -- catchup boundary instead of assuming the backup watermark exists.\n -- The storer inserts each changeLog transaction atomically, so any\n -- durable row for a watermark implies the full transaction is durable.\n WITH keep AS (\n SELECT max(watermark) AS watermark\n FROM ${this.#cdc('changeLog')}\n ), purged AS (\n DELETE FROM ${this.#cdc('changeLog')} WHERE watermark < ${watermark} \n AND watermark < (SELECT watermark FROM keep)\n RETURNING watermark, pos\n ) SELECT COUNT(*) as deleted FROM purged;`;\n\n const [{owner}] = await sql<ReplicationOwner[]>`\n SELECT \"owner\" FROM ${this.#cdc('replicationState')} FOR SHARE`;\n if (owner !== this.#taskID) {\n throw new AbortError(\n `aborting changeLog purge to ${watermark} because ownership has been taken by ${owner}`,\n );\n }\n return Number(deleted);\n });\n }\n\n /**\n * @returns The JSON stringified stream message to be sent downstream.\n */\n store(\n watermark: string,\n data: ChangeStreamData,\n serialized: SerializedChangeStreamData = serializeChangeStreamDataWithChange(\n data,\n ),\n ) {\n // Eagerly stringify the JSON payload to:\n // - avoid redundant stringification when fanning out to subscribers\n // - efficiently estimate the amount of memory the payload consumes\n const {json, change: storedChange} = serialized;\n this.#approximateQueuedBytes += json.length;\n\n const change = data[1];\n this.#queue.enqueue([\n 'change',\n watermark,\n json,\n storedChange,\n isDataChange(change) ? null : change, // drop DataChanges to save memory\n ]);\n\n return json;\n }\n\n abort() {\n this.#queue.enqueue(['abort']);\n }\n\n catchup(subscriber: Subscriber, mode: ReplicatorMode) {\n this.#queue.enqueue(['subscriber', {subscriber, mode}]);\n }\n\n #readyForMore: Resolver<void> | null = null;\n\n readyForMore(): Promise<void> | undefined {\n if (!this.#running) {\n return undefined;\n }\n if (\n this.#readyForMore === null &&\n this.#approximateQueuedBytes > this.#backPressureThresholdBytes\n ) {\n this.#lc.warn?.(\n `applying back pressure with ${this.#queue.size()} queued changes (~${(this.#approximateQueuedBytes / 1024 ** 2).toFixed(2)} MB)\\n` +\n `\\n` +\n `To inspect changeLog backlog in your change DB:\\n` +\n ` SELECT\\n` +\n ` (change->'relation'->>'schema') || '.' || (change->'relation'->>'name') AS table_name,\\n` +\n ` change->>'tag' AS operation,\\n` +\n ` COUNT(*) AS count\\n` +\n ` FROM \"<app_id>/cdc\".\"changeLog\"\\n` +\n ` GROUP BY 1, 2\\n` +\n ` ORDER BY 3 DESC\\n` +\n ` LIMIT 20;`,\n );\n this.#readyForMore = resolver();\n }\n return this.#readyForMore?.promise;\n }\n\n #maybeReleaseBackPressure() {\n if (this.#readyForMore !== null) {\n // Wait for at least 20% of the threshold to free up.\n if (\n this.#approximateQueuedBytes <\n this.#backPressureThresholdBytes * 0.8\n ) {\n this.#lc.info?.(\n `releasing back pressure with ${this.#queue.size()} queued changes (~${(this.#approximateQueuedBytes / 1024 ** 2).toFixed(2)} MB)`,\n );\n this.#readyForMore.resolve();\n this.#readyForMore = null;\n }\n }\n }\n\n /**\n * Flushes any buffered {@link PendingTransaction.batch} rows to the changeLog.\n *\n * Uses `json_to_recordset()` so the batch is a single JSON parameter: the\n * statement text stays constant regardless of batch size, avoiding the\n * unbounded prepared-statement variants (and Postgres memory growth) that a\n * multi-row INSERT would produce. See rocicorp/mono#3511.\n *\n * Returns (and updates) {@link PendingTransaction.lastFlush}; a no-op when the\n * batch is empty.\n */\n #flushChangeLog(tx: PendingTransaction): Promise<unknown> | undefined {\n const {batch} = tx;\n if (batch.length === 0) {\n return tx.lastFlush;\n }\n tx.batch = [];\n tx.lastFlush = tx.pool.process(sql => [\n sql`\n INSERT INTO ${this.#cdc('changeLog')} (\"watermark\", \"pos\", \"change\", \"precommit\")\n SELECT \"watermark\", \"pos\", \"change\"::json, \"precommit\"\n FROM json_to_recordset(${batch}) AS x(\n \"watermark\" TEXT,\n \"pos\" INT8,\n \"change\" TEXT,\n \"precommit\" TEXT\n )`,\n ]);\n return tx.lastFlush;\n }\n\n #stopped = promiseVoid;\n\n /**\n * Runs the storer loop until {@link stop()} is called, or an error is thrown.\n * Once {@link run()} completes, it can be called again.\n */\n async run() {\n assert(!this.#running, `storer is already running`);\n\n const {promise: stopped, resolve: signalStopped} = resolver();\n this.#running = true;\n this.#stopped = stopped;\n\n this.#lc.info?.('starting storer');\n this.#progressMonitor.start(); // Note: This is stopped in stop()\n let err: unknown;\n try {\n await this.#processQueue();\n } catch (e) {\n err = e; // used in finally\n throw e;\n } finally {\n // Release any pending backpressure so the upstream can proceed\n if (this.#readyForMore !== null) {\n this.#readyForMore.resolve();\n this.#readyForMore = null;\n }\n this.#cancelQueueEntries(\n this.#queue.drain().filter(entry => entry !== undefined),\n err,\n );\n this.#running = false;\n signalStopped();\n this.#lc.info?.('storer stopped');\n }\n }\n\n #cancelQueueEntries(queue: QueueEntry[], e: unknown) {\n if (queue.length === 0) {\n return;\n }\n this.#lc.info?.(\n `canceling ${queue.length} entries from the changeLog queue`,\n );\n const err = e instanceof Error ? e : new AbortError('server shutting down');\n for (const entry of queue) {\n if (entry === 'stop') {\n continue;\n }\n const type = entry[0];\n switch (type) {\n case 'subscriber': {\n // Disconnect subscribers waiting to be caught up so that they can\n // reconnect and try again.\n const {subscriber} = entry[1];\n this.#lc.info?.(`disconnecting ${subscriber.id}`);\n subscriber.fail(err);\n break;\n }\n }\n }\n }\n\n async #processQueue() {\n let tx: PendingTransaction | null = null;\n let msg: QueueEntry | false;\n\n // Track the progress of each (previous and next) queue entry before it is\n // processed in the loop.\n let lastTaskDone: TaskDoneFn | undefined;\n const nextMessage = async () => {\n lastTaskDone?.();\n lastTaskDone = undefined;\n const entry = await this.#queue.dequeue();\n if (entry !== 'stop') {\n lastTaskDone = this.#progressMonitor.trackTask({\n task: 'queue-entry',\n // Note: TaskKeys are logged, so only include entry[0] (the type) to\n // avoid logging application data.\n type: entry[0],\n });\n }\n return entry;\n };\n\n const catchupQueue: SubscriberAndMode[] = [];\n try {\n while ((msg = await nextMessage()) !== 'stop') {\n const [msgType] = msg;\n switch (msgType) {\n case 'ready': {\n const signalReady = msg[1];\n signalReady();\n continue;\n }\n case 'subscriber': {\n const subscriber = msg[1];\n if (tx) {\n catchupQueue.push(subscriber); // Wait for the current tx to complete.\n } else {\n await this.#startCatchup([subscriber]); // Catch up immediately.\n }\n continue;\n }\n case 'abort': {\n if (tx) {\n tx.pool.abort();\n await tx.pool.done();\n tx = null;\n }\n continue;\n }\n }\n // msgType === 'change'\n const [_, watermark, json, storedChange, change] = msg;\n const tag = change?.tag;\n this.#approximateQueuedBytes -= json.length;\n\n if (tag === 'begin') {\n assert(!tx, 'received BEGIN in the middle of a transaction');\n const {promise, resolve, reject} = resolver<ReplicationOwner>();\n void promise.catch(() => {}); // handle rejections before the await\n tx = {\n pool: new TransactionPool(\n this.#lc.withContext('watermark', watermark),\n {mode: Mode.READ_COMMITTED},\n ),\n preCommitWatermark: watermark,\n pos: 0,\n startingReplicationState: promise,\n ack: !change.skipAck,\n batch: [],\n lastFlush: undefined,\n };\n tx.pool.run(this.#inserter);\n // Acquire a lock on the replicationState row to detect and/or prevent\n // a concurrent ownership change.\n void tx.pool.process(tx => {\n tx<ReplicationOwner[]> /*sql*/ `\n SELECT \"owner\" FROM ${this.#cdc('replicationState')} FOR UPDATE`.then(\n ([result]) => resolve(result),\n reject,\n );\n return [];\n });\n } else {\n assert(tx, () => `received change outside of transaction: ${json}`);\n tx.pos++;\n }\n\n const entry: ChangeLogRow = {\n watermark: tag === 'commit' ? watermark : tx.preCommitWatermark,\n precommit: tag === 'commit' ? tx.preCommitWatermark : null,\n pos: tx.pos,\n // For backwards compatibility, only the change message is stored\n // in the cdc changeLog. It was serialized separately with the\n // downstream envelope, so no full-message scan is needed here.\n change: storedChange,\n };\n\n if (change !== null && isSchemaChange(change)) {\n // Schema changes carry backfill / table-metadata statements that\n // must be applied in stream order relative to the changeLog rows.\n // Flush any buffered rows first, then write this row together with\n // its metadata statements as a single unit (preserving the previous\n // per-change ordering for schema changes).\n await this.#flushChangeLog(tx);\n tx.lastFlush = tx.pool.process(sql => [\n sql`INSERT INTO ${this.#cdc('changeLog')} ${sql(entry)}`,\n ...this.#trackBackfillMetadata(sql, change),\n ]);\n } else {\n // Accumulate plain changeLog rows (begin, data changes, commit) and\n // write them as a single multi-row INSERT. Collapsing the per-change\n // single-row INSERTs into batches is the dominant cost reduction for\n // large transactions, where the previous one-statement-per-change\n // path dominated the upstream replication lag.\n tx.batch.push(entry);\n if (tx.batch.length >= this.#changeLogBatchSize) {\n // Bound pipeline depth (and thus memory) by awaiting the previous\n // flush before issuing the next. This is the batched analog of the\n // previous per-100-statement backpressure await, and likewise\n // guards against memory blowup on very large transactions.\n const prevFlush = tx.lastFlush;\n void this.#flushChangeLog(tx);\n await prevFlush;\n }\n }\n this.#maybeReleaseBackPressure();\n\n if (tag === 'commit') {\n // Flush any remaining buffered changeLog rows (including this commit\n // row) before updating the replication state, so the state update is\n // ordered after all changeLog inserts for this transaction.\n void this.#flushChangeLog(tx);\n\n const {owner} = await tx.startingReplicationState;\n if (owner !== this.#taskID) {\n // Ownership change reflected in the replicationState read in 'begin'.\n tx.pool.fail(\n new AbortError(\n `changeLog ownership has been assumed by ${owner}`,\n ),\n );\n } else {\n // Update the replication state.\n const lastWatermark = watermark;\n void tx.pool.process(tx => [\n tx`\n UPDATE ${this.#cdc('replicationState')} SET ${tx({lastWatermark})}`,\n ]);\n tx.pool.setDone();\n }\n\n await tx.pool.done();\n\n // ACK the LSN to the upstream Postgres.\n if (tx.ack) {\n this.#onCommitted(['commit', change, {watermark}]);\n }\n tx = null;\n\n // Before beginning the next transaction, open a READONLY snapshot to\n // concurrently catchup any queued subscribers.\n await this.#startCatchup(catchupQueue.splice(0));\n } else if (tag === 'rollback') {\n // Aborted transactions are not stored in the changeLog. Abort the current tx\n // and process catchup of subscribers that were waiting for it to end.\n tx.pool.abort();\n await tx.pool.done();\n tx = null;\n\n await this.#startCatchup(catchupQueue.splice(0));\n }\n }\n } catch (e) {\n catchupQueue.forEach(({subscriber}) => subscriber.fail(e));\n throw e;\n }\n }\n\n async #startCatchup(subs: SubscriberAndMode[]) {\n const numCatchups = subs.length;\n if (numCatchups === 0) {\n return;\n }\n\n const lc = this.#lc.withContext('pool', 'catchup');\n const {init, cleanup, snapshotID} = sharedSnapshot();\n const reader = new TransactionPool(lc, {\n mode: Mode.READONLY,\n init,\n cleanup,\n initialWorkers: subs.length,\n });\n\n // A dynamic connection pool is created for catchup, sized to the number\n // of subscribers being caught up.\n const catchupConns = this.#makeConnectionPool(\n 'subscriber-catchup',\n numCatchups,\n );\n reader.run(catchupConns);\n\n let lastWatermark: string | undefined;\n const catchupSnapshotted = this.#progressMonitor.trackTask({\n task: 'capture-catchup-snapshot',\n subscribers: subs.map(({subscriber: s}) => s.id),\n });\n try {\n // Ensure that the transaction has started (and is thus holding a snapshot\n // of the database) before continuing on to commit more changes. This is\n // done by performing a single read on the db, which determines the\n // snapshot for the REPEATABLE_READ transaction.\n [{lastWatermark}] = await reader.processReadTask(\n sql => sql<{lastWatermark: string}[]>`\n SELECT \"lastWatermark\" FROM ${this.#cdc('replicationState')}\n `,\n );\n lc.info?.(\n `snapshotted db at ${lastWatermark} (${await snapshotID}) ` +\n `to catchup ${numCatchups} subscriber(s)`,\n );\n } catch (e) {\n subs.map(({subscriber}) => subscriber.fail(e));\n // Nothing will run the catchup tasks that normally finalize the pool\n // (below), so tear it down here. Otherwise its workers (each holding an\n // open READ ONLY transaction) and the connection pool are leaked.\n reader.abort();\n void catchupConns.end().catch(() => {});\n throw e;\n } finally {\n catchupSnapshotted();\n }\n\n // Run the actual catchup queries in the background. Errors are handled in\n // #catchup() by disconnecting the associated subscriber.\n void Promise.allSettled(\n subs.map(sub =>\n this.#catchup(\n lc.withContext('subscriber', sub.subscriber.id),\n sub,\n lastWatermark,\n reader,\n ),\n ),\n ).finally(() => {\n reader.setDone();\n void catchupConns.end().catch(() => {});\n });\n }\n\n async #catchup(\n lc: LogContext,\n {subscriber: sub, mode}: SubscriberAndMode,\n lastWatermark: string,\n reader: TransactionPool,\n ) {\n let entriesReceived = 0;\n let catchupProgressed = this.#progressMonitor.trackTask({\n task: 'catchup',\n subscriber: sub.id,\n entriesReceived,\n });\n try {\n lc.info?.(`starting catchup`);\n await reader.processReadTask(async tx => {\n lc.info?.(`catching up`);\n const start = Date.now();\n\n // When starting from initial-sync, there won't be a change with a watermark\n // equal to the replica version. This is the empty changeLog scenario.\n let watermarkFound = sub.watermark === this.#replicaVersion;\n let count = 0;\n let lastBatchConsumed: Promise<unknown> | undefined;\n\n for await (const entries of tx<ChangeLogEntry[]> /*sql*/ `\n SELECT watermark, change->'tag' as tag, change::text FROM ${this.#cdc('changeLog')}\n WHERE watermark >= ${sub.watermark}\n AND watermark <= ${lastWatermark}\n ORDER BY watermark, pos`.cursor(2000)) {\n catchupProgressed();\n entriesReceived += entries.length;\n\n try {\n // Wait for the last batch of entries to be consumed by the\n // subscriber before sending down the current batch. This pipelining\n // allows one batch of changes to be received from the change-db\n // while the previous batch of changes are sent to the subscriber,\n // resulting in flow control that caps the number of changes\n // referenced in memory to 2 * batch-size.\n const start = performance.now();\n await lastBatchConsumed;\n const elapsed = performance.now() - start;\n if (lastBatchConsumed) {\n lc[elapsed > 100 ? 'info' : 'debug']?.(\n `waited ${elapsed.toFixed(3)} ms for ${sub.id} to consume last batch of catchup entries`,\n );\n }\n\n for (const entry of entries) {\n if (entry.watermark === sub.watermark) {\n // This should be the first entry.\n // Catchup starts from *after* the watermark.\n watermarkFound = true;\n } else if (watermarkFound) {\n lastBatchConsumed = sub.catchup(\n reconstructWatermarkedChange(entry),\n );\n count++;\n } else if (mode === 'backup') {\n throw new AutoResetSignal(\n `backup replica at watermark ${sub.watermark} is behind change db: ${entry.watermark})`,\n );\n } else {\n lc.warn?.(\n `rejecting subscriber at watermark ${sub.watermark} (earliest watermark: ${entry.watermark})`,\n );\n sub.close(\n ErrorType.WatermarkTooOld,\n `earliest supported watermark is ${entry.watermark} (requested ${sub.watermark})`,\n );\n return;\n }\n }\n } finally {\n // Track the db's read of the next chunk of changes.\n catchupProgressed = this.#progressMonitor.trackTask({\n task: 'catchup',\n subscriber: sub.id,\n entriesReceived,\n });\n }\n }\n catchupProgressed();\n\n if (watermarkFound) {\n await lastBatchConsumed;\n lc.info?.(\n `caught up ${sub.id} with ${count} changes (${\n Date.now() - start\n } ms)`,\n );\n } else {\n // The subscriber is ahead of the latest durable changeLog entry\n // (lastWatermark). This can legitimately happen: changes are\n // forwarded to subscribers (the backup replica and view-syncers)\n // concurrently with — and can outrun — the durable store, so a\n // replica may briefly lead the change DB after the storer falls\n // behind or the change-streamer restarts. No catchup is possible or\n // needed; once the change DB catches back up, forwarding resumes and\n // the subscriber dedups any watermarks it already has. Unlike the\n // AutoResetSignal / WatermarkTooOld cases above, this is not a gap in\n // replication history, so the subscriber is simply marked caught up.\n lc.warn?.(\n `subscriber ${sub.id} at watermark ${sub.watermark} is ahead of ` +\n `the latest durable watermark ${lastWatermark}; waiting for the ` +\n `change DB to catch up`,\n );\n }\n // Start draining messages buffered during catchup. The returned promise\n // is intentionally not awaited here: while the drain is in progress,\n // new sends keep appending to the subscriber backlog and inherit its\n // byte-based backpressure.\n void sub.setCaughtUp();\n });\n } catch (err) {\n lc.error?.(`error while catching up subscriber ${sub.id}`, err);\n if (err instanceof AutoResetSignal) {\n await markResetRequired(this.#db, this.#shard);\n this.#onFatal(err);\n }\n sub.fail(err);\n } finally {\n catchupProgressed();\n }\n }\n\n /**\n * Returns the db statements necessary to track backfill and table metadata\n * presented in the `change`, if any.\n *\n * This is the Postgres interpreter of {@link cookieOps}, which is also\n * interpreted against the SQLite change log by `ChangeLogCookieWriter`. The\n * two stores have to agree on every transition forever, and the failure mode\n * if they drift is a backfill that is silently never re-requested — so the\n * decision of what a schema change *means* lives in one place and only its\n * transport lives here.\n */\n #trackBackfillMetadata(sql: PostgresTransaction, change: SchemaChange) {\n return cookieOps(change).flatMap(op => this.#cookieStmts(sql, op));\n }\n\n #cookieStmts(sql: PostgresTransaction, op: CookieOp): PendingQuery<Row[]>[] {\n switch (op.op) {\n case 'upsert-metadata':\n return [this.#upsertTableMetadataStmt(sql, op.table, op.metadata)];\n\n case 'upsert-backfill':\n return [\n this.#upsertColumnBackfillStmt(sql, op.table, op.column, op.backfill),\n ];\n\n case 'rename-table': {\n const {old} = op;\n const row = {schema: op.new.schema, table: op.new.name};\n return [\n sql`UPDATE ${this.#cdc('tableMetadata')} SET ${sql(row)}\n WHERE \"schema\" = ${old.schema} AND \"table\" = ${old.name}`,\n sql`UPDATE ${this.#cdc('backfilling')} SET ${sql(row)}\n WHERE \"schema\" = ${old.schema} AND \"table\" = ${old.name}`,\n ];\n }\n\n case 'drop-table': {\n const {schema, name} = op.table;\n return [\n sql`DELETE FROM ${this.#cdc('tableMetadata')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${name}`,\n sql`DELETE FROM ${this.#cdc('backfilling')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${name}`,\n ];\n }\n\n case 'rename-column': {\n const {schema, name: table} = op.table;\n return [\n sql`UPDATE ${this.#cdc('backfilling')} SET \"column\" = ${op.new}\n WHERE \"schema\" = ${schema} AND \"table\" = ${table} AND \"column\" = ${op.old}`,\n ];\n }\n\n case 'drop-column': {\n const {schema, name} = op.table;\n return [\n sql`DELETE FROM ${this.#cdc('backfilling')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${name} AND \"column\" = ${op.column}`,\n ];\n }\n\n case 'complete-backfill': {\n const {schema, name: table} = op.table;\n return [\n sql`DELETE FROM ${this.#cdc('backfilling')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${table} AND \"column\" IN ${sql([...op.columns])}`,\n ];\n }\n\n default:\n unreachable(op);\n }\n }\n\n #upsertTableMetadataStmt(\n sql: PostgresTransaction,\n {schema, name: table}: Identifier,\n metadata: TableMetadata,\n ) {\n const row: TableMetadataRow = {schema, table, metadata};\n return sql`\n INSERT INTO ${this.#cdc('tableMetadata')} ${sql(row)}\n ON CONFLICT (\"schema\", \"table\")\n DO UPDATE SET ${sql(row)};\n `;\n }\n\n #upsertColumnBackfillStmt(\n sql: PostgresTransaction,\n {schema, name: table}: Identifier,\n column: string,\n backfill: BackfillID,\n ) {\n const row: BackfillingColumn = {schema, table, column, backfill};\n return sql`\n INSERT INTO ${this.#cdc('backfilling')} ${sql(row)}\n ON CONFLICT (\"schema\", \"table\", \"column\")\n DO UPDATE SET ${sql(row)};\n `;\n }\n\n /**\n * Waits until all currently queued entries have been processed.\n * This is only used in tests.\n */\n async allProcessed() {\n if (this.#running) {\n const {promise, resolve} = resolver();\n this.#queue.enqueue(['ready', resolve]);\n await promise;\n }\n }\n\n /**\n * Stops the storer and waits up to a drain timeout for entries to drain,\n * throwing an exception if it doesn't drain in time, in order to abort\n * the server when PG (or the connection to it) appears to be wedged.\n */\n async stop() {\n if (this.#running) {\n this.#progressMonitor.stop();\n this.#lc.info?.(`draining ${this.#queue.size()} changeLog entries`);\n this.abort(); // for cleanliness, abort any open transactions\n this.#queue.enqueue('stop');\n }\n if (\n (await orTimeout(this.#stopped, this.#drainTimeoutMs)) === 'timed-out'\n ) {\n throw new AbortError(\n `changeLog did not drain within ${this.#drainTimeoutMs}ms`,\n );\n }\n }\n}\n\nexport class PurgeLock {\n readonly #lc: LogContext;\n readonly #tx: TransactionPool;\n readonly replicaVersion: string;\n readonly minWatermark: string;\n\n constructor(\n lc: LogContext,\n tx: TransactionPool,\n replicaVersion: string,\n watermark: string,\n ) {\n this.#lc = lc;\n this.#tx = tx;\n this.replicaVersion = replicaVersion;\n this.minWatermark = watermark;\n }\n\n #released = false;\n\n async release() {\n if (this.#released) {\n return;\n }\n this.#released = true;\n this.#tx.setDone();\n await this.#tx\n .done()\n .catch(e => this.#lc.warn?.(`error from purge-lock release`, e));\n this.#lc.info?.(`released purge lock on ${this.minWatermark}`);\n }\n}\n\nexport class PurgeLocker {\n readonly #lc: LogContext;\n readonly #shard: ShardID;\n readonly #db: PostgresDB;\n\n constructor(lc: LogContext, shard: ShardID, db: PostgresDB) {\n this.#lc = lc.withContext('component', 'purge-locker');\n this.#shard = shard;\n this.#db = db;\n }\n\n // For readability in SQL statements.\n #cdc(table: string) {\n return this.#db(`${cdcSchema(this.#shard)}.${table}`);\n }\n\n async acquire() {\n const tx = new TransactionPool(this.#lc, {mode: Mode.READ_COMMITTED}).run(\n this.#db,\n );\n const row = await tx.processReadTask(\n sql => sql<{watermark: string}[]>`\n SELECT watermark FROM ${this.#cdc('changeLog')}\n ORDER BY watermark, pos LIMIT 1\n FOR SHARE \n `,\n );\n if (row.length === 0) {\n this.#lc.info?.(`changeLog is empty. No rows to purge-lock.`);\n tx.setDone();\n await tx.done();\n return null;\n }\n const [{watermark}] = row;\n const [{replicaVersion}] = await tx.processReadTask(\n sql => sql<{replicaVersion: string}[]>`\n SELECT \"replicaVersion\" FROM ${this.#cdc('replicationConfig')}\n `,\n );\n this.#lc.info?.(\n `locked watermark ${watermark} from being purged from replica@${replicaVersion}`,\n );\n return new PurgeLock(this.#lc, tx, replicaVersion, watermark);\n }\n}\n\n// A TaskKey, keyed by identity, representing an db task monitored by the\n// ProgressMonitor. The contents are stringified in error messages if the\n// task fails to make progress for more than a failure threshold interval.\ntype TaskKey = JSONObject;\n\ntype TaskDoneFn = () => void;\n\n/**\n * Periodic monitor for detecting the pathological condition in which a db\n * query hangs forever because of a connection problem, such as a half-closed\n * socket.\n *\n * Use this for db calls that recur or accumulate progress within a single\n * logical operation on the main storer loop (e.g. the queue-processing loop,\n * or a multi-batch catchup read), where \"no progress for N ms\" is the\n * meaningful signal. For a one-off db call -- including ones made before\n * {@link Storer.run} starts this monitor's polling -- use a plain timeout\n * (see `Storer.#withTimeout`) instead.\n *\n * The failure handler should stop the server. The ProgressMonitor will\n * assume this and stop itself after calling it.\n *\n * Internal to the Storer, but exported for testing.\n */\nexport class ProgressMonitor {\n readonly #lc: LogContext;\n readonly #failureThresholdMs;\n readonly #onFailure: (err: Error) => void;\n readonly #taskUpdates = new Map<TaskKey, Date>();\n\n #timer: NodeJS.Timeout | undefined;\n\n constructor(\n lc: LogContext,\n failureThresholdMs: number,\n onFailure: (err: Error) => void,\n ) {\n this.#lc = lc.withContext('component', 'storer-progress-monitor');\n this.#failureThresholdMs = failureThresholdMs;\n this.#onFailure = onFailure;\n }\n\n start() {\n clearInterval(this.#timer);\n this.#timer = setInterval(\n () => this.checkTaskProgress(new Date()),\n this.#failureThresholdMs,\n ).unref();\n }\n\n // Called by an internal periodic timer, but exported for testing.\n checkTaskProgress(now: Date) {\n for (const [task, lastUpdate] of this.#taskUpdates.entries()) {\n if (now.getTime() - lastUpdate.getTime() >= this.#failureThresholdMs) {\n this.#lc.error?.(\n `Last task update was more than ${this.#failureThresholdMs}ms ago`,\n {task, lastUpdate},\n );\n this.#onFailure(\n new Error(\n `Task failed to progress for over ${this.#failureThresholdMs}ms: ${BigIntJSON.stringify(task)}`,\n ),\n );\n this.stop();\n return;\n }\n }\n }\n\n /**\n * Starts a task to be tracked.\n *\n * @return a callback to invoke when the task is done.\n */\n trackTask(task: TaskKey, now = new Date()): TaskDoneFn {\n this.#taskUpdates.set(task, now);\n return () => {\n this.#taskUpdates.delete(task);\n };\n }\n\n stop() {\n clearInterval(this.#timer);\n this.#taskUpdates.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwGA,IAAM,yBAAyB,eAAE,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkD5D,IAAa,SAAb,MAAuC;CACrC,KAAc;CACd;CACA;CACA;CACA;CACA;CACA;CAKA;CACA;CACA;CAEA;CACA;CACA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;AACF;;;;;;;;;;;;;;;;;;AA0BA,IAAa,kBAAb,MAA6B;CAC3B;CACA;CACA;CACA,+BAAwB,IAAI,IAAmB;CAE/C;CAEA,YACE,IACA,oBACA,WACA;EACA,KAAKA,MAAM,GAAG,YAAY,aAAa,yBAAyB;EAChE,KAAKoC,sBAAsB;EAC3B,KAAKC,aAAa;CACpB;CAEA,QAAQ;EACN,cAAc,KAAKE,MAAM;EACzB,KAAKA,SAAS,kBACN,KAAK,kCAAkB,IAAI,KAAK,CAAC,GACvC,KAAKH,mBACP,EAAE,MAAM;CACV;CAGA,kBAAkB,KAAW;EAC3B,KAAK,MAAM,CAAC,MAAM,eAAe,KAAKE,aAAa,QAAQ,GACzD,IAAI,IAAI,QAAQ,IAAI,WAAW,QAAQ,KAAK,KAAKF,qBAAqB;GACpE,KAAKpC,IAAI,QACP,kCAAkC,KAAKoC,oBAAoB,SAC3D;IAAC;IAAM;GAAU,CACnB;GACA,KAAKC,2BACH,IAAI,MACF,oCAAoC,KAAKD,oBAAoB,MAAM,WAAW,UAAU,IAAI,GAC9F,CACF;GACA,KAAK,KAAK;GACV;EACF;CAEJ;;;;;;CAOA,UAAU,MAAe,sBAAM,IAAI,KAAK,GAAe;EACrD,KAAKE,aAAa,IAAI,MAAM,GAAG;EAC/B,aAAa;GACX,KAAKA,aAAa,OAAO,IAAI;EAC/B;CACF;CAEA,OAAO;EACL,cAAc,KAAKC,MAAM;EACzB,KAAKD,aAAa,MAAM;CAC1B;AACF"}
@@ -42,7 +42,7 @@ var LitestreamCheckpointer = class {
42
42
  #nextWalThreshold;
43
43
  #pendingSync;
44
44
  constructor(lc, db, litestream, config) {
45
- this.#lc = lc.withContext("litestream-checkpointer");
45
+ this.#lc = lc.withContext("component", "litestream-checkpointer");
46
46
  this.#db = db;
47
47
  this.#litestream = litestream;
48
48
  this.#attemptChunk = config.checkpointThresholdPages;
@@ -1 +1 @@
1
- {"version":3,"file":"litestream-checkpointer.js","names":["#lc","#db","#litestream","#attemptChunk","#maxWalPages","#state","#nextWalThreshold","#getNumWalPages","#pendingSync","#sync","#waitFor","#pauseUntilWalDrained"],"sources":["../../../../../../zero-cache/src/services/litestream/litestream-checkpointer.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {AbortError} from '../../../../shared/src/abort-error.ts';\nimport type {Database} from '../../../../zqlite/src/db.ts';\nimport type {ForceCheckpointConfig} from '../replicator/write-worker-client.ts';\nimport {RunningState} from '../running-state.ts';\nimport type {\n LitestreamController,\n SyncResponse,\n} from './litestream-controller.ts';\n\n// How long the soft path blocks the write path waiting for an in-flight sync\n// before letting the writer proceed. This is a backpressure knob, *not* a\n// request timeout: letting it elapse leaves the sync running (see #pendingSync)\n// rather than abandoning it. In normal operation litestream seals + runs its\n// PASSIVE checkpoint well within this budget; a sync that regularly exceeds it\n// indicates a litestream-side problem to fix (e.g. unintended snapshot), not a\n// value to raise.\nexport const SOFT_CHECKPOINT_WAIT_MS = 10_000;\n// Liveness bound on the /sync request itself, well above the soft wait budget.\n// It exists only to recover from a genuinely wedged litestream (so #pendingSync\n// can't hang forever).\nconst LITESTREAM_SYNC_TIMEOUT_MS = 5 * 60_000;\nconst PAUSE_POLL_INTERVAL_MS = 1_000;\nconst PAUSE_LOG_INTERVAL_POLLS = 30;\n\n/**\n * Forces litestream to checkpoint the WAL from the write path, so a sustained\n * high write rate can't grow the WAL until litestream's own blocking TRUNCATE\n * checkpoint locks the db (see ReplicationPauseCheckpointConfig).\n *\n * Two tiers:\n * - Soft (`checkpointThresholdPages`): after each committed transaction,\n * once the un-checkpointed WAL backlog reaches the threshold, force an\n * immediate litestream sync (which seals the WAL to LTX and attempts\n * litestream's own PASSIVE checkpoint) and block the write path until it\n * completes, but only up to {@link SOFT_CHECKPOINT_WAIT_MS}. Waiting is the\n * backpressure: it throttles upstream reads to litestream's WAL-seal rate\n * and, in the common case, gives litestream a window to checkpoint without\n * writer interference. A single sync is kept in flight at a time\n * (`#pendingSync`): if one is still running when the budget elapses, the\n * writer proceeds and the next commit waits for that sync rather than\n * issuing (and orphaning) another. Backs off by a full threshold's worth of\n * WAL growth whenever an attempt fails to drain the WAL (e.g. litestream\n * is mid-snapshot and its checkpoints are being skipped), so repeated\n * failures don't reattempt on every commit.\n * - Hard (`walMaxPages`, optional): if the WAL still exceeds this cap after\n * a soft attempt, pause (block the caller) polling litestream until the\n * WAL drains below it. This is the fail-safe against unbounded WAL growth\n * when litestream structurally cannot checkpoint — e.g. an in-progress\n * snapshot holds litestream's checkpoint lock for its full duration, so\n * neither PASSIVE nor TRUNCATE checkpoints can run until it completes.\n */\nexport class LitestreamCheckpointer {\n readonly #lc: LogContext;\n readonly #db: Database;\n readonly #litestream: LitestreamController;\n readonly #attemptChunk: number;\n readonly #maxWalPages: number | undefined;\n readonly #state = new RunningState('litestream-checkpointer');\n #nextWalThreshold: number;\n #pendingSync: Promise<void> | undefined;\n\n constructor(\n lc: LogContext,\n db: Database,\n litestream: LitestreamController,\n config: ForceCheckpointConfig,\n ) {\n this.#lc = lc.withContext('litestream-checkpointer');\n this.#db = db;\n this.#litestream = litestream;\n this.#attemptChunk = config.checkpointThresholdPages;\n this.#nextWalThreshold = config.checkpointThresholdPages;\n this.#maxWalPages = config.maxWalPages;\n }\n\n #getNumWalPages(): number {\n // wal_checkpoint(NOOP) reads WAL status without doing any work: `log` is\n // the current WAL frame count and `checkpointed` is how many of those\n // frames are already applied to the main db, so `log - checkpointed` is\n // the un-checkpointed backlog that a forced sync would actually drain.\n // (Both reset once litestream restarts the WAL.)\n const [{log, checkpointed}] = this.#db.pragma<{\n log: number;\n checkpointed: number;\n }>('wal_checkpoint(NOOP)');\n return log - checkpointed;\n }\n\n /**\n * Call after a committed transaction. No-ops unless the WAL has grown to\n * at least the current threshold, in which case it triggers a litestream\n * sync to perform a checkpoint. Assuming that snapshots are disabled, the\n * checkpoint always succeeds. In the case where the server is configured to\n * perform snapshots and checkpoints fail, the \"emergency break\"\n * {@link #pauseUntilWalDrained()} option provides the disk use protection\n * that litestream's (disabled) truncate-page-n would have served.\n */\n async maybeCheckpoint(): Promise<void> {\n let walPages = this.#getNumWalPages();\n if (walPages < this.#nextWalThreshold) {\n return;\n }\n\n // Single-flight: reuse the outstanding sync if one is already running.\n this.#pendingSync ??= this.#sync(walPages);\n\n // Soft backpressure: block the write path until the sync completes, but no\n // longer than the wait budget. Letting the budget elapse lets the writer\n // proceed *without* cancelling the sync (it keeps running, tracked by\n // #pendingSync); unbounded WAL growth is caught by the hard cap below.\n await this.#waitFor(this.#pendingSync, SOFT_CHECKPOINT_WAIT_MS);\n\n walPages = this.#getNumWalPages();\n if (this.#maxWalPages !== undefined && walPages > this.#maxWalPages) {\n // Emergency brake when best-effort checkpoints are being skipped\n // (i.e. during a snapshot) and the WAL is approaching disk capacity.\n // Pausing replication is favorable to litestream's truncate-page-n\n // because the latter involves re-encoding the database under the lock\n // (https://github.com/benbjohnson/litestream/issues/1332), which would\n // incur the full latency of an additional snapshot.\n walPages = await this.#pauseUntilWalDrained(this.#maxWalPages);\n }\n\n // In the common case where checkpoints are successful, this is always\n // just `attemptChunk`. When a checkpoint doesn't drain the WAL (e.g.\n // litestream is performing a snapshot), wait for another chunk of growth\n // before the next attempt.\n this.#nextWalThreshold = walPages + this.#attemptChunk;\n }\n\n async #waitFor(p: Promise<void>, timeoutMs: number): Promise<void> {\n const result = await Promise.race([\n p,\n this.#state.sleep(timeoutMs).then(() => 'timed-out' as const),\n ]);\n if (result === 'timed-out') {\n this.#lc.warn?.(`timed out waiting for /sync result (${timeoutMs}ms)`);\n }\n }\n\n /**\n * Runs a single litestream sync, logs its outcome, and clears\n * {@link #pendingSync} when it settles. Never rejects: sync failures and\n * post-sync bookkeeping errors (e.g. the db being closed during shutdown)\n * are caught and logged, so the shared promise can be awaited from multiple\n * places without risking an unhandled rejection.\n */\n async #sync(walPagesBefore: number): Promise<void> {\n const start = performance.now();\n let result: SyncResponse | undefined;\n let err: unknown;\n try {\n try {\n result = await this.#litestream.sync(\n {wait: false, timeoutMs: LITESTREAM_SYNC_TIMEOUT_MS},\n this.#state.signal,\n );\n } catch (e) {\n err = e;\n }\n\n const elapsed = performance.now() - start;\n const newWalPages = this.#getNumWalPages();\n if (newWalPages < this.#nextWalThreshold) {\n this.#lc.info?.(\n `checkpointed ${walPagesBefore} -> ${newWalPages} wal pages (${elapsed.toFixed(2)} ms)`,\n result,\n );\n } else if (result) {\n this.#lc.warn?.(\n `checkpoint skipped ${walPagesBefore} -> ${newWalPages}. a snapshot may be in progress (${elapsed.toFixed(2)} ms)`,\n result,\n );\n } else {\n this.#lc.warn?.(\n `checkpoint failed ${walPagesBefore} -> ${newWalPages} (${elapsed.toFixed(2)} ms)`,\n err,\n );\n }\n } catch (e) {\n this.#lc.warn?.('litestream-checkpointer sync post-processing failed', e);\n } finally {\n this.#pendingSync = undefined;\n }\n }\n\n async #pauseUntilWalDrained(maxWalPages: number): Promise<number> {\n for (let i = 0; this.#state.shouldRun(); i++) {\n const walPages = this.#getNumWalPages();\n if (walPages < maxWalPages) {\n this.#lc.info?.(\n `wal size (${walPages} pages) is under the max limit of ${maxWalPages}`,\n );\n return walPages;\n }\n\n // Log every 30 seconds.\n if (i % PAUSE_LOG_INTERVAL_POLLS === 0) {\n this.#lc.warn?.(\n `waiting for litestream to successfully checkpoint ${walPages} wal pages`,\n );\n }\n await this.#state.sleep(PAUSE_POLL_INTERVAL_MS);\n // Single-flight: reuse the outstanding sync if one is already running.\n this.#pendingSync ??= this.#sync(this.#getNumWalPages());\n // await the full liveness timeout configured in #sync()\n await this.#pendingSync;\n }\n throw new AbortError('litestream-controller stopped');\n }\n\n /** Releases the underlying litestream controller's connection. */\n close(): void {\n this.#litestream.close();\n this.#state.stop(this.#lc);\n }\n}\n"],"mappings":";;;AAiBA,IAAa,0BAA0B;AAIvC,IAAM,6BAA6B,IAAI;AACvC,IAAM,yBAAyB;AAC/B,IAAM,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BjC,IAAa,yBAAb,MAA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AgB;GACzC,IAAI,cAAc,KAAKD,mBACrB,KAAKN,IAAI,OACP,gBAAgB,eAAe,MAAM,YAAY,cAAc,QAAQ,QAAQ,CAAC,EAAE,OAClF,MACF;QACK,IAAI,QACT,KAAKA,IAAI,OACP,sBAAsB,eAAe,MAAM,YAAY,mCAAmC,QAAQ,QAAQ,CAAC,EAAE,OAC7G,MACF;QAEA,KAAKA,IAAI,OACP,qBAAqB,eAAe,MAAM,YAAY,IAAI,QAAQ,QAAQ,CAAC,EAAE,OAC7E,GACF;EAEJ,SAAS,GAAG;GACV,KAAKA,IAAI,OAAO,uDAAuD,CAAC;EAC1E,UAAU;GACR,KAAKQ,eAAe,KAAA;EACtB;CACF;CAEA,MAAMG,sBAAsB,aAAsC;EAChE,KAAK,IAAI,IAAI,GAAG,KAAKN,OAAO,UAAU,GAAG,KAAK;GAC5C,MAAM,WAAW,KAAKE,gBAAgB;GACtC,IAAI,WAAW,aAAa;IAC1B,KAAKP,IAAI,OACP,aAAa,SAAS,oCAAoC,aAC5D;IACA,OAAO;GACT;GAGA,IAAI,IAAI,6BAA6B,GACnC,KAAKA,IAAI,OACP,qDAAqD,SAAS,WAChE;GAEF,MAAM,KAAKK,OAAO,MAAM,sBAAsB;GAE9C,KAAKG,iBAAiB,KAAKC,MAAM,KAAKF,gBAAgB,CAAC;GAEvD,MAAM,KAAKC;EACb;EACA,MAAM,IAAI,WAAW,+BAA+B;CACtD;;CAGA,QAAc;EACZ,KAAKN,YAAY,MAAM;EACvB,KAAKG,OAAO,KAAK,KAAKL,GAAG;CAC3B;AACF"}
1
+ {"version":3,"file":"litestream-checkpointer.js","names":["#lc","#db","#litestream","#attemptChunk","#maxWalPages","#state","#nextWalThreshold","#getNumWalPages","#pendingSync","#sync","#waitFor","#pauseUntilWalDrained"],"sources":["../../../../../../zero-cache/src/services/litestream/litestream-checkpointer.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {AbortError} from '../../../../shared/src/abort-error.ts';\nimport type {Database} from '../../../../zqlite/src/db.ts';\nimport type {ForceCheckpointConfig} from '../replicator/write-worker-client.ts';\nimport {RunningState} from '../running-state.ts';\nimport type {\n LitestreamController,\n SyncResponse,\n} from './litestream-controller.ts';\n\n// How long the soft path blocks the write path waiting for an in-flight sync\n// before letting the writer proceed. This is a backpressure knob, *not* a\n// request timeout: letting it elapse leaves the sync running (see #pendingSync)\n// rather than abandoning it. In normal operation litestream seals + runs its\n// PASSIVE checkpoint well within this budget; a sync that regularly exceeds it\n// indicates a litestream-side problem to fix (e.g. unintended snapshot), not a\n// value to raise.\nexport const SOFT_CHECKPOINT_WAIT_MS = 10_000;\n// Liveness bound on the /sync request itself, well above the soft wait budget.\n// It exists only to recover from a genuinely wedged litestream (so #pendingSync\n// can't hang forever).\nconst LITESTREAM_SYNC_TIMEOUT_MS = 5 * 60_000;\nconst PAUSE_POLL_INTERVAL_MS = 1_000;\nconst PAUSE_LOG_INTERVAL_POLLS = 30;\n\n/**\n * Forces litestream to checkpoint the WAL from the write path, so a sustained\n * high write rate can't grow the WAL until litestream's own blocking TRUNCATE\n * checkpoint locks the db (see ReplicationPauseCheckpointConfig).\n *\n * Two tiers:\n * - Soft (`checkpointThresholdPages`): after each committed transaction,\n * once the un-checkpointed WAL backlog reaches the threshold, force an\n * immediate litestream sync (which seals the WAL to LTX and attempts\n * litestream's own PASSIVE checkpoint) and block the write path until it\n * completes, but only up to {@link SOFT_CHECKPOINT_WAIT_MS}. Waiting is the\n * backpressure: it throttles upstream reads to litestream's WAL-seal rate\n * and, in the common case, gives litestream a window to checkpoint without\n * writer interference. A single sync is kept in flight at a time\n * (`#pendingSync`): if one is still running when the budget elapses, the\n * writer proceeds and the next commit waits for that sync rather than\n * issuing (and orphaning) another. Backs off by a full threshold's worth of\n * WAL growth whenever an attempt fails to drain the WAL (e.g. litestream\n * is mid-snapshot and its checkpoints are being skipped), so repeated\n * failures don't reattempt on every commit.\n * - Hard (`walMaxPages`, optional): if the WAL still exceeds this cap after\n * a soft attempt, pause (block the caller) polling litestream until the\n * WAL drains below it. This is the fail-safe against unbounded WAL growth\n * when litestream structurally cannot checkpoint — e.g. an in-progress\n * snapshot holds litestream's checkpoint lock for its full duration, so\n * neither PASSIVE nor TRUNCATE checkpoints can run until it completes.\n */\nexport class LitestreamCheckpointer {\n readonly #lc: LogContext;\n readonly #db: Database;\n readonly #litestream: LitestreamController;\n readonly #attemptChunk: number;\n readonly #maxWalPages: number | undefined;\n readonly #state = new RunningState('litestream-checkpointer');\n #nextWalThreshold: number;\n #pendingSync: Promise<void> | undefined;\n\n constructor(\n lc: LogContext,\n db: Database,\n litestream: LitestreamController,\n config: ForceCheckpointConfig,\n ) {\n this.#lc = lc.withContext('component', 'litestream-checkpointer');\n this.#db = db;\n this.#litestream = litestream;\n this.#attemptChunk = config.checkpointThresholdPages;\n this.#nextWalThreshold = config.checkpointThresholdPages;\n this.#maxWalPages = config.maxWalPages;\n }\n\n #getNumWalPages(): number {\n // wal_checkpoint(NOOP) reads WAL status without doing any work: `log` is\n // the current WAL frame count and `checkpointed` is how many of those\n // frames are already applied to the main db, so `log - checkpointed` is\n // the un-checkpointed backlog that a forced sync would actually drain.\n // (Both reset once litestream restarts the WAL.)\n const [{log, checkpointed}] = this.#db.pragma<{\n log: number;\n checkpointed: number;\n }>('wal_checkpoint(NOOP)');\n return log - checkpointed;\n }\n\n /**\n * Call after a committed transaction. No-ops unless the WAL has grown to\n * at least the current threshold, in which case it triggers a litestream\n * sync to perform a checkpoint. Assuming that snapshots are disabled, the\n * checkpoint always succeeds. In the case where the server is configured to\n * perform snapshots and checkpoints fail, the \"emergency break\"\n * {@link #pauseUntilWalDrained()} option provides the disk use protection\n * that litestream's (disabled) truncate-page-n would have served.\n */\n async maybeCheckpoint(): Promise<void> {\n let walPages = this.#getNumWalPages();\n if (walPages < this.#nextWalThreshold) {\n return;\n }\n\n // Single-flight: reuse the outstanding sync if one is already running.\n this.#pendingSync ??= this.#sync(walPages);\n\n // Soft backpressure: block the write path until the sync completes, but no\n // longer than the wait budget. Letting the budget elapse lets the writer\n // proceed *without* cancelling the sync (it keeps running, tracked by\n // #pendingSync); unbounded WAL growth is caught by the hard cap below.\n await this.#waitFor(this.#pendingSync, SOFT_CHECKPOINT_WAIT_MS);\n\n walPages = this.#getNumWalPages();\n if (this.#maxWalPages !== undefined && walPages > this.#maxWalPages) {\n // Emergency brake when best-effort checkpoints are being skipped\n // (i.e. during a snapshot) and the WAL is approaching disk capacity.\n // Pausing replication is favorable to litestream's truncate-page-n\n // because the latter involves re-encoding the database under the lock\n // (https://github.com/benbjohnson/litestream/issues/1332), which would\n // incur the full latency of an additional snapshot.\n walPages = await this.#pauseUntilWalDrained(this.#maxWalPages);\n }\n\n // In the common case where checkpoints are successful, this is always\n // just `attemptChunk`. When a checkpoint doesn't drain the WAL (e.g.\n // litestream is performing a snapshot), wait for another chunk of growth\n // before the next attempt.\n this.#nextWalThreshold = walPages + this.#attemptChunk;\n }\n\n async #waitFor(p: Promise<void>, timeoutMs: number): Promise<void> {\n const result = await Promise.race([\n p,\n this.#state.sleep(timeoutMs).then(() => 'timed-out' as const),\n ]);\n if (result === 'timed-out') {\n this.#lc.warn?.(`timed out waiting for /sync result (${timeoutMs}ms)`);\n }\n }\n\n /**\n * Runs a single litestream sync, logs its outcome, and clears\n * {@link #pendingSync} when it settles. Never rejects: sync failures and\n * post-sync bookkeeping errors (e.g. the db being closed during shutdown)\n * are caught and logged, so the shared promise can be awaited from multiple\n * places without risking an unhandled rejection.\n */\n async #sync(walPagesBefore: number): Promise<void> {\n const start = performance.now();\n let result: SyncResponse | undefined;\n let err: unknown;\n try {\n try {\n result = await this.#litestream.sync(\n {wait: false, timeoutMs: LITESTREAM_SYNC_TIMEOUT_MS},\n this.#state.signal,\n );\n } catch (e) {\n err = e;\n }\n\n const elapsed = performance.now() - start;\n const newWalPages = this.#getNumWalPages();\n if (newWalPages < this.#nextWalThreshold) {\n this.#lc.info?.(\n `checkpointed ${walPagesBefore} -> ${newWalPages} wal pages (${elapsed.toFixed(2)} ms)`,\n result,\n );\n } else if (result) {\n this.#lc.warn?.(\n `checkpoint skipped ${walPagesBefore} -> ${newWalPages}. a snapshot may be in progress (${elapsed.toFixed(2)} ms)`,\n result,\n );\n } else {\n this.#lc.warn?.(\n `checkpoint failed ${walPagesBefore} -> ${newWalPages} (${elapsed.toFixed(2)} ms)`,\n err,\n );\n }\n } catch (e) {\n this.#lc.warn?.('litestream-checkpointer sync post-processing failed', e);\n } finally {\n this.#pendingSync = undefined;\n }\n }\n\n async #pauseUntilWalDrained(maxWalPages: number): Promise<number> {\n for (let i = 0; this.#state.shouldRun(); i++) {\n const walPages = this.#getNumWalPages();\n if (walPages < maxWalPages) {\n this.#lc.info?.(\n `wal size (${walPages} pages) is under the max limit of ${maxWalPages}`,\n );\n return walPages;\n }\n\n // Log every 30 seconds.\n if (i % PAUSE_LOG_INTERVAL_POLLS === 0) {\n this.#lc.warn?.(\n `waiting for litestream to successfully checkpoint ${walPages} wal pages`,\n );\n }\n await this.#state.sleep(PAUSE_POLL_INTERVAL_MS);\n // Single-flight: reuse the outstanding sync if one is already running.\n this.#pendingSync ??= this.#sync(this.#getNumWalPages());\n // await the full liveness timeout configured in #sync()\n await this.#pendingSync;\n }\n throw new AbortError('litestream-controller stopped');\n }\n\n /** Releases the underlying litestream controller's connection. */\n close(): void {\n this.#litestream.close();\n this.#state.stop(this.#lc);\n }\n}\n"],"mappings":";;;AAiBA,IAAa,0BAA0B;AAIvC,IAAM,6BAA6B,IAAI;AACvC,IAAM,yBAAyB;AAC/B,IAAM,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BjC,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA;CACA,SAAkB,IAAI,aAAa,yBAAyB;CAC5D;CACA;CAEA,YACE,IACA,IACA,YACA,QACA;EACA,KAAKA,MAAM,GAAG,YAAY,aAAa,yBAAyB;EAChE,KAAKC,MAAM;EACX,KAAKC,cAAc;EACnB,KAAKC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C,QAAQ,QAAQ,CAAC,EAAE,OAC7G,MACF;QAEA,KAAKA,IAAI,OACP,qBAAqB,eAAe,MAAM,YAAY,IAAI,QAAQ,QAAQ,CAAC,EAAE,OAC7E,GACF;EAEJ,SAAS,GAAG;GACV,KAAKA,IAAI,OAAO,uDAAuD,CAAC;EAC1E,UAAU;GACR,KAAKQ,eAAe,KAAA;EACtB;CACF;CAEA,MAAMG,sBAAsB,aAAsC;EAChE,KAAK,IAAI,IAAI,GAAG,KAAKN,OAAO,UAAU,GAAG,KAAK;GAC5C,MAAM,WAAW,KAAKE,gBAAgB;GACtC,IAAI,WAAW,aAAa;IAC1B,KAAKP,IAAI,OACP,aAAa,SAAS,oCAAoC,aAC5D;IACA,OAAO;GACT;GAGA,IAAI,IAAI,6BAA6B,GACnC,KAAKA,IAAI,OACP,qDAAqD,SAAS,WAChE;GAEF,MAAM,KAAKK,OAAO,MAAM,sBAAsB;GAE9C,KAAKG,iBAAiB,KAAKC,MAAM,KAAKF,gBAAgB,CAAC;GAEvD,MAAM,KAAKC;EACb;EACA,MAAM,IAAI,WAAW,+BAA+B;CACtD;;CAGA,QAAc;EACZ,KAAKN,YAAY,MAAM;EACvB,KAAKG,OAAO,KAAK,KAAKL,GAAG;CAC3B;AACF"}
@@ -14,6 +14,11 @@ export type MutationError = [
14
14
  desc: string
15
15
  ];
16
16
  export interface Mutagen extends RefCountedService {
17
+ /**
18
+ * Callers must hold a {@link ref} for the duration of a push (i.e. across
19
+ * all of its mutations). The service stops, closing its replica handle,
20
+ * when its ref count drops to zero.
21
+ */
17
22
  processMutation(mutation: Mutation, authData: JWTPayload | undefined, customMutatorsEnabled: boolean): Promise<MutationError | undefined>;
18
23
  }
19
24
  export declare class MutagenService implements Mutagen, Service {