@rocicorp/zero 1.10.0-canary.2 → 1.10.0-canary.4

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 (181) hide show
  1. package/out/zero/package.js +1 -1
  2. package/out/zero/package.js.map +1 -1
  3. package/out/zero-cache/src/auth/write-authorizer.d.ts.map +1 -1
  4. package/out/zero-cache/src/auth/write-authorizer.js +8 -1
  5. package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
  6. package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
  7. package/out/zero-cache/src/config/normalize.js +7 -2
  8. package/out/zero-cache/src/config/normalize.js.map +1 -1
  9. package/out/zero-cache/src/config/zero-config.d.ts +14 -4
  10. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  11. package/out/zero-cache/src/config/zero-config.js +26 -8
  12. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  13. package/out/zero-cache/src/db/transaction-pool.d.ts +5 -2
  14. package/out/zero-cache/src/db/transaction-pool.d.ts.map +1 -1
  15. package/out/zero-cache/src/db/transaction-pool.js +5 -3
  16. package/out/zero-cache/src/db/transaction-pool.js.map +1 -1
  17. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  18. package/out/zero-cache/src/server/change-streamer.js +24 -13
  19. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  20. package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
  21. package/out/zero-cache/src/server/replicator.js +1 -1
  22. package/out/zero-cache/src/server/replicator.js.map +1 -1
  23. package/out/zero-cache/src/server/runner/run-worker.js +1 -1
  24. package/out/zero-cache/src/server/worker-urls.d.ts +0 -1
  25. package/out/zero-cache/src/server/worker-urls.d.ts.map +1 -1
  26. package/out/zero-cache/src/server/worker-urls.js +1 -2
  27. package/out/zero-cache/src/server/worker-urls.js.map +1 -1
  28. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +1 -1
  29. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
  30. package/out/zero-cache/src/services/change-source/pg/change-source.js +1 -1
  31. package/out/zero-cache/src/services/change-source/pg/decommission.d.ts.map +1 -1
  32. package/out/zero-cache/src/services/change-source/pg/decommission.js +20 -11
  33. package/out/zero-cache/src/services/change-source/pg/decommission.js.map +1 -1
  34. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
  35. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +51 -74
  36. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  37. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts +20 -0
  38. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts.map +1 -1
  39. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js +43 -3
  40. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js.map +1 -1
  41. package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts +24 -1
  42. package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts.map +1 -1
  43. package/out/zero-cache/src/services/change-source/pg/replication-slots.js +35 -5
  44. package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
  45. package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.d.ts +1 -4
  46. package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.d.ts.map +1 -1
  47. package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js +11 -18
  48. package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js.map +1 -1
  49. package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts.map +1 -1
  50. package/out/zero-cache/src/services/change-streamer/backup-monitor.js +8 -3
  51. package/out/zero-cache/src/services/change-streamer/backup-monitor.js.map +1 -1
  52. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.d.ts +34 -0
  53. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.d.ts.map +1 -0
  54. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js +67 -0
  55. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js.map +1 -0
  56. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +2 -4
  57. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  58. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +8 -2
  59. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  60. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +34 -13
  61. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
  62. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +149 -27
  63. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  64. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +3 -9
  65. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
  66. package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
  67. package/out/zero-cache/src/services/change-streamer/shard-sampling.d.ts +11 -0
  68. package/out/zero-cache/src/services/change-streamer/shard-sampling.d.ts.map +1 -0
  69. package/out/zero-cache/src/services/change-streamer/shard-sampling.js +19 -0
  70. package/out/zero-cache/src/services/change-streamer/shard-sampling.js.map +1 -0
  71. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.d.ts +11 -1
  72. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.d.ts.map +1 -1
  73. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +38 -5
  74. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -1
  75. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.d.ts +25 -1
  76. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.d.ts.map +1 -1
  77. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js +95 -12
  78. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js.map +1 -1
  79. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.d.ts +83 -0
  80. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.d.ts.map +1 -0
  81. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js +417 -0
  82. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js.map +1 -0
  83. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.d.ts +73 -0
  84. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.d.ts.map +1 -0
  85. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js +157 -0
  86. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js.map +1 -0
  87. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.d.ts +1 -1
  88. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.d.ts.map +1 -1
  89. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js +8 -3
  90. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js.map +1 -1
  91. package/out/zero-cache/src/services/change-streamer/storer.d.ts +23 -0
  92. package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
  93. package/out/zero-cache/src/services/change-streamer/storer.js +40 -0
  94. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  95. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.d.ts +29 -0
  96. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.d.ts.map +1 -0
  97. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.js +154 -0
  98. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.js.map +1 -0
  99. package/out/zero-cache/src/services/http-service.d.ts +1 -0
  100. package/out/zero-cache/src/services/http-service.d.ts.map +1 -1
  101. package/out/zero-cache/src/services/http-service.js +7 -3
  102. package/out/zero-cache/src/services/http-service.js.map +1 -1
  103. package/out/zero-cache/src/services/litestream/metrics.d.ts +1 -0
  104. package/out/zero-cache/src/services/litestream/metrics.d.ts.map +1 -1
  105. package/out/zero-cache/src/services/litestream/metrics.js +4 -1
  106. package/out/zero-cache/src/services/litestream/metrics.js.map +1 -1
  107. package/out/zero-cache/src/services/mutagen/mutagen.d.ts.map +1 -1
  108. package/out/zero-cache/src/services/mutagen/mutagen.js +1 -1
  109. package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
  110. package/out/zero-cache/src/services/replicator/change-log-db.d.ts +10 -0
  111. package/out/zero-cache/src/services/replicator/change-log-db.d.ts.map +1 -1
  112. package/out/zero-cache/src/services/replicator/change-log-db.js +15 -1
  113. package/out/zero-cache/src/services/replicator/change-log-db.js.map +1 -1
  114. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.d.ts +3 -2
  115. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.d.ts.map +1 -1
  116. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js +8 -6
  117. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js.map +1 -1
  118. package/out/zero-cache/src/services/view-syncer/client-handler.d.ts +3 -2
  119. package/out/zero-cache/src/services/view-syncer/client-handler.d.ts.map +1 -1
  120. package/out/zero-cache/src/services/view-syncer/client-handler.js +25 -17
  121. package/out/zero-cache/src/services/view-syncer/client-handler.js.map +1 -1
  122. package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts.map +1 -1
  123. package/out/zero-cache/src/services/view-syncer/cvr-store.js +14 -1
  124. package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
  125. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts +3 -3
  126. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  127. package/out/zero-cache/src/services/view-syncer/view-syncer.js +6 -2
  128. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  129. package/out/zero-cache/src/types/downstream.d.ts +11 -0
  130. package/out/zero-cache/src/types/downstream.d.ts.map +1 -0
  131. package/out/zero-cache/src/types/pg.d.ts.map +1 -1
  132. package/out/zero-cache/src/types/pg.js +14 -4
  133. package/out/zero-cache/src/types/pg.js.map +1 -1
  134. package/out/zero-cache/src/types/poke-chunk.d.ts +18 -0
  135. package/out/zero-cache/src/types/poke-chunk.d.ts.map +1 -0
  136. package/out/zero-cache/src/types/poke-chunk.js +57 -0
  137. package/out/zero-cache/src/types/poke-chunk.js.map +1 -0
  138. package/out/zero-cache/src/types/processes.js +1 -4
  139. package/out/zero-cache/src/types/processes.js.map +1 -1
  140. package/out/zero-cache/src/workers/connection.d.ts +22 -4
  141. package/out/zero-cache/src/workers/connection.d.ts.map +1 -1
  142. package/out/zero-cache/src/workers/connection.js +112 -14
  143. package/out/zero-cache/src/workers/connection.js.map +1 -1
  144. package/out/zero-client/src/client/version.js +1 -1
  145. package/out/zero-client/src/client/zero-poke-handler.d.ts +7 -2
  146. package/out/zero-client/src/client/zero-poke-handler.d.ts.map +1 -1
  147. package/out/zero-client/src/client/zero-poke-handler.js +52 -2
  148. package/out/zero-client/src/client/zero-poke-handler.js.map +1 -1
  149. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  150. package/out/zero-client/src/client/zero.js +38 -6
  151. package/out/zero-client/src/client/zero.js.map +1 -1
  152. package/out/zero-protocol/src/down.d.ts +1 -1
  153. package/out/zero-protocol/src/poke.d.ts +89 -7
  154. package/out/zero-protocol/src/poke.d.ts.map +1 -1
  155. package/out/zero-protocol/src/poke.js +16 -8
  156. package/out/zero-protocol/src/poke.js.map +1 -1
  157. package/out/zero-protocol/src/protocol-version.d.ts +12 -7
  158. package/out/zero-protocol/src/protocol-version.d.ts.map +1 -1
  159. package/out/zero-protocol/src/protocol-version.js.map +1 -1
  160. package/out/zql/src/ivm/memory-source.d.ts +10 -2
  161. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  162. package/out/zql/src/ivm/memory-source.js +14 -6
  163. package/out/zql/src/ivm/memory-source.js.map +1 -1
  164. package/out/zql/src/ivm/stream.d.ts +0 -1
  165. package/out/zql/src/ivm/stream.d.ts.map +1 -1
  166. package/out/zql/src/ivm/stream.js +1 -7
  167. package/out/zql/src/ivm/stream.js.map +1 -1
  168. package/out/zql/src/ivm/union-fan-in.d.ts +1 -1
  169. package/out/zql/src/ivm/union-fan-in.d.ts.map +1 -1
  170. package/out/zql/src/ivm/union-fan-in.js +11 -2
  171. package/out/zql/src/ivm/union-fan-in.js.map +1 -1
  172. package/out/zqlite/src/table-source.d.ts.map +1 -1
  173. package/out/zqlite/src/table-source.js +1 -1
  174. package/out/zqlite/src/table-source.js.map +1 -1
  175. package/package.json +1 -1
  176. package/out/zero-cache/src/server/backup-watermark-poller.js +0 -31
  177. package/out/zero-cache/src/server/backup-watermark-poller.js.map +0 -1
  178. package/out/zero-cache/src/services/litestream/vfs-watermark-poller.d.ts +0 -57
  179. package/out/zero-cache/src/services/litestream/vfs-watermark-poller.d.ts.map +0 -1
  180. package/out/zero-cache/src/services/litestream/vfs-watermark-poller.js +0 -137
  181. package/out/zero-cache/src/services/litestream/vfs-watermark-poller.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"storer.js","names":["#lc","#shard","#taskID","#discoveryAddress","#discoveryProtocol","#db","#replicaVersion","#onCommitted","#onFatal","#queue","#backPressureThresholdBytes","#statementTimeoutMs","#changeLogBatchSize","#drainTimeoutMs","#cdc","#approximateQueuedBytes","#running","#readyForMore","#resetBackpressureTimeout","#backpressureTimeout","#stopped","#processQueue","#cancelQueueEntries","#startCatchup","#flushChangeLog","#trackBackfillMetadata","#maybeReleaseBackPressure","#catchup","#cookieStmts","#upsertTableMetadataStmt","#upsertColumnBackfillStmt","#tx","#released"],"sources":["../../../../../../zero-cache/src/services/change-streamer/storer.ts"],"sourcesContent":["import {getHeapStatistics} from 'node:v8';\nimport type {LogContext} from '@rocicorp/logger';\nimport {resolver, type Resolver} from '@rocicorp/resolver';\nimport {type PendingQuery, type Row} from 'postgres';\nimport {AbortError} from '../../../../shared/src/abort-error.ts';\nimport {assert, unreachable} from '../../../../shared/src/asserts.ts';\nimport {Queue} from '../../../../shared/src/queue.ts';\nimport {promiseVoid} from '../../../../shared/src/resolved-promises.ts';\nimport * as v from '../../../../shared/src/valita.ts';\nimport * as Mode from '../../db/mode-enum.ts';\nimport {runTx} from '../../db/run-transaction.ts';\nimport {TransactionPool} from '../../db/transaction-pool.ts';\nimport {type PostgresDB, type PostgresTransaction} from '../../types/pg.ts';\nimport {cdcSchema, type ShardID} from '../../types/shards.ts';\nimport {orTimeout} from '../../types/timeout.ts';\nimport {\n backfillRequestSchema,\n isDataChange,\n isSchemaChange,\n type BackfillID,\n type BackfillRequest,\n type Change,\n type DataChange,\n type Identifier,\n type SchemaChange,\n type TableMetadata,\n} from '../change-source/protocol/current.ts';\nimport {\n type ChangeStreamData,\n type Commit,\n} from '../change-source/protocol/current/downstream.ts';\nimport type {UpstreamStatusMessage} from '../change-source/protocol/current/status.ts';\nimport {\n cookieOps,\n type BackfillCookie,\n type CookieOp,\n type CookieSet,\n type TableMetadataCookie,\n} from '../replicator/change-log-cookies.ts';\nimport type {ReplicatorMode} from '../replicator/replicator.ts';\nimport type {Service} from '../service.ts';\nimport {\n extractChangeSubstring,\n reconstructWatermarkedChange,\n serializeChangeStreamData,\n type ChangeLogEntry,\n} from './change-log-codec.ts';\nimport * as ErrorType from './error-type-enum.ts';\nimport {\n AutoResetSignal,\n markResetRequired,\n type BackfillingColumn,\n type TableMetadataRow,\n} from './schema/tables.ts';\nimport type {Subscriber} from './subscriber.ts';\n\ntype SubscriberAndMode = {\n subscriber: Subscriber;\n mode: ReplicatorMode;\n};\n\ntype QueueEntry =\n | [\n 'change',\n watermark: string,\n json: string,\n orig: Exclude<Change, DataChange> | null, // null for DataChanges\n ]\n | ['ready', callback: () => void]\n | ['subscriber', SubscriberAndMode]\n | ['abort']\n | 'stop';\n\ntype PendingTransaction = {\n pool: TransactionPool;\n preCommitWatermark: string;\n pos: number;\n startingReplicationState: Promise<ReplicationOwner>;\n ack: boolean;\n // changeLog rows buffered for the next multi-row INSERT flush.\n batch: ChangeLogRow[];\n // The most recently issued flush (or metadata) process, awaited to bound\n // pipeline depth and to order the commit-time replicationState update.\n lastFlush: Promise<unknown> | undefined;\n};\n\ntype ReplicationOwner = {\n owner: string | null;\n};\n\nconst backfillRequestsSchema = v.array(backfillRequestSchema);\n\nexport type TuningOptions = {\n backPressureLimitHeapProportion: number;\n statementTimeoutMs: number;\n changeLogBatchSize: number;\n drainTimeoutMs?: number | undefined;\n};\n\n/**\n * A single `changeLog` row, accumulated in {@link PendingTransaction.batch}\n * and written via `json_to_recordset()` (see `#flushChangeLog()`).\n */\ntype ChangeLogRow = {\n watermark: string;\n precommit: string | null;\n pos: number;\n change: string;\n};\n\n/**\n * Handles the storage of changes and the catchup of subscribers\n * that are behind.\n *\n * In the context of catchup and cleanup, it is the responsibility of the\n * Storer to decide whether a client can be caught up, or whether the\n * changes needed to catch a client up have been purged.\n *\n * **Maintained invariant**: The Change DB is only empty for a\n * completely new replica (i.e. initial-sync with no changes from the\n * replication stream).\n * * In this case, all new subscribers are expected start from the\n * `replicaVersion`, which is the version at which initial sync\n * was performed, and any attempts to catchup from a different\n * point fail.\n *\n * Conversely, if non-initial changes have flowed through the system\n * (i.e. via the replication stream), the ChangeDB must *not* be empty,\n * and the earliest change in the `changeLog` represents the earliest\n * \"commit\" from (after) which a subscriber can be caught up.\n * * Any attempts to catchup from an earlier point must fail with\n * a `WatermarkTooOld` error.\n * * Failure to do so could result in streaming changes to the\n * subscriber such that there is a gap in its replication history.\n *\n * Note: Subscribers (i.e. `incremental-syncer`) consider an \"error\" signal\n * an unrecoverable error and shut down in response. This allows the\n * production system to replace it with a new task and fresh copy of the\n * replica backup.\n */\nexport class Storer implements Service {\n readonly id = 'storer';\n readonly #lc: LogContext;\n readonly #shard: ShardID;\n readonly #taskID: string;\n readonly #discoveryAddress: string;\n readonly #discoveryProtocol: string;\n readonly #db: PostgresDB;\n readonly #replicaVersion: string;\n readonly #onCommitted: (c: Commit) => void;\n readonly #onFatal: (err: Error) => void;\n readonly #queue = new Queue<QueueEntry>();\n readonly #backPressureThresholdBytes: number;\n readonly #statementTimeoutMs: number;\n readonly #changeLogBatchSize: number;\n readonly #drainTimeoutMs: number;\n\n #approximateQueuedBytes = 0;\n #running = false;\n\n constructor(\n lc: LogContext,\n shard: ShardID,\n taskID: string,\n discoveryAddress: string,\n discoveryProtocol: string,\n db: PostgresDB,\n replicaVersion: string,\n onCommitted: (c: Commit | UpstreamStatusMessage) => void,\n onFatal: (err: Error) => void,\n {\n backPressureLimitHeapProportion,\n statementTimeoutMs,\n changeLogBatchSize,\n drainTimeoutMs = 30_000,\n }: TuningOptions,\n ) {\n this.#lc = lc.withContext('component', 'change-log');\n this.#shard = shard;\n this.#taskID = taskID;\n this.#discoveryAddress = discoveryAddress;\n this.#discoveryProtocol = discoveryProtocol;\n this.#db = db;\n this.#replicaVersion = replicaVersion;\n this.#onCommitted = onCommitted;\n this.#onFatal = onFatal;\n this.#statementTimeoutMs = statementTimeoutMs;\n this.#changeLogBatchSize = Math.max(1, changeLogBatchSize);\n this.#drainTimeoutMs = drainTimeoutMs;\n\n const heapStats = getHeapStatistics();\n this.#backPressureThresholdBytes =\n (heapStats.heap_size_limit - heapStats.used_heap_size) *\n backPressureLimitHeapProportion;\n\n this.#lc.info?.(\n `Using up to ${(this.#backPressureThresholdBytes / 1024 ** 2).toFixed(2)} MB of ` +\n `--max-old-space-size (~${(heapStats.heap_size_limit / 1024 ** 2).toFixed(2)} MB) ` +\n `to absorb upstream spikes`,\n {heapStats},\n );\n }\n\n // For readability in SQL statements.\n #cdc(table: string) {\n return this.#db(`${cdcSchema(this.#shard)}.${table}`);\n }\n\n async assumeOwnership(purgeLock?: PurgeLock | null) {\n const db = this.#db;\n const owner = this.#taskID;\n const ownerAddress = this.#discoveryAddress;\n const ownerProtocol = this.#discoveryProtocol;\n // we omit `ws://` so that old view syncer versions that are not expecting the protocol continue to not get it\n const addressWithProtocol =\n ownerProtocol === 'ws'\n ? ownerAddress\n : `${ownerProtocol}://${ownerAddress}`;\n this.#lc.info?.(`assuming ownership at ${addressWithProtocol}`);\n const start = performance.now();\n await db`UPDATE ${this.#cdc('replicationState')} SET ${db({owner, ownerAddress: addressWithProtocol})}`;\n const elapsed = (performance.now() - start).toFixed(2);\n this.#lc.info?.(\n `assumed ownership at ${addressWithProtocol} (${elapsed} ms)`,\n );\n\n if (purgeLock) {\n // Once ownership has been assumed, any initial purge-lock preventing the\n // purging of change-log records can be released, as a change-streamer\n // that was attempting to purge records will correspondingly abort on the\n // ownership check.\n void purgeLock.release();\n }\n }\n\n /**\n * The whole of what a stream connection starts from: where to resume, what to\n * ask the change source to backfill, and the raw cookie set those requests\n * were derived from.\n *\n * All four statements run in one REPEATABLE READ transaction, so they see one\n * snapshot. That is invariant 15 — the resume watermark and the cookies must\n * come from the same store, read at the same position — and it is why the\n * cookies are read here rather than by a second call: a cookie set paired\n * with a watermark it was not folded to loses every backfill that completed\n * in the interval, and those rows are not replayable from the slot.\n *\n * `cookies` is not `backfillRequests` in another shape. The request list is\n * driven off `backfilling`, so it drops the metadata of every table with no\n * in-flight backfill — correct for starting a stream, lossy as the cookie\n * snapshot that the SQLite change log continues folding onto.\n */\n async getStartStreamInitializationParameters(): Promise<{\n lastWatermark: string;\n backfillRequests: BackfillRequest[];\n cookies: CookieSet;\n }> {\n const [[{lastWatermark}], result, tableMetadata, backfilling] = await runTx(\n this.#db,\n sql => [\n sql<{lastWatermark: string}[]>`\n SELECT \"lastWatermark\" FROM ${this.#cdc('replicationState')}`,\n\n // Formats a BackfillRequest using json_object_agg() to construct the\n // `columns` object. It is LEFT JOIN'ed with the `tableMetadata` table\n // to make it optional and possibly `null`.\n sql`\n SELECT\n json_build_object(\n 'schema', b.\"schema\",\n 'name', b.\"table\",\n 'metadata', t.\"metadata\"\n ) as \"table\",\n json_object_agg(b.\"column\", b.\"backfill\")\n as \"columns\"\n FROM ${this.#cdc('backfilling')} as b\n LEFT JOIN ${this.#cdc('tableMetadata')} as t\n ON (b.\"schema\" = t.\"schema\" AND b.\"table\" = t.\"table\")\n GROUP BY b.\"schema\", b.\"table\", t.\"metadata\"\n `,\n\n // Ordered by primary key, so that this set and the SQLite change log's\n // can be compared row for row. `COLLATE \"C\"` because that comparison is\n // against a store whose TEXT columns sort by byte: a linguistic\n // collation orders `foo-bar` and `foobar` differently than SQLite's\n // BINARY does, which would read as a divergence rather than as the\n // identical set it is.\n sql<TableMetadataCookie[]>`\n SELECT \"schema\", \"table\", \"metadata\" FROM ${this.#cdc('tableMetadata')}\n ORDER BY \"schema\" COLLATE \"C\", \"table\" COLLATE \"C\"`,\n\n sql<BackfillCookie[]>`\n SELECT \"schema\", \"table\", \"column\", \"backfill\" FROM ${this.#cdc('backfilling')}\n ORDER BY \"schema\" COLLATE \"C\", \"table\" COLLATE \"C\", \"column\" COLLATE \"C\"`,\n ],\n {mode: Mode.READONLY},\n );\n\n return {\n lastWatermark,\n backfillRequests: v.parse(result, backfillRequestsSchema),\n cookies: {\n tableMetadata: [...tableMetadata],\n backfilling: [...backfilling],\n },\n };\n }\n\n async getMinWatermarkForCatchup(): Promise<string | null> {\n const [{minWatermark}] = await this.#db<{minWatermark: string | null}[]>\n /*sql*/ `\n SELECT min(watermark) as \"minWatermark\" FROM ${this.#cdc('changeLog')}`;\n return minWatermark;\n }\n\n purgeRecordsBefore(watermark: string): Promise<number> {\n return runTx(this.#db, async sql => {\n // This NOWAIT pre-check is an optimization to abort the transaction\n // (and release associated resources) early.\n await sql<{watermark: string}[]>`\n SELECT watermark FROM ${this.#cdc('changeLog')}\n ORDER BY watermark, pos LIMIT 1\n FOR UPDATE NOWAIT\n `;\n // If the row is purge-locked by an incoming replication-manager, it\n // will assume ownership of the change-log before releasing the lock.\n // This DELETE blocks until the lock is released, allowing the change\n // in ownership to be reliably detected (and the transaction aborted)\n // in the subsequent check.\n const [{deleted}] = await sql<{deleted: bigint}[]>`\n -- The backup watermark can be ahead of the durable changeLog if the\n -- storer is behind but the backup replica has consumed forwarded\n -- changes. Preserve the latest durable changeLog transaction as the\n -- catchup boundary instead of assuming the backup watermark exists.\n -- The storer inserts each changeLog transaction atomically, so any\n -- durable row for a watermark implies the full transaction is durable.\n WITH keep AS (\n SELECT max(watermark) AS watermark\n FROM ${this.#cdc('changeLog')}\n ), purged AS (\n DELETE FROM ${this.#cdc('changeLog')} WHERE watermark < ${watermark} \n AND watermark < (SELECT watermark FROM keep)\n RETURNING watermark, pos\n ) SELECT COUNT(*) as deleted FROM purged;`;\n\n const [{owner}] = await sql<ReplicationOwner[]>`\n SELECT \"owner\" FROM ${this.#cdc('replicationState')} FOR SHARE`;\n if (owner !== this.#taskID) {\n throw new AbortError(\n `aborting changeLog purge to ${watermark} because ownership has been taken by ${owner}`,\n );\n }\n return Number(deleted);\n });\n }\n\n /**\n * @returns The JSON stringified stream message to be sent downstream.\n */\n store(watermark: string, data: ChangeStreamData) {\n // Eagerly stringify the JSON payload to:\n // - avoid redundant stringification when fanning out to subscribers\n // - efficiently estimate the amount of memory the payload consumes\n const json = serializeChangeStreamData(data);\n this.#approximateQueuedBytes += json.length;\n\n const change = data[1];\n this.#queue.enqueue([\n 'change',\n watermark,\n json,\n isDataChange(change) ? null : change, // drop DataChanges to save memory\n ]);\n\n return json;\n }\n\n abort() {\n this.#queue.enqueue(['abort']);\n }\n\n catchup(subscriber: Subscriber, mode: ReplicatorMode) {\n this.#queue.enqueue(['subscriber', {subscriber, mode}]);\n }\n\n #readyForMore: Resolver<void> | null = null;\n #backpressureTimeout: NodeJS.Timeout | undefined;\n\n readyForMore(): Promise<void> | undefined {\n if (!this.#running) {\n return undefined;\n }\n if (\n this.#readyForMore === null &&\n this.#approximateQueuedBytes > this.#backPressureThresholdBytes\n ) {\n this.#lc.warn?.(\n `applying back pressure with ${this.#queue.size()} queued changes (~${(this.#approximateQueuedBytes / 1024 ** 2).toFixed(2)} MB)\\n` +\n `\\n` +\n `To inspect changeLog backlog in your change DB:\\n` +\n ` SELECT\\n` +\n ` (change->'relation'->>'schema') || '.' || (change->'relation'->>'name') AS table_name,\\n` +\n ` change->>'tag' AS operation,\\n` +\n ` COUNT(*) AS count\\n` +\n ` FROM \"<app_id>/cdc\".\"changeLog\"\\n` +\n ` GROUP BY 1, 2\\n` +\n ` ORDER BY 3 DESC\\n` +\n ` LIMIT 20;`,\n );\n this.#readyForMore = resolver();\n this.#resetBackpressureTimeout(true);\n }\n return this.#readyForMore?.promise;\n }\n\n #resetBackpressureTimeout(reschedule: boolean) {\n clearTimeout(this.#backpressureTimeout);\n this.#backpressureTimeout = reschedule\n ? setTimeout(() => {\n this.#readyForMore?.reject(\n new AbortError(\n `No statement processed within the last ${this.#statementTimeoutMs}ms. Considering the change-log to be wedged.`,\n ),\n );\n this.#readyForMore = null;\n }, this.#statementTimeoutMs)\n : undefined;\n }\n\n #maybeReleaseBackPressure() {\n if (this.#readyForMore !== null) {\n // Wait for at least 20% of the threshold to free up.\n if (\n this.#approximateQueuedBytes <\n this.#backPressureThresholdBytes * 0.8\n ) {\n this.#lc.info?.(\n `releasing back pressure with ${this.#queue.size()} queued changes (~${(this.#approximateQueuedBytes / 1024 ** 2).toFixed(2)} MB)`,\n );\n this.#readyForMore.resolve();\n this.#readyForMore = null;\n this.#resetBackpressureTimeout(false);\n } else {\n this.#resetBackpressureTimeout(true);\n }\n }\n }\n\n /**\n * Flushes any buffered {@link PendingTransaction.batch} rows to the changeLog.\n *\n * Uses `json_to_recordset()` so the batch is a single JSON parameter: the\n * statement text stays constant regardless of batch size, avoiding the\n * unbounded prepared-statement variants (and Postgres memory growth) that a\n * multi-row INSERT would produce. See rocicorp/mono#3511.\n *\n * Returns (and updates) {@link PendingTransaction.lastFlush}; a no-op when the\n * batch is empty.\n */\n #flushChangeLog(tx: PendingTransaction): Promise<unknown> | undefined {\n const {batch} = tx;\n if (batch.length === 0) {\n return tx.lastFlush;\n }\n tx.batch = [];\n tx.lastFlush = tx.pool.process(sql => [\n sql`\n INSERT INTO ${this.#cdc('changeLog')} (\"watermark\", \"pos\", \"change\", \"precommit\")\n SELECT \"watermark\", \"pos\", \"change\"::json, \"precommit\"\n FROM json_to_recordset(${batch}) AS x(\n \"watermark\" TEXT,\n \"pos\" INT8,\n \"change\" TEXT,\n \"precommit\" TEXT\n )`,\n ]);\n return tx.lastFlush;\n }\n\n #stopped = promiseVoid;\n\n /**\n * Runs the storer loop until {@link stop()} is called, or an error is thrown.\n * Once {@link run()} completes, it can be called again.\n */\n async run() {\n assert(!this.#running, `storer is already running`);\n\n const {promise: stopped, resolve: signalStopped} = resolver();\n this.#running = true;\n this.#stopped = stopped;\n\n this.#lc.info?.('starting storer');\n let err: unknown;\n try {\n await this.#processQueue();\n } catch (e) {\n err = e; // used in finally\n throw e;\n } finally {\n // Release any pending backpressure so the upstream can proceed\n if (this.#readyForMore !== null) {\n this.#readyForMore.resolve();\n this.#readyForMore = null;\n }\n this.#resetBackpressureTimeout(false);\n this.#cancelQueueEntries(\n this.#queue.drain().filter(entry => entry !== undefined),\n err,\n );\n this.#running = false;\n signalStopped();\n this.#lc.info?.('storer stopped');\n }\n }\n\n #cancelQueueEntries(queue: QueueEntry[], e: unknown) {\n if (queue.length === 0) {\n return;\n }\n this.#lc.info?.(\n `canceling ${queue.length} entries from the changeLog queue`,\n );\n const err = e instanceof Error ? e : new AbortError('server shutting down');\n for (const entry of queue) {\n if (entry === 'stop') {\n continue;\n }\n const type = entry[0];\n switch (type) {\n case 'subscriber': {\n // Disconnect subscribers waiting to be caught up so that they can\n // reconnect and try again.\n const {subscriber} = entry[1];\n this.#lc.info?.(`disconnecting ${subscriber.id}`);\n subscriber.fail(err);\n break;\n }\n }\n }\n }\n\n async #processQueue() {\n let tx: PendingTransaction | null = null;\n let msg: QueueEntry | false;\n\n const catchupQueue: SubscriberAndMode[] = [];\n try {\n while ((msg = await this.#queue.dequeue()) !== 'stop') {\n const [msgType] = msg;\n switch (msgType) {\n case 'ready': {\n const signalReady = msg[1];\n signalReady();\n continue;\n }\n case 'subscriber': {\n const subscriber = msg[1];\n if (tx) {\n catchupQueue.push(subscriber); // Wait for the current tx to complete.\n } else {\n await this.#startCatchup([subscriber]); // Catch up immediately.\n }\n continue;\n }\n case 'abort': {\n if (tx) {\n tx.pool.abort();\n await tx.pool.done();\n tx = null;\n }\n continue;\n }\n }\n // msgType === 'change'\n const [_, watermark, json, change] = msg;\n const tag = change?.tag;\n this.#approximateQueuedBytes -= json.length;\n\n if (tag === 'begin') {\n assert(!tx, 'received BEGIN in the middle of a transaction');\n const {promise, resolve, reject} = resolver<ReplicationOwner>();\n void promise.catch(() => {}); // handle rejections before the await\n tx = {\n pool: new TransactionPool(\n this.#lc.withContext('watermark', watermark),\n {\n mode: Mode.READ_COMMITTED,\n statementResponseTimeout: this.#statementTimeoutMs,\n },\n ),\n preCommitWatermark: watermark,\n pos: 0,\n startingReplicationState: promise,\n ack: !change.skipAck,\n batch: [],\n lastFlush: undefined,\n };\n tx.pool.run(this.#db);\n // Acquire a lock on the replicationState row to detect and/or prevent\n // a concurrent ownership change.\n void tx.pool.process(tx => {\n tx<ReplicationOwner[]> /*sql*/ `\n SELECT \"owner\" FROM ${this.#cdc('replicationState')} FOR UPDATE`.then(\n ([result]) => resolve(result),\n reject,\n );\n return [];\n });\n } else {\n assert(tx, () => `received change outside of transaction: ${json}`);\n tx.pos++;\n }\n\n const entry: ChangeLogRow = {\n watermark: tag === 'commit' ? watermark : tx.preCommitWatermark,\n precommit: tag === 'commit' ? tx.preCommitWatermark : null,\n pos: tx.pos,\n // For backwards compatibility, only the change message is stored\n // in the cdc changeLog.\n change: extractChangeSubstring(json, tag),\n };\n\n if (change !== null && isSchemaChange(change)) {\n // Schema changes carry backfill / table-metadata statements that\n // must be applied in stream order relative to the changeLog rows.\n // Flush any buffered rows first, then write this row together with\n // its metadata statements as a single unit (preserving the previous\n // per-change ordering for schema changes).\n await this.#flushChangeLog(tx);\n tx.lastFlush = tx.pool.process(sql => [\n sql`INSERT INTO ${this.#cdc('changeLog')} ${sql(entry)}`,\n ...this.#trackBackfillMetadata(sql, change),\n ]);\n } else {\n // Accumulate plain changeLog rows (begin, data changes, commit) and\n // write them as a single multi-row INSERT. Collapsing the per-change\n // single-row INSERTs into batches is the dominant cost reduction for\n // large transactions, where the previous one-statement-per-change\n // path dominated the upstream replication lag.\n tx.batch.push(entry);\n if (tx.batch.length >= this.#changeLogBatchSize) {\n // Bound pipeline depth (and thus memory) by awaiting the previous\n // flush before issuing the next. This is the batched analog of the\n // previous per-100-statement backpressure await, and likewise\n // guards against memory blowup on very large transactions.\n const prevFlush = tx.lastFlush;\n void this.#flushChangeLog(tx);\n await prevFlush;\n }\n }\n this.#maybeReleaseBackPressure();\n\n if (tag === 'commit') {\n // Flush any remaining buffered changeLog rows (including this commit\n // row) before updating the replication state, so the state update is\n // ordered after all changeLog inserts for this transaction.\n void this.#flushChangeLog(tx);\n\n const {owner} = await tx.startingReplicationState;\n if (owner !== this.#taskID) {\n // Ownership change reflected in the replicationState read in 'begin'.\n tx.pool.fail(\n new AbortError(\n `changeLog ownership has been assumed by ${owner}`,\n ),\n );\n } else {\n // Update the replication state.\n const lastWatermark = watermark;\n void tx.pool.process(tx => [\n tx`\n UPDATE ${this.#cdc('replicationState')} SET ${tx({lastWatermark})}`,\n ]);\n tx.pool.setDone();\n }\n\n await tx.pool.done();\n\n // ACK the LSN to the upstream Postgres.\n if (tx.ack) {\n this.#onCommitted(['commit', change, {watermark}]);\n }\n tx = null;\n\n // Before beginning the next transaction, open a READONLY snapshot to\n // concurrently catchup any queued subscribers.\n await this.#startCatchup(catchupQueue.splice(0));\n } else if (tag === 'rollback') {\n // Aborted transactions are not stored in the changeLog. Abort the current tx\n // and process catchup of subscribers that were waiting for it to end.\n tx.pool.abort();\n await tx.pool.done();\n tx = null;\n\n await this.#startCatchup(catchupQueue.splice(0));\n }\n }\n } catch (e) {\n catchupQueue.forEach(({subscriber}) => subscriber.fail(e));\n throw e;\n }\n }\n\n async #startCatchup(subs: SubscriberAndMode[]) {\n if (subs.length === 0) {\n return;\n }\n\n const lc = this.#lc.withContext('pool', 'catchup');\n // TODO: Consider setting initialWorkers to accomodate parallel\n // catchups of multiple subscribers. The tricky part is\n // staying within the db's max connections.\n const reader = new TransactionPool(lc, {mode: Mode.READONLY});\n reader.run(this.#db);\n\n let lastWatermark: string | undefined;\n try {\n // Ensure that the transaction has started (and is thus holding a snapshot\n // of the database) before continuing on to commit more changes. This is\n // done by performing a single read on the db, which determines the\n // snapshot for the REPEATABLE_READ transaction.\n [{lastWatermark}] = await reader.processReadTask(\n sql => sql<{lastWatermark: string}[]>`\n SELECT \"lastWatermark\" FROM ${this.#cdc('replicationState')}\n `,\n );\n } catch (e) {\n subs.map(({subscriber}) => subscriber.fail(e));\n throw e;\n }\n\n // Run the actual catchup queries in the background. Errors are handled in\n // #catchup() by disconnecting the associated subscriber.\n void Promise.all(\n subs.map(sub =>\n this.#catchup(\n lc.withContext('subscriber', sub.subscriber.id),\n sub,\n lastWatermark,\n reader,\n ),\n ),\n ).finally(() => reader.setDone());\n }\n\n async #catchup(\n lc: LogContext,\n {subscriber: sub, mode}: SubscriberAndMode,\n lastWatermark: string,\n reader: TransactionPool,\n ) {\n try {\n lc.info?.(`starting catchup`);\n await reader.processReadTask(async tx => {\n lc.info?.(`catching up`);\n const start = Date.now();\n\n // When starting from initial-sync, there won't be a change with a watermark\n // equal to the replica version. This is the empty changeLog scenario.\n let watermarkFound = sub.watermark === this.#replicaVersion;\n let count = 0;\n let lastBatchConsumed: Promise<unknown> | undefined;\n\n for await (const entries of tx<ChangeLogEntry[]> /*sql*/ `\n SELECT watermark, change->'tag' as tag, change::text FROM ${this.#cdc('changeLog')}\n WHERE watermark >= ${sub.watermark}\n AND watermark <= ${lastWatermark}\n ORDER BY watermark, pos`.cursor(2000)) {\n // Wait for the last batch of entries to be consumed by the\n // subscriber before sending down the current batch. This pipelining\n // allows one batch of changes to be received from the change-db\n // while the previous batch of changes are sent to the subscriber,\n // resulting in flow control that caps the number of changes\n // referenced in memory to 2 * batch-size.\n const start = performance.now();\n await lastBatchConsumed;\n const elapsed = performance.now() - start;\n if (lastBatchConsumed) {\n lc[elapsed > 100 ? 'info' : 'debug']?.(\n `waited ${elapsed.toFixed(3)} ms for ${sub.id} to consume last batch of catchup entries`,\n );\n }\n\n for (const entry of entries) {\n if (entry.watermark === sub.watermark) {\n // This should be the first entry.\n // Catchup starts from *after* the watermark.\n watermarkFound = true;\n } else if (watermarkFound) {\n lastBatchConsumed = sub.catchup(\n reconstructWatermarkedChange(entry),\n );\n count++;\n } else if (mode === 'backup') {\n throw new AutoResetSignal(\n `backup replica at watermark ${sub.watermark} is behind change db: ${entry.watermark})`,\n );\n } else {\n lc.warn?.(\n `rejecting subscriber at watermark ${sub.watermark} (earliest watermark: ${entry.watermark})`,\n );\n sub.close(\n ErrorType.WatermarkTooOld,\n `earliest supported watermark is ${entry.watermark} (requested ${sub.watermark})`,\n );\n return;\n }\n }\n }\n if (watermarkFound) {\n await lastBatchConsumed;\n lc.info?.(\n `caught up ${sub.id} with ${count} changes (${\n Date.now() - start\n } ms)`,\n );\n } else {\n // The subscriber is ahead of the latest durable changeLog entry\n // (lastWatermark). This can legitimately happen: changes are\n // forwarded to subscribers (the backup replica and view-syncers)\n // concurrently with — and can outrun — the durable store, so a\n // replica may briefly lead the change DB after the storer falls\n // behind or the change-streamer restarts. No catchup is possible or\n // needed; once the change DB catches back up, forwarding resumes and\n // the subscriber dedups any watermarks it already has. Unlike the\n // AutoResetSignal / WatermarkTooOld cases above, this is not a gap in\n // replication history, so the subscriber is simply marked caught up.\n lc.warn?.(\n `subscriber ${sub.id} at watermark ${sub.watermark} is ahead of ` +\n `the latest durable watermark ${lastWatermark}; waiting for the ` +\n `change DB to catch up`,\n );\n }\n // Start draining messages buffered during catchup. The returned promise\n // is intentionally not awaited here: while the drain is in progress,\n // new sends keep appending to the subscriber backlog and inherit its\n // byte-based backpressure.\n void sub.setCaughtUp();\n });\n } catch (err) {\n lc.error?.(`error while catching up subscriber ${sub.id}`, err);\n if (err instanceof AutoResetSignal) {\n await markResetRequired(this.#db, this.#shard);\n this.#onFatal(err);\n }\n sub.fail(err);\n }\n }\n\n /**\n * Returns the db statements necessary to track backfill and table metadata\n * presented in the `change`, if any.\n *\n * This is the Postgres interpreter of {@link cookieOps}, which is also\n * interpreted against the SQLite change log by `ChangeLogCookieWriter`. The\n * two stores have to agree on every transition forever, and the failure mode\n * if they drift is a backfill that is silently never re-requested — so the\n * decision of what a schema change *means* lives in one place and only its\n * transport lives here.\n */\n #trackBackfillMetadata(sql: PostgresTransaction, change: SchemaChange) {\n return cookieOps(change).flatMap(op => this.#cookieStmts(sql, op));\n }\n\n #cookieStmts(sql: PostgresTransaction, op: CookieOp): PendingQuery<Row[]>[] {\n switch (op.op) {\n case 'upsert-metadata':\n return [this.#upsertTableMetadataStmt(sql, op.table, op.metadata)];\n\n case 'upsert-backfill':\n return [\n this.#upsertColumnBackfillStmt(sql, op.table, op.column, op.backfill),\n ];\n\n case 'rename-table': {\n const {old} = op;\n const row = {schema: op.new.schema, table: op.new.name};\n return [\n sql`UPDATE ${this.#cdc('tableMetadata')} SET ${sql(row)}\n WHERE \"schema\" = ${old.schema} AND \"table\" = ${old.name}`,\n sql`UPDATE ${this.#cdc('backfilling')} SET ${sql(row)}\n WHERE \"schema\" = ${old.schema} AND \"table\" = ${old.name}`,\n ];\n }\n\n case 'drop-table': {\n const {schema, name} = op.table;\n return [\n sql`DELETE FROM ${this.#cdc('tableMetadata')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${name}`,\n sql`DELETE FROM ${this.#cdc('backfilling')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${name}`,\n ];\n }\n\n case 'rename-column': {\n const {schema, name: table} = op.table;\n return [\n sql`UPDATE ${this.#cdc('backfilling')} SET \"column\" = ${op.new}\n WHERE \"schema\" = ${schema} AND \"table\" = ${table} AND \"column\" = ${op.old}`,\n ];\n }\n\n case 'drop-column': {\n const {schema, name} = op.table;\n return [\n sql`DELETE FROM ${this.#cdc('backfilling')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${name} AND \"column\" = ${op.column}`,\n ];\n }\n\n case 'complete-backfill': {\n const {schema, name: table} = op.table;\n return [\n sql`DELETE FROM ${this.#cdc('backfilling')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${table} AND \"column\" IN ${sql([...op.columns])}`,\n ];\n }\n\n default:\n unreachable(op);\n }\n }\n\n #upsertTableMetadataStmt(\n sql: PostgresTransaction,\n {schema, name: table}: Identifier,\n metadata: TableMetadata,\n ) {\n const row: TableMetadataRow = {schema, table, metadata};\n return sql`\n INSERT INTO ${this.#cdc('tableMetadata')} ${sql(row)}\n ON CONFLICT (\"schema\", \"table\")\n DO UPDATE SET ${sql(row)};\n `;\n }\n\n #upsertColumnBackfillStmt(\n sql: PostgresTransaction,\n {schema, name: table}: Identifier,\n column: string,\n backfill: BackfillID,\n ) {\n const row: BackfillingColumn = {schema, table, column, backfill};\n return sql`\n INSERT INTO ${this.#cdc('backfilling')} ${sql(row)}\n ON CONFLICT (\"schema\", \"table\", \"column\")\n DO UPDATE SET ${sql(row)};\n `;\n }\n\n /**\n * Waits until all currently queued entries have been processed.\n * This is only used in tests.\n */\n async allProcessed() {\n if (this.#running) {\n const {promise, resolve} = resolver();\n this.#queue.enqueue(['ready', resolve]);\n await promise;\n }\n }\n\n /**\n * Stops the storer and waits up to a drain timeout for entries to drain,\n * throwing an exception if it doesn't drain in time, in order to abort\n * the server when PG (or the connection to it) appears to be wedged.\n */\n async stop() {\n if (this.#running) {\n this.#lc.info?.(`draining ${this.#queue.size()} changeLog entries`);\n this.abort(); // for cleanliness, abort any open transactions\n this.#queue.enqueue('stop');\n }\n if (\n (await orTimeout(this.#stopped, this.#drainTimeoutMs)) === 'timed-out'\n ) {\n throw new AbortError(\n `changeLog did not drain within ${this.#drainTimeoutMs}ms`,\n );\n }\n }\n}\n\nexport class PurgeLock {\n readonly #lc: LogContext;\n readonly #tx: TransactionPool;\n readonly replicaVersion: string;\n readonly minWatermark: string;\n\n constructor(\n lc: LogContext,\n tx: TransactionPool,\n replicaVersion: string,\n watermark: string,\n ) {\n this.#lc = lc;\n this.#tx = tx;\n this.replicaVersion = replicaVersion;\n this.minWatermark = watermark;\n }\n\n #released = false;\n\n async release() {\n if (this.#released) {\n return;\n }\n this.#released = true;\n this.#tx.setDone();\n await this.#tx\n .done()\n .catch(e => this.#lc.warn?.(`error from purge-lock release`, e));\n this.#lc.info?.(`released purge lock on ${this.minWatermark}`);\n }\n}\n\nexport class PurgeLocker {\n readonly #lc: LogContext;\n readonly #shard: ShardID;\n readonly #db: PostgresDB;\n\n constructor(lc: LogContext, shard: ShardID, db: PostgresDB) {\n this.#lc = lc.withContext('component', 'purge-locker');\n this.#shard = shard;\n this.#db = db;\n }\n\n // For readability in SQL statements.\n #cdc(table: string) {\n return this.#db(`${cdcSchema(this.#shard)}.${table}`);\n }\n\n async acquire() {\n const tx = new TransactionPool(this.#lc, {mode: Mode.READ_COMMITTED}).run(\n this.#db,\n );\n const row = await tx.processReadTask(\n sql => sql<{watermark: string}[]>`\n SELECT watermark FROM ${this.#cdc('changeLog')}\n ORDER BY watermark, pos LIMIT 1\n FOR SHARE \n `,\n );\n if (row.length === 0) {\n this.#lc.info?.(`changeLog is empty. No rows to purge-lock.`);\n tx.setDone();\n await tx.done();\n return null;\n }\n const [{watermark}] = row;\n const [{replicaVersion}] = await tx.processReadTask(\n sql => sql<{replicaVersion: string}[]>`\n SELECT \"replicaVersion\" FROM ${this.#cdc('replicationConfig')}\n `,\n );\n this.#lc.info?.(\n `locked watermark ${watermark} from being purged from replica@${replicaVersion}`,\n );\n return new PurgeLock(this.#lc, tx, replicaVersion, watermark);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA0FA,IAAM,yBAAyB,eAAE,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkD5D,IAAa,SAAb,MAAuC;CACrC,KAAc;CACd;CACA;CACA;CACA;CACA;CACA;CACA;CACA;C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AY,aAAa,cAAc;EACrD,KAAKC,SAAS;EACd,KAAKI,MAAM;CACb;CAGA,KAAK,OAAe;EAClB,OAAO,KAAKA,IAAI,GAAG,UAAU,KAAKJ,MAAM,EAAE,GAAG,OAAO;CACtD;CAEA,MAAM,UAAU;EACd,MAAM,KAAK,IAAI,gBAAgB,KAAKD,KAAK,EAAC,MAAM,eAAmB,CAAC,EAAE,IACpE,KAAKK,GACP;EACA,MAAM,MAAM,MAAM,GAAG,iBACnB,QAAO,GAA0B;8BACT,KAAKS,KAAK,WAAW,EAAE;;;KAIjD;EACA,IAAI,IAAI,WAAW,GAAG;GACpB,KAAKd,IAAI,OAAO,4CAA4C;GAC5D,GAAG,QAAQ;GACX,MAAM,GAAG,KAAK;GACd,OAAO;EACT;EACA,MAAM,CAAC,EAAC,eAAc;EACtB,MAAM,CAAC,EAAC,oBAAmB,MAAM,GAAG,iBAClC,QAAO,GAA+B;uCACL,KAAKc,KAAK,mBAAmB,EAAE;OAElE;EACA,KAAKd,IAAI,OACP,oBAAoB,UAAU,kCAAkC,gBAClE;EACA,OAAO,IAAI,UAAU,KAAKA,KAAK,IAAI,gBAAgB,SAAS;CAC9D;AACF"}
