@rocicorp/zero 1.11.0-canary.11 → 1.11.0-canary.13

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 (174) 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/shared/src/ring-buffer.d.ts +2 -0
  4. package/out/shared/src/ring-buffer.d.ts.map +1 -1
  5. package/out/shared/src/ring-buffer.js +4 -0
  6. package/out/shared/src/ring-buffer.js.map +1 -1
  7. package/out/zero/package.js +1 -1
  8. package/out/zero/package.js.map +1 -1
  9. package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
  10. package/out/zero-cache/src/server/replicator.js +26 -13
  11. package/out/zero-cache/src/server/replicator.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 +169 -19
  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/custom/change-source.js +2 -2
  16. package/out/zero-cache/src/services/change-source/custom/change-source.js.map +1 -1
  17. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +45 -6
  18. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  19. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +118 -33
  20. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  21. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +2 -2
  22. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  23. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +10 -17
  24. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
  25. package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
  26. package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts.map +1 -1
  27. package/out/zero-cache/src/services/change-streamer/schema/tables.js +15 -4
  28. package/out/zero-cache/src/services/change-streamer/schema/tables.js.map +1 -1
  29. package/out/zero-cache/src/services/change-streamer/snapshot-message.d.ts +92 -0
  30. package/out/zero-cache/src/services/change-streamer/snapshot-message.d.ts.map +1 -0
  31. package/out/zero-cache/src/services/change-streamer/snapshot-message.js +42 -0
  32. package/out/zero-cache/src/services/change-streamer/snapshot-message.js.map +1 -0
  33. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.d.ts +1 -1
  34. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.d.ts.map +1 -1
  35. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +1 -1
  36. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -1
  37. package/out/zero-cache/src/services/change-streamer/snapshot.d.ts +7 -89
  38. package/out/zero-cache/src/services/change-streamer/snapshot.d.ts.map +1 -1
  39. package/out/zero-cache/src/services/change-streamer/snapshot.js +26 -98
  40. package/out/zero-cache/src/services/change-streamer/snapshot.js.map +1 -1
  41. package/out/zero-cache/src/services/change-streamer/subscribe.d.ts +358 -0
  42. package/out/zero-cache/src/services/change-streamer/subscribe.d.ts.map +1 -0
  43. package/out/zero-cache/src/services/change-streamer/subscribe.js +68 -0
  44. package/out/zero-cache/src/services/change-streamer/subscribe.js.map +1 -0
  45. package/out/zero-cache/src/services/litestream/commands.d.ts +2 -3
  46. package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
  47. package/out/zero-cache/src/services/litestream/commands.js +3 -2
  48. package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
  49. package/out/zero-cache/src/services/replicator/change-processor.js +12 -1
  50. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  51. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts +2 -1
  52. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
  53. package/out/zero-cache/src/services/replicator/incremental-sync.js +13 -7
  54. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  55. package/out/zero-cache/src/services/replicator/replicator.d.ts +2 -1
  56. package/out/zero-cache/src/services/replicator/replicator.d.ts.map +1 -1
  57. package/out/zero-cache/src/services/replicator/replicator.js +2 -2
  58. package/out/zero-cache/src/services/replicator/replicator.js.map +1 -1
  59. package/out/zero-cache/src/services/view-syncer/client-handler.d.ts +19 -2
  60. package/out/zero-cache/src/services/view-syncer/client-handler.d.ts.map +1 -1
  61. package/out/zero-cache/src/services/view-syncer/client-handler.js +8 -1
  62. package/out/zero-cache/src/services/view-syncer/client-handler.js.map +1 -1
  63. package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts +19 -1
  64. package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts.map +1 -1
  65. package/out/zero-cache/src/services/view-syncer/cvr-store.js +34 -11
  66. package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
  67. package/out/zero-cache/src/services/view-syncer/cvr.d.ts +6 -2
  68. package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
  69. package/out/zero-cache/src/services/view-syncer/cvr.js +9 -5
  70. package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
  71. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
  72. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +44 -11
  73. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  74. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts +21 -1
  75. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
  76. package/out/zero-cache/src/services/view-syncer/snapshotter.js +14 -6
  77. package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
  78. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  79. package/out/zero-cache/src/services/view-syncer/view-syncer.js +28 -4
  80. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  81. package/out/zero-cache/src/types/streams.d.ts +33 -7
  82. package/out/zero-cache/src/types/streams.d.ts.map +1 -1
  83. package/out/zero-cache/src/types/streams.js +93 -50
  84. package/out/zero-cache/src/types/streams.js.map +1 -1
  85. package/out/zero-cache/src/types/subscription.d.ts +11 -0
  86. package/out/zero-cache/src/types/subscription.d.ts.map +1 -1
  87. package/out/zero-cache/src/types/subscription.js +56 -35
  88. package/out/zero-cache/src/types/subscription.js.map +1 -1
  89. package/out/zero-cache/src/types/ws.js +1 -31
  90. package/out/zero-cache/src/types/ws.js.map +1 -1
  91. package/out/zero-cache/src/workers/connection.js +3 -3
  92. package/out/zero-cache/src/workers/connection.js.map +1 -1
  93. package/out/zero-cache/src/workers/syncer.js +2 -2
  94. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  95. package/out/zero-client/src/client/version.js +1 -1
  96. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  97. package/out/zero-client/src/client/zero.js +5 -5
  98. package/out/zero-client/src/client/zero.js.map +1 -1
  99. package/out/zero-protocol/src/inspect-down.d.ts +81 -81
  100. package/out/zql/src/builder/builder.d.ts.map +1 -1
  101. package/out/zql/src/builder/builder.js +6 -4
  102. package/out/zql/src/builder/builder.js.map +1 -1
  103. package/out/zql/src/ivm/cap.d.ts +2 -1
  104. package/out/zql/src/ivm/cap.d.ts.map +1 -1
  105. package/out/zql/src/ivm/cap.js +3 -0
  106. package/out/zql/src/ivm/cap.js.map +1 -1
  107. package/out/zql/src/ivm/exists.d.ts +2 -0
  108. package/out/zql/src/ivm/exists.d.ts.map +1 -1
  109. package/out/zql/src/ivm/exists.js +3 -0
  110. package/out/zql/src/ivm/exists.js.map +1 -1
  111. package/out/zql/src/ivm/fan-in.d.ts +5 -1
  112. package/out/zql/src/ivm/fan-in.d.ts.map +1 -1
  113. package/out/zql/src/ivm/fan-in.js +7 -0
  114. package/out/zql/src/ivm/fan-in.js.map +1 -1
  115. package/out/zql/src/ivm/fan-out.d.ts +3 -0
  116. package/out/zql/src/ivm/fan-out.d.ts.map +1 -1
  117. package/out/zql/src/ivm/fan-out.js +4 -0
  118. package/out/zql/src/ivm/fan-out.js.map +1 -1
  119. package/out/zql/src/ivm/filter-operators.d.ts +2 -0
  120. package/out/zql/src/ivm/filter-operators.d.ts.map +1 -1
  121. package/out/zql/src/ivm/filter-operators.js +9 -0
  122. package/out/zql/src/ivm/filter-operators.js.map +1 -1
  123. package/out/zql/src/ivm/filter.d.ts +4 -1
  124. package/out/zql/src/ivm/filter.d.ts.map +1 -1
  125. package/out/zql/src/ivm/filter.js +3 -0
  126. package/out/zql/src/ivm/filter.js.map +1 -1
  127. package/out/zql/src/ivm/flipped-join.d.ts +4 -3
  128. package/out/zql/src/ivm/flipped-join.d.ts.map +1 -1
  129. package/out/zql/src/ivm/flipped-join.js +73 -22
  130. package/out/zql/src/ivm/flipped-join.js.map +1 -1
  131. package/out/zql/src/ivm/join-utils.d.ts +24 -7
  132. package/out/zql/src/ivm/join-utils.d.ts.map +1 -1
  133. package/out/zql/src/ivm/join-utils.js +87 -4
  134. package/out/zql/src/ivm/join-utils.js.map +1 -1
  135. package/out/zql/src/ivm/join.d.ts +4 -4
  136. package/out/zql/src/ivm/join.d.ts.map +1 -1
  137. package/out/zql/src/ivm/join.js +55 -64
  138. package/out/zql/src/ivm/join.js.map +1 -1
  139. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  140. package/out/zql/src/ivm/memory-source.js +33 -23
  141. package/out/zql/src/ivm/memory-source.js.map +1 -1
  142. package/out/zql/src/ivm/operator.d.ts +39 -10
  143. package/out/zql/src/ivm/operator.d.ts.map +1 -1
  144. package/out/zql/src/ivm/operator.js +9 -4
  145. package/out/zql/src/ivm/operator.js.map +1 -1
  146. package/out/zql/src/ivm/push-accumulated.d.ts +6 -1
  147. package/out/zql/src/ivm/push-accumulated.d.ts.map +1 -1
  148. package/out/zql/src/ivm/push-accumulated.js +47 -2
  149. package/out/zql/src/ivm/push-accumulated.js.map +1 -1
  150. package/out/zql/src/ivm/skip.d.ts +2 -1
  151. package/out/zql/src/ivm/skip.d.ts.map +1 -1
  152. package/out/zql/src/ivm/skip.js +3 -0
  153. package/out/zql/src/ivm/skip.js.map +1 -1
  154. package/out/zql/src/ivm/take-gate.d.ts +24 -2
  155. package/out/zql/src/ivm/take-gate.d.ts.map +1 -1
  156. package/out/zql/src/ivm/take-gate.js +26 -1
  157. package/out/zql/src/ivm/take-gate.js.map +1 -1
  158. package/out/zql/src/ivm/take.d.ts +2 -1
  159. package/out/zql/src/ivm/take.d.ts.map +1 -1
  160. package/out/zql/src/ivm/take.js +59 -40
  161. package/out/zql/src/ivm/take.js.map +1 -1
  162. package/out/zql/src/ivm/union-fan-in.d.ts +3 -0
  163. package/out/zql/src/ivm/union-fan-in.d.ts.map +1 -1
  164. package/out/zql/src/ivm/union-fan-in.js +56 -5
  165. package/out/zql/src/ivm/union-fan-in.js.map +1 -1
  166. package/out/zql/src/ivm/union-fan-out.d.ts +2 -1
  167. package/out/zql/src/ivm/union-fan-out.d.ts.map +1 -1
  168. package/out/zql/src/ivm/union-fan-out.js +5 -0
  169. package/out/zql/src/ivm/union-fan-out.js.map +1 -1
  170. package/out/zql/src/query/measure-push-operator.d.ts +2 -1
  171. package/out/zql/src/query/measure-push-operator.d.ts.map +1 -1
  172. package/out/zql/src/query/measure-push-operator.js +7 -0
  173. package/out/zql/src/query/measure-push-operator.js.map +1 -1
  174. package/package.json +1 -1
