@rocicorp/zero 1.12.0 → 1.13.0-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/out/shared/src/bigint-json.d.ts +6 -0
  2. package/out/shared/src/bigint-json.d.ts.map +1 -1
  3. package/out/shared/src/bigint-json.js +14 -1
  4. package/out/shared/src/bigint-json.js.map +1 -1
  5. package/out/shared/src/objects.d.ts +7 -0
  6. package/out/shared/src/objects.d.ts.map +1 -1
  7. package/out/shared/src/objects.js +10 -1
  8. package/out/shared/src/objects.js.map +1 -1
  9. package/out/shared/src/resolver.d.ts.map +1 -1
  10. package/out/shared/src/resolver.js +12 -1
  11. package/out/shared/src/resolver.js.map +1 -1
  12. package/out/shared/src/valita.d.ts.map +1 -1
  13. package/out/shared/src/valita.js +2 -1
  14. package/out/shared/src/valita.js.map +1 -1
  15. package/out/z2s/src/compiler.d.ts.map +1 -1
  16. package/out/z2s/src/compiler.js +4 -2
  17. package/out/z2s/src/compiler.js.map +1 -1
  18. package/out/zero/package.js +2 -2
  19. package/out/zero/package.js.map +1 -1
  20. package/out/zero-cache/src/auth/write-authorizer.js +4 -3
  21. package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
  22. package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
  23. package/out/zero-cache/src/config/normalize.js +3 -23
  24. package/out/zero-cache/src/config/normalize.js.map +1 -1
  25. package/out/zero-cache/src/config/zero-config.d.ts +1 -27
  26. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  27. package/out/zero-cache/src/config/zero-config.js +19 -47
  28. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  29. package/out/zero-cache/src/custom/fetch.js +17 -2
  30. package/out/zero-cache/src/custom/fetch.js.map +1 -1
  31. package/out/zero-cache/src/db/create.js +45 -1
  32. package/out/zero-cache/src/db/create.js.map +1 -1
  33. package/out/zero-cache/src/db/lite-tables.d.ts.map +1 -1
  34. package/out/zero-cache/src/db/lite-tables.js +4 -3
  35. package/out/zero-cache/src/db/lite-tables.js.map +1 -1
  36. package/out/zero-cache/src/db/pg-copy-binary.js +61 -25
  37. package/out/zero-cache/src/db/pg-copy-binary.js.map +1 -1
  38. package/out/zero-cache/src/db/pg-to-lite.d.ts +17 -0
  39. package/out/zero-cache/src/db/pg-to-lite.d.ts.map +1 -1
  40. package/out/zero-cache/src/db/pg-to-lite.js +84 -1
  41. package/out/zero-cache/src/db/pg-to-lite.js.map +1 -1
  42. package/out/zero-cache/src/server/change-streamer.js +21 -30
  43. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  44. package/out/zero-cache/src/server/inspector-delegate.js +1 -1
  45. package/out/zero-cache/src/server/main.js +0 -1
  46. package/out/zero-cache/src/server/main.js.map +1 -1
  47. package/out/zero-cache/src/server/replicator.js +1 -1
  48. package/out/zero-cache/src/server/replicator.js.map +1 -1
  49. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +6 -5
  50. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
  51. package/out/zero-cache/src/services/change-source/pg/change-source.js +50 -12
  52. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  53. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +64 -21
  54. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  55. package/out/zero-cache/src/services/change-source/pg/replication-slots.js +11 -6
  56. package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
  57. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +13 -1
  58. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
  59. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +16 -3
  60. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
  61. package/out/zero-cache/src/services/change-source/pg/schema/init.js +6 -4
  62. package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
  63. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts +1 -0
  64. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts.map +1 -1
  65. package/out/zero-cache/src/services/change-source/pg/schema/published.js +56 -12
  66. package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
  67. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +1 -0
  68. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
  69. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +35 -12
  70. package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
  71. package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts +6 -1
  72. package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts.map +1 -1
  73. package/out/zero-cache/src/services/change-source/pg/schema/validation.js +25 -1
  74. package/out/zero-cache/src/services/change-source/pg/schema/validation.js.map +1 -1
  75. package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js +6 -5
  76. package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js.map +1 -1
  77. package/out/zero-cache/src/services/change-streamer/backfill-state.js +7 -6
  78. package/out/zero-cache/src/services/change-streamer/backfill-state.js.map +1 -1
  79. package/out/zero-cache/src/services/change-streamer/change-log-codec.js +2 -2
  80. package/out/zero-cache/src/services/change-streamer/change-log-codec.js.map +1 -1
  81. package/out/zero-cache/src/services/change-streamer/change-log-initializer.js +16 -199
  82. package/out/zero-cache/src/services/change-streamer/change-log-initializer.js.map +1 -1
  83. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +76 -127
  84. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  85. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +1 -1
  86. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -1
  87. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js.map +1 -1
  88. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.js +1 -1
  89. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js +15 -49
  90. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js.map +1 -1
  91. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js +8 -2
  92. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js.map +1 -1
  93. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js +20 -36
  94. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js.map +1 -1
  95. package/out/zero-cache/src/services/change-streamer/storer.js +32 -20
  96. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  97. package/out/zero-cache/src/services/mutagen/mutagen.js +4 -2
  98. package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
  99. package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts +0 -16
  100. package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts.map +1 -1
  101. package/out/zero-cache/src/services/replicator/change-log-cookies.js +3 -95
  102. package/out/zero-cache/src/services/replicator/change-log-cookies.js.map +1 -1
  103. package/out/zero-cache/src/services/replicator/change-log-db.js +2 -2
  104. package/out/zero-cache/src/services/replicator/change-log-db.js.map +1 -1
  105. package/out/zero-cache/src/services/replicator/change-log-stream-writer.js +1 -30
  106. package/out/zero-cache/src/services/replicator/change-log-stream-writer.js.map +1 -1
  107. package/out/zero-cache/src/services/replicator/change-processor.js +83 -38
  108. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  109. package/out/zero-cache/src/services/replicator/incremental-sync.js +7 -1
  110. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  111. package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts +1 -0
  112. package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts.map +1 -1
  113. package/out/zero-cache/src/services/replicator/reporter/report-schema.js +4 -1
  114. package/out/zero-cache/src/services/replicator/reporter/report-schema.js.map +1 -1
  115. package/out/zero-cache/src/services/replicator/schema/change-log.d.ts.map +1 -1
  116. package/out/zero-cache/src/services/replicator/schema/change-log.js +2 -1
  117. package/out/zero-cache/src/services/replicator/schema/change-log.js.map +1 -1
  118. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js +6 -102
  119. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js.map +1 -1
  120. package/out/zero-cache/src/services/statz.d.ts.map +1 -1
  121. package/out/zero-cache/src/services/statz.js +1 -1
  122. package/out/zero-cache/src/services/statz.js.map +1 -1
  123. package/out/zero-cache/src/services/view-syncer/active-users-gauge.js +1 -1
  124. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +1 -1
  125. package/out/zero-cache/src/services/view-syncer/schema/init.js +3 -0
  126. package/out/zero-cache/src/services/view-syncer/schema/init.js.map +1 -1
  127. package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js +47 -3
  128. package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js.map +1 -1
  129. package/out/zero-cache/src/services/view-syncer/view-syncer.js +51 -6
  130. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  131. package/out/zero-cache/src/types/lite.d.ts +7 -0
  132. package/out/zero-cache/src/types/lite.d.ts.map +1 -1
  133. package/out/zero-cache/src/types/lite.js +12 -2
  134. package/out/zero-cache/src/types/lite.js.map +1 -1
  135. package/out/zero-cache/src/types/pg-types.d.ts +2 -1
  136. package/out/zero-cache/src/types/pg-types.d.ts.map +1 -1
  137. package/out/zero-cache/src/types/pg-types.js +2 -1
  138. package/out/zero-cache/src/types/pg-types.js.map +1 -1
  139. package/out/zero-cache/src/types/pg.d.ts +20 -0
  140. package/out/zero-cache/src/types/pg.d.ts.map +1 -1
  141. package/out/zero-cache/src/types/pg.js +64 -27
  142. package/out/zero-cache/src/types/pg.js.map +1 -1
  143. package/out/zero-cache/src/types/streams.d.ts +2 -0
  144. package/out/zero-cache/src/types/streams.d.ts.map +1 -1
  145. package/out/zero-cache/src/types/streams.js +2 -1
  146. package/out/zero-cache/src/types/streams.js.map +1 -1
  147. package/out/zero-cache/src/workers/replicator.js +7 -6
  148. package/out/zero-cache/src/workers/replicator.js.map +1 -1
  149. package/out/zero-cache/src/workers/syncer.js +18 -1
  150. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  151. package/out/zero-client/src/client/crud-impl.js +1 -1
  152. package/out/zero-client/src/client/ivm-branch.js +1 -1
  153. package/out/zero-client/src/client/version.js +1 -1
  154. package/out/zero-protocol/src/client-schema.js +1 -1
  155. package/out/zero-protocol/src/down.d.ts +2 -2
  156. package/out/zero-schema/src/builder/schema-builder.js +1 -1
  157. package/out/zql/src/builder/builder.js +1 -1
  158. package/out/zql/src/ivm/aggregate.js +1 -1
  159. package/out/zql/src/ivm/flipped-join.js +1 -1
  160. package/out/zql/src/ivm/group-by.js +1 -1
  161. package/out/zql/src/ivm/join-index.js +1 -1
  162. package/out/zql/src/ivm/memory-source.js +1 -1
  163. package/out/zql/src/ivm/view-apply-change.js +1 -1
  164. package/out/zqlite/src/db.js +4 -1
  165. package/out/zqlite/src/db.js.map +1 -1
  166. package/out/zqlite/src/table-source.d.ts.map +1 -1
  167. package/out/zqlite/src/table-source.js +4 -2
  168. package/out/zqlite/src/table-source.js.map +1 -1
  169. package/package.json +2 -2
  170. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js +0 -67
  171. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js.map +0 -1
  172. package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js +0 -39
  173. package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js.map +0 -1
  174. package/out/zero-cache/src/services/change-streamer/shard-sampling.js +0 -19
  175. package/out/zero-cache/src/services/change-streamer/shard-sampling.js.map +0 -1
  176. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js +0 -417
  177. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js.map +0 -1