1
+ {"version":3,"file":"storer.js","names":["#lc","#shard","#taskID","#discoveryAddress","#discoveryProtocol","#db","#replicaVersion","#onCommitted","#onFatal","#queue","#backPressureThresholdBytes","#statementTimeoutMs","#changeLogBatchSize","#drainTimeoutMs","#cdc","#approximateQueuedBytes","#running","#readyForMore","#resetBackpressureTimeout","#backpressureTimeout","#stopped","#processQueue","#cancelQueueEntries","#startCatchup","#flushChangeLog","#trackBackfillMetadata","#maybeReleaseBackPressure","#catchup","#cookieStmts","#upsertTableMetadataStmt","#upsertColumnBackfillStmt","#tx","#released"],"sources":["../../../../../../zero-cache/src/services/change-streamer/storer.ts"],"sourcesContent":["import {getHeapStatistics} from 'node:v8';\nimport type {LogContext} from '@rocicorp/logger';\nimport {resolver, type Resolver} from '@rocicorp/resolver';\nimport {type PendingQuery, type Row} from 'postgres';\nimport {AbortError} from '../../../../shared/src/abort-error.ts';\nimport {assert, unreachable} from '../../../../shared/src/asserts.ts';\nimport {Queue} from '../../../../shared/src/queue.ts';\nimport {promiseVoid} from '../../../../shared/src/resolved-promises.ts';\nimport * as v from '../../../../shared/src/valita.ts';\nimport * as Mode from '../../db/mode-enum.ts';\nimport {runTx} from '../../db/run-transaction.ts';\nimport {TransactionPool} from '../../db/transaction-pool.ts';\nimport {type PostgresDB, type PostgresTransaction} from '../../types/pg.ts';\nimport {cdcSchema, type ShardID} from '../../types/shards.ts';\nimport {orTimeout} from '../../types/timeout.ts';\nimport {\n backfillRequestSchema,\n isDataChange,\n isSchemaChange,\n type BackfillID,\n type BackfillRequest,\n type Change,\n type DataChange,\n type Identifier,\n type SchemaChange,\n type TableMetadata,\n} from '../change-source/protocol/current.ts';\nimport {\n type ChangeStreamData,\n type Commit,\n} from '../change-source/protocol/current/downstream.ts';\nimport type {UpstreamStatusMessage} from '../change-source/protocol/current/status.ts';\nimport {\n cookieOps,\n type BackfillCookie,\n type CookieOp,\n type CookieSet,\n type TableMetadataCookie,\n} from '../replicator/change-log-cookies.ts';\nimport type {ReplicatorMode} from '../replicator/replicator.ts';\nimport type {Service} from '../service.ts';\nimport {\n extractChangeSubstring,\n reconstructWatermarkedChange,\n serializeChangeStreamData,\n type ChangeLogEntry,\n} from './change-log-codec.ts';\nimport * as ErrorType from './error-type-enum.ts';\nimport {\n AutoResetSignal,\n markResetRequired,\n type BackfillingColumn,\n type TableMetadataRow,\n} from './schema/tables.ts';\nimport type {Subscriber} from './subscriber.ts';\n\ntype SubscriberAndMode = {\n subscriber: Subscriber;\n mode: ReplicatorMode;\n};\n\ntype QueueEntry =\n | [\n 'change',\n watermark: string,\n json: string,\n orig: Exclude<Change, DataChange> | null, // null for DataChanges\n ]\n | ['ready', callback: () => void]\n | ['subscriber', SubscriberAndMode]\n | ['abort']\n | 'stop';\n\ntype PendingTransaction = {\n pool: TransactionPool;\n preCommitWatermark: string;\n pos: number;\n startingReplicationState: Promise<ReplicationOwner>;\n ack: boolean;\n // changeLog rows buffered for the next multi-row INSERT flush.\n batch: ChangeLogRow[];\n // The most recently issued flush (or metadata) process, awaited to bound\n // pipeline depth and to order the commit-time replicationState update.\n lastFlush: Promise<unknown> | undefined;\n};\n\ntype ReplicationOwner = {\n owner: string | null;\n};\n\nconst backfillRequestsSchema = v.array(backfillRequestSchema);\n\nexport type TuningOptions = {\n backPressureLimitHeapProportion: number;\n statementTimeoutMs: number;\n changeLogBatchSize: number;\n drainTimeoutMs?: number | undefined;\n};\n\n/**\n * A single `changeLog` row, accumulated in {@link PendingTransaction.batch}\n * and written via `json_to_recordset()` (see `#flushChangeLog()`).\n */\ntype ChangeLogRow = {\n watermark: string;\n precommit: string | null;\n pos: number;\n change: string;\n};\n\n/**\n * Handles the storage of changes and the catchup of subscribers\n * that are behind.\n *\n * In the context of catchup and cleanup, it is the responsibility of the\n * Storer to decide whether a client can be caught up, or whether the\n * changes needed to catch a client up have been purged.\n *\n * **Maintained invariant**: The Change DB is only empty for a\n * completely new replica (i.e. initial-sync with no changes from the\n * replication stream).\n * * In this case, all new subscribers are expected start from the\n * `replicaVersion`, which is the version at which initial sync\n * was performed, and any attempts to catchup from a different\n * point fail.\n *\n * Conversely, if non-initial changes have flowed through the system\n * (i.e. via the replication stream), the ChangeDB must *not* be empty,\n * and the earliest change in the `changeLog` represents the earliest\n * \"commit\" from (after) which a subscriber can be caught up.\n * * Any attempts to catchup from an earlier point must fail with\n * a `WatermarkTooOld` error.\n * * Failure to do so could result in streaming changes to the\n * subscriber such that there is a gap in its replication history.\n *\n * Note: Subscribers (i.e. `incremental-syncer`) consider an \"error\" signal\n * an unrecoverable error and shut down in response. This allows the\n * production system to replace it with a new task and fresh copy of the\n * replica backup.\n */\nexport class Storer implements Service {\n readonly id = 'storer';\n readonly #lc: LogContext;\n readonly #shard: ShardID;\n readonly #taskID: string;\n readonly #discoveryAddress: string;\n readonly #discoveryProtocol: string;\n readonly #db: PostgresDB;\n readonly #replicaVersion: string;\n readonly #onCommitted: (c: Commit) => void;\n readonly #onFatal: (err: Error) => void;\n readonly #queue = new Queue<QueueEntry>();\n readonly #backPressureThresholdBytes: number;\n readonly #statementTimeoutMs: number;\n readonly #changeLogBatchSize: number;\n readonly #drainTimeoutMs: number;\n\n #approximateQueuedBytes = 0;\n #running = false;\n\n constructor(\n lc: LogContext,\n shard: ShardID,\n taskID: string,\n discoveryAddress: string,\n discoveryProtocol: string,\n db: PostgresDB,\n replicaVersion: string,\n onCommitted: (c: Commit | UpstreamStatusMessage) => void,\n onFatal: (err: Error) => void,\n {\n backPressureLimitHeapProportion,\n statementTimeoutMs,\n changeLogBatchSize,\n drainTimeoutMs = 30_000,\n }: TuningOptions,\n ) {\n this.#lc = lc.withContext('component', 'change-log');\n this.#shard = shard;\n this.#taskID = taskID;\n this.#discoveryAddress = discoveryAddress;\n this.#discoveryProtocol = discoveryProtocol;\n this.#db = db;\n this.#replicaVersion = replicaVersion;\n this.#onCommitted = onCommitted;\n this.#onFatal = onFatal;\n this.#statementTimeoutMs = statementTimeoutMs;\n this.#changeLogBatchSize = Math.max(1, changeLogBatchSize);\n this.#drainTimeoutMs = drainTimeoutMs;\n\n const heapStats = getHeapStatistics();\n this.#backPressureThresholdBytes =\n (heapStats.heap_size_limit - heapStats.used_heap_size) *\n backPressureLimitHeapProportion;\n\n this.#lc.info?.(\n `Using up to ${(this.#backPressureThresholdBytes / 1024 ** 2).toFixed(2)} MB of ` +\n `--max-old-space-size (~${(heapStats.heap_size_limit / 1024 ** 2).toFixed(2)} MB) ` +\n `to absorb upstream spikes`,\n {heapStats},\n );\n }\n\n // For readability in SQL statements.\n #cdc(table: string) {\n return this.#db(`${cdcSchema(this.#shard)}.${table}`);\n }\n\n async assumeOwnership(purgeLock?: PurgeLock | null) {\n const db = this.#db;\n const owner = this.#taskID;\n const ownerAddress = this.#discoveryAddress;\n const ownerProtocol = this.#discoveryProtocol;\n // we omit `ws://` so that old view syncer versions that are not expecting the protocol continue to not get it\n const addressWithProtocol =\n ownerProtocol === 'ws'\n ? ownerAddress\n : `${ownerProtocol}://${ownerAddress}`;\n this.#lc.info?.(`assuming ownership at ${addressWithProtocol}`);\n const start = performance.now();\n await db`UPDATE ${this.#cdc('replicationState')} SET ${db({owner, ownerAddress: addressWithProtocol})}`;\n const elapsed = (performance.now() - start).toFixed(2);\n this.#lc.info?.(\n `assumed ownership at ${addressWithProtocol} (${elapsed} ms)`,\n );\n\n if (purgeLock) {\n // Once ownership has been assumed, any initial purge-lock preventing the\n // purging of change-log records can be released, as a change-streamer\n // that was attempting to purge records will correspondingly abort on the\n // ownership check.\n void purgeLock.release();\n }\n }\n\n /**\n * The whole of what a stream connection starts from: where to resume, what to\n * ask the change source to backfill, and the raw cookie set those requests\n * were derived from.\n *\n * All four statements run in one REPEATABLE READ transaction, so they see one\n * snapshot. That is invariant 15 — the resume watermark and the cookies must\n * come from the same store, read at the same position — and it is why the\n * cookies are read here rather than by a second call: a cookie set paired\n * with a watermark it was not folded to loses every backfill that completed\n * in the interval, and those rows are not replayable from the slot.\n *\n * `cookies` is not `backfillRequests` in another shape. The request list is\n * driven off `backfilling`, so it drops the metadata of every table with no\n * in-flight backfill — correct for starting a stream, lossy as the cookie\n * snapshot that the SQLite change log continues folding onto.\n */\n async getStartStreamInitializationParameters(): Promise<{\n lastWatermark: string;\n backfillRequests: BackfillRequest[];\n cookies: CookieSet;\n }> {\n const [[{lastWatermark}], result, tableMetadata, backfilling] = await runTx(\n this.#db,\n sql => [\n sql<{lastWatermark: string}[]>`\n SELECT \"lastWatermark\" FROM ${this.#cdc('replicationState')}`,\n\n // Formats a BackfillRequest using json_object_agg() to construct the\n // `columns` object. It is LEFT JOIN'ed with the `tableMetadata` table\n // to make it optional and possibly `null`.\n sql`\n SELECT\n json_build_object(\n 'schema', b.\"schema\",\n 'name', b.\"table\",\n 'metadata', t.\"metadata\"\n ) as \"table\",\n json_object_agg(b.\"column\", b.\"backfill\")\n as \"columns\"\n FROM ${this.#cdc('backfilling')} as b\n LEFT JOIN ${this.#cdc('tableMetadata')} as t\n ON (b.\"schema\" = t.\"schema\" AND b.\"table\" = t.\"table\")\n GROUP BY b.\"schema\", b.\"table\", t.\"metadata\"\n `,\n\n // Ordered by primary key, so that this set and the SQLite change log's\n // can be compared row for row. `COLLATE \"C\"` because that comparison is\n // against a store whose TEXT columns sort by byte: a linguistic\n // collation orders `foo-bar` and `foobar` differently than SQLite's\n // BINARY does, which would read as a divergence rather than as the\n // identical set it is.\n sql<TableMetadataCookie[]>`\n SELECT \"schema\", \"table\", \"metadata\" FROM ${this.#cdc('tableMetadata')}\n ORDER BY \"schema\" COLLATE \"C\", \"table\" COLLATE \"C\"`,\n\n sql<BackfillCookie[]>`\n SELECT \"schema\", \"table\", \"column\", \"backfill\" FROM ${this.#cdc('backfilling')}\n ORDER BY \"schema\" COLLATE \"C\", \"table\" COLLATE \"C\", \"column\" COLLATE \"C\"`,\n ],\n {mode: Mode.READONLY},\n );\n\n return {\n lastWatermark,\n backfillRequests: v.parse(result, backfillRequestsSchema),\n cookies: {\n tableMetadata: [...tableMetadata],\n backfilling: [...backfilling],\n },\n };\n }\n\n async getMinWatermarkForCatchup(): Promise<string | null> {\n const [{minWatermark}] = await this.#db<{minWatermark: string | null}[]>\n /*sql*/ `\n SELECT min(watermark) as \"minWatermark\" FROM ${this.#cdc('changeLog')}`;\n return minWatermark;\n }\n\n /**\n * Returns the retained Postgres catchup bounds.\n * `minWatermark` is the oldest transaction, or `null` for a new replica.\n * `lastWatermark` is the durable head.\n */\n async getCatchupBounds(): Promise<{\n minWatermark: string | null;\n lastWatermark: string;\n }> {\n const [bounds] = await this.#db<\n {minWatermark: string | null; lastWatermark: string}[]\n > /*sql*/ `\n SELECT\n (SELECT min(watermark) FROM ${this.#cdc('changeLog')}) as \"minWatermark\",\n (SELECT \"lastWatermark\" FROM ${this.#cdc('replicationState')}) as \"lastWatermark\"`;\n return bounds;\n }\n\n /**\n * Lists at most `limit` committed transaction watermarks in\n * `(afterWatermark, throughWatermark]`, in ascending order.\n */\n async listCommitWatermarks(\n afterWatermark: string,\n throughWatermark: string,\n limit: number,\n ): Promise<string[]> {\n const rows = await this.#db<{watermark: string}[]> /*sql*/ `\n SELECT watermark FROM ${this.#cdc('changeLog')}\n WHERE precommit IS NOT NULL\n AND watermark > ${afterWatermark}\n AND watermark <= ${throughWatermark}\n ORDER BY watermark\n LIMIT ${limit}`;\n return rows.map(({watermark}) => watermark);\n }\n\n /**\n * Reads `(afterWatermark, throughWatermark]` in stream order and bounded batches.\n * This query matches the subscriber catchup query.\n *\n * Both queries fail when an escaped NUL reaches `change->'tag'`.\n * Postgres cannot convert that value to text.\n */\n readCatchupRange(\n afterWatermark: string,\n throughWatermark: string,\n batchRows = 2000,\n ): AsyncIterable<ChangeLogEntry[]> {\n assert(\n Number.isSafeInteger(batchRows) && batchRows > 0,\n 'Postgres change log batch size must be a positive safe integer',\n );\n return this.#db<ChangeLogEntry[]> /*sql*/ `\n SELECT watermark, change->'tag' as tag, change::text FROM ${this.#cdc('changeLog')}\n WHERE watermark > ${afterWatermark}\n AND watermark <= ${throughWatermark}\n ORDER BY watermark, pos`.cursor(batchRows) as AsyncIterable<\n ChangeLogEntry[]\n >;\n }\n\n purgeRecordsBefore(watermark: string): Promise<number> {\n return runTx(this.#db, async sql => {\n // This NOWAIT pre-check is an optimization to abort the transaction\n // (and release associated resources) early.\n await sql<{watermark: string}[]>`\n SELECT watermark FROM ${this.#cdc('changeLog')}\n ORDER BY watermark, pos LIMIT 1\n FOR UPDATE NOWAIT\n `;\n // If the row is purge-locked by an incoming replication-manager, it\n // will assume ownership of the change-log before releasing the lock.\n // This DELETE blocks until the lock is released, allowing the change\n // in ownership to be reliably detected (and the transaction aborted)\n // in the subsequent check.\n const [{deleted}] = await sql<{deleted: bigint}[]>`\n -- The backup watermark can be ahead of the durable changeLog if the\n -- storer is behind but the backup replica has consumed forwarded\n -- changes. Preserve the latest durable changeLog transaction as the\n -- catchup boundary instead of assuming the backup watermark exists.\n -- The storer inserts each changeLog transaction atomically, so any\n -- durable row for a watermark implies the full transaction is durable.\n WITH keep AS (\n SELECT max(watermark) AS watermark\n FROM ${this.#cdc('changeLog')}\n ), purged AS (\n DELETE FROM ${this.#cdc('changeLog')} WHERE watermark < ${watermark} \n AND watermark < (SELECT watermark FROM keep)\n RETURNING watermark, pos\n ) SELECT COUNT(*) as deleted FROM purged;`;\n\n const [{owner}] = await sql<ReplicationOwner[]>`\n SELECT \"owner\" FROM ${this.#cdc('replicationState')} FOR SHARE`;\n if (owner !== this.#taskID) {\n throw new AbortError(\n `aborting changeLog purge to ${watermark} because ownership has been taken by ${owner}`,\n );\n }\n return Number(deleted);\n });\n }\n\n /**\n * @returns The JSON stringified stream message to be sent downstream.\n */\n store(watermark: string, data: ChangeStreamData) {\n // Eagerly stringify the JSON payload to:\n // - avoid redundant stringification when fanning out to subscribers\n // - efficiently estimate the amount of memory the payload consumes\n const json = serializeChangeStreamData(data);\n this.#approximateQueuedBytes += json.length;\n\n const change = data[1];\n this.#queue.enqueue([\n 'change',\n watermark,\n json,\n isDataChange(change) ? null : change, // drop DataChanges to save memory\n ]);\n\n return json;\n }\n\n abort() {\n this.#queue.enqueue(['abort']);\n }\n\n catchup(subscriber: Subscriber, mode: ReplicatorMode) {\n this.#queue.enqueue(['subscriber', {subscriber, mode}]);\n }\n\n #readyForMore: Resolver<void> | null = null;\n #backpressureTimeout: NodeJS.Timeout | undefined;\n\n readyForMore(): Promise<void> | undefined {\n if (!this.#running) {\n return undefined;\n }\n if (\n this.#readyForMore === null &&\n this.#approximateQueuedBytes > this.#backPressureThresholdBytes\n ) {\n this.#lc.warn?.(\n `applying back pressure with ${this.#queue.size()} queued changes (~${(this.#approximateQueuedBytes / 1024 ** 2).toFixed(2)} MB)\\n` +\n `\\n` +\n `To inspect changeLog backlog in your change DB:\\n` +\n ` SELECT\\n` +\n ` (change->'relation'->>'schema') || '.' || (change->'relation'->>'name') AS table_name,\\n` +\n ` change->>'tag' AS operation,\\n` +\n ` COUNT(*) AS count\\n` +\n ` FROM \"<app_id>/cdc\".\"changeLog\"\\n` +\n ` GROUP BY 1, 2\\n` +\n ` ORDER BY 3 DESC\\n` +\n ` LIMIT 20;`,\n );\n this.#readyForMore = resolver();\n this.#resetBackpressureTimeout(true);\n }\n return this.#readyForMore?.promise;\n }\n\n #resetBackpressureTimeout(reschedule: boolean) {\n clearTimeout(this.#backpressureTimeout);\n this.#backpressureTimeout = reschedule\n ? setTimeout(() => {\n this.#readyForMore?.reject(\n new AbortError(\n `No statement processed within the last ${this.#statementTimeoutMs}ms. Considering the change-log to be wedged.`,\n ),\n );\n this.#readyForMore = null;\n }, this.#statementTimeoutMs)\n : undefined;\n }\n\n #maybeReleaseBackPressure() {\n if (this.#readyForMore !== null) {\n // Wait for at least 20% of the threshold to free up.\n if (\n this.#approximateQueuedBytes <\n this.#backPressureThresholdBytes * 0.8\n ) {\n this.#lc.info?.(\n `releasing back pressure with ${this.#queue.size()} queued changes (~${(this.#approximateQueuedBytes / 1024 ** 2).toFixed(2)} MB)`,\n );\n this.#readyForMore.resolve();\n this.#readyForMore = null;\n this.#resetBackpressureTimeout(false);\n } else {\n this.#resetBackpressureTimeout(true);\n }\n }\n }\n\n /**\n * Flushes any buffered {@link PendingTransaction.batch} rows to the changeLog.\n *\n * Uses `json_to_recordset()` so the batch is a single JSON parameter: the\n * statement text stays constant regardless of batch size, avoiding the\n * unbounded prepared-statement variants (and Postgres memory growth) that a\n * multi-row INSERT would produce. See rocicorp/mono#3511.\n *\n * Returns (and updates) {@link PendingTransaction.lastFlush}; a no-op when the\n * batch is empty.\n */\n #flushChangeLog(tx: PendingTransaction): Promise<unknown> | undefined {\n const {batch} = tx;\n if (batch.length === 0) {\n return tx.lastFlush;\n }\n tx.batch = [];\n tx.lastFlush = tx.pool.process(sql => [\n sql`\n INSERT INTO ${this.#cdc('changeLog')} (\"watermark\", \"pos\", \"change\", \"precommit\")\n SELECT \"watermark\", \"pos\", \"change\"::json, \"precommit\"\n FROM json_to_recordset(${batch}) AS x(\n \"watermark\" TEXT,\n \"pos\" INT8,\n \"change\" TEXT,\n \"precommit\" TEXT\n )`,\n ]);\n return tx.lastFlush;\n }\n\n #stopped = promiseVoid;\n\n /**\n * Runs the storer loop until {@link stop()} is called, or an error is thrown.\n * Once {@link run()} completes, it can be called again.\n */\n async run() {\n assert(!this.#running, `storer is already running`);\n\n const {promise: stopped, resolve: signalStopped} = resolver();\n this.#running = true;\n this.#stopped = stopped;\n\n this.#lc.info?.('starting storer');\n let err: unknown;\n try {\n await this.#processQueue();\n } catch (e) {\n err = e; // used in finally\n throw e;\n } finally {\n // Release any pending backpressure so the upstream can proceed\n if (this.#readyForMore !== null) {\n this.#readyForMore.resolve();\n this.#readyForMore = null;\n }\n this.#resetBackpressureTimeout(false);\n this.#cancelQueueEntries(\n this.#queue.drain().filter(entry => entry !== undefined),\n err,\n );\n this.#running = false;\n signalStopped();\n this.#lc.info?.('storer stopped');\n }\n }\n\n #cancelQueueEntries(queue: QueueEntry[], e: unknown) {\n if (queue.length === 0) {\n return;\n }\n this.#lc.info?.(\n `canceling ${queue.length} entries from the changeLog queue`,\n );\n const err = e instanceof Error ? e : new AbortError('server shutting down');\n for (const entry of queue) {\n if (entry === 'stop') {\n continue;\n }\n const type = entry[0];\n switch (type) {\n case 'subscriber': {\n // Disconnect subscribers waiting to be caught up so that they can\n // reconnect and try again.\n const {subscriber} = entry[1];\n this.#lc.info?.(`disconnecting ${subscriber.id}`);\n subscriber.fail(err);\n break;\n }\n }\n }\n }\n\n async #processQueue() {\n let tx: PendingTransaction | null = null;\n let msg: QueueEntry | false;\n\n const catchupQueue: SubscriberAndMode[] = [];\n try {\n while ((msg = await this.#queue.dequeue()) !== 'stop') {\n const [msgType] = msg;\n switch (msgType) {\n case 'ready': {\n const signalReady = msg[1];\n signalReady();\n continue;\n }\n case 'subscriber': {\n const subscriber = msg[1];\n if (tx) {\n catchupQueue.push(subscriber); // Wait for the current tx to complete.\n } else {\n await this.#startCatchup([subscriber]); // Catch up immediately.\n }\n continue;\n }\n case 'abort': {\n if (tx) {\n tx.pool.abort();\n await tx.pool.done();\n tx = null;\n }\n continue;\n }\n }\n // msgType === 'change'\n const [_, watermark, json, change] = msg;\n const tag = change?.tag;\n this.#approximateQueuedBytes -= json.length;\n\n if (tag === 'begin') {\n assert(!tx, 'received BEGIN in the middle of a transaction');\n const {promise, resolve, reject} = resolver<ReplicationOwner>();\n void promise.catch(() => {}); // handle rejections before the await\n tx = {\n pool: new TransactionPool(\n this.#lc.withContext('watermark', watermark),\n {\n mode: Mode.READ_COMMITTED,\n statementResponseTimeout: this.#statementTimeoutMs,\n },\n ),\n preCommitWatermark: watermark,\n pos: 0,\n startingReplicationState: promise,\n ack: !change.skipAck,\n batch: [],\n lastFlush: undefined,\n };\n tx.pool.run(this.#db);\n // Acquire a lock on the replicationState row to detect and/or prevent\n // a concurrent ownership change.\n void tx.pool.process(tx => {\n tx<ReplicationOwner[]> /*sql*/ `\n SELECT \"owner\" FROM ${this.#cdc('replicationState')} FOR UPDATE`.then(\n ([result]) => resolve(result),\n reject,\n );\n return [];\n });\n } else {\n assert(tx, () => `received change outside of transaction: ${json}`);\n tx.pos++;\n }\n\n const entry: ChangeLogRow = {\n watermark: tag === 'commit' ? watermark : tx.preCommitWatermark,\n precommit: tag === 'commit' ? tx.preCommitWatermark : null,\n pos: tx.pos,\n // For backwards compatibility, only the change message is stored\n // in the cdc changeLog.\n change: extractChangeSubstring(json, tag),\n };\n\n if (change !== null && isSchemaChange(change)) {\n // Schema changes carry backfill / table-metadata statements that\n // must be applied in stream order relative to the changeLog rows.\n // Flush any buffered rows first, then write this row together with\n // its metadata statements as a single unit (preserving the previous\n // per-change ordering for schema changes).\n await this.#flushChangeLog(tx);\n tx.lastFlush = tx.pool.process(sql => [\n sql`INSERT INTO ${this.#cdc('changeLog')} ${sql(entry)}`,\n ...this.#trackBackfillMetadata(sql, change),\n ]);\n } else {\n // Accumulate plain changeLog rows (begin, data changes, commit) and\n // write them as a single multi-row INSERT. Collapsing the per-change\n // single-row INSERTs into batches is the dominant cost reduction for\n // large transactions, where the previous one-statement-per-change\n // path dominated the upstream replication lag.\n tx.batch.push(entry);\n if (tx.batch.length >= this.#changeLogBatchSize) {\n // Bound pipeline depth (and thus memory) by awaiting the previous\n // flush before issuing the next. This is the batched analog of the\n // previous per-100-statement backpressure await, and likewise\n // guards against memory blowup on very large transactions.\n const prevFlush = tx.lastFlush;\n void this.#flushChangeLog(tx);\n await prevFlush;\n }\n }\n this.#maybeReleaseBackPressure();\n\n if (tag === 'commit') {\n // Flush any remaining buffered changeLog rows (including this commit\n // row) before updating the replication state, so the state update is\n // ordered after all changeLog inserts for this transaction.\n void this.#flushChangeLog(tx);\n\n const {owner} = await tx.startingReplicationState;\n if (owner !== this.#taskID) {\n // Ownership change reflected in the replicationState read in 'begin'.\n tx.pool.fail(\n new AbortError(\n `changeLog ownership has been assumed by ${owner}`,\n ),\n );\n } else {\n // Update the replication state.\n const lastWatermark = watermark;\n void tx.pool.process(tx => [\n tx`\n UPDATE ${this.#cdc('replicationState')} SET ${tx({lastWatermark})}`,\n ]);\n tx.pool.setDone();\n }\n\n await tx.pool.done();\n\n // ACK the LSN to the upstream Postgres.\n if (tx.ack) {\n this.#onCommitted(['commit', change, {watermark}]);\n }\n tx = null;\n\n // Before beginning the next transaction, open a READONLY snapshot to\n // concurrently catchup any queued subscribers.\n await this.#startCatchup(catchupQueue.splice(0));\n } else if (tag === 'rollback') {\n // Aborted transactions are not stored in the changeLog. Abort the current tx\n // and process catchup of subscribers that were waiting for it to end.\n tx.pool.abort();\n await tx.pool.done();\n tx = null;\n\n await this.#startCatchup(catchupQueue.splice(0));\n }\n }\n } catch (e) {\n catchupQueue.forEach(({subscriber}) => subscriber.fail(e));\n throw e;\n }\n }\n\n async #startCatchup(subs: SubscriberAndMode[]) {\n if (subs.length === 0) {\n return;\n }\n\n const lc = this.#lc.withContext('pool', 'catchup');\n // TODO: Consider setting initialWorkers to accomodate parallel\n // catchups of multiple subscribers. The tricky part is\n // staying within the db's max connections.\n const reader = new TransactionPool(lc, {mode: Mode.READONLY});\n reader.run(this.#db);\n\n let lastWatermark: string | undefined;\n try {\n // Ensure that the transaction has started (and is thus holding a snapshot\n // of the database) before continuing on to commit more changes. This is\n // done by performing a single read on the db, which determines the\n // snapshot for the REPEATABLE_READ transaction.\n [{lastWatermark}] = await reader.processReadTask(\n sql => sql<{lastWatermark: string}[]>`\n SELECT \"lastWatermark\" FROM ${this.#cdc('replicationState')}\n `,\n );\n } catch (e) {\n subs.map(({subscriber}) => subscriber.fail(e));\n throw e;\n }\n\n // Run the actual catchup queries in the background. Errors are handled in\n // #catchup() by disconnecting the associated subscriber.\n void Promise.all(\n subs.map(sub =>\n this.#catchup(\n lc.withContext('subscriber', sub.subscriber.id),\n sub,\n lastWatermark,\n reader,\n ),\n ),\n ).finally(() => reader.setDone());\n }\n\n async #catchup(\n lc: LogContext,\n {subscriber: sub, mode}: SubscriberAndMode,\n lastWatermark: string,\n reader: TransactionPool,\n ) {\n try {\n lc.info?.(`starting catchup`);\n await reader.processReadTask(async tx => {\n lc.info?.(`catching up`);\n const start = Date.now();\n\n // When starting from initial-sync, there won't be a change with a watermark\n // equal to the replica version. This is the empty changeLog scenario.\n let watermarkFound = sub.watermark === this.#replicaVersion;\n let count = 0;\n let lastBatchConsumed: Promise<unknown> | undefined;\n\n for await (const entries of tx<ChangeLogEntry[]> /*sql*/ `\n SELECT watermark, change->'tag' as tag, change::text FROM ${this.#cdc('changeLog')}\n WHERE watermark >= ${sub.watermark}\n AND watermark <= ${lastWatermark}\n ORDER BY watermark, pos`.cursor(2000)) {\n // Wait for the last batch of entries to be consumed by the\n // subscriber before sending down the current batch. This pipelining\n // allows one batch of changes to be received from the change-db\n // while the previous batch of changes are sent to the subscriber,\n // resulting in flow control that caps the number of changes\n // referenced in memory to 2 * batch-size.\n const start = performance.now();\n await lastBatchConsumed;\n const elapsed = performance.now() - start;\n if (lastBatchConsumed) {\n lc[elapsed > 100 ? 'info' : 'debug']?.(\n `waited ${elapsed.toFixed(3)} ms for ${sub.id} to consume last batch of catchup entries`,\n );\n }\n\n for (const entry of entries) {\n if (entry.watermark === sub.watermark) {\n // This should be the first entry.\n // Catchup starts from *after* the watermark.\n watermarkFound = true;\n } else if (watermarkFound) {\n lastBatchConsumed = sub.catchup(\n reconstructWatermarkedChange(entry),\n );\n count++;\n } else if (mode === 'backup') {\n throw new AutoResetSignal(\n `backup replica at watermark ${sub.watermark} is behind change db: ${entry.watermark})`,\n );\n } else {\n lc.warn?.(\n `rejecting subscriber at watermark ${sub.watermark} (earliest watermark: ${entry.watermark})`,\n );\n sub.close(\n ErrorType.WatermarkTooOld,\n `earliest supported watermark is ${entry.watermark} (requested ${sub.watermark})`,\n );\n return;\n }\n }\n }\n if (watermarkFound) {\n await lastBatchConsumed;\n lc.info?.(\n `caught up ${sub.id} with ${count} changes (${\n Date.now() - start\n } ms)`,\n );\n } else {\n // The subscriber is ahead of the latest durable changeLog entry\n // (lastWatermark). This can legitimately happen: changes are\n // forwarded to subscribers (the backup replica and view-syncers)\n // concurrently with — and can outrun — the durable store, so a\n // replica may briefly lead the change DB after the storer falls\n // behind or the change-streamer restarts. No catchup is possible or\n // needed; once the change DB catches back up, forwarding resumes and\n // the subscriber dedups any watermarks it already has. Unlike the\n // AutoResetSignal / WatermarkTooOld cases above, this is not a gap in\n // replication history, so the subscriber is simply marked caught up.\n lc.warn?.(\n `subscriber ${sub.id} at watermark ${sub.watermark} is ahead of ` +\n `the latest durable watermark ${lastWatermark}; waiting for the ` +\n `change DB to catch up`,\n );\n }\n // Start draining messages buffered during catchup. The returned promise\n // is intentionally not awaited here: while the drain is in progress,\n // new sends keep appending to the subscriber backlog and inherit its\n // byte-based backpressure.\n void sub.setCaughtUp();\n });\n } catch (err) {\n lc.error?.(`error while catching up subscriber ${sub.id}`, err);\n if (err instanceof AutoResetSignal) {\n await markResetRequired(this.#db, this.#shard);\n this.#onFatal(err);\n }\n sub.fail(err);\n }\n }\n\n /**\n * Returns the db statements necessary to track backfill and table metadata\n * presented in the `change`, if any.\n *\n * This is the Postgres interpreter of {@link cookieOps}, which is also\n * interpreted against the SQLite change log by `ChangeLogCookieWriter`. The\n * two stores have to agree on every transition forever, and the failure mode\n * if they drift is a backfill that is silently never re-requested — so the\n * decision of what a schema change *means* lives in one place and only its\n * transport lives here.\n */\n #trackBackfillMetadata(sql: PostgresTransaction, change: SchemaChange) {\n return cookieOps(change).flatMap(op => this.#cookieStmts(sql, op));\n }\n\n #cookieStmts(sql: PostgresTransaction, op: CookieOp): PendingQuery<Row[]>[] {\n switch (op.op) {\n case 'upsert-metadata':\n return [this.#upsertTableMetadataStmt(sql, op.table, op.metadata)];\n\n case 'upsert-backfill':\n return [\n this.#upsertColumnBackfillStmt(sql, op.table, op.column, op.backfill),\n ];\n\n case 'rename-table': {\n const {old} = op;\n const row = {schema: op.new.schema, table: op.new.name};\n return [\n sql`UPDATE ${this.#cdc('tableMetadata')} SET ${sql(row)}\n WHERE \"schema\" = ${old.schema} AND \"table\" = ${old.name}`,\n sql`UPDATE ${this.#cdc('backfilling')} SET ${sql(row)}\n WHERE \"schema\" = ${old.schema} AND \"table\" = ${old.name}`,\n ];\n }\n\n case 'drop-table': {\n const {schema, name} = op.table;\n return [\n sql`DELETE FROM ${this.#cdc('tableMetadata')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${name}`,\n sql`DELETE FROM ${this.#cdc('backfilling')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${name}`,\n ];\n }\n\n case 'rename-column': {\n const {schema, name: table} = op.table;\n return [\n sql`UPDATE ${this.#cdc('backfilling')} SET \"column\" = ${op.new}\n WHERE \"schema\" = ${schema} AND \"table\" = ${table} AND \"column\" = ${op.old}`,\n ];\n }\n\n case 'drop-column': {\n const {schema, name} = op.table;\n return [\n sql`DELETE FROM ${this.#cdc('backfilling')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${name} AND \"column\" = ${op.column}`,\n ];\n }\n\n case 'complete-backfill': {\n const {schema, name: table} = op.table;\n return [\n sql`DELETE FROM ${this.#cdc('backfilling')}\n WHERE \"schema\" = ${schema} AND \"table\" = ${table} AND \"column\" IN ${sql([...op.columns])}`,\n ];\n }\n\n default:\n unreachable(op);\n }\n }\n\n #upsertTableMetadataStmt(\n sql: PostgresTransaction,\n {schema, name: table}: Identifier,\n metadata: TableMetadata,\n ) {\n const row: TableMetadataRow = {schema, table, metadata};\n return sql`\n INSERT INTO ${this.#cdc('tableMetadata')} ${sql(row)}\n ON CONFLICT (\"schema\", \"table\")\n DO UPDATE SET ${sql(row)};\n `;\n }\n\n #upsertColumnBackfillStmt(\n sql: PostgresTransaction,\n {schema, name: table}: Identifier,\n column: string,\n backfill: BackfillID,\n ) {\n const row: BackfillingColumn = {schema, table, column, backfill};\n return sql`\n INSERT INTO ${this.#cdc('backfilling')} ${sql(row)}\n ON CONFLICT (\"schema\", \"table\", \"column\")\n DO UPDATE SET ${sql(row)};\n `;\n }\n\n /**\n * Waits until all currently queued entries have been processed.\n * This is only used in tests.\n */\n async allProcessed() {\n if (this.#running) {\n const {promise, resolve} = resolver();\n this.#queue.enqueue(['ready', resolve]);\n await promise;\n }\n }\n\n /**\n * Stops the storer and waits up to a drain timeout for entries to drain,\n * throwing an exception if it doesn't drain in time, in order to abort\n * the server when PG (or the connection to it) appears to be wedged.\n */\n async stop() {\n if (this.#running) {\n this.#lc.info?.(`draining ${this.#queue.size()} changeLog entries`);\n this.abort(); // for cleanliness, abort any open transactions\n this.#queue.enqueue('stop');\n }\n if (\n (await orTimeout(this.#stopped, this.#drainTimeoutMs)) === 'timed-out'\n ) {\n throw new AbortError(\n `changeLog did not drain within ${this.#drainTimeoutMs}ms`,\n );\n }\n }\n}\n\nexport class PurgeLock {\n readonly #lc: LogContext;\n readonly #tx: TransactionPool;\n readonly replicaVersion: string;\n readonly minWatermark: string;\n\n constructor(\n lc: LogContext,\n tx: TransactionPool,\n replicaVersion: string,\n watermark: string,\n ) {\n this.#lc = lc;\n this.#tx = tx;\n this.replicaVersion = replicaVersion;\n this.minWatermark = watermark;\n }\n\n #released = false;\n\n async release() {\n if (this.#released) {\n return;\n }\n this.#released = true;\n this.#tx.setDone();\n await this.#tx\n .done()\n .catch(e => this.#lc.warn?.(`error from purge-lock release`, e));\n this.#lc.info?.(`released purge lock on ${this.minWatermark}`);\n }\n}\n\nexport class PurgeLocker {\n readonly #lc: LogContext;\n readonly #shard: ShardID;\n readonly #db: PostgresDB;\n\n constructor(lc: LogContext, shard: ShardID, db: PostgresDB) {\n this.#lc = lc.withContext('component', 'purge-locker');\n this.#shard = shard;\n this.#db = db;\n }\n\n // For readability in SQL statements.\n #cdc(table: string) {\n return this.#db(`${cdcSchema(this.#shard)}.${table}`);\n }\n\n async acquire() {\n const tx = new TransactionPool(this.#lc, {mode: Mode.READ_COMMITTED}).run(\n this.#db,\n );\n const row = await tx.processReadTask(\n sql => sql<{watermark: string}[]>`\n SELECT watermark FROM ${this.#cdc('changeLog')}\n ORDER BY watermark, pos LIMIT 1\n FOR SHARE \n `,\n );\n if (row.length === 0) {\n this.#lc.info?.(`changeLog is empty. No rows to purge-lock.`);\n tx.setDone();\n await tx.done();\n return null;\n }\n const [{watermark}] = row;\n const [{replicaVersion}] = await tx.processReadTask(\n sql => sql<{replicaVersion: string}[]>`\n SELECT \"replicaVersion\" FROM ${this.#cdc('replicationConfig')}\n `,\n );\n this.#lc.info?.(\n `locked watermark ${watermark} from being purged from replica@${replicaVersion}`,\n );\n return new PurgeLock(this.#lc, tx, replicaVersion, watermark);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA0FA,IAAM,yBAAyB,eAAE,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkD5D,IAAa,SAAb,MAAuC;CACrC,KAAc;CACd;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA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KAAK,IAAI,gBAAgB,SAAS;CAC9D;AACF"}
@@ -0,0 +1,29 @@
1
+ import type { LogContext } from '@rocicorp/logger';
2
+ import type { Source } from '../../types/streams.ts';
3
+ import type { BackedUpWatermark } from './backup-monitor.ts';
4
+ export type VfsPollerConfig = {
5
+ executable: string;
6
+ remotePollIntervalMs: number;
7
+ remoteQueryTimeoutMs?: number;
8
+ backupURL: string;
9
+ region?: string | undefined;
10
+ endpoint?: string | undefined;
11
+ logLevel?: string;
12
+ logFormat?: string;
13
+ };
14
+ export declare class VfsWatermarkPoller {
15
+ #private;
16
+ constructor(lc: LogContext, replicaFile: string, pollerConfig: VfsPollerConfig);
17
+ /**
18
+ * Starts polling for watermarks and pushes new ones to returned stream.
19
+ * Must only be called once.
20
+ */
21
+ start(): Source<BackedUpWatermark>;
22
+ readonly checkLocalWatermark: () => void;
23
+ }
24
+ export declare function buildLitestreamVfsReplicaURL({ backupURL, endpoint, region, }: {
25
+ readonly backupURL: string;
26
+ readonly endpoint?: string | undefined;
27
+ readonly region?: string | undefined;
28
+ }): string;
29
+ //# sourceMappingURL=vfs-watermark-poller.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vfs-watermark-poller.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/change-streamer/vfs-watermark-poller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAIjD,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,wBAAwB,CAAC;AAGnD,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,qBAAqB,CAAC;AAe3D,MAAM,MAAM,eAAe,GAAG;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAyBF,qBAAa,kBAAkB;;gBAmB3B,EAAE,EAAE,UAAU,EACd,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,eAAe;IAyB/B;;;OAGG;IACH,KAAK,IAAI,MAAM,CAAC,iBAAiB,CAAC;IAYlC,QAAQ,CAAC,mBAAmB,aAiB1B;CA+GH;AAED,wBAAgB,4BAA4B,CAAC,EAC3C,SAAS,EACT,QAAQ,EACR,MAAM,GACP,EAAE;IACD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACvC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACtC,GAAG,MAAM,CAiBT"}
@@ -0,0 +1,154 @@
1
+ import { assert } from "../../../../shared/src/asserts.js";
2
+ import { parse, valita_exports } from "../../../../shared/src/valita.js";
3
+ import { Database } from "../../../../zqlite/src/db.js";
4
+ import { RunningState } from "../running-state.js";
5
+ import { Subscription } from "../../types/subscription.js";
6
+ import { spawn } from "node:child_process";
7
+ import { createInterface } from "node:readline";
8
+ //#region ../zero-cache/src/services/change-streamer/vfs-watermark-poller.ts
9
+ var LOCAL_CHECK_INTERVAL_MS = 1e3;
10
+ var queryResultRowSchema = valita_exports.object({
11
+ stateVersion: valita_exports.string(),
12
+ writeTimeMs: valita_exports.number()
13
+ });
14
+ var remoteQueryMetadataSchema = valita_exports.object({ litestream_time: valita_exports.string().map((str) => new Date(str).getTime()).optional() });
15
+ var remoteQueryLineSchema = valita_exports.object({
16
+ query_result: valita_exports.tuple([queryResultRowSchema]),
17
+ metadata: remoteQueryMetadataSchema
18
+ });
19
+ var INITIAL_BACKOFF_MS = 2e3;
20
+ var MAX_BACKOFF_MS = 3e4;
21
+ var VfsWatermarkPoller = class {
22
+ #lc;
23
+ #state = new RunningState("vfs-watermark-poller");
24
+ #pollerConfig;
25
+ #readLocalWatermark;
26
+ #stream;
27
+ #localWatermark;
28
+ #remoteWatermark;
29
+ #localPollTimer;
30
+ #shouldPollRemote = false;
31
+ #remotePoller;
32
+ #remotePollerBackoffMs = INITIAL_BACKOFF_MS;
33
+ #remotePollerBackoffTimer;
34
+ constructor(lc, replicaFile, pollerConfig) {
35
+ this.#lc = lc.withContext("component", "vfs-watermark-poller");
36
+ this.#pollerConfig = pollerConfig;
37
+ const db = new Database(this.#lc, replicaFile, { readonly: true });
38
+ this.#readLocalWatermark = db.prepare(`SELECT stateVersion, writeTimeMs FROM "_zero.replicationState"`);
39
+ this.#localWatermark = parse(this.#readLocalWatermark.get(), queryResultRowSchema);
40
+ this.#stream = Subscription.create({ cleanup: () => {
41
+ this.#disableRemotePoller();
42
+ clearInterval(this.#localPollTimer);
43
+ clearTimeout(this.#remotePollerBackoffTimer);
44
+ this.#state.stop(this.#lc);
45
+ db.close();
46
+ } });
47
+ }
48
+ /**
49
+ * Starts polling for watermarks and pushes new ones to returned stream.
50
+ * Must only be called once.
51
+ */
52
+ start() {
53
+ assert(this.#localPollTimer === void 0, `Already called start()`);
54
+ this.#lc.info?.(`monitoring backups at ${this.#pollerConfig.backupURL}`);
55
+ this.#localPollTimer = setInterval(this.checkLocalWatermark, LOCAL_CHECK_INTERVAL_MS);
56
+ this.checkLocalWatermark();
57
+ return this.#stream;
58
+ }
59
+ checkLocalWatermark = () => {
60
+ try {
61
+ this.#localWatermark = parse(this.#readLocalWatermark.get(), queryResultRowSchema);
62
+ } catch (e) {
63
+ this.#lc.warn?.(`unable to read local watermark`, e);
64
+ return;
65
+ }
66
+ if (this.#localWatermark.stateVersion !== this.#remoteWatermark?.watermark) this.#enableRemotePoller();
67
+ else this.#disableRemotePoller();
68
+ };
69
+ #enableRemotePoller() {
70
+ if (this.#remotePoller || this.#remotePollerBackoffTimer) return;
71
+ this.#shouldPollRemote = true;
72
+ if (this.#remoteWatermark) this.#lc.debug?.(`local and remote watermarks differ. resuming backup polling`, {
73
+ local: this.#localWatermark,
74
+ remote: this.#remoteWatermark
75
+ });
76
+ const child = spawn(this.#pollerConfig.executable, [
77
+ "--replica-url",
78
+ buildLitestreamVfsReplicaURL(this.#pollerConfig),
79
+ "--query",
80
+ `SELECT stateVersion, writeTimeMs FROM "_zero.replicationState"`,
81
+ "--remote-poll-interval",
82
+ `${this.#pollerConfig.remotePollIntervalMs}ms`,
83
+ ...this.#pollerConfig.logLevel ? ["--log-level", this.#pollerConfig.logLevel] : [],
84
+ ...this.#pollerConfig.logFormat ? ["--log-format", this.#pollerConfig.logFormat] : [],
85
+ ...this.#pollerConfig.remoteQueryTimeoutMs ? ["--query-timeout", `${this.#pollerConfig.remoteQueryTimeoutMs}ms`] : []
86
+ ], { stdio: [
87
+ "pipe",
88
+ "pipe",
89
+ "inherit"
90
+ ] }).on("error", (err) => {
91
+ this.#lc.error?.(`received error from vfs-query process`, err);
92
+ }).on("close", (code, signal) => {
93
+ this.#remotePoller = void 0;
94
+ if (this.#shouldPollRemote) {
95
+ if (code !== 0) this.#lc.warn?.(`vfs-query exited with ${code}, ${signal}. retrying in ${this.#remotePollerBackoffMs}ms`);
96
+ if (!this.#remotePollerBackoffTimer) {
97
+ this.#remotePollerBackoffTimer = setTimeout(() => {
98
+ this.#remotePollerBackoffTimer = void 0;
99
+ if (this.#shouldPollRemote) this.#enableRemotePoller();
100
+ }, this.#remotePollerBackoffMs);
101
+ this.#remotePollerBackoffMs = Math.min(this.#remotePollerBackoffMs * 2, MAX_BACKOFF_MS);
102
+ }
103
+ }
104
+ });
105
+ createInterface({ input: child.stdout }).on("line", this.#readRemotePollerLine);
106
+ this.#remotePoller = child;
107
+ }
108
+ #readRemotePollerLine = (line) => {
109
+ try {
110
+ const update = parse(JSON.parse(line), remoteQueryLineSchema, "passthrough");
111
+ const [{ stateVersion: watermark, writeTimeMs }] = update.query_result;
112
+ const remoteWatermark = {
113
+ watermark,
114
+ writeTimeMs,
115
+ backupTimeMs: update.metadata.litestream_time ?? Date.now()
116
+ };
117
+ if (remoteWatermark.watermark !== this.#remoteWatermark?.watermark) {
118
+ this.#lc.debug?.(`backup watermark advanced from ${this.#remoteWatermark?.watermark} to ${remoteWatermark.watermark}`, {
119
+ local: this.#localWatermark,
120
+ remote: remoteWatermark
121
+ });
122
+ this.#stream.push(remoteWatermark);
123
+ }
124
+ this.#remoteWatermark = remoteWatermark;
125
+ this.#remotePollerBackoffMs = INITIAL_BACKOFF_MS;
126
+ } catch (e) {
127
+ this.#lc.error?.(`unable to parse vfs-query output: ${line}`, e);
128
+ }
129
+ };
130
+ #disableRemotePoller() {
131
+ if (!this.#shouldPollRemote) return;
132
+ this.#shouldPollRemote = false;
133
+ if (this.#remotePoller || this.#remotePollerBackoffTimer) this.#lc.debug?.(`local and remote watermarks match. pausing backup polling`, {
134
+ local: this.#localWatermark,
135
+ remote: this.#remoteWatermark
136
+ });
137
+ this.#remotePoller?.kill("SIGTERM");
138
+ this.#remotePoller = void 0;
139
+ clearTimeout(this.#remotePollerBackoffTimer);
140
+ this.#remotePollerBackoffTimer = void 0;
141
+ }
142
+ };
143
+ function buildLitestreamVfsReplicaURL({ backupURL, endpoint, region }) {
144
+ if (endpoint === void 0 && region === void 0) return backupURL;
145
+ const url = new URL(backupURL);
146
+ if (url.protocol !== "s3:") return backupURL;
147
+ if (endpoint !== void 0 && !url.searchParams.has("endpoint")) url.searchParams.set("endpoint", endpoint);
148
+ if (region !== void 0 && !url.searchParams.has("region")) url.searchParams.set("region", region);
149
+ return url.toString();
150
+ }
151
+ //#endregion
152
+ export { VfsWatermarkPoller };
153
+
154
+ //# sourceMappingURL=vfs-watermark-poller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vfs-watermark-poller.js","names":["#lc","#state","#pollerConfig","#readLocalWatermark","#stream","#localWatermark","#disableRemotePoller","#localPollTimer","#remotePollerBackoffTimer","#remoteWatermark","#enableRemotePoller","#remotePoller","#shouldPollRemote","#remotePollerBackoffMs","#readRemotePollerLine"],"sources":["../../../../../../zero-cache/src/services/change-streamer/vfs-watermark-poller.ts"],"sourcesContent":["import {spawn, type ChildProcess} from 'node:child_process';\nimport {createInterface} from 'node:readline';\nimport type {LogContext} from '@rocicorp/logger';\nimport {assert} from '../../../../shared/src/asserts.ts';\nimport * as v from '../../../../shared/src/valita.ts';\nimport {Database, type Statement} from '../../../../zqlite/src/db.ts';\nimport type {Source} from '../../types/streams.ts';\nimport {Subscription} from '../../types/subscription.ts';\nimport {RunningState} from '../running-state.ts';\nimport type {BackedUpWatermark} from './backup-monitor.ts';\n\nconst LOCAL_CHECK_INTERVAL_MS = 1_000;\n\ntype LocalWatermark = {\n stateVersion: string;\n writeTimeMs: number;\n};\n\ntype RemoteWatermark = {\n watermark: string;\n writeTimeMs: number;\n backupTimeMs: number;\n};\n\nexport type VfsPollerConfig = {\n executable: string;\n remotePollIntervalMs: number;\n remoteQueryTimeoutMs?: number;\n backupURL: string;\n region?: string | undefined;\n endpoint?: string | undefined;\n logLevel?: string;\n logFormat?: string;\n};\n\nconst queryResultRowSchema = v.object({\n stateVersion: v.string(),\n writeTimeMs: v.number(),\n});\n\nconst remoteQueryMetadataSchema = v.object({\n litestream_time: v\n .string()\n .map(str => new Date(str).getTime())\n .optional(),\n});\n\n// Expected format of each line of stdout from the vfs-query, e.g.\n// {\"query_result\":[{\"stateVersion\":\"51y50ko\",\"writeTimeMs\":1787259951121}],\"metadata\":{\"litestream_time\":\"2026-08-20T21:05:57.36439Z\"}}\n// {\"query_result\":[{\"stateVersion\":\"51y7360\",\"writeTimeMs\":1787259966137}],\"metadata\":{\"litestream_time\":\"2026-08-20T21:06:12.384531Z\"}}\nconst remoteQueryLineSchema = v.object({\n query_result: v.tuple([queryResultRowSchema]),\n metadata: remoteQueryMetadataSchema,\n});\n\nconst INITIAL_BACKOFF_MS = 2_000;\nconst MAX_BACKOFF_MS = 30_000;\n\nexport class VfsWatermarkPoller {\n readonly #lc: LogContext;\n readonly #state = new RunningState('vfs-watermark-poller');\n readonly #pollerConfig: VfsPollerConfig;\n readonly #readLocalWatermark: Statement;\n\n readonly #stream: Subscription<BackedUpWatermark>;\n\n #localWatermark: LocalWatermark;\n #remoteWatermark: RemoteWatermark | undefined;\n #localPollTimer: NodeJS.Timeout | undefined;\n\n #shouldPollRemote = false;\n\n #remotePoller: ChildProcess | undefined;\n #remotePollerBackoffMs = INITIAL_BACKOFF_MS;\n #remotePollerBackoffTimer: NodeJS.Timeout | undefined;\n\n constructor(\n lc: LogContext,\n replicaFile: string,\n pollerConfig: VfsPollerConfig,\n ) {\n this.#lc = lc.withContext('component', 'vfs-watermark-poller');\n this.#pollerConfig = pollerConfig;\n\n const db = new Database(this.#lc, replicaFile, {readonly: true});\n this.#readLocalWatermark = db.prepare(\n `SELECT stateVersion, writeTimeMs FROM \"_zero.replicationState\"`,\n );\n // Purely to type the member variable as always defined\n this.#localWatermark = v.parse(\n this.#readLocalWatermark.get(),\n queryResultRowSchema,\n );\n this.#stream = Subscription.create<BackedUpWatermark>({\n cleanup: () => {\n this.#disableRemotePoller();\n clearInterval(this.#localPollTimer);\n clearTimeout(this.#remotePollerBackoffTimer);\n this.#state.stop(this.#lc);\n db.close();\n },\n });\n }\n\n /**\n * Starts polling for watermarks and pushes new ones to returned stream.\n * Must only be called once.\n */\n start(): Source<BackedUpWatermark> {\n assert(this.#localPollTimer === undefined, `Already called start()`);\n this.#lc.info?.(`monitoring backups at ${this.#pollerConfig.backupURL}`);\n this.#localPollTimer = setInterval(\n this.checkLocalWatermark,\n LOCAL_CHECK_INTERVAL_MS,\n );\n this.checkLocalWatermark();\n return this.#stream;\n }\n\n // Exported for testing\n readonly checkLocalWatermark = () => {\n try {\n this.#localWatermark = v.parse(\n this.#readLocalWatermark.get(),\n queryResultRowSchema,\n );\n } catch (e) {\n this.#lc.warn?.(`unable to read local watermark`, e);\n return;\n }\n if (\n this.#localWatermark.stateVersion !== this.#remoteWatermark?.watermark\n ) {\n this.#enableRemotePoller();\n } else {\n this.#disableRemotePoller();\n }\n };\n\n #enableRemotePoller() {\n if (this.#remotePoller || this.#remotePollerBackoffTimer) {\n return; // already polling or backing off\n }\n this.#shouldPollRemote = true;\n if (this.#remoteWatermark) {\n this.#lc.debug?.(\n `local and remote watermarks differ. resuming backup polling`,\n {local: this.#localWatermark, remote: this.#remoteWatermark},\n );\n }\n const child = spawn(\n this.#pollerConfig.executable,\n [\n '--replica-url',\n buildLitestreamVfsReplicaURL(this.#pollerConfig),\n '--query',\n `SELECT stateVersion, writeTimeMs FROM \"_zero.replicationState\"`,\n '--remote-poll-interval',\n `${this.#pollerConfig.remotePollIntervalMs}ms`,\n ...(this.#pollerConfig.logLevel\n ? ['--log-level', this.#pollerConfig.logLevel]\n : []),\n ...(this.#pollerConfig.logFormat\n ? ['--log-format', this.#pollerConfig.logFormat]\n : []),\n ...(this.#pollerConfig.remoteQueryTimeoutMs\n ? ['--query-timeout', `${this.#pollerConfig.remoteQueryTimeoutMs}ms`]\n : []),\n ],\n {stdio: ['pipe', 'pipe', 'inherit']},\n )\n .on('error', err => {\n this.#lc.error?.(`received error from vfs-query process`, err);\n })\n .on('close', (code, signal) => {\n this.#remotePoller = undefined;\n if (this.#shouldPollRemote) {\n if (code !== 0) {\n this.#lc.warn?.(\n `vfs-query exited with ${code}, ${signal}. retrying in ${this.#remotePollerBackoffMs}ms`,\n );\n }\n if (!this.#remotePollerBackoffTimer) {\n this.#remotePollerBackoffTimer = setTimeout(() => {\n this.#remotePollerBackoffTimer = undefined;\n if (this.#shouldPollRemote) {\n this.#enableRemotePoller();\n }\n }, this.#remotePollerBackoffMs);\n this.#remotePollerBackoffMs = Math.min(\n this.#remotePollerBackoffMs * 2,\n MAX_BACKOFF_MS,\n );\n }\n }\n });\n createInterface({input: child.stdout}).on(\n 'line',\n this.#readRemotePollerLine,\n );\n this.#remotePoller = child;\n }\n\n readonly #readRemotePollerLine = (line: string) => {\n try {\n const update = v.parse(\n JSON.parse(line),\n remoteQueryLineSchema,\n 'passthrough',\n );\n const [{stateVersion: watermark, writeTimeMs}] = update.query_result;\n const remoteWatermark: RemoteWatermark = {\n watermark,\n writeTimeMs,\n backupTimeMs: update.metadata.litestream_time ?? Date.now(),\n };\n if (remoteWatermark.watermark !== this.#remoteWatermark?.watermark) {\n this.#lc.debug?.(\n `backup watermark advanced from ${this.#remoteWatermark?.watermark} to ${remoteWatermark.watermark}`,\n {local: this.#localWatermark, remote: remoteWatermark},\n );\n this.#stream.push(remoteWatermark);\n }\n this.#remoteWatermark = remoteWatermark;\n\n // Reset backoff on successful output from the poller\n this.#remotePollerBackoffMs = INITIAL_BACKOFF_MS;\n } catch (e) {\n this.#lc.error?.(`unable to parse vfs-query output: ${line}`, e);\n }\n };\n\n #disableRemotePoller() {\n if (!this.#shouldPollRemote) {\n return;\n }\n this.#shouldPollRemote = false;\n if (this.#remotePoller || this.#remotePollerBackoffTimer) {\n this.#lc.debug?.(\n `local and remote watermarks match. pausing backup polling`,\n {local: this.#localWatermark, remote: this.#remoteWatermark},\n );\n }\n this.#remotePoller?.kill('SIGTERM');\n this.#remotePoller = undefined;\n clearTimeout(this.#remotePollerBackoffTimer);\n this.#remotePollerBackoffTimer = undefined;\n }\n}\n\nexport function buildLitestreamVfsReplicaURL({\n backupURL,\n endpoint,\n region,\n}: {\n readonly backupURL: string;\n readonly endpoint?: string | undefined;\n readonly region?: string | undefined;\n}): string {\n if (endpoint === undefined && region === undefined) {\n return backupURL;\n }\n\n const url = new URL(backupURL);\n if (url.protocol !== 's3:') {\n return backupURL;\n }\n\n if (endpoint !== undefined && !url.searchParams.has('endpoint')) {\n url.searchParams.set('endpoint', endpoint);\n }\n if (region !== undefined && !url.searchParams.has('region')) {\n url.searchParams.set('region', region);\n }\n return url.toString();\n}\n"],"mappings":";;;;;;;;AAWA,IAAM,0BAA0B;AAwBhC,IAAM,uBAAuB,eAAE,OAAO;CACpC,cAAc,eAAE,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AAI,UAAU,GAC5D,IAAI,aAAa,IAAI,YAAY,QAAQ;CAE3C,IAAI,WAAW,KAAA,KAAa,CAAC,IAAI,aAAa,IAAI,QAAQ,GACxD,IAAI,aAAa,IAAI,UAAU,MAAM;CAEvC,OAAO,IAAI,SAAS;AACtB"}
@@ -5,6 +5,7 @@ import type { Service } from './service.ts';
5
5
  export type Options = {
6
6
  port: number;
7
7
  keepaliveTimeoutMs: number | undefined;
8
+ readinessGate?: Promise<void> | undefined;
8
9
  };