@@ -119,13 +119,24 @@ async function ensureReplicationConfig(lc, db, subscriptionState, shard, autoRes
119
119
  stmts.push(sql`INSERT INTO ${sql(schema)}."replicationConfig" ${sql(replicaConfig)}`, sql`INSERT INTO ${sql(schema)}."replicationState" ${sql(replicationState)}
120
120
  ON CONFLICT (lock) DO UPDATE SET ${sql(replicationState)}`, ...initialTx.map((change) => sql`INSERT INTO ${sql(schema)}."changeLog" ${sql(change)}`));
121
121
  if (needsTruncate) {
122
- const timer = setTimeoutFn(async () => {
123
- lc.info?.("ensureReplicationConfig blocked, terminating lock holders");
124
- await terminateChangeDBLockHolders(lc, db, shard);
125
- }, LOCK_HOLDER_TERMINATE_TIMEOUT_MS);
122
+ let done = false;
123
+ let timer;
124
+ const scheduleTerminate = () => {
125
+ timer = setTimeoutFn(async () => {
126
+ lc.info?.("ensureReplicationConfig blocked, terminating lock holders");
127
+ try {
128
+ await terminateChangeDBLockHolders(lc, db, shard);
129
+ } catch (e) {
130
+ lc.warn?.("error terminating lock holders", e);
131
+ }
132
+ if (!done) scheduleTerminate();
133
+ }, LOCK_HOLDER_TERMINATE_TIMEOUT_MS);
134
+ };
135
+ scheduleTerminate();
126
136
  try {
127
137
  return await Promise.all(stmts);
128
138
  } finally {
139
+ done = true;
129
140
  clearTimeout(timer);
130
141
  }
131
142
  }
@@ -1 +1 @@
1
- {"version":3,"file":"tables.js","names":[],"sources":["../../../../../../../zero-cache/src/services/change-streamer/schema/tables.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {ident} from 'pg-format';\nimport type postgres from 'postgres';\nimport {type PendingQuery, type Row} from 'postgres';\nimport {AbortError} from '../../../../../shared/src/abort-error.ts';\nimport {equals} from '../../../../../shared/src/set-utils.ts';\nimport {runTx} from '../../../db/run-transaction.ts';\nimport {type PostgresDB} from '../../../types/pg.ts';\nimport {cdcSchema, type ShardID} from '../../../types/shards.ts';\nimport type {\n BackfillID,\n Change,\n TableMetadata,\n} from '../../change-source/protocol/current/data.ts';\nimport type {SubscriptionState} from '../../replicator/schema/replication-state.ts';\n\n// For readability in the sql statements.\nfunction schema(shard: ShardID) {\n return ident(cdcSchema(shard));\n}\n\nexport const PG_SCHEMA = 'cdc';\n\nfunction createSchema(shard: ShardID) {\n return /*sql*/ `CREATE SCHEMA IF NOT EXISTS ${schema(shard)};`;\n}\n\nexport type ChangeLogEntry = {\n // A strictly monotonically increasing, lexicographically sortable\n // value that uniquely identifies a position in the change stream.\n watermark: string;\n change: Change;\n};\n\ntype FullChangeLogEntry = ChangeLogEntry & {pos: number};\n\nfunction createChangeLogTable(shard: ShardID) {\n // Note: The \"change\" column used to be JSONB, but that was problematic in that\n // it does not handle the NULL unicode character.\n // https://vladimir.varank.in/notes/2021/01/you-dont-insert-unicode-null-character-as-postgres-jsonb/\n return /*sql*/ `\n CREATE TABLE ${schema(shard)}.\"changeLog\" (\n watermark TEXT,\n pos INT8,\n change JSON NOT NULL,\n precommit TEXT, -- Only exists on commit entries. Purely for debugging.\n PRIMARY KEY (watermark, pos)\n );\n`;\n}\n\n/**\n * Tracks the watermark from which to resume the change stream and the\n * current owner (task ID) acting as the single writer to the changeLog.\n */\nexport type ReplicationState = {\n lastWatermark: string;\n owner: string | null;\n ownerAddress: string | null;\n};\n\nexport function createReplicationStateTable(shard: ShardID) {\n return /*sql*/ `\n CREATE TABLE ${schema(shard)}.\"replicationState\" (\n \"lastWatermark\" TEXT NOT NULL,\n \"owner\" TEXT,\n \"ownerAddress\" TEXT,\n \"lock\" INTEGER PRIMARY KEY DEFAULT 1 CHECK (lock=1)\n );\n`;\n}\n\nexport async function discoverChangeStreamerAddress(\n shard: ShardID,\n sql: PostgresDB,\n): Promise<string | null> {\n const result = await sql<{ownerAddress: string | null}[]> /*sql*/ `\n SELECT \"ownerAddress\" FROM ${sql(cdcSchema(shard))}.\"replicationState\"`;\n return result[0].ownerAddress;\n}\n\n/**\n * This mirrors the analogously named table in the SQLite replica\n * (`services/replicator/schema/replication-state.ts`), and is used\n * to detect when the replica has been reset and is no longer compatible\n * with the current ChangeLog.\n */\nexport type ReplicationConfig = {\n replicaVersion: string;\n publications: readonly string[];\n};\n\nfunction createReplicationConfigTable(shard: ShardID) {\n return /*sql*/ `\n CREATE TABLE ${schema(shard)}.\"replicationConfig\" (\n \"replicaVersion\" TEXT NOT NULL,\n \"publications\" TEXT[] NOT NULL,\n \"resetRequired\" BOOL,\n \"lock\" INTEGER PRIMARY KEY DEFAULT 1 CHECK (lock=1)\n );\n`;\n}\n\nexport function createBackfillTables(shard: ShardID) {\n return /*sql*/ `\n CREATE TABLE ${schema(shard)}.\"tableMetadata\" (\n \"schema\" TEXT NOT NULL,\n \"table\" TEXT NOT NULL,\n \"metadata\" JSONB NOT NULL,\n PRIMARY KEY(\"schema\", \"table\")\n );\n\n CREATE TABLE ${schema(shard)}.\"backfilling\" (\n \"schema\" TEXT NOT NULL,\n \"table\" TEXT NOT NULL,\n \"column\" TEXT NOT NULL,\n \"backfill\" JSONB NOT NULL,\n PRIMARY KEY(\"schema\", \"table\", \"column\")\n );\n `;\n}\n\nexport type TableMetadataRow = {\n schema: string;\n table: string;\n metadata: TableMetadata;\n};\n\nexport type BackfillingColumn = {\n schema: string;\n table: string;\n column: string;\n backfill: BackfillID;\n};\n\nfunction createTables(shard: ShardID) {\n return (\n createSchema(shard) +\n createChangeLogTable(shard) +\n createReplicationStateTable(shard) +\n createReplicationConfigTable(shard) +\n createBackfillTables(shard)\n );\n}\n\ninterface PurgeLock {\n release(): Promise<void>;\n}\n\nexport async function setupCDCTables(\n lc: LogContext,\n db: postgres.TransactionSql,\n shard: ShardID,\n) {\n lc.info?.(`Setting up CDC tables`);\n await db.unsafe(createTables(shard));\n}\n\nexport async function markResetRequired(sql: PostgresDB, shard: ShardID) {\n const schema = cdcSchema(shard);\n await sql`\n UPDATE ${sql(schema)}.\"replicationConfig\"\n SET \"resetRequired\" = true`;\n}\n\nexport async function ensureReplicationConfig(\n lc: LogContext,\n db: PostgresDB,\n subscriptionState: Pick<\n SubscriptionState,\n 'publications' | 'replicaVersion' | 'watermark'\n >,\n shard: ShardID,\n autoReset: boolean,\n purgeLock?: PurgeLock,\n setTimeoutFn: typeof setTimeout = setTimeout,\n pgChangeLogEnabled = true,\n) {\n const {publications, replicaVersion, watermark} = subscriptionState;\n const replicaConfig = {publications, replicaVersion};\n const replicationState: ReplicationState = {\n lastWatermark: replicaVersion,\n owner: null,\n ownerAddress: null,\n };\n const schema = cdcSchema(shard);\n\n await runTx(db, async sql => {\n const stmts: PendingQuery<Row[]>[] = [];\n let needsTruncate = false;\n const results = await sql<\n {\n replicaVersion: string;\n publications: string[];\n resetRequired: boolean | null;\n }[]\n > /*sql*/ `\n SELECT \"replicaVersion\", \"publications\", \"resetRequired\" \n FROM ${sql(schema)}.\"replicationConfig\"`;\n\n if (results.length) {\n const {replicaVersion, publications} = results[0];\n if (\n replicaVersion !== replicaConfig.replicaVersion ||\n !equals(new Set(publications), new Set(replicaConfig.publications))\n ) {\n if (replicaConfig.replicaVersion !== watermark) {\n throw new AutoResetSignal(\n `Cannot reset change db@${replicaVersion} to ` +\n `service replica@${replicaConfig.replicaVersion} ` +\n `from watermark ${watermark}`,\n );\n }\n lc.info?.(\n `Data in cdc tables @${replicaVersion} is incompatible ` +\n `with replica @${replicaConfig.replicaVersion}. Clearing tables.`,\n );\n // Release any purge lock held by the caller; the changeLog is\n // incompatible with the replica and needs to be truncated.\n void purgeLock?.release();\n\n // Note: The order of TRUNCATE matters. The replicationState table is\n // truncated before the changeLog table, in order to acquire\n // (exclusive) locks on the tables in the same order that the\n // storer.ts acquires locks when writing the changeLog, namely:\n //\n // 1. SELECT ... FROM replicationState FOR UPDATE;\n // 2. INSERT INTO changeLog ...;\n // ...\n // n. UPDATE replicationState ...;\n needsTruncate = true;\n stmts.push(\n sql`TRUNCATE TABLE ${sql(schema)}.\"replicationState\"`,\n ...(pgChangeLogEnabled\n ? [sql`TRUNCATE TABLE ${sql(schema)}.\"changeLog\"`]\n : []),\n sql`TRUNCATE TABLE ${sql(schema)}.\"replicationConfig\"`,\n sql`TRUNCATE TABLE ${sql(schema)}.\"tableMetadata\"`,\n sql`TRUNCATE TABLE ${sql(schema)}.\"backfilling\"`,\n );\n }\n }\n // Initialize (or re-initialize TRUNCATED) tables\n if (results.length === 0 || needsTruncate) {\n // When enabled, the PG storer uses the earliest changeLog entry as the\n // safe watermark from which subscribers can be resumed. These initial\n // entries ensure that subscribers can start from a freshly synced\n // replica, even if new changes have been replicated and not purged.\n //\n // TODO: Replace this with an explicit `firstWatermark` column in the\n // change db.\n const watermark = replicaConfig.replicaVersion;\n const initialTx: FullChangeLogEntry[] = pgChangeLogEnabled\n ? [\n {watermark, pos: 0, change: {tag: 'begin'}},\n {watermark, pos: 1, change: {tag: 'commit'}},\n ]\n : [];\n\n stmts.push(\n sql`INSERT INTO ${sql(schema)}.\"replicationConfig\" ${sql(replicaConfig)}`,\n sql`INSERT INTO ${sql(schema)}.\"replicationState\" ${sql(replicationState)} \n ON CONFLICT (lock) DO UPDATE SET ${sql(replicationState)}`,\n ...initialTx.map(\n change => sql`INSERT INTO ${sql(schema)}.\"changeLog\" ${sql(change)}`,\n ),\n );\n\n if (needsTruncate) {\n // The TRUNCATE statements require ACCESS EXCLUSIVE locks, which may\n // be blocked by old storer catchup reads. Race against a timeout\n // that terminates the blocking backends if the TRUNCATE takes too\n // long.\n const timer = setTimeoutFn(async () => {\n lc.info?.(\n 'ensureReplicationConfig blocked, terminating lock holders',\n );\n await terminateChangeDBLockHolders(lc, db, shard);\n }, LOCK_HOLDER_TERMINATE_TIMEOUT_MS);\n try {\n return await Promise.all(stmts);\n } finally {\n clearTimeout(timer);\n }\n }\n return Promise.all(stmts);\n }\n\n const {resetRequired} = results[0];\n if (resetRequired) {\n if (autoReset) {\n throw new AutoResetSignal('reset required by replication stream');\n }\n lc.error?.(\n '\\n\\n\\n' +\n 'Reset required but --auto-reset is not enabled.\\n' +\n 'This can happen for upstream databases that do not support event triggers.\\n' +\n 'To correct this, see https://zero.rocicorp.dev/docs/connecting-to-postgres#schema-changes' +\n '\\n\\n\\n',\n );\n }\n\n return [];\n });\n}\n\n// The time to wait for a TRUNCATE in ensureReplicationConfig before\n// terminating blocking backends via terminateChangeDBLockHolders.\nconst LOCK_HOLDER_TERMINATE_TIMEOUT_MS = 5_000;\n\nexport const CHANGE_STREAMER_APP_NAME = 'zero-change-streamer';\n\nexport class AutoResetSignal extends AbortError {\n readonly name = 'AutoResetSignal';\n}\n\n/**\n * Terminates zero-cache backends that are blocking the current backend\n * from acquiring locks on CDC tables (e.g., during TRUNCATE).\n *\n * This is used during change-DB takeover when the new replication-manager's\n * `ensureReplicationConfig` needs to TRUNCATE tables, but the old\n * replication-manager's storer is still reading from them (e.g., large\n * catchup cursors).\n *\n * The function:\n * 1. Finds backends waiting for a lock on a TRUNCATE in {schema}\n * 2. Uses `pg_blocking_pids()` to identify which backends are blocking them\n * 3. Terminates blocking backends that have `application_name = 'zero-change-streamer'`\n *\n * Must be called on a **separate connection** from the one that is blocked,\n * since the blocked connection is inside a pending transaction.\n */\nexport async function terminateChangeDBLockHolders(\n lc: LogContext,\n db: PostgresDB,\n shard: ShardID,\n) {\n const schema = cdcSchema(shard);\n\n // Step 1: Find backends that are blocked waiting for a lock,\n // whose query involves a TRUNCATE on this shard's CDC schema.\n const blocked = await db<{pid: number}[]>`\n SELECT pid FROM pg_stat_activity\n WHERE wait_event_type = 'Lock'\n AND application_name = ${CHANGE_STREAMER_APP_NAME}\n AND query LIKE ${'%TRUNCATE%' + schema + '%'}`;\n\n if (blocked.length === 0) {\n lc.info?.('no blocked TRUNCATE backends found');\n return;\n }\n\n const blockedPids = blocked.map(r => r.pid);\n lc.info?.(`found blocked TRUNCATE backends: ${JSON.stringify(blockedPids)}`);\n\n // Step 2: For each blocked backend, find and terminate its blockers\n // that are zero-change-streamer connections.\n const terminated = await db<\n {pid: number; applicationName: string; query: string; terminated: boolean}[]\n >`\n SELECT pid, application_name as \"applicationName\", query,\n pg_terminate_backend(pid) as terminated\n FROM pg_stat_activity\n WHERE pid = ANY(\n SELECT unnest(pg_blocking_pids(blocked.pid))\n FROM unnest(${blockedPids}::int[]) AS blocked(pid)\n )\n AND application_name = ${CHANGE_STREAMER_APP_NAME}\n AND pid != ALL(${blockedPids}::int[])`;\n\n if (terminated.length === 0) {\n lc.info?.(`no ${CHANGE_STREAMER_APP_NAME} blockers found to terminate`);\n } else {\n for (const {pid, applicationName, query, terminated: ok} of terminated) {\n lc.info?.(\n `terminated blocking backend pid=${pid} app=${applicationName} ok=${ok} query=${query.slice(0, 200)}`,\n );\n }\n }\n}\n"],"mappings":";;;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;IAKjB,MAAM,QAAQ,aAAa,YAAY;KACrC,GAAG,OACD,2DACF;KACA,MAAM,6BAA6B,IAAI,IAAI,KAAK;IAClD,GAAG,gCAAgC;IACnC,IAAI;KACF,OAAO,MAAM,QAAQ,IAAI,KAAK;IAChC,UAAU;KACR,aAAa,KAAK;IACpB;GACF;GACA,OAAO,QAAQ,IAAI,KAAK;EAC1B;EAEA,MAAM,EAAC,kBAAiB,QAAQ;EAChC,IAAI,eAAe;GACjB,IAAI,WACF,MAAM,IAAI,gBAAgB,sCAAsC;GAElE,GAAG,QACD,oOAKF;EACF;EAEA,OAAO,CAAC;CACV,CAAC;AACH;AAIA,IAAM,mCAAmC;AAEzC,IAAa,2BAA2B;AAExC,IAAa,kBAAb,cAAqC,WAAW;CAC9C,OAAgB;AAClB;;;;;;;;;;;;;;;;;;AAmBA,eAAsB,6BACpB,IACA,IACA,OACA;CAKA,MAAM,UAAU,MAAM,EAAmB;;;iCAGV,yBAAyB;yBACjC,eARR,UAAU,KAQa,IAAS;CAE/C,IAAI,QAAQ,WAAW,GAAG;EACxB,GAAG,OAAO,oCAAoC;EAC9C;CACF;CAEA,MAAM,cAAc,QAAQ,KAAI,MAAK,EAAE,GAAG;CAC1C,GAAG,OAAO,oCAAoC,KAAK,UAAU,WAAW,GAAG;CAI3E,MAAM,aAAa,MAAM,EAExB;;;;;;wBAMqB,YAAY;;+BAEL,yBAAyB;uBACjC,YAAY;CAEjC,IAAI,WAAW,WAAW,GACxB,GAAG,OAAO,MAAM,yBAAyB,6BAA6B;MAEtE,KAAK,MAAM,EAAC,KAAK,iBAAiB,OAAO,YAAY,QAAO,YAC1D,GAAG,OACD,mCAAmC,IAAI,OAAO,gBAAgB,MAAM,GAAG,SAAS,MAAM,MAAM,GAAG,GAAG,GACpG;AAGN"}
1
+ {"version":3,"file":"tables.js","names":[],"sources":["../../../../../../../zero-cache/src/services/change-streamer/schema/tables.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {ident} from 'pg-format';\nimport type postgres from 'postgres';\nimport {type PendingQuery, type Row} from 'postgres';\nimport {AbortError} from '../../../../../shared/src/abort-error.ts';\nimport {equals} from '../../../../../shared/src/set-utils.ts';\nimport {runTx} from '../../../db/run-transaction.ts';\nimport {type PostgresDB} from '../../../types/pg.ts';\nimport {cdcSchema, type ShardID} from '../../../types/shards.ts';\nimport type {\n BackfillID,\n Change,\n TableMetadata,\n} from '../../change-source/protocol/current/data.ts';\nimport type {SubscriptionState} from '../../replicator/schema/replication-state.ts';\n\n// For readability in the sql statements.\nfunction schema(shard: ShardID) {\n return ident(cdcSchema(shard));\n}\n\nexport const PG_SCHEMA = 'cdc';\n\nfunction createSchema(shard: ShardID) {\n return /*sql*/ `CREATE SCHEMA IF NOT EXISTS ${schema(shard)};`;\n}\n\nexport type ChangeLogEntry = {\n // A strictly monotonically increasing, lexicographically sortable\n // value that uniquely identifies a position in the change stream.\n watermark: string;\n change: Change;\n};\n\ntype FullChangeLogEntry = ChangeLogEntry & {pos: number};\n\nfunction createChangeLogTable(shard: ShardID) {\n // Note: The \"change\" column used to be JSONB, but that was problematic in that\n // it does not handle the NULL unicode character.\n // https://vladimir.varank.in/notes/2021/01/you-dont-insert-unicode-null-character-as-postgres-jsonb/\n return /*sql*/ `\n CREATE TABLE ${schema(shard)}.\"changeLog\" (\n watermark TEXT,\n pos INT8,\n change JSON NOT NULL,\n precommit TEXT, -- Only exists on commit entries. Purely for debugging.\n PRIMARY KEY (watermark, pos)\n );\n`;\n}\n\n/**\n * Tracks the watermark from which to resume the change stream and the\n * current owner (task ID) acting as the single writer to the changeLog.\n */\nexport type ReplicationState = {\n lastWatermark: string;\n owner: string | null;\n ownerAddress: string | null;\n};\n\nexport function createReplicationStateTable(shard: ShardID) {\n return /*sql*/ `\n CREATE TABLE ${schema(shard)}.\"replicationState\" (\n \"lastWatermark\" TEXT NOT NULL,\n \"owner\" TEXT,\n \"ownerAddress\" TEXT,\n \"lock\" INTEGER PRIMARY KEY DEFAULT 1 CHECK (lock=1)\n );\n`;\n}\n\nexport async function discoverChangeStreamerAddress(\n shard: ShardID,\n sql: PostgresDB,\n): Promise<string | null> {\n const result = await sql<{ownerAddress: string | null}[]> /*sql*/ `\n SELECT \"ownerAddress\" FROM ${sql(cdcSchema(shard))}.\"replicationState\"`;\n return result[0].ownerAddress;\n}\n\n/**\n * This mirrors the analogously named table in the SQLite replica\n * (`services/replicator/schema/replication-state.ts`), and is used\n * to detect when the replica has been reset and is no longer compatible\n * with the current ChangeLog.\n */\nexport type ReplicationConfig = {\n replicaVersion: string;\n publications: readonly string[];\n};\n\nfunction createReplicationConfigTable(shard: ShardID) {\n return /*sql*/ `\n CREATE TABLE ${schema(shard)}.\"replicationConfig\" (\n \"replicaVersion\" TEXT NOT NULL,\n \"publications\" TEXT[] NOT NULL,\n \"resetRequired\" BOOL,\n \"lock\" INTEGER PRIMARY KEY DEFAULT 1 CHECK (lock=1)\n );\n`;\n}\n\nexport function createBackfillTables(shard: ShardID) {\n return /*sql*/ `\n CREATE TABLE ${schema(shard)}.\"tableMetadata\" (\n \"schema\" TEXT NOT NULL,\n \"table\" TEXT NOT NULL,\n \"metadata\" JSONB NOT NULL,\n PRIMARY KEY(\"schema\", \"table\")\n );\n\n CREATE TABLE ${schema(shard)}.\"backfilling\" (\n \"schema\" TEXT NOT NULL,\n \"table\" TEXT NOT NULL,\n \"column\" TEXT NOT NULL,\n \"backfill\" JSONB NOT NULL,\n PRIMARY KEY(\"schema\", \"table\", \"column\")\n );\n `;\n}\n\nexport type TableMetadataRow = {\n schema: string;\n table: string;\n metadata: TableMetadata;\n};\n\nexport type BackfillingColumn = {\n schema: string;\n table: string;\n column: string;\n backfill: BackfillID;\n};\n\nfunction createTables(shard: ShardID) {\n return (\n createSchema(shard) +\n createChangeLogTable(shard) +\n createReplicationStateTable(shard) +\n createReplicationConfigTable(shard) +\n createBackfillTables(shard)\n );\n}\n\ninterface PurgeLock {\n release(): Promise<void>;\n}\n\nexport async function setupCDCTables(\n lc: LogContext,\n db: postgres.TransactionSql,\n shard: ShardID,\n) {\n lc.info?.(`Setting up CDC tables`);\n await db.unsafe(createTables(shard));\n}\n\nexport async function markResetRequired(sql: PostgresDB, shard: ShardID) {\n const schema = cdcSchema(shard);\n await sql`\n UPDATE ${sql(schema)}.\"replicationConfig\"\n SET \"resetRequired\" = true`;\n}\n\nexport async function ensureReplicationConfig(\n lc: LogContext,\n db: PostgresDB,\n subscriptionState: Pick<\n SubscriptionState,\n 'publications' | 'replicaVersion' | 'watermark'\n >,\n shard: ShardID,\n autoReset: boolean,\n purgeLock?: PurgeLock,\n setTimeoutFn: typeof setTimeout = setTimeout,\n pgChangeLogEnabled = true,\n) {\n const {publications, replicaVersion, watermark} = subscriptionState;\n const replicaConfig = {publications, replicaVersion};\n const replicationState: ReplicationState = {\n lastWatermark: replicaVersion,\n owner: null,\n ownerAddress: null,\n };\n const schema = cdcSchema(shard);\n\n await runTx(db, async sql => {\n const stmts: PendingQuery<Row[]>[] = [];\n let needsTruncate = false;\n const results = await sql<\n {\n replicaVersion: string;\n publications: string[];\n resetRequired: boolean | null;\n }[]\n > /*sql*/ `\n SELECT \"replicaVersion\", \"publications\", \"resetRequired\" \n FROM ${sql(schema)}.\"replicationConfig\"`;\n\n if (results.length) {\n const {replicaVersion, publications} = results[0];\n if (\n replicaVersion !== replicaConfig.replicaVersion ||\n !equals(new Set(publications), new Set(replicaConfig.publications))\n ) {\n if (replicaConfig.replicaVersion !== watermark) {\n throw new AutoResetSignal(\n `Cannot reset change db@${replicaVersion} to ` +\n `service replica@${replicaConfig.replicaVersion} ` +\n `from watermark ${watermark}`,\n );\n }\n lc.info?.(\n `Data in cdc tables @${replicaVersion} is incompatible ` +\n `with replica @${replicaConfig.replicaVersion}. Clearing tables.`,\n );\n // Release any purge lock held by the caller; the changeLog is\n // incompatible with the replica and needs to be truncated.\n void purgeLock?.release();\n\n // Note: The order of TRUNCATE matters. The replicationState table is\n // truncated before the changeLog table, in order to acquire\n // (exclusive) locks on the tables in the same order that the\n // storer.ts acquires locks when writing the changeLog, namely:\n //\n // 1. SELECT ... FROM replicationState FOR UPDATE;\n // 2. INSERT INTO changeLog ...;\n // ...\n // n. UPDATE replicationState ...;\n needsTruncate = true;\n stmts.push(\n sql`TRUNCATE TABLE ${sql(schema)}.\"replicationState\"`,\n ...(pgChangeLogEnabled\n ? [sql`TRUNCATE TABLE ${sql(schema)}.\"changeLog\"`]\n : []),\n sql`TRUNCATE TABLE ${sql(schema)}.\"replicationConfig\"`,\n sql`TRUNCATE TABLE ${sql(schema)}.\"tableMetadata\"`,\n sql`TRUNCATE TABLE ${sql(schema)}.\"backfilling\"`,\n );\n }\n }\n // Initialize (or re-initialize TRUNCATED) tables\n if (results.length === 0 || needsTruncate) {\n // When enabled, the PG storer uses the earliest changeLog entry as the\n // safe watermark from which subscribers can be resumed. These initial\n // entries ensure that subscribers can start from a freshly synced\n // replica, even if new changes have been replicated and not purged.\n //\n // TODO: Replace this with an explicit `firstWatermark` column in the\n // change db.\n const watermark = replicaConfig.replicaVersion;\n const initialTx: FullChangeLogEntry[] = pgChangeLogEnabled\n ? [\n {watermark, pos: 0, change: {tag: 'begin'}},\n {watermark, pos: 1, change: {tag: 'commit'}},\n ]\n : [];\n\n stmts.push(\n sql`INSERT INTO ${sql(schema)}.\"replicationConfig\" ${sql(replicaConfig)}`,\n sql`INSERT INTO ${sql(schema)}.\"replicationState\" ${sql(replicationState)} \n ON CONFLICT (lock) DO UPDATE SET ${sql(replicationState)}`,\n ...initialTx.map(\n change => sql`INSERT INTO ${sql(schema)}.\"changeLog\" ${sql(change)}`,\n ),\n );\n\n if (needsTruncate) {\n // The TRUNCATE statements require ACCESS EXCLUSIVE locks, which may\n // be blocked by old storer catchup reads. Race against a timeout\n // that terminates the blocking backends if the TRUNCATE takes too\n // long. The check is repeated until the statements complete, since\n // the TRUNCATE may not yet be waiting on a lock when the timer fires.\n let done = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const scheduleTerminate = () => {\n timer = setTimeoutFn(async () => {\n lc.info?.(\n 'ensureReplicationConfig blocked, terminating lock holders',\n );\n try {\n await terminateChangeDBLockHolders(lc, db, shard);\n } catch (e) {\n lc.warn?.('error terminating lock holders', e);\n }\n if (!done) {\n scheduleTerminate();\n }\n }, LOCK_HOLDER_TERMINATE_TIMEOUT_MS);\n };\n scheduleTerminate();\n try {\n return await Promise.all(stmts);\n } finally {\n done = true;\n clearTimeout(timer);\n }\n }\n return Promise.all(stmts);\n }\n\n const {resetRequired} = results[0];\n if (resetRequired) {\n if (autoReset) {\n throw new AutoResetSignal('reset required by replication stream');\n }\n lc.error?.(\n '\\n\\n\\n' +\n 'Reset required but --auto-reset is not enabled.\\n' +\n 'This can happen for upstream databases that do not support event triggers.\\n' +\n 'To correct this, see https://zero.rocicorp.dev/docs/connecting-to-postgres#schema-changes' +\n '\\n\\n\\n',\n );\n }\n\n return [];\n });\n}\n\n// The time to wait for a TRUNCATE in ensureReplicationConfig before\n// terminating blocking backends via terminateChangeDBLockHolders.\nconst LOCK_HOLDER_TERMINATE_TIMEOUT_MS = 5_000;\n\nexport const CHANGE_STREAMER_APP_NAME = 'zero-change-streamer';\n\nexport class AutoResetSignal extends AbortError {\n readonly name = 'AutoResetSignal';\n}\n\n/**\n * Terminates zero-cache backends that are blocking the current backend\n * from acquiring locks on CDC tables (e.g., during TRUNCATE).\n *\n * This is used during change-DB takeover when the new replication-manager's\n * `ensureReplicationConfig` needs to TRUNCATE tables, but the old\n * replication-manager's storer is still reading from them (e.g., large\n * catchup cursors).\n *\n * The function:\n * 1. Finds backends waiting for a lock on a TRUNCATE in {schema}\n * 2. Uses `pg_blocking_pids()` to identify which backends are blocking them\n * 3. Terminates blocking backends that have `application_name = 'zero-change-streamer'`\n *\n * Must be called on a **separate connection** from the one that is blocked,\n * since the blocked connection is inside a pending transaction.\n */\nexport async function terminateChangeDBLockHolders(\n lc: LogContext,\n db: PostgresDB,\n shard: ShardID,\n) {\n const schema = cdcSchema(shard);\n\n // Step 1: Find backends that are blocked waiting for a lock,\n // whose query involves a TRUNCATE on this shard's CDC schema.\n const blocked = await db<{pid: number}[]>`\n SELECT pid FROM pg_stat_activity\n WHERE wait_event_type = 'Lock'\n AND application_name = ${CHANGE_STREAMER_APP_NAME}\n AND query LIKE ${'%TRUNCATE%' + schema + '%'}`;\n\n if (blocked.length === 0) {\n lc.info?.('no blocked TRUNCATE backends found');\n return;\n }\n\n const blockedPids = blocked.map(r => r.pid);\n lc.info?.(`found blocked TRUNCATE backends: ${JSON.stringify(blockedPids)}`);\n\n // Step 2: For each blocked backend, find and terminate its blockers\n // that are zero-change-streamer connections.\n const terminated = await db<\n {pid: number; applicationName: string; query: string; terminated: boolean}[]\n >`\n SELECT pid, application_name as \"applicationName\", query,\n pg_terminate_backend(pid) as terminated\n FROM pg_stat_activity\n WHERE pid = ANY(\n SELECT unnest(pg_blocking_pids(blocked.pid))\n FROM unnest(${blockedPids}::int[]) AS blocked(pid)\n )\n AND application_name = ${CHANGE_STREAMER_APP_NAME}\n AND pid != ALL(${blockedPids}::int[])`;\n\n if (terminated.length === 0) {\n lc.info?.(`no ${CHANGE_STREAMER_APP_NAME} blockers found to terminate`);\n } else {\n for (const {pid, applicationName, query, terminated: ok} of terminated) {\n lc.info?.(\n `terminated blocking backend pid=${pid} app=${applicationName} ok=${ok} query=${query.slice(0, 200)}`,\n );\n }\n }\n}\n"],"mappings":";;;;;;;;AAiBA,SAAS,OAAO,OAAgB;CAC9B,OAAO,MAAM,UAAU,KAAK,CAAC;AAC/B;AAIA,SAAS,aAAa,OAAgB;CACpC,OAAe,+BAA+B,OAAO,KAAK,EAAE;AAC9D;AAWA,SAAS,qBAAqB,OAAgB;CAI5C,OAAe;iBACA,OAAO,KAAK,EAAE;;;;;;;;AAQ/B;AAYA,SAAgB,4BAA4B,OAAgB;CAC1D,OAAe;iBACA,OAAO,KAAK,EAAE;;;;;;;AAO/B;AAEA,eAAsB,8BACpB,OACA,KACwB;CAGxB,QAAO,MAFc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KAAK;IACpB;GACF;GACA,OAAO,QAAQ,IAAI,KAAK;EAC1B;EAEA,MAAM,EAAC,kBAAiB,QAAQ;EAChC,IAAI,eAAe;GACjB,IAAI,WACF,MAAM,IAAI,gBAAgB,sCAAsC;GAElE,GAAG,QACD,oOAKF;EACF;EAEA,OAAO,CAAC;CACV,CAAC;AACH;AAIA,IAAM,mCAAmC;AAEzC,IAAa,2BAA2B;AAExC,IAAa,kBAAb,cAAqC,WAAW;CAC9C,OAAgB;AAClB;;;;;;;;;;;;;;;;;;AAmBA,eAAsB,6BACpB,IACA,IACA,OACA;CAKA,MAAM,UAAU,MAAM,EAAmB;;;iCAGV,yBAAyB;yBACjC,eARR,UAAU,KAQa,IAAS;CAE/C,IAAI,QAAQ,WAAW,GAAG;EACxB,GAAG,OAAO,oCAAoC;EAC9C;CACF;CAEA,MAAM,cAAc,QAAQ,KAAI,MAAK,EAAE,GAAG;CAC1C,GAAG,OAAO,oCAAoC,KAAK,UAAU,WAAW,GAAG;CAI3E,MAAM,aAAa,MAAM,EAExB;;;;;;wBAMqB,YAAY;;+BAEL,yBAAyB;uBACjC,YAAY;CAEjC,IAAI,WAAW,WAAW,GACxB,GAAG,OAAO,MAAM,yBAAyB,6BAA6B;MAEtE,KAAK,MAAM,EAAC,KAAK,iBAAiB,OAAO,YAAY,QAAO,YAC1D,GAAG,OACD,mCAAmC,IAAI,OAAO,gBAAgB,MAAM,GAAG,SAAS,MAAM,MAAM,GAAG,GAAG,GACpG;AAGN"}
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Pure schema definitions for the `/snapshot` reservation status message.
3
+ *
4
+ * These live in their own module (depending only on valita) so that both
5
+ * {@link snapshot.ts} (which also pulls in the change-streamer HTTP client) and
6
+ * {@link subscribe.ts} can import them without forming an import cycle.
7
+ */
8
+ import * as v from '../../../../shared/src/valita.ts';
9
+ export declare const statusSchema: v.ObjectType<{
10
+ tag: v.Type<"status">;
11
+ /**
12
+ * The location from which litestream should perform the restore.
13
+ */
14
+ backupURL: v.Type<string>;
15
+ /**
16
+ * The `replicaVersion` of the backup. If a subscriber's restored or
17
+ * existing replica is of a different version, it should delete it and
18
+ * retry the restore from litestream (i.e. equivalent to a
19
+ * `WrongReplicaVersion` response from a `/changes` subscription).
20
+ */
21
+ replicaVersion: v.Type<string>;
22
+ /**
23
+ * The earliest watermark from which catchup is possible. If the
24
+ * subscriber's replica is older that this watermark, it should delete it
25
+ * and (retry the) restore from litestream (i.e. equivalent to a
26
+ * `WatermarkTooOld` response from a `/changes` subscription).
27
+ */
28
+ minWatermark: v.Type<string>;
29
+ /**
30
+ * The size in bytes of the replication-manager's replica when the snapshot
31
+ * was reserved, used as an estimate of the size of the restored replica
32
+ * when reporting restore progress. Absent from older replication-managers.
33
+ */
34
+ replicaSize: v.Optional<number>;
35
+ }, undefined>;
36
+ export type SnapshotStatus = v.Infer<typeof statusSchema>;
37
+ export declare const statusMessageSchema: v.TupleType<[v.Type<"status">, v.ObjectType<{
38
+ tag: v.Type<"status">;
39
+ /**
40
+ * The location from which litestream should perform the restore.
41
+ */
42
+ backupURL: v.Type<string>;
43
+ /**
44
+ * The `replicaVersion` of the backup. If a subscriber's restored or
45
+ * existing replica is of a different version, it should delete it and
46
+ * retry the restore from litestream (i.e. equivalent to a
47
+ * `WrongReplicaVersion` response from a `/changes` subscription).
48
+ */
49
+ replicaVersion: v.Type<string>;
50
+ /**
51
+ * The earliest watermark from which catchup is possible. If the
52
+ * subscriber's replica is older that this watermark, it should delete it
53
+ * and (retry the) restore from litestream (i.e. equivalent to a
54
+ * `WatermarkTooOld` response from a `/changes` subscription).
55
+ */
56
+ minWatermark: v.Type<string>;
57
+ /**
58
+ * The size in bytes of the replication-manager's replica when the snapshot
59
+ * was reserved, used as an estimate of the size of the restored replica
60
+ * when reporting restore progress. Absent from older replication-managers.
61
+ */
62
+ replicaSize: v.Optional<number>;
63
+ }, undefined>]>;
64
+ export declare const snapshotMessageSchema: v.UnionType<[v.TupleType<[v.Type<"status">, v.ObjectType<{
65
+ tag: v.Type<"status">;
66
+ /**
67
+ * The location from which litestream should perform the restore.
68
+ */
69
+ backupURL: v.Type<string>;
70
+ /**
71
+ * The `replicaVersion` of the backup. If a subscriber's restored or
72
+ * existing replica is of a different version, it should delete it and
73
+ * retry the restore from litestream (i.e. equivalent to a
74
+ * `WrongReplicaVersion` response from a `/changes` subscription).
75
+ */
76
+ replicaVersion: v.Type<string>;
77
+ /**
78
+ * The earliest watermark from which catchup is possible. If the
79
+ * subscriber's replica is older that this watermark, it should delete it
80
+ * and (retry the) restore from litestream (i.e. equivalent to a
81
+ * `WatermarkTooOld` response from a `/changes` subscription).
82
+ */
83
+ minWatermark: v.Type<string>;
84
+ /**
85
+ * The size in bytes of the replication-manager's replica when the snapshot
86
+ * was reserved, used as an estimate of the size of the restored replica
87
+ * when reporting restore progress. Absent from older replication-managers.
88
+ */
89
+ replicaSize: v.Optional<number>;
90
+ }, undefined>]>]>;
91
+ export type SnapshotMessage = v.Infer<typeof statusMessageSchema>;
92
+ //# sourceMappingURL=snapshot-message.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"snapshot-message.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/change-streamer/snapshot-message.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,CAAC,MAAM,kCAAkC,CAAC;AAEtD,eAAO,MAAM,YAAY;;IAGvB;;OAEG;;IAGH;;;;;OAKG;;IAGH;;;;;OAKG;;IAGH;;;;OAIG;;aAEH,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,YAAY,CAAC,CAAC;AAE1D,eAAO,MAAM,mBAAmB;;IA/B9B;;OAEG;;IAGH;;;;;OAKG;;IAGH;;;;;OAKG;;IAGH;;;;OAIG;;eAM0E,CAAC;AAEhF,eAAO,MAAM,qBAAqB;;IAjChC;;OAEG;;IAGH;;;;;OAKG;;IAGH;;;;;OAKG;;IAGH;;;;OAIG;;iBAQ4D,CAAC;AAElE,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC"}
@@ -0,0 +1,42 @@
1
+ import { valita_exports } from "../../../../shared/src/valita.js";
2
+ //#region ../zero-cache/src/services/change-streamer/snapshot-message.ts
3
+ /**
4
+ * Pure schema definitions for the `/snapshot` reservation status message.
5
+ *
6
+ * These live in their own module (depending only on valita) so that both
7
+ * {@link snapshot.ts} (which also pulls in the change-streamer HTTP client) and
8
+ * {@link subscribe.ts} can import them without forming an import cycle.
9
+ */
10
+ var statusSchema = valita_exports.object({
11
+ tag: valita_exports.literal("status"),
12
+ /**
13
+ * The location from which litestream should perform the restore.
14
+ */
15
+ backupURL: valita_exports.string(),
16
+ /**
17
+ * The `replicaVersion` of the backup. If a subscriber's restored or
18
+ * existing replica is of a different version, it should delete it and
19
+ * retry the restore from litestream (i.e. equivalent to a
20
+ * `WrongReplicaVersion` response from a `/changes` subscription).
21
+ */
22
+ replicaVersion: valita_exports.string(),
23
+ /**
24
+ * The earliest watermark from which catchup is possible. If the
25
+ * subscriber's replica is older that this watermark, it should delete it
26
+ * and (retry the) restore from litestream (i.e. equivalent to a
27
+ * `WatermarkTooOld` response from a `/changes` subscription).
28
+ */
29
+ minWatermark: valita_exports.string(),
30
+ /**
31
+ * The size in bytes of the replication-manager's replica when the snapshot
32
+ * was reserved, used as an estimate of the size of the restored replica
33
+ * when reporting restore progress. Absent from older replication-managers.
34
+ */
35
+ replicaSize: valita_exports.number().optional()
36
+ });
37
+ var statusMessageSchema = valita_exports.tuple([valita_exports.literal("status"), statusSchema]);
38
+ valita_exports.union(statusMessageSchema);
39
+ //#endregion
40
+ export { statusSchema };
41
+
42
+ //# sourceMappingURL=snapshot-message.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"snapshot-message.js","names":[],"sources":["../../../../../../zero-cache/src/services/change-streamer/snapshot-message.ts"],"sourcesContent":["/**\n * Pure schema definitions for the `/snapshot` reservation status message.\n *\n * These live in their own module (depending only on valita) so that both\n * {@link snapshot.ts} (which also pulls in the change-streamer HTTP client) and\n * {@link subscribe.ts} can import them without forming an import cycle.\n */\n\nimport * as v from '../../../../shared/src/valita.ts';\n\nexport const 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 /**\n * The size in bytes of the replication-manager's replica when the snapshot\n * was reserved, used as an estimate of the size of the restored replica\n * when reporting restore progress. Absent from older replication-managers.\n */\n replicaSize: v.number().optional(),\n});\n\nexport type SnapshotStatus = v.Infer<typeof statusSchema>;\n\nexport const statusMessageSchema = v.tuple([v.literal('status'), statusSchema]);\n\nexport const snapshotMessageSchema = v.union(statusMessageSchema);\n\nexport type SnapshotMessage = v.Infer<typeof statusMessageSchema>;\n"],"mappings":";;;;;;;;;AAUA,IAAa,eAAe,eAAE,OAAO;CACnC,KAAK,eAAE,QAAQ,QAAQ;;;;CAKvB,WAAW,eAAE,OAAO;;;;;;;CAQpB,gBAAgB,eAAE,OAAO;;;;;;;CAQzB,cAAc,eAAE,OAAO;;;;;;CAOvB,aAAa,eAAE,OAAO,EAAE,SAAS;AACnC,CAAC;AAID,IAAa,sBAAsB,eAAE,MAAM,CAAC,eAAE,QAAQ,QAAQ,GAAG,YAAY,CAAC;AAEzC,eAAE,MAAM,mBAAmB"}
@@ -1,7 +1,7 @@
1
1
  import type { LogContext } from '@rocicorp/logger';
2
2
  import type { Source } from '../../types/streams.ts';
3
3
  import type { BackupConfig } from './change-streamer-service.ts';
4
- import type { SnapshotMessage } from './snapshot.ts';
4
+ import type { SnapshotMessage } from './snapshot-message.ts';
5
5
  import type { ChangeLogReadSource } from './sqlite-change-log-read-router.ts';
6
6
  export declare class SnapshotReservations {
7
7
  #private;
@@ -1 +1 @@
1
- {"version":3,"file":"snapshot-reservations.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/change-streamer/snapshot-reservations.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,wBAAwB,CAAC;AAOnD,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,8BAA8B,CAAC;AAC/D,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,eAAe,CAAC;AACnD,OAAO,KAAK,EAAC,mBAAmB,EAAC,MAAM,oCAAoC,CAAC;AAE5E,qBAAa,oBAAoB;;IAM/B,YACE,EAAE,EAAE,UAAU,EACd,YAAY,EAAE,YAAY,EAC1B,OAAO,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,SAAS,EAKjD;IAED,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,eAAe,CAAC,CAU5C;IAED,KAAK,CAAC,MAAM,EAAE,MAAM,QAEnB;IAED,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,eAAe,CAAC,GAAG,OAAO,CAElE;IAsCD,qBAAqB,YAOpB;IAED,kBAAkB,IAAI,MAAM,EAAE,CAI7B;IAED,0EAA0E;IAC1E,UAAU,CACR,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,MAAM,EACtB,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,mBAAmB,GAC1B,IAAI,CAmBN;IAeD;;;;OAIG;IACH,uBAAuB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAE/C;IAED,qBAAqB,aAKpB;CACF"}
1
+ {"version":3,"file":"snapshot-reservations.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/change-streamer/snapshot-reservations.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,wBAAwB,CAAC;AAOnD,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,8BAA8B,CAAC;AAC/D,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,uBAAuB,CAAC;AAC3D,OAAO,KAAK,EAAC,mBAAmB,EAAC,MAAM,oCAAoC,CAAC;AAE5E,qBAAa,oBAAoB;;IAM/B,YACE,EAAE,EAAE,UAAU,EACd,YAAY,EAAE,YAAY,EAC1B,OAAO,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,SAAS,EAKjD;IAED,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,eAAe,CAAC,CAU5C;IAED,KAAK,CAAC,MAAM,EAAE,MAAM,QAEnB;IAED,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,eAAe,CAAC,GAAG,OAAO,CAElE;IAsCD,qBAAqB,YAOpB;IAED,kBAAkB,IAAI,MAAM,EAAE,CAI7B;IAED,0EAA0E;IAC1E,UAAU,CACR,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,MAAM,EACtB,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,mBAAmB,GAC1B,IAAI,CAmBN;IAeD;;;;OAIG;IACH,uBAAuB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAE/C;IAED,qBAAqB,aAKpB;CACF"}
@@ -17,7 +17,7 @@ var SnapshotReservations = class {
17
17
  const instanceID = {};
18
18
  const downstream = Subscription.create({ cleanup: () => this.#close(taskID, instanceID) });
19
19
  this.#reservations.set(taskID, new Reservation(instanceID, downstream));
20
- this.#lc.info?.(`created snasphot reservation for ${taskID}`);
20
+ this.#lc.info?.(`created snapshot reservation for ${taskID}`);
21
21
  return downstream;
22
22
  }
23
23
  close(taskID) {
@@ -1 +1 @@
1
- {"version":3,"file":"snapshot-reservations.js","names":["#lc","#backupConfig","#onClose","#reservations","#close","#metricAttrs","#replicaSize","#downstream","#watermark","#delayNoted"],"sources":["../../../../../../zero-cache/src/services/change-streamer/snapshot-reservations.ts"],"sourcesContent":["import {statSync} from 'node:fs';\nimport type {LogContext} from '@rocicorp/logger';\nimport type {Source} from '../../types/streams.ts';\nimport {Subscription} from '../../types/subscription.ts';\nimport {\n litestreamMonitorMetricAttrs,\n litestreamSnapshotReservationConfirmDuration,\n litestreamSnapshotReservationDuration,\n} from '../litestream/metrics.ts';\nimport type {BackupConfig} from './change-streamer-service.ts';\nimport type {SnapshotMessage} from './snapshot.ts';\nimport type {ChangeLogReadSource} from './sqlite-change-log-read-router.ts';\n\nexport class SnapshotReservations {\n readonly #lc: LogContext;\n readonly #backupConfig: BackupConfig;\n readonly #onClose: ((taskID: string) => void) | undefined;\n readonly #reservations = new Map<string, Reservation>();\n\n constructor(\n lc: LogContext,\n backupConfig: BackupConfig,\n onClose?: ((taskID: string) => void) | undefined,\n ) {\n this.#lc = lc.withContext('component', 'snapshot-reserver');\n this.#backupConfig = backupConfig;\n this.#onClose = onClose;\n }\n\n open(taskID: string): Source<SnapshotMessage> {\n this.close(taskID);\n\n const instanceID = {};\n const downstream = Subscription.create<SnapshotMessage>({\n cleanup: () => this.#close(taskID, instanceID),\n });\n this.#reservations.set(taskID, new Reservation(instanceID, downstream));\n this.#lc.info?.(`created snasphot reservation for ${taskID}`);\n return downstream;\n }\n\n close(taskID: string) {\n this.#close(taskID, undefined);\n }\n\n isCurrent(taskID: string, source: Source<SnapshotMessage>): boolean {\n return this.#reservations.get(taskID)?.owns(source) ?? false;\n }\n\n #metricAttrs() {\n return litestreamMonitorMetricAttrs(\n this.#backupConfig.backupURL,\n this.#backupConfig.litestreamVersion,\n 'view_syncer',\n );\n }\n\n #close(taskID: string, cancelledInstanceID: InstanceID | undefined) {\n const res = this.#reservations.get(taskID);\n if (\n res &&\n (!cancelledInstanceID || res.instanceID === cancelledInstanceID)\n ) {\n // Note: delete first, so that the reservation is gone when close() is called.\n this.#reservations.delete(taskID);\n this.#onClose?.(taskID);\n res.close();\n\n const duration = Date.now() - res.startTime.getTime();\n this.#lc.info?.(\n `ended snapshot reservation for ${taskID} (${duration} ms)`,\n );\n // `result` reports how the reservation ended and `confirmed` whether it\n // ever received its bounds. They are separate dimensions: a follower\n // that gives up while waiting for a confirmation is\n // `result=cancelled, confirmed=false`, which a single collapsed\n // attribute cannot distinguish from a client that simply went away.\n litestreamSnapshotReservationDuration().recordMs(duration, {\n ...this.#metricAttrs(),\n result: cancelledInstanceID ? 'cancelled' : 'closed',\n confirmed: res.confirmed(),\n });\n }\n }\n\n confirmationsRequired() {\n for (const res of this.#reservations.values()) {\n if (!res.confirmed()) {\n return true;\n }\n }\n return false;\n }\n\n unconfirmedTaskIDs(): string[] {\n return [...this.#reservations.entries()]\n .filter(([, reservation]) => !reservation.confirmed())\n .map(([taskID]) => taskID);\n }\n\n /** Confirms one reservation with the bounds of its pinned read source. */\n confirmFor(\n taskID: string,\n replicaVersion: string,\n minWatermark: string,\n source: ChangeLogReadSource,\n ): void {\n const res = this.#reservations.get(taskID);\n if (res && !res.confirmed()) {\n this.#lc.info?.(\n `reserving change-log entries since ${minWatermark} for ${taskID}`,\n );\n res.confirm(\n this.#backupConfig.backupURL,\n replicaVersion,\n minWatermark,\n this.#replicaSize(),\n );\n // Measured from `open()`, not from the first confirmation attempt: what\n // matters is how long the follower waited before it could restore.\n litestreamSnapshotReservationConfirmDuration().recordMs(\n Date.now() - res.startTime.getTime(),\n {...this.#metricAttrs(), source},\n );\n }\n }\n\n #replicaSize(): number | undefined {\n const {replicaFile} = this.#backupConfig;\n if (!replicaFile) {\n return undefined;\n }\n try {\n return statSync(replicaFile).size;\n } catch (e) {\n this.#lc.warn?.(`Unable to get the size of ${replicaFile}`, e);\n return undefined;\n }\n }\n\n /**\n * Notes that a confirmation was deferred, returning true only the first time\n * for this reservation. Confirmation is retried on every backup, so an\n * undeduplicated count would measure backups rather than delayed followers.\n */\n noteConfirmationDelayed(taskID: string): boolean {\n return this.#reservations.get(taskID)?.noteDelayed() ?? false;\n }\n\n getReservedWatermarks() {\n return Array.from(\n this.#reservations.values(),\n ({reservedWatermark}) => reservedWatermark,\n ).filter(watermark => watermark !== null);\n }\n}\n\ntype InstanceID = {};\n\nclass Reservation {\n readonly instanceID: InstanceID;\n readonly startTime: Date = new Date();\n readonly #downstream: Subscription<SnapshotMessage>;\n #watermark: string | null = null;\n #delayNoted = false;\n\n constructor(\n instanceID: InstanceID,\n downstream: Subscription<SnapshotMessage>,\n ) {\n this.instanceID = instanceID;\n this.#downstream = downstream;\n }\n\n get reservedWatermark() {\n return this.#watermark;\n }\n\n confirmed() {\n return this.#watermark !== null;\n }\n\n owns(source: Source<SnapshotMessage>): boolean {\n return this.#downstream === source;\n }\n\n noteDelayed(): boolean {\n if (this.#delayNoted) {\n return false;\n }\n this.#delayNoted = true;\n return true;\n }\n\n confirm(\n backupURL: string,\n replicaVersion: string,\n minWatermark: string,\n replicaSize: number | undefined,\n ) {\n if (this.#watermark === null) {\n if (this.#downstream.active) {\n this.#downstream.push([\n 'status',\n {tag: 'status', backupURL, replicaVersion, minWatermark, replicaSize},\n ]);\n }\n this.#watermark = minWatermark;\n }\n }\n\n close() {\n this.#downstream.cancel();\n }\n}\n"],"mappings":";;;;AAaA,IAAa,uBAAb,MAAkC;CAChC;CACA;CACA;CACA,gCAAyB,IAAI,IAAyB;CAEtD,YACE,IACA,cACA,SACA;EACA,KAAKA,MAAM,GAAG,YAAY,aAAa,mBAAmB;EAC1D,KAAKC,gBAAgB;EACrB,KAAKC,WAAW;CAClB;CAEA,KAAK,QAAyC;EAC5C,KAAK,MAAM,MAAM;EAEjB,MAAM,aAAa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;GAAW,CACtE,CAAC;GAEH,KAAKC,aAAa;EACpB;CACF;CAEA,QAAQ;EACN,KAAKD,YAAY,OAAO;CAC1B;AACF"}
1
+ {"version":3,"file":"snapshot-reservations.js","names":["#lc","#backupConfig","#onClose","#reservations","#close","#metricAttrs","#replicaSize","#downstream","#watermark","#delayNoted"],"sources":["../../../../../../zero-cache/src/services/change-streamer/snapshot-reservations.ts"],"sourcesContent":["import {statSync} from 'node:fs';\nimport type {LogContext} from '@rocicorp/logger';\nimport type {Source} from '../../types/streams.ts';\nimport {Subscription} from '../../types/subscription.ts';\nimport {\n litestreamMonitorMetricAttrs,\n litestreamSnapshotReservationConfirmDuration,\n litestreamSnapshotReservationDuration,\n} from '../litestream/metrics.ts';\nimport type {BackupConfig} from './change-streamer-service.ts';\nimport type {SnapshotMessage} from './snapshot-message.ts';\nimport type {ChangeLogReadSource} from './sqlite-change-log-read-router.ts';\n\nexport class SnapshotReservations {\n readonly #lc: LogContext;\n readonly #backupConfig: BackupConfig;\n readonly #onClose: ((taskID: string) => void) | undefined;\n readonly #reservations = new Map<string, Reservation>();\n\n constructor(\n lc: LogContext,\n backupConfig: BackupConfig,\n onClose?: ((taskID: string) => void) | undefined,\n ) {\n this.#lc = lc.withContext('component', 'snapshot-reserver');\n this.#backupConfig = backupConfig;\n this.#onClose = onClose;\n }\n\n open(taskID: string): Source<SnapshotMessage> {\n this.close(taskID);\n\n const instanceID = {};\n const downstream = Subscription.create<SnapshotMessage>({\n cleanup: () => this.#close(taskID, instanceID),\n });\n this.#reservations.set(taskID, new Reservation(instanceID, downstream));\n this.#lc.info?.(`created snapshot reservation for ${taskID}`);\n return downstream;\n }\n\n close(taskID: string) {\n this.#close(taskID, undefined);\n }\n\n isCurrent(taskID: string, source: Source<SnapshotMessage>): boolean {\n return this.#reservations.get(taskID)?.owns(source) ?? false;\n }\n\n #metricAttrs() {\n return litestreamMonitorMetricAttrs(\n this.#backupConfig.backupURL,\n this.#backupConfig.litestreamVersion,\n 'view_syncer',\n );\n }\n\n #close(taskID: string, cancelledInstanceID: InstanceID | undefined) {\n const res = this.#reservations.get(taskID);\n if (\n res &&\n (!cancelledInstanceID || res.instanceID === cancelledInstanceID)\n ) {\n // Note: delete first, so that the reservation is gone when close() is called.\n this.#reservations.delete(taskID);\n this.#onClose?.(taskID);\n res.close();\n\n const duration = Date.now() - res.startTime.getTime();\n this.#lc.info?.(\n `ended snapshot reservation for ${taskID} (${duration} ms)`,\n );\n // `result` reports how the reservation ended and `confirmed` whether it\n // ever received its bounds. They are separate dimensions: a follower\n // that gives up while waiting for a confirmation is\n // `result=cancelled, confirmed=false`, which a single collapsed\n // attribute cannot distinguish from a client that simply went away.\n litestreamSnapshotReservationDuration().recordMs(duration, {\n ...this.#metricAttrs(),\n result: cancelledInstanceID ? 'cancelled' : 'closed',\n confirmed: res.confirmed(),\n });\n }\n }\n\n confirmationsRequired() {\n for (const res of this.#reservations.values()) {\n if (!res.confirmed()) {\n return true;\n }\n }\n return false;\n }\n\n unconfirmedTaskIDs(): string[] {\n return [...this.#reservations.entries()]\n .filter(([, reservation]) => !reservation.confirmed())\n .map(([taskID]) => taskID);\n }\n\n /** Confirms one reservation with the bounds of its pinned read source. */\n confirmFor(\n taskID: string,\n replicaVersion: string,\n minWatermark: string,\n source: ChangeLogReadSource,\n ): void {\n const res = this.#reservations.get(taskID);\n if (res && !res.confirmed()) {\n this.#lc.info?.(\n `reserving change-log entries since ${minWatermark} for ${taskID}`,\n );\n res.confirm(\n this.#backupConfig.backupURL,\n replicaVersion,\n minWatermark,\n this.#replicaSize(),\n );\n // Measured from `open()`, not from the first confirmation attempt: what\n // matters is how long the follower waited before it could restore.\n litestreamSnapshotReservationConfirmDuration().recordMs(\n Date.now() - res.startTime.getTime(),\n {...this.#metricAttrs(), source},\n );\n }\n }\n\n #replicaSize(): number | undefined {\n const {replicaFile} = this.#backupConfig;\n if (!replicaFile) {\n return undefined;\n }\n try {\n return statSync(replicaFile).size;\n } catch (e) {\n this.#lc.warn?.(`Unable to get the size of ${replicaFile}`, e);\n return undefined;\n }\n }\n\n /**\n * Notes that a confirmation was deferred, returning true only the first time\n * for this reservation. Confirmation is retried on every backup, so an\n * undeduplicated count would measure backups rather than delayed followers.\n */\n noteConfirmationDelayed(taskID: string): boolean {\n return this.#reservations.get(taskID)?.noteDelayed() ?? false;\n }\n\n getReservedWatermarks() {\n return Array.from(\n this.#reservations.values(),\n ({reservedWatermark}) => reservedWatermark,\n ).filter(watermark => watermark !== null);\n }\n}\n\ntype InstanceID = {};\n\nclass Reservation {\n readonly instanceID: InstanceID;\n readonly startTime: Date = new Date();\n readonly #downstream: Subscription<SnapshotMessage>;\n #watermark: string | null = null;\n #delayNoted = false;\n\n constructor(\n instanceID: InstanceID,\n downstream: Subscription<SnapshotMessage>,\n ) {\n this.instanceID = instanceID;\n this.#downstream = downstream;\n }\n\n get reservedWatermark() {\n return this.#watermark;\n }\n\n confirmed() {\n return this.#watermark !== null;\n }\n\n owns(source: Source<SnapshotMessage>): boolean {\n return this.#downstream === source;\n }\n\n noteDelayed(): boolean {\n if (this.#delayNoted) {\n return false;\n }\n this.#delayNoted = true;\n return true;\n }\n\n confirm(\n backupURL: string,\n replicaVersion: string,\n minWatermark: string,\n replicaSize: number | undefined,\n ) {\n if (this.#watermark === null) {\n if (this.#downstream.active) {\n this.#downstream.push([\n 'status',\n {tag: 'status', backupURL, replicaVersion, minWatermark, replicaSize},\n ]);\n }\n this.#watermark = minWatermark;\n }\n }\n\n close() {\n this.#downstream.cancel();\n }\n}\n"],"mappings":";;;;AAaA,IAAa,uBAAb,MAAkC;CAChC;CACA;CACA;CACA,gCAAyB,IAAI,IAAyB;CAEtD,YACE,IACA,cACA,SACA;EACA,KAAKA,MAAM,GAAG,YAAY,aAAa,mBAAmB;EAC1D,KAAKC,gBAAgB;EACrB,KAAKC,WAAW;CAClB;CAEA,KAAK,QAAyC;EAC5C,KAAK,MAAM,MAAM;EAEjB,MAAM,aAAa,CAAC;EACpB,MAAM,aAAa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,KAAKC,aAAa;EACpB;CACF;CAEA,QAAQ;EACN,KAAKD,YAAY,OAAO;CAC1B;AACF"}
@@ -12,93 +12,11 @@
12
12
  * backed up changes.
13
13
  */
14
14
  import type { LogContext } from '@rocicorp/logger';
15
- import * as v from '../../../../shared/src/valita.ts';
16
- import { type NormalizedZeroConfig } from '../../config/normalize.ts';
17
- import type { Source } from '../../types/streams.ts';
18
- declare const statusSchema: v.ObjectType<{
19
- tag: v.Type<"status">;
20
- /**
21
- * The location from which litestream should perform the restore.
22
- */
23
- backupURL: v.Type<string>;
24
- /**
25
- * The `replicaVersion` of the backup. If a subscriber's restored or
26
- * existing replica is of a different version, it should delete it and
27
- * retry the restore from litestream (i.e. equivalent to a
28
- * `WrongReplicaVersion` response from a `/changes` subscription).
29
- */
30
- replicaVersion: v.Type<string>;
31
- /**
32
- * The earliest watermark from which catchup is possible. If the
33
- * subscriber's replica is older that this watermark, it should delete it
34
- * and (retry the) restore from litestream (i.e. equivalent to a
35
- * `WatermarkTooOld` response from a `/changes` subscription).
36
- */
37
- minWatermark: v.Type<string>;
38
- /**
39
- * The size in bytes of the replication-manager's replica when the snapshot
40
- * was reserved, used as an estimate of the size of the restored replica
41
- * when reporting restore progress. Absent from older replication-managers.
42
- */
43
- replicaSize: v.Optional<number>;
44
- }, undefined>;
45
- export type SnapshotStatus = v.Infer<typeof statusSchema>;
46
- declare const statusMessageSchema: v.TupleType<[v.Type<"status">, v.ObjectType<{
47
- tag: v.Type<"status">;
48
- /**
49
- * The location from which litestream should perform the restore.
50
- */
51
- backupURL: v.Type<string>;
52
- /**
53
- * The `replicaVersion` of the backup. If a subscriber's restored or
54
- * existing replica is of a different version, it should delete it and
55
- * retry the restore from litestream (i.e. equivalent to a
56
- * `WrongReplicaVersion` response from a `/changes` subscription).
57
- */
58
- replicaVersion: v.Type<string>;
59
- /**
60
- * The earliest watermark from which catchup is possible. If the
61
- * subscriber's replica is older that this watermark, it should delete it
62
- * and (retry the) restore from litestream (i.e. equivalent to a
63
- * `WatermarkTooOld` response from a `/changes` subscription).
64
- */
65
- minWatermark: v.Type<string>;
66
- /**
67
- * The size in bytes of the replication-manager's replica when the snapshot
68
- * was reserved, used as an estimate of the size of the restored replica
69
- * when reporting restore progress. Absent from older replication-managers.
70
- */
71
- replicaSize: v.Optional<number>;
72
- }, undefined>]>;
73
- export declare const snapshotMessageSchema: v.UnionType<[v.TupleType<[v.Type<"status">, v.ObjectType<{
74
- tag: v.Type<"status">;
75
- /**
76
- * The location from which litestream should perform the restore.
77
- */
78
- backupURL: v.Type<string>;
79
- /**
80
- * The `replicaVersion` of the backup. If a subscriber's restored or
81
- * existing replica is of a different version, it should delete it and
82
- * retry the restore from litestream (i.e. equivalent to a
83
- * `WrongReplicaVersion` response from a `/changes` subscription).
84
- */
85
- replicaVersion: v.Type<string>;
86
- /**
87
- * The earliest watermark from which catchup is possible. If the
88
- * subscriber's replica is older that this watermark, it should delete it
89
- * and (retry the) restore from litestream (i.e. equivalent to a
90
- * `WatermarkTooOld` response from a `/changes` subscription).
91
- */
92
- minWatermark: v.Type<string>;
93
- /**
94
- * The size in bytes of the replication-manager's replica when the snapshot
95
- * was reserved, used as an estimate of the size of the restored replica
96
- * when reporting restore progress. Absent from older replication-managers.
97
- */
98
- replicaSize: v.Optional<number>;
99
- }, undefined>]>]>;
100
- export type SnapshotMessage = v.Infer<typeof statusMessageSchema>;
101
- export type ReserveSnapshot = (lc: LogContext, config: NormalizedZeroConfig) => Promise<Source<SnapshotMessage>>;
102
- export declare function reserveAndGetSnapshotStatus(lc: LogContext, config: NormalizedZeroConfig, reserve?: ReserveSnapshot): Promise<SnapshotStatus>;
103
- export {};
15
+ import type { ReservationFollowup, SnapshotReserver } from './change-streamer-http.ts';
16
+ import type { SnapshotStatus } from './subscribe.ts';
17
+ export type { SnapshotStatus };
18
+ export declare function reserveAndGetSnapshotStatus(lc: LogContext, taskID: string, changeStreamer: SnapshotReserver): Promise<{
19
+ reserved: SnapshotStatus;
20
+ followup: ReservationFollowup;
21
+ }>;
104
22
  //# 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,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAIjD,OAAO,KAAK,CAAC,MAAM,kCAAkC,CAAC;AACtD,OAAO,EAAC,KAAK,oBAAoB,EAAC,MAAM,2BAA2B,CAAC;AAEpE,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,wBAAwB,CAAC;AAGnD,QAAA,MAAM,YAAY;;IAGhB;;OAEG;;IAGH;;;;;OAKG;;IAGH;;;;;OAKG;;IAGH;;;;OAIG;;aAEH,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,YAAY,CAAC,CAAC;AAE1D,QAAA,MAAM,mBAAmB;;IA/BvB;;OAEG;;IAGH;;;;;OAKG;;IAGH;;;;;OAKG;;IAGH;;;;OAIG;;eAMmE,CAAC;AAEzE,eAAO,MAAM,qBAAqB;;IAjChC;;OAEG;;IAGH;;;;;OAKG;;IAGH;;;;;OAKG;;IAGH;;;;OAIG;;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
+ {"version":3,"file":"snapshot.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/change-streamer/snapshot.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AASjD,OAAO,KAAK,EACV,mBAAmB,EACnB,gBAAgB,EACjB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,gBAAgB,CAAC;AAEnD,YAAY,EAAC,cAAc,EAAC,CAAC;AAE7B,wBAAsB,2BAA2B,CAC/C,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,gBAAgB,GAC/B,OAAO,CAAC;IAAC,QAAQ,EAAE,cAAc,CAAC;IAAC,QAAQ,EAAE,mBAAmB,CAAA;CAAC,CAAC,CAmDpE"}
@@ -1,107 +1,35 @@
1
1
  import { AbortError } from "../../../../shared/src/abort-error.js";
2
2
  import { sleep } from "../../../../shared/src/sleep.js";
3
- import { valita_exports } from "../../../../shared/src/valita.js";
4
- import { getShardConfig } from "../../types/shards.js";
5
- import "../../config/normalize.js";
6
- import { ChangeStreamerHttpClient } from "./change-streamer-http.js";
7
- import { resolver } from "@rocicorp/resolver";
3
+ import { promiseOrAbort } from "../../../../shared/src/promise-race.js";
8
4
  //#region ../zero-cache/src/services/change-streamer/snapshot.ts
9
- var statusSchema = valita_exports.object({
10
- tag: valita_exports.literal("status"),
11
- /**
12
- * The location from which litestream should perform the restore.
13
- */
14
- backupURL: valita_exports.string(),
15
- /**
16
- * The `replicaVersion` of the backup. If a subscriber's restored or
17
- * existing replica is of a different version, it should delete it and
18
- * retry the restore from litestream (i.e. equivalent to a
19
- * `WrongReplicaVersion` response from a `/changes` subscription).
20
- */
21
- replicaVersion: valita_exports.string(),
22
- /**
23
- * The earliest watermark from which catchup is possible. If the
24
- * subscriber's replica is older that this watermark, it should delete it
25
- * and (retry the) restore from litestream (i.e. equivalent to a
26
- * `WatermarkTooOld` response from a `/changes` subscription).
27
- */
28
- minWatermark: valita_exports.string(),
29
- /**
30
- * The size in bytes of the replication-manager's replica when the snapshot
31
- * was reserved, used as an estimate of the size of the restored replica
32
- * when reporting restore progress. Absent from older replication-managers.
33
- */
34
- replicaSize: valita_exports.number().optional()
35
- });
36
- var statusMessageSchema = valita_exports.tuple([valita_exports.literal("status"), statusSchema]);
37
- var snapshotMessageSchema = valita_exports.union(statusMessageSchema);
38
- function reserveAndGetSnapshotStatus(lc, config, reserve = reserveSnapshot) {
39
- const { promise: status, resolve, reject } = resolver();
40
- (async function() {
41
- const abort = new AbortController();
42
- const { signal } = abort;
43
- const onSignal = () => abort.abort();
44
- process.on("SIGINT", onSignal);
45
- process.on("SIGTERM", onSignal);
46
- try {
47
- for (let i = 0;; i++) {
48
- let err;
49
- try {
50
- let resolved = false;
51
- const stream = await untilAborted(reserve(lc, config), signal);
52
- const cancelStream = () => stream.cancel(new AbortError("Aborted"));
53
- signal.addEventListener("abort", cancelStream, { once: true });
54
- try {
55
- for await (const msg of stream) {
56
- resolve(msg[1]);
57
- resolved = true;
58
- }
59
- } finally {
60
- signal.removeEventListener("abort", cancelStream);
61
- }
62
- if (resolved) break;
63
- } catch (e) {
64
- err = e;
65
- }
66
- if (signal.aborted) return reject(err instanceof AbortError ? err : new AbortError("Aborted"));
67
- lc.warn?.(`Unable to reserve snapshot (attempt ${i + 1}). Retrying in 5 seconds.`, String(err));
68
- try {
69
- await sleep(5e3, abort.signal);
70
- } catch (e) {
71
- return reject(e);
72
- }
5
+ async function reserveAndGetSnapshotStatus(lc, taskID, changeStreamer) {
6
+ const abort = new AbortController();
7
+ const { signal } = abort;
8
+ const onSignal = () => abort.abort(new AbortError("SIGTERM/SIGINT"));
9
+ process.on("SIGINT", onSignal);
10
+ process.on("SIGTERM", onSignal);
11
+ try {
12
+ for (let i = 0;; i++) {
13
+ let err;
14
+ const reservation = changeStreamer.reserveSnapshot(taskID);
15
+ try {
16
+ return await promiseOrAbort(reservation, signal);
17
+ } catch (e) {
18
+ err = e;
73
19
  }
74
- } finally {
75
- process.off("SIGINT", onSignal);
76
- process.off("SIGTERM", onSignal);
20
+ if (signal.aborted) {
21
+ reservation.then(({ followup }) => followup.cancel(), () => {});
22
+ throw err;
23
+ }
24
+ lc.warn?.(`Unable to reserve snapshot (attempt ${i + 1}). Retrying in 5 seconds.`, String(err));
25
+ await sleep(5e3, signal);
77
26
  }
78
- })();
79
- return status;
80
- }
81
- /**
82
- * Resolves with the reserved stream, or rejects with an AbortError if the
83
- * `signal` is aborted while the reservation is pending (in which case a
84
- * stream that arrives later is canceled rather than held open).
85
- */
86
- function untilAborted(reservation, signal) {
87
- return new Promise((resolve, reject) => {
88
- const onAbort = () => reject(new AbortError("Aborted"));
89
- signal.addEventListener("abort", onAbort, { once: true });
90
- reservation.then((stream) => {
91
- signal.removeEventListener("abort", onAbort);
92
- if (signal.aborted) stream.cancel();
93
- else resolve(stream);
94
- }, (e) => {
95
- signal.removeEventListener("abort", onAbort);
96
- reject(e);
97
- });
98
- });
99
- }
100
- function reserveSnapshot(lc, config) {
101
- const { taskID, change, changeStreamer } = config;
102
- return new ChangeStreamerHttpClient(lc, getShardConfig(config), change.db, changeStreamer.uri).reserveSnapshot(taskID);
27
+ } finally {
28
+ process.off("SIGINT", onSignal);
29
+ process.off("SIGTERM", onSignal);
30
+ }
103
31
  }
104
32
  //#endregion
105
- export { reserveAndGetSnapshotStatus, snapshotMessageSchema };
33
+ export { reserveAndGetSnapshotStatus };
106
34
 
107
35
  //# sourceMappingURL=snapshot.js.map