@@ -1,75 +1,41 @@
1
- import { assert } from "../../../../shared/src/asserts.js";
2
- import { must } from "../../../../shared/src/must.js";
3
- import { BigIntJSON } from "../../../../shared/src/bigint-json.js";
4
- import { schemaChangeTags } from "../change-source/protocol/current/schema-change-tags.js";
5
1
  import { Database } from "../../../../zqlite/src/db.js";
6
- import { getOrCreateCounter } from "../../observability/metrics.js";
7
2
  import { StatementRunner } from "../../db/statements.js";
8
- import { backfillRequestsFrom, foldCookies } from "../replicator/change-log-cookies.js";
3
+ import { backfillRequestsFrom } from "../replicator/change-log-cookies.js";
9
4
  import { readBackfillRequests, readReplicaCookies } from "../replicator/schema/backfilling.js";
10
5
  import { getReplicationState } from "../replicator/schema/replication-state.js";
11
- import { CHANGE_LOG_STREAM_TABLE } from "../replicator/change-log-db.js";
12
- import { SQLITE_CHANGE_LOG_BOUNDARY_SQL } from "./sqlite-change-log-reader.js";
13
6
  //#region ../zero-cache/src/services/change-streamer/change-log-initializer.ts
14
- /**
15
- * The most change-log rows one comparison will scan.
16
- *
17
- * The interval is `(replicaWatermark, pgWatermark]`, so it is normally a
18
- * handful of transactions — but a replicator that has been stalled can leave it
19
- * arbitrarily large, and this runs on the stream loop between reconciliation and
20
- * `startStream`, where latency delays the resumption of replication. Over the
21
- * cap the comparison declines rather than pays: a chronically lagging replicator
22
- * shows up as `inconclusive`, which is charted, and not as a stall.
23
- */
24
- var MAX_FOLD_SCAN_ROWS = 1e4;
25
7
  var ChangeLogInitializer = class {
26
8
  #lc;
27
9
  #initFromPgChangeLog;
28
- #initFromReplica;
29
10
  #sources;
30
- #resultCounter = getOrCreateCounter("replica", "sqlite_change_log.init_compare_result", "Comparisons of the replica-derived stream initialization parameters against the Postgres-derived ones, by classification.");
31
- #lastComparison;
32
11
  /**
33
12
  * The (restored) replica's resume point that the Postgres change log must
34
13
  * cover, read once. See {@link #pgChangeLog}.
35
14
  */
36
15
  #restoredReplica;
37
- constructor(lc, { initFromPgChangeLog, initFromReplica }, sources) {
38
- assert(initFromPgChangeLog || initFromReplica, `At least one of initFromPgChangeLog or initFromReplica must be true`);
16
+ /**
17
+ * @param initFromPgChangeLog Whether the Postgres change log (rather than
18
+ * the SQLite change log) supplies the initialization parameters.
19
+ */
20
+ constructor(lc, initFromPgChangeLog, sources) {
39
21
  this.#lc = lc.withContext("component", "change-log-initializer");
40
22
  this.#initFromPgChangeLog = initFromPgChangeLog;
41
- this.#initFromReplica = initFromReplica;
42
23
  this.#sources = sources;
43
24
  }
44
25
  /**
45
- * Returns the comparison result from the most recent {@link initialize}
46
- * call. Returns `undefined` when that call used only one source.
47
- *
48
- * Tests and metrics use this result. It does not affect initialization.
26
+ * Returns the initialization parameters for one stream connection, after
27
+ * reconciling the SQLite change log when it is the one in use.
49
28
  */
50
- lastComparison() {
51
- return this.#lastComparison;
29
+ async initialize() {
30
+ return this.#initFromPgChangeLog ? await this.#pgChangeLog() : this.#sqliteChangeLog();
52
31
  }
53
32
  /**
54
- * Returns the initialization parameters for one stream connection after it
55
- * reconciles the change log.
56
- *
57
- * The selected source determines how reconciliation works. Keeping both
58
- * operations here hides that choice from the caller.
33
+ * The replica is read up front, as it seeds a new log and supplies the
34
+ * resume point when the writer is unavailable.
59
35
  */
60
- async initialize() {
61
- this.#lastComparison = void 0;
62
- const pg = this.#initFromPgChangeLog ? await this.#pgChangeLog() : void 0;
63
- const replica = this.#initFromReplica ? this.#readReplica(pg === void 0) : void 0;
64
- const reconciled = this.#sources.reconcileChangeLog(pg && {
65
- resumeWatermark: pg.lastWatermark,
66
- cookies: pg.cookies
67
- }, () => resumePointOf(must(replica, "no seed for the SQLite change log")));
68
- if (pg) {
69
- if (replica) this.#lastComparison = this.#compare(pg, replica);
70
- return pg;
71
- }
72
- const resumePoint = reconciled ?? resumePointOf(must(replica, "no initialization source"));
36
+ #sqliteChangeLog() {
37
+ const replica = this.#sources.replica();
38
+ const resumePoint = this.#sources.reconcileChangeLog(() => resumePointOf(replica)) ?? resumePointOf(replica);
73
39
  return {
74
40
  lastWatermark: resumePoint.resumeWatermark,
75
41
  cookies: resumePoint.cookies,
@@ -114,58 +80,6 @@ var ChangeLogInitializer = class {
114
80
  this.#lc.info?.(`Postgres change log at ${pg.lastWatermark} is behind the replica at ${lastWatermark}: ${result}`);
115
81
  return this.#sources.pgChangeLog();
116
82
  }
117
- /**
118
- * Compares both sources and records the result. Postgres remains
119
- * authoritative when both sources are enabled.
120
- */
121
- #compare(pg, replica) {
122
- let result;
123
- try {
124
- result = this.#classify(pg, replica);
125
- } catch (e) {
126
- this.#lc.warn?.("failed to compare change-log initialization sources", e);
127
- result = "error";
128
- }
129
- this.#resultCounter.add(1, { result });
130
- this.#lc.debug?.("compared change-log initialization sources", { changeLogInitCompare: {
131
- result,
132
- pgWatermark: pg.lastWatermark,
133
- replicaWatermark: replica.lastWatermark
134
- } });
135
- return result;
136
- }
137
- #readReplica(required) {
138
- try {
139
- return this.#sources.replica();
140
- } catch (e) {
141
- if (required) throw e;
142
- this.#lc.warn?.("failed to derive change-log initialization from the replica", e);
143
- this.#resultCounter.add(1, { result: "error" });
144
- return;
145
- }
146
- }
147
- #classify(pg, replica) {
148
- if (replica.lastWatermark > pg.lastWatermark) return "inconclusive";
149
- if (replica.lastWatermark === pg.lastWatermark) return this.#report(pg, replica, replica.cookies, "equal");
150
- const db = this.#sources.changeLog();
151
- if (db === void 0 || !spansInterval(db, replica.lastWatermark)) return "inconclusive";
152
- const changes = readSchemaChanges(db, replica.lastWatermark, pg.lastWatermark);
153
- if (changes === void 0) return "inconclusive";
154
- return this.#report(pg, replica, foldCookies(replica.cookies, changes), "equal-after-fold", changes.length);
155
- }
156
- #report(pg, replica, derived, whenEqual, foldedChanges = 0) {
157
- const expected = canonicalizeCookies(pg.cookies);
158
- const actual = canonicalizeCookies(derived);
159
- if (expected === actual) return whenEqual;
160
- this.#lc.error?.("the replica-derived change-log cookies do not match Postgres", { changeLogInitCompare: {
161
- pgWatermark: pg.lastWatermark,
162
- replicaWatermark: replica.lastWatermark,
163
- foldedChanges,
164
- expected,
165
- actual
166
- } });
167
- return "divergent";
168
- }
169
83
  };