9
10
  /**
10
11
  * Common functionality for all HttpServices. These include:
@@ -1 +1 @@
1
- {"version":3,"file":"http-service.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/services/http-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAgB,EAAC,KAAK,eAAe,EAAC,MAAM,SAAS,CAAC;AAGtD,OAAO,EAAC,YAAY,EAAC,MAAM,oBAAoB,CAAC;AAChD,OAAO,KAAK,EAAC,OAAO,EAAC,MAAM,cAAc,CAAC;AAE1C,MAAM,MAAM,OAAO,GAAG;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,kBAAkB,EAAE,MAAM,GAAG,SAAS,CAAC;CACxC,CAAC;AAEF;;;;GAIG;AACH,qBAAa,WAAY,YAAW,OAAO;;IACzC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,UAAU,CAAC;IAGnC,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;gBAKtC,EAAE,EAAE,MAAM,EACV,EAAE,EAAE,UAAU,EACd,IAAI,EAAE,OAAO,EACb,IAAI,EAAE,CAAC,OAAO,EAAE,eAAe,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAe1D,SAAS,CAAC,QAAQ;IAClB,SAAS,CAAC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAK5B,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC;IAgBxB,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC;IAKpB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAO5B"}
1
+ {"version":3,"file":"http-service.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/services/http-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAgB,EAAC,KAAK,eAAe,EAAC,MAAM,SAAS,CAAC;AAGtD,OAAO,EAAC,YAAY,EAAC,MAAM,oBAAoB,CAAC;AAChD,OAAO,KAAK,EAAC,OAAO,EAAC,MAAM,cAAc,CAAC;AAE1C,MAAM,MAAM,OAAO,GAAG;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,kBAAkB,EAAE,MAAM,GAAG,SAAS,CAAC;IAGvC,aAAa,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC;CAC3C,CAAC;AAEF;;;;GAIG;AACH,qBAAa,WAAY,YAAW,OAAO;;IACzC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,UAAU,CAAC;IAGnC,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;gBAOtC,EAAE,EAAE,MAAM,EACV,EAAE,EAAE,UAAU,EACd,IAAI,EAAE,OAAO,EACb,IAAI,EAAE,CAAC,OAAO,EAAE,eAAe,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAiB1D,SAAS,CAAC,QAAQ;IAClB,SAAS,CAAC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAK5B,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC;IAsBxB,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC;IAKpB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAO5B"}
@@ -16,8 +16,9 @@ var HttpService = class {
16
16
  _state;
17
17
  #heartbeatMonitor;
18
18
  #init;
19
+ #ready = false;
19
20
  constructor(id, lc, opts, init) {
20
- const { port, keepaliveTimeoutMs } = opts;
21
+ const { port, keepaliveTimeoutMs, readinessGate = promiseVoid } = opts;
21
22
  this.id = id;
22
23
  this._lc = lc.withContext("component", this.id);
23
24
  this.#fastify = Fastify();
@@ -25,16 +26,19 @@ var HttpService = class {
25
26
  this.#init = init;
26
27
  this._state = new RunningState(id);
27
28
  this.#heartbeatMonitor = keepaliveTimeoutMs ? new HeartbeatMonitor(this._lc, keepaliveTimeoutMs) : void 0;
29
+ readinessGate.then(() => this.#ready = true);
28
30
  }
29
31
  _onStart() {}
30
32
  _onStop() {
31
33
  return promiseVoid;
32
34
  }
33
35
  async start() {
34
- this.#fastify.get("/", (_req, res) => res.send("OK"));
36
+ this.#fastify.get("/", (_req, res) => {
37
+ if (this.#ready) res.send("OK");
38
+ });
35
39
  this.#fastify.get("/keepalive", ({ headers }, res) => {
36
40
  this.#heartbeatMonitor?.onHeartbeat(headers);
37
- return res.send("OK");
41
+ if (this.#ready) res.send("OK");
38
42
  });
39
43
  await this.#init(this.#fastify);
40
44
  const address = await this.#fastify.listen({
@@ -1 +1 @@
1
- {"version":3,"file":"http-service.js","names":["#fastify","#port","#heartbeatMonitor","#init"],"sources":["../../../../../zero-cache/src/services/http-service.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport Fastify, {type FastifyInstance} from 'fastify';\nimport {promiseVoid} from '../../../shared/src/resolved-promises.ts';\nimport {HeartbeatMonitor} from './life-cycle.ts';\nimport {RunningState} from './running-state.ts';\nimport type {Service} from './service.ts';\n\nexport type Options = {\n port: number;\n keepaliveTimeoutMs: number | undefined;\n};\n\n/**\n * Common functionality for all HttpServices. These include:\n * * Responding to health checks at \"/\"\n * * Tracking optional heartbeats at \"/keepalive\" and draining when they stop.\n */\nexport class HttpService implements Service {\n readonly id: string;\n protected readonly _lc: LogContext;\n readonly #fastify: FastifyInstance;\n readonly #port: number;\n protected readonly _state: RunningState;\n readonly #heartbeatMonitor: HeartbeatMonitor | undefined;\n readonly #init: (fastify: FastifyInstance) => void | Promise<void>;\n\n constructor(\n id: string,\n lc: LogContext,\n opts: Options,\n init: (fastify: FastifyInstance) => void | Promise<void>,\n ) {\n const {port, keepaliveTimeoutMs} = opts;\n this.id = id;\n this._lc = lc.withContext('component', this.id);\n this.#fastify = Fastify();\n this.#port = port;\n this.#init = init;\n this._state = new RunningState(id);\n this.#heartbeatMonitor = keepaliveTimeoutMs\n ? new HeartbeatMonitor(this._lc, keepaliveTimeoutMs)\n : undefined;\n }\n\n // Life-cycle hooks for subclass implementations\n protected _onStart() {}\n protected _onStop(): Promise<void> {\n return promiseVoid;\n }\n // start() is used in unit tests.\n // run() is the lifecycle method called by the ServiceRunner.\n async start(): Promise<string> {\n this.#fastify.get('/', (_req, res) => res.send('OK'));\n this.#fastify.get('/keepalive', ({headers}, res) => {\n this.#heartbeatMonitor?.onHeartbeat(headers);\n return res.send('OK');\n });\n await this.#init(this.#fastify);\n const address = await this.#fastify.listen({\n host: '::',\n port: this.#port,\n });\n this._lc.info?.(`${this.id} listening at ${address}`);\n this._onStart();\n return address;\n }\n\n async run(): Promise<void> {\n await this.start();\n await this._state.stopped();\n }\n\n async stop(): Promise<void> {\n this._lc.info?.(`${this.id}: no longer accepting connections`);\n this.#heartbeatMonitor?.stop();\n this._state.stop(this._lc);\n await this.#fastify.close();\n await this._onStop();\n }\n}\n"],"mappings":";;;;;;;;;;AAiBA,IAAa,cAAb,MAA4C;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YACE,IACA,IACA,MACA,MACA;EACA,MAAM,EAAC,MAAM,uBAAsB;EACnC,KAAK,KAAK;EACV,KAAK,MAAM,GAAG,YAAY,aAAa,KAAK,EAAE;EAC9C,KAAKA,WAAW,QAAQ;EACxB,KAAKC,QAAQ;EACb,KAAKE,QAAQ;EACb,KAAK,SAAS,IAAI,aAAa,EAAE;EACjC,KAAKD,oBAAoB,qBACrB,IAAI,iBAAiB,KAAK,KAAK,kBAAkB,IACjD,KAAA;CACN;CAGA,WAAqB,CAAC;CACtB,UAAmC;EACjC,OAAO;CACT;CAGA,MAAM,QAAyB;EAC7B,KAAKF,SAAS,IAAI,MAAM,MAAM,QAAQ,IAAI,KAAK,IAAI,CAAC;EACpD,KAAKA,SAAS,IAAI,eAAe,EAAC,WAAU,QAAQ;GAClD,KAAKE,mBAAmB,YAAY,OAAO;GAC3C,OAAO,IAAI,KAAK,IAAI;EACtB,CAAC;EACD,MAAM,KAAKC,MAAM,KAAKH,QAAQ;EAC9B,MAAM,UAAU,MAAM,KAAKA,SAAS,OAAO;GACzC,MAAM;GACN,MAAM,KAAKC;EACb,CAAC;EACD,KAAK,IAAI,OAAO,GAAG,KAAK,GAAG,gBAAgB,SAAS;EACpD,KAAK,SAAS;EACd,OAAO;CACT;CAEA,MAAM,MAAqB;EACzB,MAAM,KAAK,MAAM;EACjB,MAAM,KAAK,OAAO,QAAQ;CAC5B;CAEA,MAAM,OAAsB;EAC1B,KAAK,IAAI,OAAO,GAAG,KAAK,GAAG,kCAAkC;EAC7D,KAAKC,mBAAmB,KAAK;EAC7B,KAAK,OAAO,KAAK,KAAK,GAAG;EACzB,MAAM,KAAKF,SAAS,MAAM;EAC1B,MAAM,KAAK,QAAQ;CACrB;AACF"}
1
+ {"version":3,"file":"http-service.js","names":["#fastify","#port","#heartbeatMonitor","#init","#ready"],"sources":["../../../../../zero-cache/src/services/http-service.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport Fastify, {type FastifyInstance} from 'fastify';\nimport {promiseVoid} from '../../../shared/src/resolved-promises.ts';\nimport {HeartbeatMonitor} from './life-cycle.ts';\nimport {RunningState} from './running-state.ts';\nimport type {Service} from './service.ts';\n\nexport type Options = {\n port: number;\n keepaliveTimeoutMs: number | undefined;\n\n // Wait for the readinessGate to resolve before responding to health checks.\n readinessGate?: Promise<void> | undefined;\n};\n\n/**\n * Common functionality for all HttpServices. These include:\n * * Responding to health checks at \"/\"\n * * Tracking optional heartbeats at \"/keepalive\" and draining when they stop.\n */\nexport class HttpService implements Service {\n readonly id: string;\n protected readonly _lc: LogContext;\n readonly #fastify: FastifyInstance;\n readonly #port: number;\n protected readonly _state: RunningState;\n readonly #heartbeatMonitor: HeartbeatMonitor | undefined;\n readonly #init: (fastify: FastifyInstance) => void | Promise<void>;\n\n #ready = false;\n\n constructor(\n id: string,\n lc: LogContext,\n opts: Options,\n init: (fastify: FastifyInstance) => void | Promise<void>,\n ) {\n const {port, keepaliveTimeoutMs, readinessGate = promiseVoid} = opts;\n this.id = id;\n this._lc = lc.withContext('component', this.id);\n this.#fastify = Fastify();\n this.#port = port;\n this.#init = init;\n this._state = new RunningState(id);\n this.#heartbeatMonitor = keepaliveTimeoutMs\n ? new HeartbeatMonitor(this._lc, keepaliveTimeoutMs)\n : undefined;\n\n void readinessGate.then(() => (this.#ready = true));\n }\n\n // Life-cycle hooks for subclass implementations\n protected _onStart() {}\n protected _onStop(): Promise<void> {\n return promiseVoid;\n }\n // start() is used in unit tests.\n // run() is the lifecycle method called by the ServiceRunner.\n async start(): Promise<string> {\n this.#fastify.get('/', (_req, res) => {\n if (this.#ready) {\n res.send('OK');\n }\n });\n this.#fastify.get('/keepalive', ({headers}, res) => {\n this.#heartbeatMonitor?.onHeartbeat(headers);\n if (this.#ready) {\n res.send('OK');\n }\n });\n await this.#init(this.#fastify);\n const address = await this.#fastify.listen({\n host: '::',\n port: this.#port,\n });\n this._lc.info?.(`${this.id} listening at ${address}`);\n this._onStart();\n return address;\n }\n\n async run(): Promise<void> {\n await this.start();\n await this._state.stopped();\n }\n\n async stop(): Promise<void> {\n this._lc.info?.(`${this.id}: no longer accepting connections`);\n this.#heartbeatMonitor?.stop();\n this._state.stop(this._lc);\n await this.#fastify.close();\n await this._onStop();\n }\n}\n"],"mappings":";;;;;;;;;;AAoBA,IAAa,cAAb,MAA4C;CAC1C;CACA;CACA;CACA;CACA;CAC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cessDuration(): import("../../observa
26
26
  export declare function litestreamBackupListDuration(): import("../../observability/metrics.ts").LatencyHistogram;
27
27
  export declare function litestreamBackupVerificationDuration(): import("../../observability/metrics.ts").LatencyHistogram;
28
28
  export declare function litestreamSnapshotReservationDuration(): import("../../observability/metrics.ts").LatencyHistogram;
29
+ export declare function litestreamSnapshotReservationConfirmDuration(): import("../../observability/metrics.ts").LatencyHistogram;
29
30
  export {};
30
31
  //# sourceMappingURL=metrics.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"metrics.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/litestream/metrics.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,2BAA2B,CAAC;AAOhE,MAAM,MAAM,cAAc,GAAG,qBAAqB,GAAG,aAAa,CAAC;AACnE,MAAM,MAAM,iBAAiB,GAAG,QAAQ,GAAG,IAAI,CAAC;AAEhD,MAAM,MAAM,qBAAqB,GAAG;IAClC,IAAI,EAAE,cAAc,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,iBAAiB,CAAC;CAC/B,CAAC;AAEF,KAAK,8BAA8B,GAAG;IACpC,qBAAqB,EAAE,MAAM,CAAC;IAC9B,kBAAkB,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,wBAAgB,4BAA4B,CAC1C,MAAM,EAAE,gBAAgB,EACxB,IAAI,EAAE,cAAc,EACpB,SAAS,qBAAmB,GAC3B,qBAAqB,GAAG,8BAA8B,CAaxD;AAED,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,gBAAgB,GACvB,qBAAqB,CAUvB;AAED,wBAAgB,kCAAkC,CAChD,MAAM,EAAE,gBAAgB,GACvB,qBAAqB,GAAG,8BAA8B,CAKxD;AAED,wBAAgB,4BAA4B,CAC1C,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,iBAAiB,EAC7B,IAAI,EAAE,cAAc,GACnB,qBAAqB,CAMvB;AAuBD,wBAAgB,qBAAqB,kFAMpC;AAED,wBAAgB,yBAAyB,kFAMxC;AAED,wBAAgB,yBAAyB,kFAMxC;AAED,wBAAgB,2BAA2B,kFAM1C;AAED,wBAAgB,yBAAyB,8DAKxC;AAED,wBAAgB,6BAA6B,8DAK5C;AAED,wBAAgB,gCAAgC,8DAK/C;AAED,wBAAgB,mCAAmC,8DAKlD;AAED,wBAAgB,+BAA+B,8DAK9C;AAED,wBAAgB,4BAA4B,8DAK3C;AAED,wBAAgB,oCAAoC,8DAKnD;AAED,wBAAgB,qCAAqC,8DAKpD"}
1
+ {"version":3,"file":"metrics.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/litestream/metrics.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,2BAA2B,CAAC;AAOhE,MAAM,MAAM,cAAc,GAAG,qBAAqB,GAAG,aAAa,CAAC;AACnE,MAAM,MAAM,iBAAiB,GAAG,QAAQ,GAAG,IAAI,CAAC;AAEhD,MAAM,MAAM,qBAAqB,GAAG;IAClC,IAAI,EAAE,cAAc,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,iBAAiB,CAAC;CAC/B,CAAC;AAEF,KAAK,8BAA8B,GAAG;IACpC,qBAAqB,EAAE,MAAM,CAAC;IAC9B,kBAAkB,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,wBAAgB,4BAA4B,CAC1C,MAAM,EAAE,gBAAgB,EACxB,IAAI,EAAE,cAAc,EACpB,SAAS,qBAAmB,GAC3B,qBAAqB,GAAG,8BAA8B,CAaxD;AAED,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,gBAAgB,GACvB,qBAAqB,CAUvB;AAED,wBAAgB,kCAAkC,CAChD,MAAM,EAAE,gBAAgB,GACvB,qBAAqB,GAAG,8BAA8B,CAKxD;AAED,wBAAgB,4BAA4B,CAC1C,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,iBAAiB,EAC7B,IAAI,EAAE,cAAc,GACnB,qBAAqB,CAMvB;AAuBD,wBAAgB,qBAAqB,kFAMpC;AAED,wBAAgB,yBAAyB,kFAMxC;AAED,wBAAgB,yBAAyB,kFAMxC;AAED,wBAAgB,2BAA2B,kFAM1C;AAED,wBAAgB,yBAAyB,8DAKxC;AAED,wBAAgB,6BAA6B,8DAK5C;AAED,wBAAgB,gCAAgC,8DAK/C;AAED,wBAAgB,mCAAmC,8DAKlD;AAED,wBAAgB,+BAA+B,8DAK9C;AAED,wBAAgB,4BAA4B,8DAK3C;AAED,wBAAgB,oCAAoC,8DAKnD;AAED,wBAAgB,qCAAqC,8DAKpD;AAED,wBAAgB,4CAA4C,8DAM3D"}
@@ -81,6 +81,9 @@ function litestreamBackupVerificationDuration() {
81
81
  function litestreamSnapshotReservationDuration() {
82
82
  return litestreamDurationHistogram("litestream.snapshot.reservation_duration", "Duration of a snapshot reservation while a view-syncer restores and subscribes.");
83
83
  }
84
+ function litestreamSnapshotReservationConfirmDuration() {
85
+ return litestreamDurationHistogram("litestream.snapshot.reservation_confirm_duration", "Time from opening a snapshot reservation to confirming its change-log bounds, by the source those bounds came from.");
86
+ }
84
87
  function litestreamDurationHistogram(name, description) {
85
88
  return getOrCreateHistogram("replica", name, {
86
89
  description,
@@ -89,6 +92,6 @@ function litestreamDurationHistogram(name, description) {
89
92
  });
90
93
  }
91
94
  //#endregion
92
- export { litestreamBackupListDuration, litestreamBackupMetricAttrs, litestreamBackupProcessDuration, litestreamBackupProcessMetricAttrs, litestreamBackupProcessRuns, litestreamBackupVerificationDuration, litestreamMonitorMetricAttrs, litestreamRestoreAttempts, litestreamRestoreDuration, litestreamRestoreMetricAttrs, litestreamRestoreProcessDuration, litestreamRestoreRuns, litestreamRestoreValidationDuration, litestreamRestoredDbBytes, litestreamSnapshotReservationDuration };
95
+ export { litestreamBackupListDuration, litestreamBackupMetricAttrs, litestreamBackupProcessDuration, litestreamBackupProcessMetricAttrs, litestreamBackupProcessRuns, litestreamBackupVerificationDuration, litestreamMonitorMetricAttrs, litestreamRestoreAttempts, litestreamRestoreDuration, litestreamRestoreMetricAttrs, litestreamRestoreProcessDuration, litestreamRestoreRuns, litestreamRestoreValidationDuration, litestreamRestoredDbBytes, litestreamSnapshotReservationConfirmDuration, litestreamSnapshotReservationDuration };
93
96
 
94
97
  //# sourceMappingURL=metrics.js.map