170
84
  var resumePointOf = ({ lastWatermark, cookies }) => ({
171
85
  resumeWatermark: lastWatermark,
@@ -198,8 +112,7 @@ function readReplicaInitializationParameters(db) {
198
112
  * replica's cookie tables are written by the change-processor and by nothing
199
113
  * else. Note that a read-only SQLite connection still needs to attach the
200
114
  * WAL's `-shm`, so this can fail if it opens at a moment when no writer holds
201
- * the replica; that surfaces as the `error` classification, which is the point
202
- * of running the path under observation before anything depends on it.
115
+ * the replica.
203
116
  */
204
117
  function replicaInitializationSource(lc, replicaFile) {
205
118
  return () => {
@@ -211,102 +124,6 @@ function replicaInitializationSource(lc, replicaFile) {
211
124
  }
212
125
  };
213
126
  }
214
- /**
215
- * Whether the log holds the complete interval above `fromWatermark`, using the
216
- * same predicate catchup uses to decide `too-old`: the log both reaches back
217
- * that far and contains that transaction's `commit` row, so the next row after
218
- * it is the first change of the interval rather than the middle of a
219
- * transaction the log only partly holds.
220
- */
221
- function spansInterval(db, fromWatermark) {
222
- if (!streamTableExists(db)) return false;
223
- const row = db.prepare(`
224
- SELECT
225
- (SELECT min("watermark") FROM "${CHANGE_LOG_STREAM_TABLE}")
226
- AS "minWatermark",
227
- coalesce((${SQLITE_CHANGE_LOG_BOUNDARY_SQL}), 0) AS "boundaryExists"
228
- `).get({ fromWatermark });
229
- return row.minWatermark !== null && fromWatermark >= row.minWatermark && row.boundaryExists === 1;
230
- }
231
- var SCHEMA_CHANGE_TAG_LIST = schemaChangeTags.map((tag) => `'${tag}'`).join(", ");
232
- /**
233
- * The log's schema changes over `(after, through]`, in stream order, or
234
- * `undefined` if the interval is too large to scan (see
235
- * {@link MAX_FOLD_SCAN_ROWS}).
236
- *
237
- * The tag is stored beside the verbatim change so this scan never parses the
238
- * payloads of ordinary data changes. The row count is still checked first so a
239
- * stalled replicator cannot make the range scan unbounded.
240
- *
241
- * The count is itself capped, at one row past the cap it is deciding. A bare
242
- * `count(*)` over the interval is `O(interval)`, so the unbounded interval this
243
- * exists to decline would still be walked in full before being declined —
244
- * which is the latency the cap is here to avoid, not a cheaper form of it. The
245
- * `LIMIT` makes the decision `O(MAX_FOLD_SCAN_ROWS)`, and the comparison is
246
- * unaffected: the subquery returns the true count whenever it is within the
247
- * cap, and `cap + 1` whenever it is not.
248
- */
249
- function readSchemaChanges(db, after, through) {
250
- const { rows } = db.prepare(`
251
- SELECT count(*) AS "rows" FROM (
252
- SELECT 1 FROM "${CHANGE_LOG_STREAM_TABLE}"
253
- WHERE "watermark" > ? AND "watermark" <= ?
254
- LIMIT 10001
255
- )
256
- `).get(after, through);
257
- if (rows > MAX_FOLD_SCAN_ROWS) return;
258
- return db.prepare(`
259
- SELECT "change" FROM "${CHANGE_LOG_STREAM_TABLE}"
260
- WHERE "watermark" > ? AND "watermark" <= ?
261
- AND "tag" IN (${SCHEMA_CHANGE_TAG_LIST})
262
- ORDER BY "watermark", "pos"
263
- `).all(after, through).map(({ change }) => BigIntJSON.parse(change));
264
- }
265
- function streamTableExists(db) {
266
- return db.prepare(`
267
- SELECT 1 FROM "sqlite_master" WHERE "type" = 'table' AND "name" = ?
268
- `).get(CHANGE_LOG_STREAM_TABLE) !== void 0;
269
- }
270
- /**
271
- * A canonical rendering of a whole cookie set: rows sorted by primary key,
272
- * object keys sorted at every depth.
273
- *
274
- * Both the equality check and the `divergent` log line fall out of this one
275
- * value, and neither can be defeated by a difference that is not a difference.
276
- * Postgres stores the cookie documents as `jsonb`, which does not preserve key
277
- * order, and the two readers order their rows in SQL in two engines under two
278
- * collations -- `storer.ts` pins `COLLATE "C"` for exactly that reason. Sorting
279
- * again here means an ordering or key-order regression can never be reported as
280
- * a divergence, which is a class of false alert that would cost more than it
281
- * caught.
282
- */
283
- function canonicalizeCookies(cookies) {
284
- return BigIntJSON.stringify({
285
- tableMetadata: byKey(cookies.tableMetadata, (c) => [c.schema, c.table]).map((c) => [
286
- c.schema,
287
- c.table,
288
- sortKeys(c.metadata)
289
- ]),
290
- backfilling: byKey(cookies.backfilling, (c) => [
291
- c.schema,
292
- c.table,
293
- c.column
294
- ]).map((c) => [
295
- c.schema,
296
- c.table,
297
- c.column,
298
- sortKeys(c.backfill)
299
- ])
300
- });
301
- }
302
- function byKey(rows, key) {
303
- return rows.map((row) => [JSON.stringify(key(row)), row]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, row]) => row);
304
- }
305
- function sortKeys(value) {
306
- if (Array.isArray(value)) return value.map(sortKeys);
307
- if (value === null || typeof value !== "object") return value;
308
- return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => [k, sortKeys(v)]));
309
- }
310
127
  //#endregion
311
128
  export { ChangeLogInitializer, readReplicaInitializationParameters, replicaInitializationSource };
312
129
 
@@ -1 +1 @@
1
- {"version":3,"file":"change-log-initializer.js","names":[],"sources":["../../../../../../zero-cache/src/services/change-streamer/change-log-initializer.ts"],"sourcesContent":["/**\n * Where a stream connection's initialization parameters come from.\n *\n * A change-streamer starts a stream from three things read at one position: the\n * watermark to resume at, the {@link BackfillRequest}s to hand the change\n * source, and the cookie set those requests were derived from. Postgres has\n * always supplied all three (`Storer.getStartStreamInitializationParameters()`).\n * The point of this workstream is that a restored replica can supply them\n * instead, which is what lets the `cdc` schema be decommissioned.\n *\n * This is the two-source stage. Both are computed on every stream connection,\n * compared, and Postgres's is used — so the replica-derived path runs in\n * production, at full rate, before anything depends on it. The flip is\n * `initFromPgChangeLog: false`, not a rewrite.\n *\n * The shape is {@link UpstreamAcker}'s, deliberately: two stores, one output, a\n * flag per store, and the Postgres flag carrying the marker that retires it.\n * That class solved the identical problem for upstream ACKs earlier in this\n * workstream.\n *\n * ### Why the comparison is a fold and not an equality\n *\n * The replica is a subscriber downstream of the change-streamer's write loop,\n * so its state version trails the log's head by however long the replicator is\n * behind. A raw difference between the two cookie sets is therefore the normal\n * case and says nothing. What is checked instead is that the replica's set,\n * carried forward over exactly the schema changes the log holds in the interval,\n * equals Postgres's set at Postgres's watermark. The log holds precisely those\n * transactions, schema changes are rare, and the check is exact rather than\n * approximate — so it also happens to be the strongest available test of the\n * premise that three interpreters of one fold agree.\n */\n\nimport type {LogContext} from '@rocicorp/logger';\nimport {assert} from '../../../../shared/src/asserts.ts';\nimport {BigIntJSON} from '../../../../shared/src/bigint-json.ts';\nimport {must} from '../../../../shared/src/must.ts';\nimport {Database} from '../../../../zqlite/src/db.ts';\nimport {StatementRunner} from '../../db/statements.ts';\nimport {getOrCreateCounter} from '../../observability/metrics.ts';\nimport type {SchemaChange} from '../change-source/protocol/current/data.ts';\nimport {schemaChangeTags} from '../change-source/protocol/current/schema-change-tags.ts';\nimport type {BackfillRequest} from '../change-source/protocol/current/upstream.ts';\nimport {\n backfillRequestsFrom,\n foldCookies,\n type CookieSet,\n} from '../replicator/change-log-cookies.ts';\nimport {\n CHANGE_LOG_STREAM_TABLE,\n type ChangeLogResumePoint,\n} from '../replicator/change-log-db.ts';\nimport {\n readBackfillRequests,\n readReplicaCookies,\n} from '../replicator/schema/backfilling.ts';\nimport {getReplicationState} from '../replicator/schema/replication-state.ts';\nimport {SQLITE_CHANGE_LOG_BOUNDARY_SQL} from './sqlite-change-log-reader.ts';\n\n/** Everything one stream connection starts from, read at one position. */\nexport type InitializationParameters = {\n readonly lastWatermark: string;\n readonly backfillRequests: BackfillRequest[];\n readonly cookies: CookieSet;\n};\n\n/**\n * - `equal` — the two stores were at the same watermark and held the same\n * cookies. Nothing had to be folded, which is the strongest of the four.\n * - `equal-after-fold` — the replica trailed, and carrying its set forward over\n * the log's schema changes in the interval reproduced Postgres's exactly.\n * The expected steady-state result.\n * - `divergent` — the two disagree at the same position. Alert; investigate\n * individually.\n * - `inconclusive` — the log does not span the interval, so the fold cannot be\n * performed. Routine on a cold log, and not a finding.\n * - `error` — the comparison itself failed: the replica could not be read, or\n * the fold threw. Not one of the four classifications, because it is a\n * statement about this process rather than about the two stores. Kept\n * separate rather than folded into `inconclusive` so that a change-streamer\n * that has silently stopped being able to read its replica is visible before\n * that read becomes the only source.\n */\nexport type InitComparisonResult =\n | 'equal'\n | 'equal-after-fold'\n | 'divergent'\n | 'inconclusive'\n | 'error';\n\nexport type ChangeLogInitializerSources = {\n /** `Storer.getStartStreamInitializationParameters()`. */\n readonly pgChangeLog: () => Promise<InitializationParameters>;\n /** Typically {@link replicaInitializationSource}. */\n readonly replica: () => InitializationParameters;\n /**\n * Reconciles the SQLite change log and returns its current resume point.\n *\n * When `resumeFrom` is present, it supplies the resume point. Otherwise, a\n * valid log uses its own head. A new or invalid log uses `seed`.\n *\n * Returns `undefined` when the writer is disabled or unavailable.\n */\n readonly reconcileChangeLog: (\n resumeFrom: ChangeLogResumePoint | undefined,\n seed: () => ChangeLogResumePoint,\n ) => ChangeLogResumePoint | undefined;\n /**\n * The change log, for the fold. `undefined` before the stream loop's first\n * reconcile has created it, and again once the writer has failed soft and\n * deleted it — both of which make the comparison `inconclusive` rather than\n * an error, since neither says anything about the two stores.\n */\n readonly changeLog: () => Database | undefined;\n /**\n * Re-initializes the Postgres change log from the replica's resume point\n * (taking ownership of it) if it does not contain all of the replica's\n * changes, re-checking under lock. Typically\n * `Storer.reinitializeFromReplica()`.\n *\n * Supplied only when the change log's head is behind the position of the\n * replication slot from which replication resumes, i.e. when it may be\n * missing transactions that the slot will not stream. Otherwise, a replica\n * that is ahead of the change log (as changes are forwarded before they are\n * stored) is caught up by the change stream, which resumes from the change\n * log's head.\n */\n readonly reinitializePgChangeLog?:\n | ((params: {\n watermark: string;\n cookies: CookieSet;\n }) => Promise<'reinitialized' | 'maintained'>)\n | undefined;\n};\n\ntype Opts = {\n /**\n * When true, Postgres supplies the resume point and the cookies for a new\n * change log.\n *\n * When false, a valid log resumes from its own head. The replica supplies the\n * resume point for a new or invalid log.\n */\n // TODO: set false when retiring PG\n readonly initFromPgChangeLog: boolean;\n /**\n * Derive the parameters from the replica. When Postgres is enabled, these\n * parameters are used only for comparison.\n *\n * When Postgres is disabled, the replica supplies the seed and the fallback\n * resume point.\n */\n readonly initFromReplica: boolean;\n};\n\n/**\n * The most change-log rows one comparison will scan.\n *\n * The interval is `(replicaWatermark, pgWatermark]`, so it is normally a\n * handful of transactions — but a replicator that has been stalled can leave it\n * arbitrarily large, and this runs on the stream loop between reconciliation and\n * `startStream`, where latency delays the resumption of replication. Over the\n * cap the comparison declines rather than pays: a chronically lagging replicator\n * shows up as `inconclusive`, which is charted, and not as a stall.\n */\nconst MAX_FOLD_SCAN_ROWS = 10_000;\n\nexport class ChangeLogInitializer {\n readonly #lc: LogContext;\n readonly #initFromPgChangeLog: boolean;\n readonly #initFromReplica: boolean;\n readonly #sources: ChangeLogInitializerSources;\n\n readonly #resultCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.init_compare_result',\n 'Comparisons of the replica-derived stream initialization parameters ' +\n 'against the Postgres-derived ones, by classification.',\n );\n\n #lastComparison: InitComparisonResult | undefined;\n\n /**\n * The (restored) replica's resume point that the Postgres change log must\n * cover, read once. See {@link #pgChangeLog}.\n */\n #restoredReplica: InitializationParameters | undefined;\n\n constructor(\n lc: LogContext,\n {initFromPgChangeLog, initFromReplica}: Opts,\n sources: ChangeLogInitializerSources,\n ) {\n assert(\n initFromPgChangeLog || initFromReplica,\n `At least one of initFromPgChangeLog or initFromReplica must be true`,\n );\n this.#lc = lc.withContext('component', 'change-log-initializer');\n this.#initFromPgChangeLog = initFromPgChangeLog;\n this.#initFromReplica = initFromReplica;\n this.#sources = sources;\n }\n\n /**\n * Returns the comparison result from the most recent {@link initialize}\n * call. Returns `undefined` when that call used only one source.\n *\n * Tests and metrics use this result. It does not affect initialization.\n */\n lastComparison(): InitComparisonResult | undefined {\n return this.#lastComparison;\n }\n\n /**\n * Returns the initialization parameters for one stream connection after it\n * reconciles the change log.\n *\n * The selected source determines how reconciliation works. Keeping both\n * operations here hides that choice from the caller.\n */\n async initialize(): Promise<InitializationParameters> {\n this.#lastComparison = undefined;\n const pg = this.#initFromPgChangeLog\n ? await this.#pgChangeLog()\n : undefined;\n // The replica is required when Postgres is disabled. It seeds a new log and\n // supplies a resume point when the writer is unavailable.\n const replica = this.#initFromReplica\n ? this.#readReplica(pg === undefined)\n : undefined;\n\n const reconciled = this.#sources.reconcileChangeLog(\n pg && {resumeWatermark: pg.lastWatermark, cookies: pg.cookies},\n () => resumePointOf(must(replica, 'no seed for the SQLite change log')),\n );\n\n if (pg) {\n if (replica) {\n // Compare only after reconciliation. The fold must read the schema\n // changes from the replica watermark through the Postgres watermark.\n // Reconciliation makes sure that the log contains that interval.\n this.#lastComparison = this.#compare(pg, replica);\n }\n return pg;\n }\n\n // Use the reconciled log position. If the writer is unavailable, use the\n // replica position.\n const resumePoint =\n reconciled ?? resumePointOf(must(replica, 'no initialization source'));\n return {\n lastWatermark: resumePoint.resumeWatermark,\n cookies: resumePoint.cookies,\n // Derive the requests from these cookies so that the requests and the\n // watermark describe the same position.\n backfillRequests: backfillRequestsFrom(resumePoint.cookies),\n };\n }\n\n /**\n * Reads the Postgres change log's initialization parameters, first\n * re-initializing it from the replica (taking ownership of it) if it may be\n * missing transactions that the replication slot will not stream, e.g. if it\n * is no longer maintained after running in high-availability mode. This is\n * the Postgres counterpart of seeding a new SQLite change log from the\n * replica.\n *\n * This only applies when the change log's head is behind the slot's position\n * (i.e. when {@link ChangeLogInitializerSources.reinitializePgChangeLog} is\n * supplied), and the change log is only re-initialized if its head is also\n * behind the replica's. Otherwise, it contains every transaction before the\n * slot's position: one that was acked after being stored would be in the\n * change log, and one that was acked after being backed up would be in the\n * replica, which the change log's head covers.\n *\n * The replica is read only once, i.e. as it was restored from the backup,\n * before any stream is started. The live replica is no reference: it is\n * caught up from the forwarded changes, which can be ahead of what has been\n * stored, e.g. by the change log's previous owner. Against that fixed\n * resume point, re-initialization is idempotent: afterwards, the change log's\n * head (which only advances) covers it, so subsequent stream connections\n * leave it untouched.\n */\n async #pgChangeLog(): Promise<InitializationParameters> {\n const pg = await this.#sources.pgChangeLog();\n const reinitialize = this.#sources.reinitializePgChangeLog;\n if (!reinitialize) {\n return pg;\n }\n this.#restoredReplica ??= this.#sources.replica();\n const {lastWatermark, cookies} = this.#restoredReplica;\n if (pg.lastWatermark >= lastWatermark) {\n return pg;\n }\n const result = await reinitialize({watermark: lastWatermark, cookies});\n this.#lc.info?.(\n `Postgres change log at ${pg.lastWatermark} is behind the replica at ` +\n `${lastWatermark}: ${result}`,\n );\n // Either way, the change log has changed since it was read.\n return this.#sources.pgChangeLog();\n }\n\n /**\n * Compares both sources and records the result. Postgres remains\n * authoritative when both sources are enabled.\n */\n #compare(\n pg: InitializationParameters,\n replica: InitializationParameters,\n ): InitComparisonResult {\n let result: InitComparisonResult;\n try {\n result = this.#classify(pg, replica);\n } catch (e) {\n this.#lc.warn?.('failed to compare change-log initialization sources', e);\n result = 'error';\n }\n this.#resultCounter.add(1, {result});\n this.#lc.debug?.('compared change-log initialization sources', {\n changeLogInitCompare: {\n result,\n pgWatermark: pg.lastWatermark,\n replicaWatermark: replica.lastWatermark,\n },\n });\n return result;\n }\n\n #readReplica(required: boolean): InitializationParameters | undefined {\n try {\n return this.#sources.replica();\n } catch (e) {\n if (required) {\n throw e;\n }\n // Observational until the flip, so a replica that cannot be read must not\n // stop replication -- but it must not be quiet either, since the flip\n // makes this read the only source.\n this.#lc.warn?.(\n 'failed to derive change-log initialization from the replica',\n e,\n );\n this.#resultCounter.add(1, {result: 'error'});\n return undefined;\n }\n }\n\n #classify(\n pg: InitializationParameters,\n replica: InitializationParameters,\n ): InitComparisonResult {\n if (replica.lastWatermark > pg.lastWatermark) {\n // Transactions reach subscribers before the storer's commit, so a replica\n // read taken while one is in flight can be a transaction ahead. The fold\n // only runs forward, so there is nothing to be said either way.\n return 'inconclusive';\n }\n if (replica.lastWatermark === pg.lastWatermark) {\n return this.#report(pg, replica, replica.cookies, 'equal');\n }\n\n const db = this.#sources.changeLog();\n if (db === undefined || !spansInterval(db, replica.lastWatermark)) {\n return 'inconclusive';\n }\n const changes = readSchemaChanges(\n db,\n replica.lastWatermark,\n pg.lastWatermark,\n );\n if (changes === undefined) {\n return 'inconclusive'; // over MAX_FOLD_SCAN_ROWS\n }\n return this.#report(\n pg,\n replica,\n foldCookies(replica.cookies, changes),\n 'equal-after-fold',\n changes.length,\n );\n }\n\n #report(\n pg: InitializationParameters,\n replica: InitializationParameters,\n derived: CookieSet,\n whenEqual: InitComparisonResult,\n foldedChanges = 0,\n ): InitComparisonResult {\n const expected = canonicalizeCookies(pg.cookies);\n const actual = canonicalizeCookies(derived);\n if (expected === actual) {\n return whenEqual;\n }\n // Both sets are normally empty and are at most a handful of rows, so they\n // are logged whole: a divergence is investigated individually (`P§:10`)\n // and the two renderings are the whole of what there is to look at.\n this.#lc.error?.(\n 'the replica-derived change-log cookies do not match Postgres',\n {\n changeLogInitCompare: {\n pgWatermark: pg.lastWatermark,\n replicaWatermark: replica.lastWatermark,\n foldedChanges,\n expected,\n actual,\n },\n },\n );\n return 'divergent';\n }\n}\n\nconst resumePointOf = ({\n lastWatermark,\n cookies,\n}: InitializationParameters): ChangeLogResumePoint => ({\n resumeWatermark: lastWatermark,\n cookies,\n});\n\n/**\n * Reads the replica's initialization parameters in one snapshot, which is\n * invariant 15 on the replica side: the state version and the cookies are only\n * meaningful together.\n */\nexport function readReplicaInitializationParameters(\n db: Database,\n): InitializationParameters {\n const runner = new StatementRunner(db);\n runner.begin(); // deferred, i.e. one read snapshot for the three statements\n try {\n return {\n lastWatermark: getReplicationState(runner).stateVersion,\n backfillRequests: readBackfillRequests(db),\n cookies: readReplicaCookies(db),\n };\n } finally {\n if (db.inTransaction) {\n runner.rollback();\n }\n }\n}\n\n/**\n * The replica source for {@link ChangeLogInitializer}, opening and closing the\n * file per stream connection rather than holding a handle on a database another\n * process owns.\n *\n * The handle is read-only, which is invariant 19 stated in the API: the\n * replica's cookie tables are written by the change-processor and by nothing\n * else. Note that a read-only SQLite connection still needs to attach the\n * WAL's `-shm`, so this can fail if it opens at a moment when no writer holds\n * the replica; that surfaces as the `error` classification, which is the point\n * of running the path under observation before anything depends on it.\n */\nexport function replicaInitializationSource(\n lc: LogContext,\n replicaFile: string,\n): () => InitializationParameters {\n return () => {\n const db = new Database(\n lc.withContext('component', 'change-log-initializer'),\n replicaFile,\n {readonly: true},\n );\n try {\n return readReplicaInitializationParameters(db);\n } finally {\n db.close();\n }\n };\n}\n\n/**\n * Whether the log holds the complete interval above `fromWatermark`, using the\n * same predicate catchup uses to decide `too-old`: the log both reaches back\n * that far and contains that transaction's `commit` row, so the next row after\n * it is the first change of the interval rather than the middle of a\n * transaction the log only partly holds.\n */\nfunction spansInterval(db: Database, fromWatermark: string): boolean {\n if (!streamTableExists(db)) {\n return false;\n }\n const row = db\n .prepare(/*sql*/ `\n SELECT\n (SELECT min(\"watermark\") FROM \"${CHANGE_LOG_STREAM_TABLE}\")\n AS \"minWatermark\",\n coalesce((${SQLITE_CHANGE_LOG_BOUNDARY_SQL}), 0) AS \"boundaryExists\"\n `)\n .get<{minWatermark: string | null; boundaryExists: number}>({\n fromWatermark,\n });\n return (\n row.minWatermark !== null &&\n fromWatermark >= row.minWatermark &&\n row.boundaryExists === 1\n );\n}\n\nconst SCHEMA_CHANGE_TAG_LIST = schemaChangeTags\n .map(tag => `'${tag}'`)\n .join(', ');\n\n/**\n * The log's schema changes over `(after, through]`, in stream order, or\n * `undefined` if the interval is too large to scan (see\n * {@link MAX_FOLD_SCAN_ROWS}).\n *\n * The tag is stored beside the verbatim change so this scan never parses the\n * payloads of ordinary data changes. The row count is still checked first so a\n * stalled replicator cannot make the range scan unbounded.\n *\n * The count is itself capped, at one row past the cap it is deciding. A bare\n * `count(*)` over the interval is `O(interval)`, so the unbounded interval this\n * exists to decline would still be walked in full before being declined —\n * which is the latency the cap is here to avoid, not a cheaper form of it. The\n * `LIMIT` makes the decision `O(MAX_FOLD_SCAN_ROWS)`, and the comparison is\n * unaffected: the subquery returns the true count whenever it is within the\n * cap, and `cap + 1` whenever it is not.\n */\nfunction readSchemaChanges(\n db: Database,\n after: string,\n through: string,\n): SchemaChange[] | undefined {\n const {rows} = db\n .prepare(/*sql*/ `\n SELECT count(*) AS \"rows\" FROM (\n SELECT 1 FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n WHERE \"watermark\" > ? AND \"watermark\" <= ?\n LIMIT ${MAX_FOLD_SCAN_ROWS + 1}\n )\n `)\n .get<{rows: number}>(after, through);\n if (rows > MAX_FOLD_SCAN_ROWS) {\n return undefined;\n }\n return db\n .prepare(/*sql*/ `\n SELECT \"change\" FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n WHERE \"watermark\" > ? AND \"watermark\" <= ?\n AND \"tag\" IN (${SCHEMA_CHANGE_TAG_LIST})\n ORDER BY \"watermark\", \"pos\"\n `)\n .all<{change: string}>(after, through)\n .map(({change}) => BigIntJSON.parse(change) as SchemaChange);\n}\n\nfunction streamTableExists(db: Database): boolean {\n return (\n db\n .prepare(/*sql*/ `\n SELECT 1 FROM \"sqlite_master\" WHERE \"type\" = 'table' AND \"name\" = ?\n `)\n .get<{1: number} | undefined>(CHANGE_LOG_STREAM_TABLE) !== undefined\n );\n}\n\n/**\n * A canonical rendering of a whole cookie set: rows sorted by primary key,\n * object keys sorted at every depth.\n *\n * Both the equality check and the `divergent` log line fall out of this one\n * value, and neither can be defeated by a difference that is not a difference.\n * Postgres stores the cookie documents as `jsonb`, which does not preserve key\n * order, and the two readers order their rows in SQL in two engines under two\n * collations -- `storer.ts` pins `COLLATE \"C\"` for exactly that reason. Sorting\n * again here means an ordering or key-order regression can never be reported as\n * a divergence, which is a class of false alert that would cost more than it\n * caught.\n */\nfunction canonicalizeCookies(cookies: CookieSet): string {\n return BigIntJSON.stringify({\n tableMetadata: byKey(cookies.tableMetadata, c => [c.schema, c.table]).map(\n c => [c.schema, c.table, sortKeys(c.metadata)],\n ),\n backfilling: byKey(cookies.backfilling, c => [\n c.schema,\n c.table,\n c.column,\n ]).map(c => [c.schema, c.table, c.column, sortKeys(c.backfill)]),\n });\n}\n\nfunction byKey<T>(rows: readonly T[], key: (row: T) => string[]): T[] {\n return rows\n .map(row => [JSON.stringify(key(row)), row] as const)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([, row]) => row);\n}\n\nfunction sortKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortKeys);\n }\n if (value === null || typeof value !== 'object') {\n return value;\n }\n return Object.fromEntries(\n Object.entries(value)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => [k, sortKeys(v)]),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqKA,IAAM,qBAAqB;AAE3B,IAAa,uBAAb,MAAkC;CAChC;CACA;CACA;CACA;CAEA,iBAA0B,mBACxB,WACA,yCACA,2HAEF;CAEA;;;;;CAMA;CAEA,YACE,IACA,EAAC,qBAAqB,mBACtB,SACA;EACA,OACE,uBAAuB,iBACvB,qEACF;EACA,KAAK,MAAM,GAAG,YAAY,aAAa,wBAAwB;EAC/D,KAAK,uBAAuB;EAC5B,KAAK,mBAAmB;EACxB,KAAK,WAAW;CAClB;;;;;;;CAQA,iBAAmD;EACjD,OAAO,KAAK;CACd;;;;;;;;CASA,MAAM,aAAgD;EACpD,KAAK,kBAAkB,KAAA;EACvB,MAAM,KAAK,KAAK,uBACZ,MAAM,KAAK,aAAa,IACxB,KAAA;EAGJ,MAAM,UAAU,KAAK,mBACjB,KAAK,aAAa,OAAO,KAAA,CAAS,IAClC,KAAA;EAEJ,MAAM,aAAa,KAAK,SAAS,mBAC/B,MAAM;GAAC,iBAAiB,GAAG;GAAe,SAAS,GAAG;EAAO,SACvD,cAAc,KAAK,SAAS,mCAAmC,CAAC,CACxE;EAEA,IAAI,IAAI;GACN,IAAI,SAIF,KAAK,kBAAkB,KAAK,SAAS,IAAI,OAAO;GAElD,OAAO;EACT;EAIA,MAAM,cACJ,cAAc,cAAc,KAAK,SAAS,0BAA0B,CAAC;EACvE,OAAO;GACL,eAAe,YAAY;GAC3B,SAAS,YAAY;GAGrB,kBAAkB,qBAAqB,YAAY,OAAO;EAC5D;C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SAAS,GAAG;AACzB;AAEA,SAAS,SAAS,OAAyB;CACzC,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,IAAI,QAAQ;CAE3B,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO;CAET,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,CAAC,CAClB,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,CAAC,CAChD,KAAK,CAAC,GAAG,OAAO,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CACrC;AACF"}
1
+ {"version":3,"file":"change-log-initializer.js","names":[],"sources":["../../../../../../zero-cache/src/services/change-streamer/change-log-initializer.ts"],"sourcesContent":["/**\n * Where a stream connection's initialization parameters come from.\n *\n * A change-streamer starts a stream from three things read at one position: the\n * watermark to resume at, the {@link BackfillRequest}s to hand the change\n * source, and the cookie set those requests were derived from. They come from\n * whichever change log is in use:\n *\n * - The Postgres change log supplies them itself\n * (`Storer.getStartStreamInitializationParameters()`), after it is first\n * re-initialized from the restored replica if it may be missing transactions\n * that the replication slot will not stream.\n *\n * - The SQLite change log (i.e. when the Postgres change log is disabled)\n * resumes from its own head when it is valid. A new or invalid log is seeded\n * from the replica, which also supplies the resume point when the change-log\n * writer is unavailable.\n */\n\nimport type {LogContext} from '@rocicorp/logger';\nimport {Database} from '../../../../zqlite/src/db.ts';\nimport {StatementRunner} from '../../db/statements.ts';\nimport type {BackfillRequest} from '../change-source/protocol/current/upstream.ts';\nimport {\n backfillRequestsFrom,\n type CookieSet,\n} from '../replicator/change-log-cookies.ts';\nimport type {ChangeLogResumePoint} from '../replicator/change-log-db.ts';\nimport {\n readBackfillRequests,\n readReplicaCookies,\n} from '../replicator/schema/backfilling.ts';\nimport {getReplicationState} from '../replicator/schema/replication-state.ts';\n\n/** Everything one stream connection starts from, read at one position. */\nexport type InitializationParameters = {\n readonly lastWatermark: string;\n readonly backfillRequests: BackfillRequest[];\n readonly cookies: CookieSet;\n};\n\nexport type ChangeLogInitializerSources = {\n /**\n * `Storer.getStartStreamInitializationParameters()`. Only consulted when\n * initializing from the Postgres change log.\n */\n readonly pgChangeLog: () => Promise<InitializationParameters>;\n /** Typically {@link replicaInitializationSource}. */\n readonly replica: () => InitializationParameters;\n /**\n * Reconciles the SQLite change log and returns its current resume point: a\n * valid log uses its own head, and a new or invalid log uses `seed`. Only\n * consulted when not initializing from the Postgres change log.\n *\n * Returns `undefined` when the writer is disabled or unavailable.\n */\n readonly reconcileChangeLog: (\n seed: () => ChangeLogResumePoint,\n ) => ChangeLogResumePoint | undefined;\n /**\n * Re-initializes the Postgres change log from the replica's resume point\n * (taking ownership of it) if it does not contain all of the replica's\n * changes, re-checking under lock. Typically\n * `Storer.reinitializeFromReplica()`.\n *\n * Supplied only when the change log's head is behind the position of the\n * replication slot from which replication resumes, i.e. when it may be\n * missing transactions that the slot will not stream. Otherwise, a replica\n * that is ahead of the change log (as changes are forwarded before they are\n * stored) is caught up by the change stream, which resumes from the change\n * log's head.\n */\n readonly reinitializePgChangeLog?:\n | ((params: {\n watermark: string;\n cookies: CookieSet;\n }) => Promise<'reinitialized' | 'maintained'>)\n | undefined;\n};\n\nexport class ChangeLogInitializer {\n readonly #lc: LogContext;\n readonly #initFromPgChangeLog: boolean;\n readonly #sources: ChangeLogInitializerSources;\n\n /**\n * The (restored) replica's resume point that the Postgres change log must\n * cover, read once. See {@link #pgChangeLog}.\n */\n #restoredReplica: InitializationParameters | undefined;\n\n /**\n * @param initFromPgChangeLog Whether the Postgres change log (rather than\n * the SQLite change log) supplies the initialization parameters.\n */\n constructor(\n lc: LogContext,\n initFromPgChangeLog: boolean,\n sources: ChangeLogInitializerSources,\n ) {\n this.#lc = lc.withContext('component', 'change-log-initializer');\n this.#initFromPgChangeLog = initFromPgChangeLog;\n this.#sources = sources;\n }\n\n /**\n * Returns the initialization parameters for one stream connection, after\n * reconciling the SQLite change log when it is the one in use.\n */\n async initialize(): Promise<InitializationParameters> {\n return this.#initFromPgChangeLog\n ? await this.#pgChangeLog()\n : this.#sqliteChangeLog();\n }\n\n /**\n * The replica is read up front, as it seeds a new log and supplies the\n * resume point when the writer is unavailable.\n */\n #sqliteChangeLog(): InitializationParameters {\n const replica = this.#sources.replica();\n // Use the reconciled log position. If the writer is unavailable, use the\n // replica position.\n const resumePoint =\n this.#sources.reconcileChangeLog(() => resumePointOf(replica)) ??\n resumePointOf(replica);\n return {\n lastWatermark: resumePoint.resumeWatermark,\n cookies: resumePoint.cookies,\n // Derive the requests from these cookies so that the requests and the\n // watermark describe the same position.\n backfillRequests: backfillRequestsFrom(resumePoint.cookies),\n };\n }\n\n /**\n * Reads the Postgres change log's initialization parameters, first\n * re-initializing it from the replica (taking ownership of it) if it may be\n * missing transactions that the replication slot will not stream, e.g. if it\n * is no longer maintained after running in high-availability mode. This is\n * the Postgres counterpart of seeding a new SQLite change log from the\n * replica.\n *\n * This only applies when the change log's head is behind the slot's position\n * (i.e. when {@link ChangeLogInitializerSources.reinitializePgChangeLog} is\n * supplied), and the change log is only re-initialized if its head is also\n * behind the replica's. Otherwise, it contains every transaction before the\n * slot's position: one that was acked after being stored would be in the\n * change log, and one that was acked after being backed up would be in the\n * replica, which the change log's head covers.\n *\n * The replica is read only once, i.e. as it was restored from the backup,\n * before any stream is started. The live replica is no reference: it is\n * caught up from the forwarded changes, which can be ahead of what has been\n * stored, e.g. by the change log's previous owner. Against that fixed\n * resume point, re-initialization is idempotent: afterwards, the change log's\n * head (which only advances) covers it, so subsequent stream connections\n * leave it untouched.\n */\n async #pgChangeLog(): Promise<InitializationParameters> {\n const pg = await this.#sources.pgChangeLog();\n const reinitialize = this.#sources.reinitializePgChangeLog;\n if (!reinitialize) {\n return pg;\n }\n this.#restoredReplica ??= this.#sources.replica();\n const {lastWatermark, cookies} = this.#restoredReplica;\n if (pg.lastWatermark >= lastWatermark) {\n return pg;\n }\n const result = await reinitialize({watermark: lastWatermark, cookies});\n this.#lc.info?.(\n `Postgres change log at ${pg.lastWatermark} is behind the replica at ` +\n `${lastWatermark}: ${result}`,\n );\n // Either way, the change log has changed since it was read.\n return this.#sources.pgChangeLog();\n }\n}\n\nconst resumePointOf = ({\n lastWatermark,\n cookies,\n}: InitializationParameters): ChangeLogResumePoint => ({\n resumeWatermark: lastWatermark,\n cookies,\n});\n\n/**\n * Reads the replica's initialization parameters in one snapshot, which is\n * invariant 15 on the replica side: the state version and the cookies are only\n * meaningful together.\n */\nexport function readReplicaInitializationParameters(\n db: Database,\n): InitializationParameters {\n const runner = new StatementRunner(db);\n runner.begin(); // deferred, i.e. one read snapshot for the three statements\n try {\n return {\n lastWatermark: getReplicationState(runner).stateVersion,\n backfillRequests: readBackfillRequests(db),\n cookies: readReplicaCookies(db),\n };\n } finally {\n if (db.inTransaction) {\n runner.rollback();\n }\n }\n}\n\n/**\n * The replica source for {@link ChangeLogInitializer}, opening and closing the\n * file per stream connection rather than holding a handle on a database another\n * process owns.\n *\n * The handle is read-only, which is invariant 19 stated in the API: the\n * replica's cookie tables are written by the change-processor and by nothing\n * else. Note that a read-only SQLite connection still needs to attach the\n * WAL's `-shm`, so this can fail if it opens at a moment when no writer holds\n * the replica.\n */\nexport function replicaInitializationSource(\n lc: LogContext,\n replicaFile: string,\n): () => InitializationParameters {\n return () => {\n const db = new Database(\n lc.withContext('component', 'change-log-initializer'),\n replicaFile,\n {readonly: true},\n );\n try {\n return readReplicaInitializationParameters(db);\n } finally {\n db.close();\n }\n };\n}\n"],"mappings":";;;;;;AAgFA,IAAa,uBAAb,MAAkC;CAChC;CACA;CACA;;;;;CAMA;;;;;CAMA,YACE,IACA,qBACA,SACA;EACA,KAAK,MAAM,GAAG,YAAY,aAAa,wBAAwB;EAC/D,KAAK,uBAAuB;EAC5B,KAAK,WAAW;CAClB;;;;;CAMA,MAAM,aAAgD;EACpD,OAAO,KAAK,uBACR,MAAM,KAAK,aAAa,IACxB,KAAK,iBAAiB;CAC5B;;;;;CAMA,mBAA6C;EAC3C,MAAM,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