@rocicorp/zero 1.11.0-canary.1 → 1.11.0-canary.3

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 (102) hide show
  1. package/out/replicache/src/btree/read.d.ts +12 -1
  2. package/out/replicache/src/btree/read.d.ts.map +1 -1
  3. package/out/replicache/src/btree/read.js +24 -12
  4. package/out/replicache/src/btree/read.js.map +1 -1
  5. package/out/replicache/src/db/write.js.map +1 -1
  6. package/out/replicache/src/replicache-impl.d.ts.map +1 -1
  7. package/out/replicache/src/replicache-impl.js +10 -0
  8. package/out/replicache/src/replicache-impl.js.map +1 -1
  9. package/out/replicache/src/transactions.d.ts.map +1 -1
  10. package/out/replicache/src/transactions.js +1 -1
  11. package/out/replicache/src/transactions.js.map +1 -1
  12. package/out/zero/package.js +1 -1
  13. package/out/zero/package.js.map +1 -1
  14. package/out/zero-cache/src/config/zero-config.d.ts +2 -0
  15. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  16. package/out/zero-cache/src/config/zero-config.js +12 -4
  17. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  18. package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
  19. package/out/zero-cache/src/server/replicator.js +1 -1
  20. package/out/zero-cache/src/server/replicator.js.map +1 -1
  21. package/out/zero-cache/src/services/change-source/common/replica-schema.d.ts.map +1 -1
  22. package/out/zero-cache/src/services/change-source/common/replica-schema.js +2 -39
  23. package/out/zero-cache/src/services/change-source/common/replica-schema.js.map +1 -1
  24. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +2 -2
  25. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  26. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +2 -2
  27. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  28. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +6 -6
  29. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
  30. package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
  31. package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
  32. package/out/zero-cache/src/services/litestream/commands.js +3 -1
  33. package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
  34. package/out/zero-cache/src/services/litestream/config-v5.yml +3 -4
  35. package/out/zero-cache/src/services/replicator/change-log-db.js.map +1 -1
  36. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
  37. package/out/zero-cache/src/services/replicator/incremental-sync.js +22 -5
  38. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  39. package/out/zero-cache/src/services/replicator/replicator.js.map +1 -1
  40. package/out/zero-cache/src/services/replicator/write-worker-client.d.ts +4 -4
  41. package/out/zero-cache/src/services/replicator/write-worker-client.d.ts.map +1 -1
  42. package/out/zero-cache/src/services/replicator/write-worker-client.js +2 -2
  43. package/out/zero-cache/src/services/replicator/write-worker-client.js.map +1 -1
  44. package/out/zero-cache/src/services/replicator/write-worker.js +10 -4
  45. package/out/zero-cache/src/services/replicator/write-worker.js.map +1 -1
  46. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  47. package/out/zero-cache/src/services/view-syncer/view-syncer.js +75 -27
  48. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  49. package/out/zero-cache/src/types/streams.d.ts +6 -6
  50. package/out/zero-cache/src/types/streams.d.ts.map +1 -1
  51. package/out/zero-cache/src/types/streams.js +6 -11
  52. package/out/zero-cache/src/types/streams.js.map +1 -1
  53. package/out/zero-client/src/client/context.d.ts +15 -0
  54. package/out/zero-client/src/client/context.d.ts.map +1 -1
  55. package/out/zero-client/src/client/context.js +44 -0
  56. package/out/zero-client/src/client/context.js.map +1 -1
  57. package/out/zero-client/src/client/inspector/lazy-inspector.js +2 -2
  58. package/out/zero-client/src/client/inspector/lazy-inspector.js.map +1 -1
  59. package/out/zero-client/src/client/ivm-branch.js.map +1 -1
  60. package/out/zero-client/src/client/version.js +1 -1
  61. package/out/zero-client/src/client/zero-rep.d.ts.map +1 -1
  62. package/out/zero-client/src/client/zero-rep.js +2 -1
  63. package/out/zero-client/src/client/zero-rep.js.map +1 -1
  64. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  65. package/out/zero-client/src/client/zero.js +48 -11
  66. package/out/zero-client/src/client/zero.js.map +1 -1
  67. package/out/zero-protocol/src/down.d.ts +29 -29
  68. package/out/zero-protocol/src/inspect-down.d.ts +81 -81
  69. package/out/zero-protocol/src/poke.d.ts +6 -6
  70. package/out/zero-react/src/use-query.d.ts.map +1 -1
  71. package/out/zero-react/src/use-query.js +24 -5
  72. package/out/zero-react/src/use-query.js.map +1 -1
  73. package/out/zero-solid/src/use-query.js +4 -1
  74. package/out/zero-solid/src/use-query.js.map +1 -1
  75. package/out/zql/src/ivm/array-view.d.ts.map +1 -1
  76. package/out/zql/src/ivm/array-view.js +5 -3
  77. package/out/zql/src/ivm/array-view.js.map +1 -1
  78. package/out/zql/src/ivm/deferred-input.d.ts +44 -0
  79. package/out/zql/src/ivm/deferred-input.d.ts.map +1 -0
  80. package/out/zql/src/ivm/deferred-input.js +88 -0
  81. package/out/zql/src/ivm/deferred-input.js.map +1 -0
  82. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  83. package/out/zql/src/ivm/memory-source.js +5 -10
  84. package/out/zql/src/ivm/memory-source.js.map +1 -1
  85. package/out/zql/src/query/query-delegate-base.d.ts +6 -0
  86. package/out/zql/src/query/query-delegate-base.d.ts.map +1 -1
  87. package/out/zql/src/query/query-delegate-base.js +73 -10
  88. package/out/zql/src/query/query-delegate-base.js.map +1 -1
  89. package/out/zql/src/query/query-delegate.d.ts +22 -0
  90. package/out/zql/src/query/query-delegate.d.ts.map +1 -1
  91. package/out/zql/src/query/query-impl.d.ts +12 -11
  92. package/out/zql/src/query/query-impl.d.ts.map +1 -1
  93. package/out/zql/src/query/query-impl.js +383 -60
  94. package/out/zql/src/query/query-impl.js.map +1 -1
  95. package/out/zql/src/query/query-transitions.d.ts +171 -0
  96. package/out/zql/src/query/query-transitions.d.ts.map +1 -0
  97. package/out/zql/src/query/query-transitions.js +207 -0
  98. package/out/zql/src/query/query-transitions.js.map +1 -0
  99. package/out/zql/src/query/runnable-query-impl.d.ts.map +1 -1
  100. package/out/zql/src/query/runnable-query-impl.js +21 -1
  101. package/out/zql/src/query/runnable-query-impl.js.map +1 -1
  102. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"change-log-db.js","names":[],"sources":["../../../../../../zero-cache/src/services/replicator/change-log-db.ts"],"sourcesContent":["/**\n * The change log lives in its own SQLite database, `${replicaFile}-change-log`,\n * rather than in the replica file. It is a catchup cache: everything it holds is\n * either already durable in the replica's litestream backup or re-derivable from\n * the upstream replication slot, so it is deliberately excluded from the backup\n * and is never a source of truth.\n *\n * The change-streamer writes it, from the stream loop that fans changes out to\n * subscribers, and commits it before forwarding each transaction's `commit`\n * message. Its head is therefore always at or above the watermark the stream\n * would resume from, which is what {@link reconcileChangeLog} anchors on.\n *\n * Beside the buffer it holds the log's *cookie jar* — the backfill progress\n * state folded up to the same head. That is `change-log-cookies.ts`; this file\n * owns its tables' lifecycle, because a cookie set is only meaningful paired\n * with the watermark it was folded to, and so must be created, dropped, and —\n * whenever reconciliation moves the head — replaced with the anchor's, all with\n * the buffer rather than beside it.\n *\n * Because it is disposable, it has no migration framework. Any inconsistency —\n * a schema change, a leftover file from a different replica, a gap left by a\n * crash or by running with the writer disabled, a corrupt file — is resolved by\n * {@link reconcileChangeLog} and {@link openChangeLogDBForWriting}, which\n * truncate a bounded suffix or replace and reseed the log at the resume\n * watermark. The worst outcome is a `too-old` for a lagging subscriber; a\n * silently delivered gap is not reachable.\n *\n * Disk sizing: a task that writes the log needs room for the replica *plus* the\n * retained change stream — the log's main file, its wal2 sidecars, and pages a\n * purge has freed but not yet returned to the OS. The change-streamer schedules\n * purges against the same floor as the PG change log, so retention is bounded\n * by the confirmed backup watermark ANDed with the minimum retention window —\n * a function of the backup interval, not a constant: 15–30+ minutes behind an\n * RMv1 sync interval, ~60 seconds once litestream v5 backs up every 15–30 s.\n * A held snapshot reservation pins retention unboundedly for its duration, so\n * peak retained bytes is set by the slowest concurrent restore rather than by\n * the retention setting — size disk and alerts on that. The log is excluded\n * from the litestream backup, so this is local disk only and never S3.\n */\n\nimport {existsSync} from 'node:fs';\nimport type {LogContext} from '@rocicorp/logger';\nimport {Database} from '../../../../zqlite/src/db.ts';\nimport {deleteLiteDB} from '../../db/delete-lite-db.ts';\nimport {\n isSQLiteCorruption,\n logSQLiteCorruptionDiagnostics,\n} from '../../db/sqlite-corruption.ts';\nimport {\n CHANGE_LOG_BACKFILLING_TABLE,\n CHANGE_LOG_TABLE_METADATA_TABLE,\n CREATE_CHANGE_LOG_COOKIE_SCHEMA,\n DROP_CHANGE_LOG_COOKIE_TABLES,\n replaceCookies,\n type CookieSet,\n} from './change-log-cookies.ts';\n\n/**\n * Bumped whenever the change-log database's schema changes. Since the file is a\n * cache, a mismatch costs one reseed rather than a migration.\n *\n * v2 re-homed the writer to the change-streamer: the log anchors on the\n * watermark its stream connection resumes from rather than on the replica's\n * state version, and its meta row carries the replica's identity triple plus\n * the seed point.\n *\n * v3 added the cookie tables (see `change-log-cookies.ts`), i.e. the log's\n * second job. The reseed it costs on upgrade buys one retention window of\n * catchup reach on a log nothing reads yet.\n *\n * v4 stores each row's tag and estimated retained bytes alongside its JSON.\n * Readers can now filter without parsing arbitrary row payloads, and\n * reconciliation can bound truncation by bytes as well as rows.\n *\n * `auto_vacuum = INCREMENTAL` arrived within v2, deliberately without a bump:\n * it is a file-header property rather than a schema change, and the reseed a\n * version mismatch triggers cannot enable it (see\n * {@link applyChangeLogPragmas}), so {@link openChangeLogDBForWriting} guards\n * on the pragma itself instead of on this number.\n */\nexport const CHANGE_LOG_DB_SCHEMA_VERSION = 4;\n\n/** https://www.sqlite.org/pragma.html#pragma_auto_vacuum */\nconst AUTO_VACUUM_INCREMENTAL = 2;\n\nexport const CHANGE_LOG_STREAM_TABLE = '_zero.changeLogStream';\nexport const CHANGE_LOG_STREAM_WRITE_TIME_INDEX =\n '_zero.changeLogStream_writeTimeMs';\n\nconst INTEGER_BYTES = 8;\n\n/**\n * Estimates the retained payload size of a stream row. This deliberately does\n * not claim to measure SQLite b-tree/page overhead; it is stable across the\n * write path, reconciliation, and the startup scan used by observability.\n */\nexport function estimateChangeLogStreamRowBytes(\n watermark: string,\n tag: string,\n change: string,\n precommit?: string,\n hasWriteTime = false,\n): number {\n return (\n Buffer.byteLength(watermark) +\n INTEGER_BYTES +\n Buffer.byteLength(tag) +\n Buffer.byteLength(change) +\n (precommit === undefined ? 0 : Buffer.byteLength(precommit)) +\n (hasWriteTime ? INTEGER_BYTES : 0)\n );\n}\n\n// The index is partial because only commit rows carry a \"writeTimeMs\", so it\n// holds one entry per transaction rather than one per change. It is what the\n// purger scans to find transactions older than the retention window.\n//\n// The replica carried this table's original shape through versions 14 and 15;\n// see `CREATE_V14_CHANGE_LOG_STREAM` in\n// `change-source/common/replica-schema.ts`, which is frozen at the v14 shape\n// and must not be kept in sync with this one.\nexport const CREATE_CHANGE_LOG_STREAM_SCHEMA = /*sql*/ `\n CREATE TABLE \"${CHANGE_LOG_STREAM_TABLE}\" (\n \"watermark\" TEXT NOT NULL,\n \"pos\" INTEGER NOT NULL,\n \"tag\" TEXT NOT NULL,\n \"estimatedBytes\" INTEGER NOT NULL,\n \"change\" TEXT NOT NULL,\n \"precommit\" TEXT,\n \"writeTimeMs\" INTEGER,\n PRIMARY KEY (\"watermark\", \"pos\")\n );\n\n CREATE INDEX \"${CHANGE_LOG_STREAM_WRITE_TIME_INDEX}\"\n ON \"${CHANGE_LOG_STREAM_TABLE}\" (\"writeTimeMs\", \"watermark\")\n WHERE \"writeTimeMs\" IS NOT NULL;\n`;\n\n/**\n * Inserts the synthetic begin/commit pair for the seed watermark.\n *\n * Both rows are inserted by one statement so a caller outside a larger\n * transaction cannot leave a partial seed.\n */\nconst SEED_CHANGE_LOG_STREAM_SQL = /*sql*/ `\n INSERT INTO \"${CHANGE_LOG_STREAM_TABLE}\"\n (\"watermark\", \"pos\", \"tag\", \"estimatedBytes\", \"change\", \"precommit\",\n \"writeTimeMs\")\n VALUES\n (@watermark, 0, 'begin', @beginBytes, @beginChange, NULL, NULL),\n (@watermark, 1, 'commit', @commitBytes, @commitChange, @watermark,\n @writeTimeMs)\n ON CONFLICT (\"watermark\", \"pos\") DO NOTHING\n`;\n\nexport const CHANGE_LOG_META_TABLE = '_zero.changeLogMeta';\n\n// The identity triple (see ChangeLogIdentity) detects a file left behind by a\n// different replica -- most concretely, a leftover log on a reused volume.\n//\n// \"seededAtMs\" : when the log was seeded, i.e. how far its retention window\n// can possibly reach back. Slice 11 uses it as the warm-up\n// signal for canary reads.\n// \"seedWatermark\" : where the log was seeded. `min(\"watermark\")` cannot answer\n// this once purge has advanced the minimum, and the\n// difference is what distinguishes a log that purged past the\n// retention floor (an invariant violation) from one that\n// never held that history at all (routine at every fork).\n// \"lock\" : enforces single-row semantics, as in\n// \"_zero.replicationConfig\".\nconst CREATE_CHANGE_LOG_META_SCHEMA = /*sql*/ `\n CREATE TABLE \"${CHANGE_LOG_META_TABLE}\" (\n \"epoch\" TEXT,\n \"generation\" TEXT NOT NULL,\n \"replicaID\" TEXT,\n \"schemaVersion\" INTEGER NOT NULL,\n \"seededAtMs\" INTEGER NOT NULL,\n \"seedWatermark\" TEXT NOT NULL,\n \"lock\" INTEGER PRIMARY KEY DEFAULT 1 CHECK (\"lock\" = 1)\n );\n`;\n\n/**\n * `${replicaFile}-change-log`, matching the `-serving-copy` convention.\n *\n * The name outlives the writer's move into the change-streamer: the\n * change-streamer derives the path from the replica file it owns, so renaming\n * would save no plumbing and would orphan the old file on every existing\n * volume, where nothing would delete it.\n *\n * Its `-wal` / `-wal2` / `-shm` sidecars are suffixes of *this* name, so they\n * never collide with the replica's own sidecars.\n */\nexport function changeLogFileName(replicaFile: string): string {\n return `${replicaFile}-change-log`;\n}\n\n/**\n * Removes the change-log database and its `-wal` / `-wal2` / `-shm` sidecars.\n * Safe to call when the file does not exist.\n */\nexport function deleteChangeLogDB(replicaFile: string): void {\n deleteLiteDB(changeLogFileName(replicaFile));\n}\n\n/**\n * Which replica the log's contents belong to.\n *\n * `generation` is RMv1's `replicaVersion`: the version at which initial sync\n * copied every row. It is shared by every sibling of a forked replica, which is\n * why it cannot be the whole of the identity under RMv2 — `epoch` and\n * `replicaID` are what distinguish two siblings' logs. Both are `null` until\n * RMv2 supplies them, and a `null` matches only another `null`, so a log\n * written before they exist is still recognized as this replica's.\n */\nexport type ChangeLogIdentity = {\n readonly epoch: string | null;\n readonly generation: string;\n readonly replicaID: string | null;\n};\n\n/**\n * Where the stream connection resumes, and everything the log's state at that\n * position consists of.\n *\n * The two fields travel together because a cookie set is only meaningful paired\n * with the watermark it was folded up to (invariant 15). They are read from one\n * store, in one snapshot: `Storer.getStartStreamInitializationParameters()`\n * reads both from Postgres in a single REPEATABLE READ transaction. Pairing one\n * store's cookies with another's watermark would silently drop every backfill\n * that completed in the interval, and those rows are unrecoverable — backfill\n * transactions are synthesized by the change source rather than replayed from\n * the slot.\n */\nexport type ChangeLogResumePoint = {\n /**\n * The watermark this stream connection resumes from. The log's own head is\n * measured against it, and a reseed seeds a synthetic transaction at it.\n *\n * Deliberately *not* \"the replica's state version\": after the writer moved to\n * the change-streamer, the canonical replicator is a subscriber downstream of\n * the write loop, so its state version is a consequence of this log rather\n * than a constraint on it.\n */\n readonly resumeWatermark: string;\n /**\n * The cookie set that belongs to {@link resumeWatermark}. Any reconciliation\n * that moves the head invalidates the set the log was holding — the cookies\n * are unversioned point-in-time state, and truncating the stream above `W`\n * does not roll them back to `W` — so the same transaction installs this one\n * in its place (invariant 17).\n *\n * Postgres supplies it while it remains the store the stream resumes from. At\n * the C5 flip the log's own head *is* the resume point, phantoms cannot\n * exist, and both this field and the truncate-above path become dead code.\n */\n readonly cookies: CookieSet;\n};\n\n/**\n * What the log is reconciled against. Reconciliation runs once per stream\n * connection, since every reconnect can re-read a different resume point.\n */\nexport type ChangeLogAnchor = ChangeLogResumePoint & {\n readonly identity: ChangeLogIdentity;\n /**\n * The change-streamer's clock, at reconciliation time. Supplied rather than\n * read inline so that tests control it. Used for `seededAtMs` and for the\n * seed transaction's `writeTimeMs`, which is what the purger's time floor\n * measures.\n */\n readonly nowMs: number;\n};\n\n/** The meta row, i.e. everything the log records about itself. */\nexport type ChangeLogMeta = ChangeLogIdentity & {\n readonly schemaVersion: number;\n readonly seededAtMs: number;\n readonly seedWatermark: string;\n};\n\n/**\n * Opens the change-log database beside `replicaFile`.\n *\n * A writable handle creates the file if it is absent; a `readonly` handle\n * throws, which is the normal state for a change-streamer whose writer is\n * disabled. Pragmas are the caller's responsibility, since only the writer sets\n * the persistent ones.\n */\nexport function openChangeLogDB(\n lc: LogContext,\n replicaFile: string,\n opts: {readonly: boolean},\n): Database {\n return new Database(\n lc.withContext('component', 'change-log-db'),\n changeLogFileName(replicaFile),\n {readonly: opts.readonly},\n );\n}\n\n/**\n * Configures the change-log database, which the change-streamer's writer owns\n * exclusively. These are the settings the `separate-files` mode of\n * `sqlite-change-log-ceiling.bench.ts` measured.\n *\n * `wal2` because the log is a continuous append that catchup reads\n * continuously, which is the case wal2 exists for: it avoids checkpoint\n * starvation without needing an autocheckpoint. `wal_autocheckpoint` therefore\n * keeps its default, unlike the backup replica's 0, which hands checkpointing\n * to litestream — nothing else owns this file.\n *\n * `synchronous = NORMAL` because the commit sits on the forward path, once per\n * upstream transaction, and NORMAL keeps that from costing an fsync. It is not\n * a durability compromise here: in WAL mode NORMAL still writes every commit\n * through to the OS, so it survives a process crash, an OOM kill, or a SIGKILL.\n * It is lost only to kernel panic or power loss, and those destroy the node —\n * the task restarts elsewhere, restores the replica from S3, and has no\n * change-log file at all. Whatever a power loss does take is detected by\n * {@link reconcileChangeLog} and reseeded.\n *\n * `auto_vacuum = INCREMENTAL` so that purge can return freed pages to the OS\n * rather than leaving the file at its high-water mark. **It must be the first\n * statement here.** SQLite honours a `none` -> `incremental` transition only\n * while the file is still empty, and `journal_mode = wal2` materializes page 1;\n * appending the pragma instead of prepending it silently leaves the file at\n * mode 0 forever, since neither `DROP TABLE` nor a reseed makes a file empty\n * again. {@link openChangeLogDBForWriting} verifies the result.\n */\nexport function applyChangeLogPragmas(db: Database): void {\n db.pragma('auto_vacuum = INCREMENTAL');\n db.pragma('busy_timeout = 30000');\n db.pragma('analysis_limit = 1000');\n db.pragma('journal_mode = wal2');\n db.pragma('synchronous = NORMAL');\n}\n\nfunction readAutoVacuum(db: Database): number {\n const [{auto_vacuum: mode}] = db.pragma<{auto_vacuum: number}>('auto_vacuum');\n return mode;\n}\n\n/**\n * Opens the change-log database for the writer, applies its pragmas, and\n * reconciles it against `anchor`, returning the handle and what reconciliation\n * had to do.\n *\n * Corruption is answered with a rebuild rather than an escalation, which is a\n * deliberate divergence from how the replica's own corruption is handled. A\n * corrupt replica is a lost source of truth, so it ends in a restore or an\n * auto-reset; the change log holds nothing that is not either already in the\n * replica's litestream backup or re-derivable from the upstream slot, so the\n * entire response is to delete the file and seed a new one at the resume\n * watermark. The cost is one retention window of catchup — reconnecting\n * subscribers below the head get `too-old` — which is what every other\n * {@link ReseedReason} costs.\n *\n * Only corruption is rebuilt through. Anything else (a bad path, a permissions\n * error, a full disk) is a problem with the environment rather than with the\n * file's contents, and deleting a database in response would destroy state\n * without fixing it. Those propagate to the caller, which disables the writer\n * and keeps replicating.\n *\n * A file that predates `auto_vacuum = INCREMENTAL` takes the same rebuild, for\n * the same reason and at the same cost: the pragma only takes on an empty file,\n * so a reseed cannot enable it. Unlike corruption, a *second* failure there is\n * tolerated rather than thrown — see {@link ensureIncrementalAutoVacuum}.\n */\n/**\n * Returns an anchor after the database opens.\n *\n * The resolver can inspect the existing file before it selects the anchor. A\n * valid log can use its own head. A new or invalid log uses the replica seed.\n * The rebuild path calls the resolver again for the new file.\n */\nexport type AnchorResolver = (db: Database) => ChangeLogAnchor;\n\nexport function openChangeLogDBForWriting(\n lc: LogContext,\n replicaFile: string,\n anchor: AnchorResolver,\n): {db: Database; result: ReconcileResult; replacedFile: boolean} {\n const existed = existsSync(changeLogFileName(replicaFile));\n const opened = openOrRebuildCorrupt(lc, replicaFile, anchor, existed);\n const {db, result, replacedFile} = ensureIncrementalAutoVacuum(\n lc,\n replicaFile,\n anchor,\n opened,\n );\n return {db, result, replacedFile};\n}\n\nfunction openOrRebuildCorrupt(\n lc: LogContext,\n replicaFile: string,\n anchor: AnchorResolver,\n boundReconciliation: boolean,\n): OpenedChangeLog {\n try {\n return openAndReconcile(lc, replicaFile, anchor, boundReconciliation);\n } catch (e) {\n if (e instanceof ChangeLogRebuildRequired) {\n return rebuildChangeLog(lc, replicaFile, anchor, e);\n }\n if (!isSQLiteCorruption(e)) {\n throw e;\n }\n const file = changeLogFileName(replicaFile);\n logSQLiteCorruptionDiagnostics(lc, 'change-log', file, e);\n lc.error?.('rebuilding the corrupt SQLite change log', {\n sqliteChangeLog: {file},\n });\n return rebuildChangeLog(lc, replicaFile, anchor);\n }\n}\n\n/**\n * Rebuilds a log whose `auto_vacuum` mode is not `INCREMENTAL`, which is every\n * log created before the pragma shipped — including every v2 file the writer\n * wrote in the meantime, which is why the guard is on the pragma rather than\n * on the schema version. Deleting the file is the only way to enable it:\n * `DROP TABLE` leaves the header's mode intact, and the in-place alternative —\n * a full `VACUUM` — is an unbounded blocking statement on a file the writer\n * needs.\n *\n * A mode that is still wrong after the rebuild is logged and tolerated, which\n * is the one place this diverges from the corruption path. The two failures are\n * not alike: a file that stays corrupt after a rebuild is an environment\n * problem, but a pragma that stays wrong on a brand-new file can only mean\n * {@link applyChangeLogPragmas}' statement order is wrong — a code bug, present\n * on every task, on every start. Throwing there turns a lost optimization into\n * a crash loop, and rebuilding again turns it into a reseed per start, which is\n * worse than the freelist growth it was trying to avoid. `Database.compact()`\n * already warns and no-ops when the mode is not `INCREMENTAL`, so degrading is\n * the accepted fallback.\n */\nfunction ensureIncrementalAutoVacuum(\n lc: LogContext,\n replicaFile: string,\n anchor: AnchorResolver,\n opened: OpenedChangeLog,\n): OpenedChangeLog {\n if (opened.autoVacuum === AUTO_VACUUM_INCREMENTAL) {\n return opened;\n }\n const file = changeLogFileName(replicaFile);\n lc.info?.('rebuilding the SQLite change log to enable incremental vacuum', {\n sqliteChangeLog: {file, autoVacuum: opened.autoVacuum},\n });\n opened.db.close();\n const rebuilt = rebuildChangeLog(lc, replicaFile, anchor);\n if (rebuilt.autoVacuum !== AUTO_VACUUM_INCREMENTAL) {\n lc.error?.(\n 'SQLite change log does not support incremental vacuum; ' +\n 'it will plateau at its high-water mark',\n {sqliteChangeLog: {file, autoVacuum: rebuilt.autoVacuum}},\n );\n }\n return rebuilt;\n}\n\n/** The shared \"delete the file and open a new one\" body. */\nfunction rebuildChangeLog(\n lc: LogContext,\n replicaFile: string,\n anchor: AnchorResolver,\n required?: ChangeLogRebuildRequired | undefined,\n): OpenedChangeLog {\n if (required) {\n lc.warn?.(\n 'rebuilding the SQLite change log instead of running an unbounded reconciliation',\n {\n sqliteChangeLogRebuild: {\n reason: required.reason,\n rows: required.rows,\n estimatedBytes: required.estimatedBytes,\n },\n },\n );\n }\n deleteChangeLogDB(replicaFile);\n // The file is absent, so the reseed only drops empty/nonexistent tables. A\n // second failure is the environment's, not the old file's.\n const opened = openAndReconcile(\n lc,\n replicaFile,\n anchor,\n false,\n required?.reason,\n );\n return {...opened, replacedFile: true};\n}\n\n/**\n * Replaces an already-closed change-log file after bounded reconciliation\n * declined its work. The caller closes cached readers before calling this so\n * none can continue serving the unlinked inode.\n */\nexport function rebuildChangeLogDBForWriting(\n lc: LogContext,\n replicaFile: string,\n anchor: ChangeLogAnchor,\n required: ChangeLogRebuildRequired,\n): {db: Database; result: ReconcileResult; replacedFile: true} {\n const {db, result} = rebuildChangeLog(\n lc,\n replicaFile,\n () => anchor,\n required,\n );\n return {db, result, replacedFile: true};\n}\n\ntype OpenedChangeLog = {\n db: Database;\n result: ReconcileResult;\n replacedFile: boolean;\n /** The file's persistent `auto_vacuum` mode, read back after the pragmas. */\n autoVacuum: number;\n};\n\nfunction openAndReconcile(\n lc: LogContext,\n replicaFile: string,\n anchor: AnchorResolver,\n boundReconciliation: boolean,\n reseedReason?: ReseedReason | undefined,\n): OpenedChangeLog {\n const db = openChangeLogDB(lc, replicaFile, {readonly: false});\n try {\n applyChangeLogPragmas(db);\n const autoVacuum = readAutoVacuum(db);\n return {\n db,\n result: reconcileChangeLog(lc, db, anchor(db), {\n rebuildInsteadOfUnboundedWork: boundReconciliation,\n reseedReason,\n }),\n replacedFile: false,\n autoVacuum,\n };\n } catch (e) {\n // The caller never sees this handle, so it closes here or leaks — and it\n // must be closed before the corruption path deletes the file.\n db.close();\n throw e;\n }\n}\n\nexport type ReseedReason =\n | 'created' // file or table absent\n | 'schema-mismatch'\n | 'identity-mismatch'\n | 'gap' // head does not land on the resume watermark after truncation\n | 'oversized-truncate'; // preserving the prefix would require too much work\n\n/**\n * Reconciliation runs synchronously on the change-streamer's event loop. A\n * normal phantom is one transaction, so work above either limit is answered by\n * unlinking and reseeding this disposable cache rather than deleting an\n * arbitrarily large suffix in place.\n */\nexport const MAX_RECONCILE_TRUNCATE_ROWS = 10_000;\nexport const MAX_RECONCILE_TRUNCATE_BYTES = 16 * 1024 * 1024;\n\nexport class ChangeLogRebuildRequired extends Error {\n override readonly name = 'ChangeLogRebuildRequired';\n readonly reason: ReseedReason;\n readonly rows?: number | undefined;\n readonly estimatedBytes?: number | undefined;\n\n constructor(\n reason: ReseedReason,\n rows?: number | undefined,\n estimatedBytes?: number | undefined,\n ) {\n super(`SQLite change log requires a ${reason} rebuild`);\n this.reason = reason;\n this.rows = rows;\n this.estimatedBytes = estimatedBytes;\n }\n}\n\ntype ReconcileOptions = {\n /** Throw before an unbounded delete/drop so the file owner can unlink it. */\n readonly rebuildInsteadOfUnboundedWork?: boolean | undefined;\n /** Preserve the reason that caused an old file to be unlinked. */\n readonly reseedReason?: ReseedReason | undefined;\n};\n\n/**\n * `cookiesStale` records that the cookie set the log held did not survive\n * reconciliation. The cookies are unversioned point-in-time state, so any\n * reconciliation that moves the head invalidates them, and the same transaction\n * replaces them with the anchor's — the set that belongs to the resume\n * watermark (see `change-log-cookies.ts`). It is `action !== 'none'` today; it\n * is a field rather than a derivation because the replacement reads as intent\n * at the call site, and because it is what the `cookie_reseed` counter is keyed\n * on.\n */\nexport type ReconcileResult =\n | {action: 'none'; head: string; cookiesStale: false}\n | {action: 'truncated'; head: string; rows: number; cookiesStale: true}\n | {\n action: 'reseeded';\n head: string;\n reason: ReseedReason;\n cookiesStale: true;\n };\n\n/**\n * Brings the change log into agreement with the watermark its stream connection\n * resumes from, in one transaction on the change-log database:\n *\n * ```\n * head === resumeWatermark → keep appending\n * head > resumeWatermark → truncate above resumeWatermark\n * otherwise → wipe, seed at resumeWatermark, record the reason\n * ```\n *\n * The log commits before anything that can advance the resume watermark, so a\n * *phantom* — a transaction the log holds whose watermark the resumed stream\n * re-delivers — is the normal state, and truncate-above is the whole of\n * reconciliation rather than a special case. A phantom's rows all carry the\n * transaction's commit watermark, which is strictly greater than the resume\n * watermark, so deleting on that predicate removes phantoms whole and retains\n * every transaction at or below the resume point.\n *\n * It must run per stream connection, not once per process: the stream loop\n * re-reads its resume watermark on every reconnect, and the writer inserts with\n * a plain `INSERT` against `PRIMARY KEY (\"watermark\",\"pos\")`, so an\n * un-truncated overlap is a constraint violation on the first re-delivered\n * transaction.\n *\n * Anything truncation cannot resolve — the file was deleted, the writer was\n * disabled for a while, the replica was restored, power was lost with\n * `synchronous=NORMAL` — surfaces as a head that does not land on the resume\n * watermark, and is resolved by wiping and reseeding there.\n *\n * Whichever of the two moves the head also replaces the cookie set with the one\n * the anchor carries, in the same transaction: the head and the cookies are one\n * position, and nothing may observe them at two.\n */\nexport function reconcileChangeLog(\n lc: LogContext,\n db: Database,\n anchor: ChangeLogAnchor,\n opts: ReconcileOptions = {},\n): ReconcileResult {\n db.exec('BEGIN IMMEDIATE');\n try {\n if (opts.rebuildInsteadOfUnboundedWork) {\n const required = rebuildRequired(db, anchor);\n if (required) {\n throw required;\n }\n }\n const result = opts.reseedReason\n ? reseed(lc, db, anchor, opts.reseedReason)\n : reconcile(lc, db, anchor);\n db.exec('COMMIT');\n return result;\n } catch (e) {\n if (db.inTransaction) {\n db.exec('ROLLBACK');\n }\n throw e;\n }\n}\n\n/**\n * Decides whether reconciliation can be performed within its synchronous work\n * budget. Every query is either an index seek or a scan capped at one row past\n * the delete limit. No state changes before the decision is complete.\n */\nfunction rebuildRequired(\n db: Database,\n anchor: ChangeLogAnchor,\n): ChangeLogRebuildRequired | undefined {\n const wipe = changeLogWipeReason(db, anchor.identity);\n if (wipe !== undefined) {\n return new ChangeLogRebuildRequired(wipe);\n }\n\n const head = readChangeLogHead(db);\n const {resumeWatermark} = anchor;\n if (head === null || head < resumeWatermark) {\n return new ChangeLogRebuildRequired('gap');\n }\n if (head === resumeWatermark) {\n return undefined;\n }\n\n const boundary = db\n .prepare(/*sql*/ `\n SELECT 1 FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n WHERE \"watermark\" = ?\n LIMIT 1\n `)\n .get<{1: number} | undefined>(resumeWatermark);\n if (boundary === undefined) {\n return new ChangeLogRebuildRequired('gap');\n }\n\n const {rows, estimatedBytes} = db\n .prepare(/*sql*/ `\n SELECT count(*) AS \"rows\",\n coalesce(sum(\"estimatedBytes\"), 0) AS \"estimatedBytes\"\n FROM (\n SELECT \"estimatedBytes\" FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n WHERE \"watermark\" > ?\n LIMIT ${MAX_RECONCILE_TRUNCATE_ROWS + 1}\n )\n `)\n .get<{rows: number; estimatedBytes: number}>(resumeWatermark);\n return rows > MAX_RECONCILE_TRUNCATE_ROWS ||\n estimatedBytes > MAX_RECONCILE_TRUNCATE_BYTES\n ? new ChangeLogRebuildRequired('oversized-truncate', rows, estimatedBytes)\n : undefined;\n}\n\nfunction reconcile(\n lc: LogContext,\n db: Database,\n anchor: ChangeLogAnchor,\n): ReconcileResult {\n const wipe = changeLogWipeReason(db, anchor.identity);\n if (wipe !== undefined) {\n return reseed(lc, db, anchor, wipe);\n }\n\n const {resumeWatermark} = anchor;\n let head = readChangeLogHead(db);\n let rows = 0;\n if (head !== null && head > resumeWatermark) {\n rows = db\n .prepare(/*sql*/ `\n DELETE FROM \"${CHANGE_LOG_STREAM_TABLE}\" WHERE \"watermark\" > ?\n `)\n .run(resumeWatermark).changes;\n head = readChangeLogHead(db);\n }\n\n if (head !== resumeWatermark) {\n return reseed(lc, db, anchor, 'gap');\n }\n if (rows > 0) {\n // The truncated transactions can have carried `create-table`,\n // `add-column`, and `backfill-completed`, none of which the truncate rolls\n // back, so the cookie set no longer belongs to the head. The anchor's set\n // does, and it lands in this same transaction: invariant 17 holds at every\n // point another connection could observe the log.\n replaceCookies(db, anchor.cookies);\n lc.info?.('truncated phantom transactions from the SQLite change log', {\n sqliteChangeLogReconcile: {head, rows, cookies: cookieCounts(anchor)},\n });\n return {action: 'truncated', head, rows, cookiesStale: true};\n }\n lc.debug?.('SQLite change log is at the resume watermark', {\n sqliteChangeLogReconcile: {head},\n });\n return {action: 'none', head, cookiesStale: false};\n}\n\n/**\n * Returns the reason that the log must be recreated. Returns `undefined` when\n * the writer can continue to use the log.\n *\n * This function takes only the expected identity because callers use the result\n * to select the anchor.\n */\nexport function changeLogWipeReason(\n db: Database,\n identity: ChangeLogIdentity,\n): ReseedReason | undefined {\n if (\n !tableExists(db, CHANGE_LOG_STREAM_TABLE) ||\n !tableExists(db, CHANGE_LOG_META_TABLE)\n ) {\n return 'created';\n }\n // The schema version is read on its own because it is the one column every\n // version of this table has had. Reading the rest of a v1 row would fail on\n // its missing columns instead of reporting the mismatch that explains it.\n const version = db\n .prepare(/*sql*/ `\n SELECT \"schemaVersion\" FROM \"${CHANGE_LOG_META_TABLE}\"\n `)\n .get<{schemaVersion: number} | undefined>();\n if (version === undefined) {\n return 'created';\n }\n if (version.schemaVersion !== CHANGE_LOG_DB_SCHEMA_VERSION) {\n return 'schema-mismatch';\n }\n // Checked *after* the version, so that every pre-v4 file — which is every\n // file in the fleet at the upgrade — reports the `schema-mismatch` that\n // explains it rather than the `created` its absent cookie tables would\n // otherwise look like.\n if (\n !tableExists(db, CHANGE_LOG_TABLE_METADATA_TABLE) ||\n !tableExists(db, CHANGE_LOG_BACKFILLING_TABLE)\n ) {\n return 'created';\n }\n const {epoch, generation, replicaID} = readChangeLogMeta(db);\n if (\n epoch !== identity.epoch ||\n generation !== identity.generation ||\n replicaID !== identity.replicaID\n ) {\n return 'identity-mismatch';\n }\n return undefined;\n}\n\nfunction reseed(\n lc: LogContext,\n db: Database,\n anchor: ChangeLogAnchor,\n reason: ReseedReason,\n): ReconcileResult {\n const {identity, resumeWatermark, nowMs} = anchor;\n // Dropping the table drops its partial index with it. The cookie tables go\n // with the buffer: a cookie set without the transactions it was folded from\n // is not a smaller cookie set, it is a wrong one.\n db.exec(/*sql*/ `\n DROP TABLE IF EXISTS \"${CHANGE_LOG_STREAM_TABLE}\";\n DROP TABLE IF EXISTS \"${CHANGE_LOG_META_TABLE}\";\n ${DROP_CHANGE_LOG_COOKIE_TABLES}\n ${CREATE_CHANGE_LOG_STREAM_SCHEMA}\n ${CREATE_CHANGE_LOG_META_SCHEMA}\n ${CREATE_CHANGE_LOG_COOKIE_SCHEMA}\n `);\n db.prepare(/*sql*/ `\n INSERT INTO \"${CHANGE_LOG_META_TABLE}\"\n (\"epoch\", \"generation\", \"replicaID\", \"schemaVersion\", \"seededAtMs\",\n \"seedWatermark\")\n VALUES (@epoch, @generation, @replicaID, @schemaVersion, @seededAtMs,\n @seedWatermark)\n `).run({\n epoch: identity.epoch,\n generation: identity.generation,\n replicaID: identity.replicaID,\n schemaVersion: CHANGE_LOG_DB_SCHEMA_VERSION,\n seededAtMs: nowMs,\n seedWatermark: resumeWatermark,\n });\n seedChangeLogStream(db, anchor);\n // Into tables this statement just created, so the wholesale replacement is\n // all insert. It is still the same call the truncate path makes: a reseed is\n // the case where the log's cookie set was not merely moved but discarded, and\n // the anchor's is equally what belongs at the head either way.\n replaceCookies(db, anchor.cookies);\n\n lc.info?.('reseeded the SQLite change log', {\n sqliteChangeLogReconcile: {\n reason,\n head: resumeWatermark,\n ...identity,\n schemaVersion: CHANGE_LOG_DB_SCHEMA_VERSION,\n seededAtMs: nowMs,\n cookies: cookieCounts(anchor),\n },\n });\n return {\n action: 'reseeded',\n head: resumeWatermark,\n reason,\n cookiesStale: true,\n };\n}\n\n/**\n * Seeds a valid synthetic transaction at the anchor's resume watermark, making\n * an otherwise empty log serviceable as a catchup boundary for a subscriber\n * that is exactly at that watermark.\n */\nexport function seedChangeLogStream(\n db: Database,\n anchor: ChangeLogAnchor,\n): void {\n const beginChange = '{\"tag\":\"begin\"}';\n const commitChange = '{\"tag\":\"commit\"}';\n db.prepare(SEED_CHANGE_LOG_STREAM_SQL).run({\n watermark: anchor.resumeWatermark,\n beginBytes: estimateChangeLogStreamRowBytes(\n anchor.resumeWatermark,\n 'begin',\n beginChange,\n ),\n beginChange,\n commitBytes: estimateChangeLogStreamRowBytes(\n anchor.resumeWatermark,\n 'commit',\n commitChange,\n anchor.resumeWatermark,\n true,\n ),\n commitChange,\n writeTimeMs: anchor.nowMs,\n });\n}\n\n/** Reads the whole meta row. Throws if the log has not been reconciled. */\nexport function readChangeLogMeta(db: Database): ChangeLogMeta {\n const meta = db\n .prepare(/*sql*/ `\n SELECT \"epoch\", \"generation\", \"replicaID\", \"schemaVersion\",\n \"seededAtMs\", \"seedWatermark\"\n FROM \"${CHANGE_LOG_META_TABLE}\"\n `)\n .get<ChangeLogMeta | undefined>();\n if (meta === undefined) {\n throw new Error('the SQLite change log has no meta row');\n }\n return meta;\n}\n\n/**\n * `max()` on the primary key's leading column, i.e. an index seek. Null when\n * the log is empty.\n */\nexport function readChangeLogHead(db: Database): string | null {\n const {head} = db\n .prepare(/*sql*/ `\n SELECT max(\"watermark\") AS \"head\" FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n `)\n .get<{head: string | null}>();\n return head;\n}\n\n/**\n * The covered watermark range. Both scalar subqueries seek the watermark\n * index, so unlike a `count()` this does not scan the log. Both bounds are\n * null when it is empty.\n */\nexport function readChangeLogBounds(db: Database): ChangeLogBounds {\n return db\n .prepare(/*sql*/ `\n SELECT\n (SELECT min(\"watermark\") FROM \"${CHANGE_LOG_STREAM_TABLE}\")\n AS \"minWatermark\",\n (SELECT max(\"watermark\") FROM \"${CHANGE_LOG_STREAM_TABLE}\")\n AS \"headWatermark\"\n `)\n .get<ChangeLogBounds>();\n}\n\nexport type ChangeLogBounds = {\n readonly minWatermark: string | null;\n readonly headWatermark: string | null;\n};\n\n/**\n * What was installed, for the reconcile log line. Normally `{0, 0}`: a nonzero\n * `backfilling` means the resumed stream is being handed backfills to re-request.\n */\nfunction cookieCounts({cookies}: ChangeLogAnchor) {\n return {\n tableMetadata: cookies.tableMetadata.length,\n backfilling: cookies.backfilling.length,\n };\n}\n\nfunction tableExists(db: Database, table: string): boolean {\n return (\n db\n .prepare(/*sql*/ `\n SELECT 1 FROM \"sqlite_master\" WHERE \"type\" = 'table' AND \"name\" = ?\n `)\n .get<{1: number} | undefined>(table) !== undefined\n );\n}\n"],"mappings":";;;;;;AAmFA,IAAM,0BAA0B;AAEhC,IAAa,0BAA0B;AACvC,IAAa,qCACX;AAEF,IAAM,gBAAgB;;;;;;AAOtB,SAAgB,gCACd,WACA,KACA,QACA,WACA,eAAe,OACP;CACR,OACE,OAAO,WAAW,SAAS,IAC3B,gBACA,OAAO,WAAW,GAAG,IACrB,OAAO,WAAW,MAAM,KACvB,cAAc,KAAA,IAAY,IAAI,OAAO,WAAW,SAAS,MACzD,eAAe,gBAAgB;AAEpC;AAUA,IAAa,kCAA0C;kBACrC,wBAAwB;;;;;;;;;;;kBAWxB,mCAAmC;UAC3C,wBAAwB;;;;;;;;;AAUlC,IAAM,6BAAqC;iBAC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AoB,IAA+B;CACjE,OAAO,GACJ,QAAgB;;yCAEoB,wBAAwB;;yCAExB,wBAAwB;;KAE5D,EACA,IAAqB;AAC1B;;;;;AAWA,SAAS,aAAa,EAAC,WAA2B;CAChD,OAAO;EACL,eAAe,QAAQ,cAAc;EACrC,aAAa,QAAQ,YAAY;CACnC;AACF;AAEA,SAAS,YAAY,IAAc,OAAwB;CACzD,OACE,GACG,QAAgB;;OAEhB,EACA,IAA6B,KAAK,MAAM,KAAA;AAE/C"}
1
+ {"version":3,"file":"change-log-db.js","names":[],"sources":["../../../../../../zero-cache/src/services/replicator/change-log-db.ts"],"sourcesContent":["/**\n * The change log lives in its own SQLite database, `${replicaFile}-change-log`,\n * rather than in the replica file. It is a catchup cache: everything it holds is\n * either already durable in the replica's litestream backup or re-derivable from\n * the upstream replication slot, so it is deliberately excluded from the backup\n * and is never a source of truth.\n *\n * The change-streamer writes it, from the stream loop that fans changes out to\n * subscribers, and commits it before forwarding each transaction's `commit`\n * message. Its head is therefore always at or above the watermark the stream\n * would resume from, which is what {@link reconcileChangeLog} anchors on.\n *\n * Beside the buffer it holds the log's *cookie jar* — the backfill progress\n * state folded up to the same head. That is `change-log-cookies.ts`; this file\n * owns its tables' lifecycle, because a cookie set is only meaningful paired\n * with the watermark it was folded to, and so must be created, dropped, and —\n * whenever reconciliation moves the head — replaced with the anchor's, all with\n * the buffer rather than beside it.\n *\n * Because it is disposable, it has no migration framework. Any inconsistency —\n * a schema change, a leftover file from a different replica, a gap left by a\n * crash or by running with the writer disabled, a corrupt file — is resolved by\n * {@link reconcileChangeLog} and {@link openChangeLogDBForWriting}, which\n * truncate a bounded suffix or replace and reseed the log at the resume\n * watermark. The worst outcome is a `too-old` for a lagging subscriber; a\n * silently delivered gap is not reachable.\n *\n * Disk sizing: a task that writes the log needs room for the replica *plus* the\n * retained change stream — the log's main file, its wal2 sidecars, and pages a\n * purge has freed but not yet returned to the OS. The change-streamer schedules\n * purges against the same floor as the PG change log, so retention is bounded\n * by the confirmed backup watermark ANDed with the minimum retention window —\n * a function of the backup interval, not a constant: 15–30+ minutes behind an\n * RMv1 sync interval, ~60 seconds once litestream v5 backs up every 15–30 s.\n * A held snapshot reservation pins retention unboundedly for its duration, so\n * peak retained bytes is set by the slowest concurrent restore rather than by\n * the retention setting — size disk and alerts on that. The log is excluded\n * from the litestream backup, so this is local disk only and never S3.\n */\n\nimport {existsSync} from 'node:fs';\nimport type {LogContext} from '@rocicorp/logger';\nimport {Database} from '../../../../zqlite/src/db.ts';\nimport {deleteLiteDB} from '../../db/delete-lite-db.ts';\nimport {\n isSQLiteCorruption,\n logSQLiteCorruptionDiagnostics,\n} from '../../db/sqlite-corruption.ts';\nimport {\n CHANGE_LOG_BACKFILLING_TABLE,\n CHANGE_LOG_TABLE_METADATA_TABLE,\n CREATE_CHANGE_LOG_COOKIE_SCHEMA,\n DROP_CHANGE_LOG_COOKIE_TABLES,\n replaceCookies,\n type CookieSet,\n} from './change-log-cookies.ts';\n\n/**\n * Bumped whenever the change-log database's schema changes. Since the file is a\n * cache, a mismatch costs one reseed rather than a migration.\n *\n * v2 re-homed the writer to the change-streamer: the log anchors on the\n * watermark its stream connection resumes from rather than on the replica's\n * state version, and its meta row carries the replica's identity triple plus\n * the seed point.\n *\n * v3 added the cookie tables (see `change-log-cookies.ts`), i.e. the log's\n * second job. The reseed it costs on upgrade buys one retention window of\n * catchup reach on a log nothing reads yet.\n *\n * v4 stores each row's tag and estimated retained bytes alongside its JSON.\n * Readers can now filter without parsing arbitrary row payloads, and\n * reconciliation can bound truncation by bytes as well as rows.\n *\n * `auto_vacuum = INCREMENTAL` arrived within v2, deliberately without a bump:\n * it is a file-header property rather than a schema change, and the reseed a\n * version mismatch triggers cannot enable it (see\n * {@link applyChangeLogPragmas}), so {@link openChangeLogDBForWriting} guards\n * on the pragma itself instead of on this number.\n */\nexport const CHANGE_LOG_DB_SCHEMA_VERSION = 4;\n\n/** https://www.sqlite.org/pragma.html#pragma_auto_vacuum */\nconst AUTO_VACUUM_INCREMENTAL = 2;\n\nexport const CHANGE_LOG_STREAM_TABLE = '_zero.changeLogStream';\nexport const CHANGE_LOG_STREAM_WRITE_TIME_INDEX =\n '_zero.changeLogStream_writeTimeMs';\n\nconst INTEGER_BYTES = 8;\n\n/**\n * Estimates the retained payload size of a stream row. This deliberately does\n * not claim to measure SQLite b-tree/page overhead; it is stable across the\n * write path, reconciliation, and the startup scan used by observability.\n */\nexport function estimateChangeLogStreamRowBytes(\n watermark: string,\n tag: string,\n change: string,\n precommit?: string,\n hasWriteTime = false,\n): number {\n return (\n Buffer.byteLength(watermark) +\n INTEGER_BYTES +\n Buffer.byteLength(tag) +\n Buffer.byteLength(change) +\n (precommit === undefined ? 0 : Buffer.byteLength(precommit)) +\n (hasWriteTime ? INTEGER_BYTES : 0)\n );\n}\n\n// The index is partial because only commit rows carry a \"writeTimeMs\", so it\n// holds one entry per transaction rather than one per change. It is what the\n// purger scans to find transactions older than the retention window.\n//\n// Pre-release builds briefly carried this table in the replica; see the test\n// fixture `CREATE_V14_CHANGE_LOG_STREAM` in\n// `change-source/common/replica-schema.ts`. Its old shape must not be kept in\n// sync with this one.\nexport const CREATE_CHANGE_LOG_STREAM_SCHEMA = /*sql*/ `\n CREATE TABLE \"${CHANGE_LOG_STREAM_TABLE}\" (\n \"watermark\" TEXT NOT NULL,\n \"pos\" INTEGER NOT NULL,\n \"tag\" TEXT NOT NULL,\n \"estimatedBytes\" INTEGER NOT NULL,\n \"change\" TEXT NOT NULL,\n \"precommit\" TEXT,\n \"writeTimeMs\" INTEGER,\n PRIMARY KEY (\"watermark\", \"pos\")\n );\n\n CREATE INDEX \"${CHANGE_LOG_STREAM_WRITE_TIME_INDEX}\"\n ON \"${CHANGE_LOG_STREAM_TABLE}\" (\"writeTimeMs\", \"watermark\")\n WHERE \"writeTimeMs\" IS NOT NULL;\n`;\n\n/**\n * Inserts the synthetic begin/commit pair for the seed watermark.\n *\n * Both rows are inserted by one statement so a caller outside a larger\n * transaction cannot leave a partial seed.\n */\nconst SEED_CHANGE_LOG_STREAM_SQL = /*sql*/ `\n INSERT INTO \"${CHANGE_LOG_STREAM_TABLE}\"\n (\"watermark\", \"pos\", \"tag\", \"estimatedBytes\", \"change\", \"precommit\",\n \"writeTimeMs\")\n VALUES\n (@watermark, 0, 'begin', @beginBytes, @beginChange, NULL, NULL),\n (@watermark, 1, 'commit', @commitBytes, @commitChange, @watermark,\n @writeTimeMs)\n ON CONFLICT (\"watermark\", \"pos\") DO NOTHING\n`;\n\nexport const CHANGE_LOG_META_TABLE = '_zero.changeLogMeta';\n\n// The identity triple (see ChangeLogIdentity) detects a file left behind by a\n// different replica -- most concretely, a leftover log on a reused volume.\n//\n// \"seededAtMs\" : when the log was seeded, i.e. how far its retention window\n// can possibly reach back. Slice 11 uses it as the warm-up\n// signal for canary reads.\n// \"seedWatermark\" : where the log was seeded. `min(\"watermark\")` cannot answer\n// this once purge has advanced the minimum, and the\n// difference is what distinguishes a log that purged past the\n// retention floor (an invariant violation) from one that\n// never held that history at all (routine at every fork).\n// \"lock\" : enforces single-row semantics, as in\n// \"_zero.replicationConfig\".\nconst CREATE_CHANGE_LOG_META_SCHEMA = /*sql*/ `\n CREATE TABLE \"${CHANGE_LOG_META_TABLE}\" (\n \"epoch\" TEXT,\n \"generation\" TEXT NOT NULL,\n \"replicaID\" TEXT,\n \"schemaVersion\" INTEGER NOT NULL,\n \"seededAtMs\" INTEGER NOT NULL,\n \"seedWatermark\" TEXT NOT NULL,\n \"lock\" INTEGER PRIMARY KEY DEFAULT 1 CHECK (\"lock\" = 1)\n );\n`;\n\n/**\n * `${replicaFile}-change-log`, matching the `-serving-copy` convention.\n *\n * The name outlives the writer's move into the change-streamer: the\n * change-streamer derives the path from the replica file it owns, so renaming\n * would save no plumbing and would orphan the old file on every existing\n * volume, where nothing would delete it.\n *\n * Its `-wal` / `-wal2` / `-shm` sidecars are suffixes of *this* name, so they\n * never collide with the replica's own sidecars.\n */\nexport function changeLogFileName(replicaFile: string): string {\n return `${replicaFile}-change-log`;\n}\n\n/**\n * Removes the change-log database and its `-wal` / `-wal2` / `-shm` sidecars.\n * Safe to call when the file does not exist.\n */\nexport function deleteChangeLogDB(replicaFile: string): void {\n deleteLiteDB(changeLogFileName(replicaFile));\n}\n\n/**\n * Which replica the log's contents belong to.\n *\n * `generation` is RMv1's `replicaVersion`: the version at which initial sync\n * copied every row. It is shared by every sibling of a forked replica, which is\n * why it cannot be the whole of the identity under RMv2 — `epoch` and\n * `replicaID` are what distinguish two siblings' logs. Both are `null` until\n * RMv2 supplies them, and a `null` matches only another `null`, so a log\n * written before they exist is still recognized as this replica's.\n */\nexport type ChangeLogIdentity = {\n readonly epoch: string | null;\n readonly generation: string;\n readonly replicaID: string | null;\n};\n\n/**\n * Where the stream connection resumes, and everything the log's state at that\n * position consists of.\n *\n * The two fields travel together because a cookie set is only meaningful paired\n * with the watermark it was folded up to (invariant 15). They are read from one\n * store, in one snapshot: `Storer.getStartStreamInitializationParameters()`\n * reads both from Postgres in a single REPEATABLE READ transaction. Pairing one\n * store's cookies with another's watermark would silently drop every backfill\n * that completed in the interval, and those rows are unrecoverable — backfill\n * transactions are synthesized by the change source rather than replayed from\n * the slot.\n */\nexport type ChangeLogResumePoint = {\n /**\n * The watermark this stream connection resumes from. The log's own head is\n * measured against it, and a reseed seeds a synthetic transaction at it.\n *\n * Deliberately *not* \"the replica's state version\": after the writer moved to\n * the change-streamer, the canonical replicator is a subscriber downstream of\n * the write loop, so its state version is a consequence of this log rather\n * than a constraint on it.\n */\n readonly resumeWatermark: string;\n /**\n * The cookie set that belongs to {@link resumeWatermark}. Any reconciliation\n * that moves the head invalidates the set the log was holding — the cookies\n * are unversioned point-in-time state, and truncating the stream above `W`\n * does not roll them back to `W` — so the same transaction installs this one\n * in its place (invariant 17).\n *\n * Postgres supplies it while it remains the store the stream resumes from. At\n * the C5 flip the log's own head *is* the resume point, phantoms cannot\n * exist, and both this field and the truncate-above path become dead code.\n */\n readonly cookies: CookieSet;\n};\n\n/**\n * What the log is reconciled against. Reconciliation runs once per stream\n * connection, since every reconnect can re-read a different resume point.\n */\nexport type ChangeLogAnchor = ChangeLogResumePoint & {\n readonly identity: ChangeLogIdentity;\n /**\n * The change-streamer's clock, at reconciliation time. Supplied rather than\n * read inline so that tests control it. Used for `seededAtMs` and for the\n * seed transaction's `writeTimeMs`, which is what the purger's time floor\n * measures.\n */\n readonly nowMs: number;\n};\n\n/** The meta row, i.e. everything the log records about itself. */\nexport type ChangeLogMeta = ChangeLogIdentity & {\n readonly schemaVersion: number;\n readonly seededAtMs: number;\n readonly seedWatermark: string;\n};\n\n/**\n * Opens the change-log database beside `replicaFile`.\n *\n * A writable handle creates the file if it is absent; a `readonly` handle\n * throws, which is the normal state for a change-streamer whose writer is\n * disabled. Pragmas are the caller's responsibility, since only the writer sets\n * the persistent ones.\n */\nexport function openChangeLogDB(\n lc: LogContext,\n replicaFile: string,\n opts: {readonly: boolean},\n): Database {\n return new Database(\n lc.withContext('component', 'change-log-db'),\n changeLogFileName(replicaFile),\n {readonly: opts.readonly},\n );\n}\n\n/**\n * Configures the change-log database, which the change-streamer's writer owns\n * exclusively. These are the settings the `separate-files` mode of\n * `sqlite-change-log-ceiling.bench.ts` measured.\n *\n * `wal2` because the log is a continuous append that catchup reads\n * continuously, which is the case wal2 exists for: it avoids checkpoint\n * starvation without needing an autocheckpoint. `wal_autocheckpoint` therefore\n * keeps its default, unlike the backup replica's 0, which hands checkpointing\n * to litestream — nothing else owns this file.\n *\n * `synchronous = NORMAL` because the commit sits on the forward path, once per\n * upstream transaction, and NORMAL keeps that from costing an fsync. It is not\n * a durability compromise here: in WAL mode NORMAL still writes every commit\n * through to the OS, so it survives a process crash, an OOM kill, or a SIGKILL.\n * It is lost only to kernel panic or power loss, and those destroy the node —\n * the task restarts elsewhere, restores the replica from S3, and has no\n * change-log file at all. Whatever a power loss does take is detected by\n * {@link reconcileChangeLog} and reseeded.\n *\n * `auto_vacuum = INCREMENTAL` so that purge can return freed pages to the OS\n * rather than leaving the file at its high-water mark. **It must be the first\n * statement here.** SQLite honours a `none` -> `incremental` transition only\n * while the file is still empty, and `journal_mode = wal2` materializes page 1;\n * appending the pragma instead of prepending it silently leaves the file at\n * mode 0 forever, since neither `DROP TABLE` nor a reseed makes a file empty\n * again. {@link openChangeLogDBForWriting} verifies the result.\n */\nexport function applyChangeLogPragmas(db: Database): void {\n db.pragma('auto_vacuum = INCREMENTAL');\n db.pragma('busy_timeout = 30000');\n db.pragma('analysis_limit = 1000');\n db.pragma('journal_mode = wal2');\n db.pragma('synchronous = NORMAL');\n}\n\nfunction readAutoVacuum(db: Database): number {\n const [{auto_vacuum: mode}] = db.pragma<{auto_vacuum: number}>('auto_vacuum');\n return mode;\n}\n\n/**\n * Opens the change-log database for the writer, applies its pragmas, and\n * reconciles it against `anchor`, returning the handle and what reconciliation\n * had to do.\n *\n * Corruption is answered with a rebuild rather than an escalation, which is a\n * deliberate divergence from how the replica's own corruption is handled. A\n * corrupt replica is a lost source of truth, so it ends in a restore or an\n * auto-reset; the change log holds nothing that is not either already in the\n * replica's litestream backup or re-derivable from the upstream slot, so the\n * entire response is to delete the file and seed a new one at the resume\n * watermark. The cost is one retention window of catchup — reconnecting\n * subscribers below the head get `too-old` — which is what every other\n * {@link ReseedReason} costs.\n *\n * Only corruption is rebuilt through. Anything else (a bad path, a permissions\n * error, a full disk) is a problem with the environment rather than with the\n * file's contents, and deleting a database in response would destroy state\n * without fixing it. Those propagate to the caller, which disables the writer\n * and keeps replicating.\n *\n * A file that predates `auto_vacuum = INCREMENTAL` takes the same rebuild, for\n * the same reason and at the same cost: the pragma only takes on an empty file,\n * so a reseed cannot enable it. Unlike corruption, a *second* failure there is\n * tolerated rather than thrown — see {@link ensureIncrementalAutoVacuum}.\n */\n/**\n * Returns an anchor after the database opens.\n *\n * The resolver can inspect the existing file before it selects the anchor. A\n * valid log can use its own head. A new or invalid log uses the replica seed.\n * The rebuild path calls the resolver again for the new file.\n */\nexport type AnchorResolver = (db: Database) => ChangeLogAnchor;\n\nexport function openChangeLogDBForWriting(\n lc: LogContext,\n replicaFile: string,\n anchor: AnchorResolver,\n): {db: Database; result: ReconcileResult; replacedFile: boolean} {\n const existed = existsSync(changeLogFileName(replicaFile));\n const opened = openOrRebuildCorrupt(lc, replicaFile, anchor, existed);\n const {db, result, replacedFile} = ensureIncrementalAutoVacuum(\n lc,\n replicaFile,\n anchor,\n opened,\n );\n return {db, result, replacedFile};\n}\n\nfunction openOrRebuildCorrupt(\n lc: LogContext,\n replicaFile: string,\n anchor: AnchorResolver,\n boundReconciliation: boolean,\n): OpenedChangeLog {\n try {\n return openAndReconcile(lc, replicaFile, anchor, boundReconciliation);\n } catch (e) {\n if (e instanceof ChangeLogRebuildRequired) {\n return rebuildChangeLog(lc, replicaFile, anchor, e);\n }\n if (!isSQLiteCorruption(e)) {\n throw e;\n }\n const file = changeLogFileName(replicaFile);\n logSQLiteCorruptionDiagnostics(lc, 'change-log', file, e);\n lc.error?.('rebuilding the corrupt SQLite change log', {\n sqliteChangeLog: {file},\n });\n return rebuildChangeLog(lc, replicaFile, anchor);\n }\n}\n\n/**\n * Rebuilds a log whose `auto_vacuum` mode is not `INCREMENTAL`, which is every\n * log created before the pragma shipped — including every v2 file the writer\n * wrote in the meantime, which is why the guard is on the pragma rather than\n * on the schema version. Deleting the file is the only way to enable it:\n * `DROP TABLE` leaves the header's mode intact, and the in-place alternative —\n * a full `VACUUM` — is an unbounded blocking statement on a file the writer\n * needs.\n *\n * A mode that is still wrong after the rebuild is logged and tolerated, which\n * is the one place this diverges from the corruption path. The two failures are\n * not alike: a file that stays corrupt after a rebuild is an environment\n * problem, but a pragma that stays wrong on a brand-new file can only mean\n * {@link applyChangeLogPragmas}' statement order is wrong — a code bug, present\n * on every task, on every start. Throwing there turns a lost optimization into\n * a crash loop, and rebuilding again turns it into a reseed per start, which is\n * worse than the freelist growth it was trying to avoid. `Database.compact()`\n * already warns and no-ops when the mode is not `INCREMENTAL`, so degrading is\n * the accepted fallback.\n */\nfunction ensureIncrementalAutoVacuum(\n lc: LogContext,\n replicaFile: string,\n anchor: AnchorResolver,\n opened: OpenedChangeLog,\n): OpenedChangeLog {\n if (opened.autoVacuum === AUTO_VACUUM_INCREMENTAL) {\n return opened;\n }\n const file = changeLogFileName(replicaFile);\n lc.info?.('rebuilding the SQLite change log to enable incremental vacuum', {\n sqliteChangeLog: {file, autoVacuum: opened.autoVacuum},\n });\n opened.db.close();\n const rebuilt = rebuildChangeLog(lc, replicaFile, anchor);\n if (rebuilt.autoVacuum !== AUTO_VACUUM_INCREMENTAL) {\n lc.error?.(\n 'SQLite change log does not support incremental vacuum; ' +\n 'it will plateau at its high-water mark',\n {sqliteChangeLog: {file, autoVacuum: rebuilt.autoVacuum}},\n );\n }\n return rebuilt;\n}\n\n/** The shared \"delete the file and open a new one\" body. */\nfunction rebuildChangeLog(\n lc: LogContext,\n replicaFile: string,\n anchor: AnchorResolver,\n required?: ChangeLogRebuildRequired | undefined,\n): OpenedChangeLog {\n if (required) {\n lc.warn?.(\n 'rebuilding the SQLite change log instead of running an unbounded reconciliation',\n {\n sqliteChangeLogRebuild: {\n reason: required.reason,\n rows: required.rows,\n estimatedBytes: required.estimatedBytes,\n },\n },\n );\n }\n deleteChangeLogDB(replicaFile);\n // The file is absent, so the reseed only drops empty/nonexistent tables. A\n // second failure is the environment's, not the old file's.\n const opened = openAndReconcile(\n lc,\n replicaFile,\n anchor,\n false,\n required?.reason,\n );\n return {...opened, replacedFile: true};\n}\n\n/**\n * Replaces an already-closed change-log file after bounded reconciliation\n * declined its work. The caller closes cached readers before calling this so\n * none can continue serving the unlinked inode.\n */\nexport function rebuildChangeLogDBForWriting(\n lc: LogContext,\n replicaFile: string,\n anchor: ChangeLogAnchor,\n required: ChangeLogRebuildRequired,\n): {db: Database; result: ReconcileResult; replacedFile: true} {\n const {db, result} = rebuildChangeLog(\n lc,\n replicaFile,\n () => anchor,\n required,\n );\n return {db, result, replacedFile: true};\n}\n\ntype OpenedChangeLog = {\n db: Database;\n result: ReconcileResult;\n replacedFile: boolean;\n /** The file's persistent `auto_vacuum` mode, read back after the pragmas. */\n autoVacuum: number;\n};\n\nfunction openAndReconcile(\n lc: LogContext,\n replicaFile: string,\n anchor: AnchorResolver,\n boundReconciliation: boolean,\n reseedReason?: ReseedReason | undefined,\n): OpenedChangeLog {\n const db = openChangeLogDB(lc, replicaFile, {readonly: false});\n try {\n applyChangeLogPragmas(db);\n const autoVacuum = readAutoVacuum(db);\n return {\n db,\n result: reconcileChangeLog(lc, db, anchor(db), {\n rebuildInsteadOfUnboundedWork: boundReconciliation,\n reseedReason,\n }),\n replacedFile: false,\n autoVacuum,\n };\n } catch (e) {\n // The caller never sees this handle, so it closes here or leaks — and it\n // must be closed before the corruption path deletes the file.\n db.close();\n throw e;\n }\n}\n\nexport type ReseedReason =\n | 'created' // file or table absent\n | 'schema-mismatch'\n | 'identity-mismatch'\n | 'gap' // head does not land on the resume watermark after truncation\n | 'oversized-truncate'; // preserving the prefix would require too much work\n\n/**\n * Reconciliation runs synchronously on the change-streamer's event loop. A\n * normal phantom is one transaction, so work above either limit is answered by\n * unlinking and reseeding this disposable cache rather than deleting an\n * arbitrarily large suffix in place.\n */\nexport const MAX_RECONCILE_TRUNCATE_ROWS = 10_000;\nexport const MAX_RECONCILE_TRUNCATE_BYTES = 16 * 1024 * 1024;\n\nexport class ChangeLogRebuildRequired extends Error {\n override readonly name = 'ChangeLogRebuildRequired';\n readonly reason: ReseedReason;\n readonly rows?: number | undefined;\n readonly estimatedBytes?: number | undefined;\n\n constructor(\n reason: ReseedReason,\n rows?: number | undefined,\n estimatedBytes?: number | undefined,\n ) {\n super(`SQLite change log requires a ${reason} rebuild`);\n this.reason = reason;\n this.rows = rows;\n this.estimatedBytes = estimatedBytes;\n }\n}\n\ntype ReconcileOptions = {\n /** Throw before an unbounded delete/drop so the file owner can unlink it. */\n readonly rebuildInsteadOfUnboundedWork?: boolean | undefined;\n /** Preserve the reason that caused an old file to be unlinked. */\n readonly reseedReason?: ReseedReason | undefined;\n};\n\n/**\n * `cookiesStale` records that the cookie set the log held did not survive\n * reconciliation. The cookies are unversioned point-in-time state, so any\n * reconciliation that moves the head invalidates them, and the same transaction\n * replaces them with the anchor's — the set that belongs to the resume\n * watermark (see `change-log-cookies.ts`). It is `action !== 'none'` today; it\n * is a field rather than a derivation because the replacement reads as intent\n * at the call site, and because it is what the `cookie_reseed` counter is keyed\n * on.\n */\nexport type ReconcileResult =\n | {action: 'none'; head: string; cookiesStale: false}\n | {action: 'truncated'; head: string; rows: number; cookiesStale: true}\n | {\n action: 'reseeded';\n head: string;\n reason: ReseedReason;\n cookiesStale: true;\n };\n\n/**\n * Brings the change log into agreement with the watermark its stream connection\n * resumes from, in one transaction on the change-log database:\n *\n * ```\n * head === resumeWatermark → keep appending\n * head > resumeWatermark → truncate above resumeWatermark\n * otherwise → wipe, seed at resumeWatermark, record the reason\n * ```\n *\n * The log commits before anything that can advance the resume watermark, so a\n * *phantom* — a transaction the log holds whose watermark the resumed stream\n * re-delivers — is the normal state, and truncate-above is the whole of\n * reconciliation rather than a special case. A phantom's rows all carry the\n * transaction's commit watermark, which is strictly greater than the resume\n * watermark, so deleting on that predicate removes phantoms whole and retains\n * every transaction at or below the resume point.\n *\n * It must run per stream connection, not once per process: the stream loop\n * re-reads its resume watermark on every reconnect, and the writer inserts with\n * a plain `INSERT` against `PRIMARY KEY (\"watermark\",\"pos\")`, so an\n * un-truncated overlap is a constraint violation on the first re-delivered\n * transaction.\n *\n * Anything truncation cannot resolve — the file was deleted, the writer was\n * disabled for a while, the replica was restored, power was lost with\n * `synchronous=NORMAL` — surfaces as a head that does not land on the resume\n * watermark, and is resolved by wiping and reseeding there.\n *\n * Whichever of the two moves the head also replaces the cookie set with the one\n * the anchor carries, in the same transaction: the head and the cookies are one\n * position, and nothing may observe them at two.\n */\nexport function reconcileChangeLog(\n lc: LogContext,\n db: Database,\n anchor: ChangeLogAnchor,\n opts: ReconcileOptions = {},\n): ReconcileResult {\n db.exec('BEGIN IMMEDIATE');\n try {\n if (opts.rebuildInsteadOfUnboundedWork) {\n const required = rebuildRequired(db, anchor);\n if (required) {\n throw required;\n }\n }\n const result = opts.reseedReason\n ? reseed(lc, db, anchor, opts.reseedReason)\n : reconcile(lc, db, anchor);\n db.exec('COMMIT');\n return result;\n } catch (e) {\n if (db.inTransaction) {\n db.exec('ROLLBACK');\n }\n throw e;\n }\n}\n\n/**\n * Decides whether reconciliation can be performed within its synchronous work\n * budget. Every query is either an index seek or a scan capped at one row past\n * the delete limit. No state changes before the decision is complete.\n */\nfunction rebuildRequired(\n db: Database,\n anchor: ChangeLogAnchor,\n): ChangeLogRebuildRequired | undefined {\n const wipe = changeLogWipeReason(db, anchor.identity);\n if (wipe !== undefined) {\n return new ChangeLogRebuildRequired(wipe);\n }\n\n const head = readChangeLogHead(db);\n const {resumeWatermark} = anchor;\n if (head === null || head < resumeWatermark) {\n return new ChangeLogRebuildRequired('gap');\n }\n if (head === resumeWatermark) {\n return undefined;\n }\n\n const boundary = db\n .prepare(/*sql*/ `\n SELECT 1 FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n WHERE \"watermark\" = ?\n LIMIT 1\n `)\n .get<{1: number} | undefined>(resumeWatermark);\n if (boundary === undefined) {\n return new ChangeLogRebuildRequired('gap');\n }\n\n const {rows, estimatedBytes} = db\n .prepare(/*sql*/ `\n SELECT count(*) AS \"rows\",\n coalesce(sum(\"estimatedBytes\"), 0) AS \"estimatedBytes\"\n FROM (\n SELECT \"estimatedBytes\" FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n WHERE \"watermark\" > ?\n LIMIT ${MAX_RECONCILE_TRUNCATE_ROWS + 1}\n )\n `)\n .get<{rows: number; estimatedBytes: number}>(resumeWatermark);\n return rows > MAX_RECONCILE_TRUNCATE_ROWS ||\n estimatedBytes > MAX_RECONCILE_TRUNCATE_BYTES\n ? new ChangeLogRebuildRequired('oversized-truncate', rows, estimatedBytes)\n : undefined;\n}\n\nfunction reconcile(\n lc: LogContext,\n db: Database,\n anchor: ChangeLogAnchor,\n): ReconcileResult {\n const wipe = changeLogWipeReason(db, anchor.identity);\n if (wipe !== undefined) {\n return reseed(lc, db, anchor, wipe);\n }\n\n const {resumeWatermark} = anchor;\n let head = readChangeLogHead(db);\n let rows = 0;\n if (head !== null && head > resumeWatermark) {\n rows = db\n .prepare(/*sql*/ `\n DELETE FROM \"${CHANGE_LOG_STREAM_TABLE}\" WHERE \"watermark\" > ?\n `)\n .run(resumeWatermark).changes;\n head = readChangeLogHead(db);\n }\n\n if (head !== resumeWatermark) {\n return reseed(lc, db, anchor, 'gap');\n }\n if (rows > 0) {\n // The truncated transactions can have carried `create-table`,\n // `add-column`, and `backfill-completed`, none of which the truncate rolls\n // back, so the cookie set no longer belongs to the head. The anchor's set\n // does, and it lands in this same transaction: invariant 17 holds at every\n // point another connection could observe the log.\n replaceCookies(db, anchor.cookies);\n lc.info?.('truncated phantom transactions from the SQLite change log', {\n sqliteChangeLogReconcile: {head, rows, cookies: cookieCounts(anchor)},\n });\n return {action: 'truncated', head, rows, cookiesStale: true};\n }\n lc.debug?.('SQLite change log is at the resume watermark', {\n sqliteChangeLogReconcile: {head},\n });\n return {action: 'none', head, cookiesStale: false};\n}\n\n/**\n * Returns the reason that the log must be recreated. Returns `undefined` when\n * the writer can continue to use the log.\n *\n * This function takes only the expected identity because callers use the result\n * to select the anchor.\n */\nexport function changeLogWipeReason(\n db: Database,\n identity: ChangeLogIdentity,\n): ReseedReason | undefined {\n if (\n !tableExists(db, CHANGE_LOG_STREAM_TABLE) ||\n !tableExists(db, CHANGE_LOG_META_TABLE)\n ) {\n return 'created';\n }\n // The schema version is read on its own because it is the one column every\n // version of this table has had. Reading the rest of a v1 row would fail on\n // its missing columns instead of reporting the mismatch that explains it.\n const version = db\n .prepare(/*sql*/ `\n SELECT \"schemaVersion\" FROM \"${CHANGE_LOG_META_TABLE}\"\n `)\n .get<{schemaVersion: number} | undefined>();\n if (version === undefined) {\n return 'created';\n }\n if (version.schemaVersion !== CHANGE_LOG_DB_SCHEMA_VERSION) {\n return 'schema-mismatch';\n }\n // Checked *after* the version, so that every pre-v4 file — which is every\n // file in the fleet at the upgrade — reports the `schema-mismatch` that\n // explains it rather than the `created` its absent cookie tables would\n // otherwise look like.\n if (\n !tableExists(db, CHANGE_LOG_TABLE_METADATA_TABLE) ||\n !tableExists(db, CHANGE_LOG_BACKFILLING_TABLE)\n ) {\n return 'created';\n }\n const {epoch, generation, replicaID} = readChangeLogMeta(db);\n if (\n epoch !== identity.epoch ||\n generation !== identity.generation ||\n replicaID !== identity.replicaID\n ) {\n return 'identity-mismatch';\n }\n return undefined;\n}\n\nfunction reseed(\n lc: LogContext,\n db: Database,\n anchor: ChangeLogAnchor,\n reason: ReseedReason,\n): ReconcileResult {\n const {identity, resumeWatermark, nowMs} = anchor;\n // Dropping the table drops its partial index with it. The cookie tables go\n // with the buffer: a cookie set without the transactions it was folded from\n // is not a smaller cookie set, it is a wrong one.\n db.exec(/*sql*/ `\n DROP TABLE IF EXISTS \"${CHANGE_LOG_STREAM_TABLE}\";\n DROP TABLE IF EXISTS \"${CHANGE_LOG_META_TABLE}\";\n ${DROP_CHANGE_LOG_COOKIE_TABLES}\n ${CREATE_CHANGE_LOG_STREAM_SCHEMA}\n ${CREATE_CHANGE_LOG_META_SCHEMA}\n ${CREATE_CHANGE_LOG_COOKIE_SCHEMA}\n `);\n db.prepare(/*sql*/ `\n INSERT INTO \"${CHANGE_LOG_META_TABLE}\"\n (\"epoch\", \"generation\", \"replicaID\", \"schemaVersion\", \"seededAtMs\",\n \"seedWatermark\")\n VALUES (@epoch, @generation, @replicaID, @schemaVersion, @seededAtMs,\n @seedWatermark)\n `).run({\n epoch: identity.epoch,\n generation: identity.generation,\n replicaID: identity.replicaID,\n schemaVersion: CHANGE_LOG_DB_SCHEMA_VERSION,\n seededAtMs: nowMs,\n seedWatermark: resumeWatermark,\n });\n seedChangeLogStream(db, anchor);\n // Into tables this statement just created, so the wholesale replacement is\n // all insert. It is still the same call the truncate path makes: a reseed is\n // the case where the log's cookie set was not merely moved but discarded, and\n // the anchor's is equally what belongs at the head either way.\n replaceCookies(db, anchor.cookies);\n\n lc.info?.('reseeded the SQLite change log', {\n sqliteChangeLogReconcile: {\n reason,\n head: resumeWatermark,\n ...identity,\n schemaVersion: CHANGE_LOG_DB_SCHEMA_VERSION,\n seededAtMs: nowMs,\n cookies: cookieCounts(anchor),\n },\n });\n return {\n action: 'reseeded',\n head: resumeWatermark,\n reason,\n cookiesStale: true,\n };\n}\n\n/**\n * Seeds a valid synthetic transaction at the anchor's resume watermark, making\n * an otherwise empty log serviceable as a catchup boundary for a subscriber\n * that is exactly at that watermark.\n */\nexport function seedChangeLogStream(\n db: Database,\n anchor: ChangeLogAnchor,\n): void {\n const beginChange = '{\"tag\":\"begin\"}';\n const commitChange = '{\"tag\":\"commit\"}';\n db.prepare(SEED_CHANGE_LOG_STREAM_SQL).run({\n watermark: anchor.resumeWatermark,\n beginBytes: estimateChangeLogStreamRowBytes(\n anchor.resumeWatermark,\n 'begin',\n beginChange,\n ),\n beginChange,\n commitBytes: estimateChangeLogStreamRowBytes(\n anchor.resumeWatermark,\n 'commit',\n commitChange,\n anchor.resumeWatermark,\n true,\n ),\n commitChange,\n writeTimeMs: anchor.nowMs,\n });\n}\n\n/** Reads the whole meta row. Throws if the log has not been reconciled. */\nexport function readChangeLogMeta(db: Database): ChangeLogMeta {\n const meta = db\n .prepare(/*sql*/ `\n SELECT \"epoch\", \"generation\", \"replicaID\", \"schemaVersion\",\n \"seededAtMs\", \"seedWatermark\"\n FROM \"${CHANGE_LOG_META_TABLE}\"\n `)\n .get<ChangeLogMeta | undefined>();\n if (meta === undefined) {\n throw new Error('the SQLite change log has no meta row');\n }\n return meta;\n}\n\n/**\n * `max()` on the primary key's leading column, i.e. an index seek. Null when\n * the log is empty.\n */\nexport function readChangeLogHead(db: Database): string | null {\n const {head} = db\n .prepare(/*sql*/ `\n SELECT max(\"watermark\") AS \"head\" FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n `)\n .get<{head: string | null}>();\n return head;\n}\n\n/**\n * The covered watermark range. Both scalar subqueries seek the watermark\n * index, so unlike a `count()` this does not scan the log. Both bounds are\n * null when it is empty.\n */\nexport function readChangeLogBounds(db: Database): ChangeLogBounds {\n return db\n .prepare(/*sql*/ `\n SELECT\n (SELECT min(\"watermark\") FROM \"${CHANGE_LOG_STREAM_TABLE}\")\n AS \"minWatermark\",\n (SELECT max(\"watermark\") FROM \"${CHANGE_LOG_STREAM_TABLE}\")\n AS \"headWatermark\"\n `)\n .get<ChangeLogBounds>();\n}\n\nexport type ChangeLogBounds = {\n readonly minWatermark: string | null;\n readonly headWatermark: string | null;\n};\n\n/**\n * What was installed, for the reconcile log line. Normally `{0, 0}`: a nonzero\n * `backfilling` means the resumed stream is being handed backfills to re-request.\n */\nfunction cookieCounts({cookies}: ChangeLogAnchor) {\n return {\n tableMetadata: cookies.tableMetadata.length,\n backfilling: cookies.backfilling.length,\n };\n}\n\nfunction tableExists(db: Database, table: string): boolean {\n return (\n db\n .prepare(/*sql*/ `\n SELECT 1 FROM \"sqlite_master\" WHERE \"type\" = 'table' AND \"name\" = ?\n `)\n .get<{1: number} | undefined>(table) !== undefined\n );\n}\n"],"mappings":";;;;;;AAmFA,IAAM,0BAA0B;AAEhC,IAAa,0BAA0B;AACvC,IAAa,qCACX;AAEF,IAAM,gBAAgB;;;;;;AAOtB,SAAgB,gCACd,WACA,KACA,QACA,WACA,eAAe,OACP;CACR,OACE,OAAO,WAAW,SAAS,IAC3B,gBACA,OAAO,WAAW,GAAG,IACrB,OAAO,WAAW,MAAM,KACvB,cAAc,KAAA,IAAY,IAAI,OAAO,WAAW,SAAS,MACzD,eAAe,gBAAgB;AAEpC;AAUA,IAAa,kCAA0C;kBACrC,wBAAwB;;;;;;;;;;;kBAWxB,mCAAmC;UAC3C,wBAAwB;;;;;;;;;AAUlC,IAAM,6BAAqC;iBAC1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oB,IAA+B;CACjE,OAAO,GACJ,QAAgB;;yCAEoB,wBAAwB;;yCAExB,wBAAwB;;KAE5D,EACA,IAAqB;AAC1B;;;;;AAWA,SAAS,aAAa,EAAC,WAA2B;CAChD,OAAO;EACL,eAAe,QAAQ,cAAc;EACrC,aAAa,QAAQ,YAAY;CACnC;AACF;AAEA,SAAS,YAAY,IAAc,OAAwB;CACzD,OACE,GACG,QAAgB;;OAEhB,EACA,IAA6B,KAAK,MAAM,KAAA;AAE/C"}
@@ -1 +1 @@
1
- {"version":3,"file":"incremental-sync.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/replicator/incremental-sync.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAIjD,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,wBAAwB,CAAC;AAGnD,OAAO,EAGL,KAAK,cAAc,EAEpB,MAAM,uCAAuC,CAAC;AAK/C,OAAO,KAAK,EAAC,0BAA0B,EAAC,MAAM,yBAAyB,CAAC;AACxE,OAAO,KAAK,EAAC,YAAY,EAAE,cAAc,EAAC,MAAM,iBAAiB,CAAC;AAGlE,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,0BAA0B,CAAC;AAIhE;;;;;;GAMG;AACH,qBAAa,iBAAiB;;IAmB5B,YACE,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,MAAM,EACd,EAAE,EAAE,MAAM,EACV,cAAc,EAAE,cAAc,EAC9B,MAAM,EAAE,iBAAiB,EACzB,IAAI,EAAE,cAAc,EACpB,eAAe,EAAE,0BAA0B,GAAG,IAAI,EAWnD;IAEK,GAAG,kBA8IR;IA6BD,SAAS,IAAI,MAAM,CAAC,YAAY,CAAC,CAEhC;IAED,IAAI,CAAC,EAAE,EAAE,UAAU,EAAE,GAAG,CAAC,EAAE,OAAO,QAIjC;CACF"}
1
+ {"version":3,"file":"incremental-sync.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/replicator/incremental-sync.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAIjD,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,wBAAwB,CAAC;AAGnD,OAAO,EAGL,KAAK,cAAc,EAEpB,MAAM,uCAAuC,CAAC;AAK/C,OAAO,KAAK,EAAC,0BAA0B,EAAC,MAAM,yBAAyB,CAAC;AACxE,OAAO,KAAK,EAAC,YAAY,EAAE,cAAc,EAAC,MAAM,iBAAiB,CAAC;AAGlE,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,0BAA0B,CAAC;AAOhE;;;;;;GAMG;AACH,qBAAa,iBAAiB;;IAmB5B,YACE,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,MAAM,EACd,EAAE,EAAE,MAAM,EACV,cAAc,EAAE,cAAc,EAC9B,MAAM,EAAE,iBAAiB,EACzB,IAAI,EAAE,cAAc,EACpB,eAAe,EAAE,0BAA0B,GAAG,IAAI,EAWnD;IAEK,GAAG,kBAiLR;IA6BD,SAAS,IAAI,MAAM,CAAC,YAAY,CAAC,CAEhC;IAED,IAAI,CAAC,EAAE,EAAE,UAAU,EAAE,GAAG,CAAC,EAAE,OAAO,QAIjC;CACF"}
@@ -5,6 +5,8 @@ import { errorTypeToReadableName } from "../change-streamer/change-streamer.js";
5
5
  import { Notifier } from "./notifier.js";
6
6
  import { ReplicationReportRecorder } from "./reporter/recorder.js";
7
7
  //#region ../zero-cache/src/services/replicator/incremental-sync.ts
8
+ var MAX_WORKER_BATCH_MESSAGES = 256;
9
+ var MAX_WORKER_BATCH_SIZE = 1024 * 1024;
8
10
  /**
9
11
  * The {@link IncrementalSyncer} manages a logical replication stream from upstream,
10
12
  * handling application lifecycle events (start, stop) and retrying the
@@ -68,7 +70,19 @@ var IncrementalSyncer = class {
68
70
  unregister = this.#state.cancelOnStop(downstream);
69
71
  this.#statusPublisher?.publish(lc, "Replicating", `Replicating from ${watermark}`);
70
72
  let backfillStatus;
71
- for await (const { data: message } of downstream) {
73
+ let writeBatch = [];
74
+ let writeBatchSize = 0;
75
+ let inTransaction = false;
76
+ const flushWrites = async () => {
77
+ if (writeBatch.length === 0) return;
78
+ const batch = writeBatch;
79
+ writeBatch = [];
80
+ writeBatchSize = 0;
81
+ const result = await this.#worker.processMessages(batch);
82
+ this.#handleResult(lc, result);
83
+ if (result?.completedBackfill) backfillStatus = void 0;
84
+ };
85
+ for await (const { data: message, size } of downstream) {
72
86
  this.#replicationEvents.add(1);
73
87
  switch (message[0]) {
74
88
  case "status": {
@@ -102,10 +116,13 @@ var IncrementalSyncer = class {
102
116
  }
103
117
  backfillStatus = status;
104
118
  }
105
- const data = message;
106
- const result = await this.#worker.processMessage(data);
107
- this.#handleResult(lc, result);
108
- if (result?.completedBackfill) backfillStatus = void 0;
119
+ const type = message[0];
120
+ const invalidTransactionSequence = type === "begin" ? inTransaction : !inTransaction;
121
+ if (type === "begin") inTransaction = true;
122
+ else if (type === "commit" || type === "rollback") inTransaction = false;
123
+ writeBatch.push(message);
124
+ writeBatchSize += size;
125
+ if (type === "commit" || type === "rollback" || invalidTransactionSequence || writeBatch.length >= MAX_WORKER_BATCH_MESSAGES || writeBatchSize >= MAX_WORKER_BATCH_SIZE) await flushWrites();
109
126
  break;
110
127
  }
111
128
  }
@@ -1 +1 @@
1
- {"version":3,"file":"incremental-sync.js","names":["#lc","#taskID","#id","#changeStreamer","#worker","#mode","#statusPublisher","#notifier","#reporter","#state","#replicationEvents","#handleResult"],"sources":["../../../../../../zero-cache/src/services/replicator/incremental-sync.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {AbortError} from '../../../../shared/src/abort-error.ts';\nimport type {Enum} from '../../../../shared/src/enum.ts';\nimport {getOrCreateCounter} from '../../observability/metrics.ts';\nimport type {Source} from '../../types/streams.ts';\nimport type {DownloadStatus} from '../change-source/protocol/current.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport {\n errorTypeToReadableName,\n PROTOCOL_VERSION,\n type ChangeStreamer,\n type SerializedDownstream,\n} from '../change-streamer/change-streamer.ts';\nimport type * as ErrorType from '../change-streamer/error-type-enum.ts';\nimport {RunningState} from '../running-state.ts';\nimport type {CommitResult} from './change-processor.ts';\nimport {Notifier} from './notifier.ts';\nimport type {ReplicationStatusPublisher} from './replication-status.ts';\nimport type {ReplicaState, ReplicatorMode} from './replicator.ts';\nimport {ReplicationReportRecorder} from './reporter/recorder.ts';\nimport type {ReplicationReport} from './reporter/report-schema.ts';\nimport type {WriteWorkerClient} from './write-worker-client.ts';\n\ntype ErrorType = Enum<typeof ErrorType>;\n\n/**\n * The {@link IncrementalSyncer} manages a logical replication stream from upstream,\n * handling application lifecycle events (start, stop) and retrying the\n * connection with exponential backoff. The actual handling of the logical\n * replication messages is done by the {@link ChangeProcessor}, which runs\n * in a worker thread via the {@link WriteWorkerClient}.\n */\nexport class IncrementalSyncer {\n readonly #lc: LogContext;\n readonly #taskID: string;\n readonly #id: string;\n readonly #changeStreamer: ChangeStreamer;\n readonly #worker: WriteWorkerClient;\n readonly #mode: ReplicatorMode;\n readonly #statusPublisher: ReplicationStatusPublisher | null;\n readonly #notifier: Notifier;\n readonly #reporter: ReplicationReportRecorder;\n\n readonly #state = new RunningState('IncrementalSyncer');\n\n readonly #replicationEvents = getOrCreateCounter(\n 'replication',\n 'events',\n 'Number of replication events processed',\n );\n\n constructor(\n lc: LogContext,\n taskID: string,\n id: string,\n changeStreamer: ChangeStreamer,\n worker: WriteWorkerClient,\n mode: ReplicatorMode,\n statusPublisher: ReplicationStatusPublisher | null,\n ) {\n this.#lc = lc;\n this.#taskID = taskID;\n this.#id = id;\n this.#changeStreamer = changeStreamer;\n this.#worker = worker;\n this.#mode = mode;\n this.#statusPublisher = statusPublisher;\n this.#notifier = new Notifier();\n this.#reporter = new ReplicationReportRecorder(lc);\n }\n\n async run() {\n const lc = this.#lc;\n let workerError: Error | undefined;\n this.#worker.onError(err => {\n workerError ??= err;\n this.#state.stop(lc, err);\n });\n lc.info?.(`Starting IncrementalSyncer`);\n const {watermark: initialWatermark} =\n await this.#worker.getSubscriptionState();\n\n // Notify any waiting subscribers that the replica is ready to be read.\n // This initial notification intentionally omits replicaReadyTimeMs because\n // it represents already-current state, not newly-unserved work.\n void this.#notifier.notifySubscribers({\n state: 'version-ready',\n watermark: initialWatermark,\n });\n\n while (this.#state.shouldRun()) {\n const {replicaVersion, watermark} =\n await this.#worker.getSubscriptionState();\n\n let downstream: Source<SerializedDownstream> | undefined;\n let unregister = () => {};\n let err: unknown | undefined;\n\n try {\n downstream = await this.#changeStreamer.subscribe({\n protocolVersion: PROTOCOL_VERSION,\n taskID: this.#taskID,\n id: this.#id,\n mode: this.#mode,\n watermark,\n replicaVersion,\n initial: watermark === initialWatermark,\n // The SQLite change log is written by the change-streamer itself, so\n // no replicator logs the change stream any more. The parameter stays\n // on the wire for change-streamers that still exclude a writer from\n // SQLite catchup.\n logsChangeStream: false,\n });\n this.#state.resetBackoff();\n unregister = this.#state.cancelOnStop(downstream);\n this.#statusPublisher?.publish(\n lc,\n 'Replicating',\n `Replicating from ${watermark}`,\n );\n\n let backfillStatus: DownloadStatus | undefined;\n\n for await (const {data: message} of downstream) {\n this.#replicationEvents.add(1);\n switch (message[0]) {\n case 'status': {\n const {lagReport} = message[1];\n if (lagReport) {\n const report: ReplicationReport = {\n nextSendTimeMs: lagReport.nextSendTimeMs,\n };\n if (lagReport.lastTimings) {\n report.lastTimings = {\n ...lagReport.lastTimings,\n replicateTimeMs: Date.now(),\n };\n }\n this.#reporter.record(report);\n }\n break;\n }\n case 'error': {\n // Signal from the replication-manager that the view-syncer must\n // shut down and restore a new backup from litestream.\n const {type, message: msg} = message[1];\n this.stop(\n lc,\n // Note: The AbortError indicates a clean / intentional shutdown.\n new AbortError(\n `${errorTypeToReadableName(type as ErrorType)}: ${msg}`,\n ),\n );\n break;\n }\n default: {\n const msg = message[1];\n if (msg.tag === 'backfill' && msg.status) {\n const {status} = msg;\n if (!backfillStatus) {\n // Start publishing the status every 3 seconds.\n backfillStatus = status;\n this.#statusPublisher?.publish(\n lc,\n 'Replicating',\n `Backfilling ${msg.relation.name} table`,\n 3000,\n () =>\n backfillStatus\n ? {\n downloadStatus: [\n {\n ...backfillStatus,\n table: msg.relation.name,\n columns: [\n ...msg.relation.rowKey.columns,\n ...msg.columns,\n ],\n },\n ],\n }\n : {},\n );\n }\n backfillStatus = status; // Update the current status\n }\n\n const data = message as ChangeStreamData;\n const result = await this.#worker.processMessage(data);\n\n this.#handleResult(lc, result);\n if (result?.completedBackfill) {\n backfillStatus = undefined;\n }\n break;\n }\n }\n }\n this.#worker.abort();\n } catch (e) {\n err = e;\n this.#worker.abort();\n } finally {\n downstream?.cancel();\n unregister();\n this.#statusPublisher?.stop();\n }\n await this.#state.backoff(lc, err);\n }\n lc.info?.('IncrementalSyncer stopped');\n if (workerError) {\n throw workerError;\n }\n }\n\n #handleResult(lc: LogContext, result: CommitResult | null) {\n if (!result) {\n return;\n }\n if (result.completedBackfill) {\n // Publish the final status\n const status = result.completedBackfill;\n this.#statusPublisher?.publish(\n lc,\n 'Replicating',\n `Backfilled ${status.table} table`,\n 0,\n () => ({downloadStatus: [status]}),\n );\n } else if (result.schemaUpdated) {\n this.#statusPublisher?.publish(lc, 'Replicating', 'Schema updated');\n }\n if (result.watermark && result.changeLogUpdated) {\n void this.#notifier.notifySubscribers({\n state: 'version-ready',\n watermark: result.watermark,\n replicaReadyTimeMs: Date.now(),\n upstreamCommitTimeMs: result.upstreamCommitTimeMs,\n });\n }\n }\n\n subscribe(): Source<ReplicaState> {\n return this.#notifier.subscribe();\n }\n\n stop(lc: LogContext, err?: unknown) {\n this.#state.stop(lc, err);\n // Abort any polling loop that the write worker may be in.\n this.#worker.abort();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAgCA,IAAa,oBAAb,MAA+B;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,SAAk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GAE5B,MAAM,SAAS,OAAO;GACtB,KAAKH,kBAAkB,QACrB,IACA,eACA,cAAc,OAAO,MAAM,SAC3B,UACO,EAAC,gBAAgB,CAAC,MAAM,EAAC,EAClC;EACF,OAAO,IAAI,OAAO,eAChB,KAAKA,kBAAkB,QAAQ,IAAI,eAAe,gBAAgB;EAEpE,IAAI,OAAO,aAAa,OAAO,kBAC7B,KAAUC,UAAU,kBAAkB;GACpC,OAAO;GACP,WAAW,OAAO;GAClB,oBAAoB,KAAK,IAAI;GAC7B,sBAAsB,OAAO;EAC/B,CAAC;CAEL;CAEA,YAAkC;EAChC,OAAO,KAAKA,UAAU,UAAU;CAClC;CAEA,KAAK,IAAgB,KAAe;EAClC,KAAKE,OAAO,KAAK,IAAI,GAAG;EAExB,KAAKL,QAAQ,MAAM;CACrB;AACF"}
1
+ {"version":3,"file":"incremental-sync.js","names":["#lc","#taskID","#id","#changeStreamer","#worker","#mode","#statusPublisher","#notifier","#reporter","#state","#replicationEvents","#handleResult"],"sources":["../../../../../../zero-cache/src/services/replicator/incremental-sync.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {AbortError} from '../../../../shared/src/abort-error.ts';\nimport type {Enum} from '../../../../shared/src/enum.ts';\nimport {getOrCreateCounter} from '../../observability/metrics.ts';\nimport type {Source} from '../../types/streams.ts';\nimport type {DownloadStatus} from '../change-source/protocol/current.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport {\n errorTypeToReadableName,\n PROTOCOL_VERSION,\n type ChangeStreamer,\n type SizedDownstream,\n} from '../change-streamer/change-streamer.ts';\nimport type * as ErrorType from '../change-streamer/error-type-enum.ts';\nimport {RunningState} from '../running-state.ts';\nimport type {CommitResult} from './change-processor.ts';\nimport {Notifier} from './notifier.ts';\nimport type {ReplicationStatusPublisher} from './replication-status.ts';\nimport type {ReplicaState, ReplicatorMode} from './replicator.ts';\nimport {ReplicationReportRecorder} from './reporter/recorder.ts';\nimport type {ReplicationReport} from './reporter/report-schema.ts';\nimport type {WriteWorkerClient} from './write-worker-client.ts';\n\ntype ErrorType = Enum<typeof ErrorType>;\n\nconst MAX_WORKER_BATCH_MESSAGES = 256;\nconst MAX_WORKER_BATCH_SIZE = 1024 * 1024;\n\n/**\n * The {@link IncrementalSyncer} manages a logical replication stream from upstream,\n * handling application lifecycle events (start, stop) and retrying the\n * connection with exponential backoff. The actual handling of the logical\n * replication messages is done by the {@link ChangeProcessor}, which runs\n * in a worker thread via the {@link WriteWorkerClient}.\n */\nexport class IncrementalSyncer {\n readonly #lc: LogContext;\n readonly #taskID: string;\n readonly #id: string;\n readonly #changeStreamer: ChangeStreamer;\n readonly #worker: WriteWorkerClient;\n readonly #mode: ReplicatorMode;\n readonly #statusPublisher: ReplicationStatusPublisher | null;\n readonly #notifier: Notifier;\n readonly #reporter: ReplicationReportRecorder;\n\n readonly #state = new RunningState('IncrementalSyncer');\n\n readonly #replicationEvents = getOrCreateCounter(\n 'replication',\n 'events',\n 'Number of replication events processed',\n );\n\n constructor(\n lc: LogContext,\n taskID: string,\n id: string,\n changeStreamer: ChangeStreamer,\n worker: WriteWorkerClient,\n mode: ReplicatorMode,\n statusPublisher: ReplicationStatusPublisher | null,\n ) {\n this.#lc = lc;\n this.#taskID = taskID;\n this.#id = id;\n this.#changeStreamer = changeStreamer;\n this.#worker = worker;\n this.#mode = mode;\n this.#statusPublisher = statusPublisher;\n this.#notifier = new Notifier();\n this.#reporter = new ReplicationReportRecorder(lc);\n }\n\n async run() {\n const lc = this.#lc;\n let workerError: Error | undefined;\n this.#worker.onError(err => {\n workerError ??= err;\n this.#state.stop(lc, err);\n });\n lc.info?.(`Starting IncrementalSyncer`);\n const {watermark: initialWatermark} =\n await this.#worker.getSubscriptionState();\n\n // Notify any waiting subscribers that the replica is ready to be read.\n // This initial notification intentionally omits replicaReadyTimeMs because\n // it represents already-current state, not newly-unserved work.\n void this.#notifier.notifySubscribers({\n state: 'version-ready',\n watermark: initialWatermark,\n });\n\n while (this.#state.shouldRun()) {\n const {replicaVersion, watermark} =\n await this.#worker.getSubscriptionState();\n\n let downstream: Source<SizedDownstream> | undefined;\n let unregister = () => {};\n let err: unknown | undefined;\n\n try {\n downstream = await this.#changeStreamer.subscribe({\n protocolVersion: PROTOCOL_VERSION,\n taskID: this.#taskID,\n id: this.#id,\n mode: this.#mode,\n watermark,\n replicaVersion,\n initial: watermark === initialWatermark,\n // The SQLite change log is written by the change-streamer itself, so\n // no replicator logs the change stream any more. The parameter stays\n // on the wire for change-streamers that still exclude a writer from\n // SQLite catchup.\n logsChangeStream: false,\n });\n this.#state.resetBackoff();\n unregister = this.#state.cancelOnStop(downstream);\n this.#statusPublisher?.publish(\n lc,\n 'Replicating',\n `Replicating from ${watermark}`,\n );\n\n let backfillStatus: DownloadStatus | undefined;\n let writeBatch: ChangeStreamData[] = [];\n let writeBatchSize = 0;\n let inTransaction = false;\n\n const flushWrites = async () => {\n if (writeBatch.length === 0) {\n return;\n }\n const batch = writeBatch;\n writeBatch = [];\n writeBatchSize = 0;\n\n const result = await this.#worker.processMessages(batch);\n this.#handleResult(lc, result);\n if (result?.completedBackfill) {\n backfillStatus = undefined;\n }\n };\n\n for await (const {data: message, size} of downstream) {\n this.#replicationEvents.add(1);\n switch (message[0]) {\n case 'status': {\n const {lagReport} = message[1];\n if (lagReport) {\n const report: ReplicationReport = {\n nextSendTimeMs: lagReport.nextSendTimeMs,\n };\n if (lagReport.lastTimings) {\n report.lastTimings = {\n ...lagReport.lastTimings,\n replicateTimeMs: Date.now(),\n };\n }\n this.#reporter.record(report);\n }\n break;\n }\n case 'error': {\n // Signal from the replication-manager that the view-syncer must\n // shut down and restore a new backup from litestream.\n const {type, message: msg} = message[1];\n this.stop(\n lc,\n // Note: The AbortError indicates a clean / intentional shutdown.\n new AbortError(\n `${errorTypeToReadableName(type as ErrorType)}: ${msg}`,\n ),\n );\n break;\n }\n default: {\n const msg = message[1];\n if (msg.tag === 'backfill' && msg.status) {\n const {status} = msg;\n if (!backfillStatus) {\n // Start publishing the status every 3 seconds.\n backfillStatus = status;\n this.#statusPublisher?.publish(\n lc,\n 'Replicating',\n `Backfilling ${msg.relation.name} table`,\n 3000,\n () =>\n backfillStatus\n ? {\n downloadStatus: [\n {\n ...backfillStatus,\n table: msg.relation.name,\n columns: [\n ...msg.relation.rowKey.columns,\n ...msg.columns,\n ],\n },\n ],\n }\n : {},\n );\n }\n backfillStatus = status; // Update the current status\n }\n\n const type = message[0];\n const invalidTransactionSequence =\n type === 'begin' ? inTransaction : !inTransaction;\n if (type === 'begin') {\n inTransaction = true;\n } else if (type === 'commit' || type === 'rollback') {\n inTransaction = false;\n }\n\n writeBatch.push(message as ChangeStreamData);\n writeBatchSize += size;\n if (\n // Waiting here ensures that consuming the commit, which ACKs\n // it upstream, only happens after the SQLite commit finishes.\n type === 'commit' ||\n type === 'rollback' ||\n // Promptly surface malformed transaction sequences instead\n // of leaving a partial batch waiting for another message.\n invalidTransactionSequence ||\n writeBatch.length >= MAX_WORKER_BATCH_MESSAGES ||\n writeBatchSize >= MAX_WORKER_BATCH_SIZE\n ) {\n await flushWrites();\n }\n break;\n }\n }\n }\n this.#worker.abort();\n } catch (e) {\n err = e;\n this.#worker.abort();\n } finally {\n downstream?.cancel();\n unregister();\n this.#statusPublisher?.stop();\n }\n await this.#state.backoff(lc, err);\n }\n lc.info?.('IncrementalSyncer stopped');\n if (workerError) {\n throw workerError;\n }\n }\n\n #handleResult(lc: LogContext, result: CommitResult | null) {\n if (!result) {\n return;\n }\n if (result.completedBackfill) {\n // Publish the final status\n const status = result.completedBackfill;\n this.#statusPublisher?.publish(\n lc,\n 'Replicating',\n `Backfilled ${status.table} table`,\n 0,\n () => ({downloadStatus: [status]}),\n );\n } else if (result.schemaUpdated) {\n this.#statusPublisher?.publish(lc, 'Replicating', 'Schema updated');\n }\n if (result.watermark && result.changeLogUpdated) {\n void this.#notifier.notifySubscribers({\n state: 'version-ready',\n watermark: result.watermark,\n replicaReadyTimeMs: Date.now(),\n upstreamCommitTimeMs: result.upstreamCommitTimeMs,\n });\n }\n }\n\n subscribe(): Source<ReplicaState> {\n return this.#notifier.subscribe();\n }\n\n stop(lc: LogContext, err?: unknown) {\n this.#state.stop(lc, err);\n // Abort any polling loop that the write worker may be in.\n this.#worker.abort();\n }\n}\n"],"mappings":";;;;;;;AAyBA,IAAM,4BAA4B;AAClC,IAAM,wBAAwB,OAAO;;;;;;;;AASrC,IAAa,oBAAb,MAA+B;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,SAAkB,IAAI,aAAa,mBAAmB;CAEtD,qBAA8B,mBAC5B,eACA,UACA,wCACF;CAEA,YACE,IACA,QACA,IACA,gBACA,QACA,MACA,iBACA;EACA,KAAKA,MAAM;EACX,KAAKC,UAAU;EACf,KAAKC,MAAM;EACX,KAAKC,kBAAkB;EACvB,KAAKC,UAAU;EACf,KAAKC,QAAQ;EACb,KAAKC,mBAAmB;EACxB,KAAKC,YAAY,IAAI,SAAS;EAC9B,KAAKC,YAAY,IAAI,0BAA0B,EAAE;CACnD;CAEA,MAAM,MAAM;EACV,MAAM,KAAK,KAAKR;EAChB,IAAI;EACJ,KAAKI,QAAQ,SAAQ,QAAO;GAC1B,gBAAgB;GAChB,KAAKK,OAAO,KAAK,IAAI,GAAG;EAC1B,CAAC;EACD,GAAG,OAAO,4BAA4B;EACtC,MAAM,EAAC,WAAW,qBAChB,MAAM,KAAKL,QAAQ,qBAAqB;EAK1C,KAAUG,UAAU,kBAAkB;GACpC,OAAO;GACP,WAAW;EACb,CAAC;EAED,OAAO,KAAKE,OAAO,UAAU,GAAG;GAC9B,MAAM,EAAC,gBAAgB,cACrB,MAAM,KAAKL,QAAQ,qBAAqB;GAE1C,IAAI;GACJ,IAAI,mBAAmB,CAAC;GACxB,IAAI;GAEJ,IAAI;IACF,aAAa,MAAM,KAAKD,gBAAgB,UAAU;KAChD,iBAAA;KACA,QAAQ,KAAKF;KACb,IAAI,KAAKC;KACT,MAAM,K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AAKE,OAAO,KAAK,IAAI,GAAG;EAExB,KAAKL,QAAQ,MAAM;CACrB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"replicator.js","names":["#lc","#incrementalSyncer","#shouldPublishErrors","#worker","#runPromise"],"sources":["../../../../../../zero-cache/src/services/replicator/replicator.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport type {ReadonlyJSONObject} from '../../../../shared/src/json.ts';\nimport type {Source} from '../../types/streams.ts';\nimport type {ChangeStreamer} from '../change-streamer/change-streamer.ts';\nimport type {Service} from '../service.ts';\nimport {IncrementalSyncer} from './incremental-sync.ts';\nimport {\n publishReplicationError,\n type ReplicationStatusPublisher,\n} from './replication-status.ts';\nimport type {WriteWorkerClient} from './write-worker-client.ts';\n\n/** See {@link ReplicaStateNotifier.subscribe()}. */\nexport type ReplicaState = {\n readonly state: 'version-ready';\n /**\n * The replica watermark that became ready. Omitted for the initial\n * \"current state is ready\" notification, which should not count as newly\n * unserved work for a freshly-started ViewSyncer.\n */\n readonly watermark?: string | undefined;\n /**\n * Millisecond epoch when `watermark` became ready to read from the replica.\n */\n readonly replicaReadyTimeMs?: number | undefined;\n\n /**\n * Millisecond epoch at which the transaction behind `watermark` committed\n * *upstream*, as reported by the ChangeSource. Unlike `replicaReadyTimeMs`,\n * which is stamped locally when the change lands in the replica, this is the\n * origin of the whole pipeline, so `now - upstreamCommitTimeMs` at the point\n * the change is poked to clients is the end-to-end serving lag.\n *\n * Note that this crosses a clock domain: it comes from the upstream\n * database, whereas it is subtracted from the local clock in the ViewSyncer.\n * The existing `zero.replication.total_lag` metric spans the same boundary.\n *\n * Undefined when the ChangeSource does not report a commit time, and for the\n * initial \"current state is ready\" notification.\n */\n readonly upstreamCommitTimeMs?: number | undefined;\n\n // Used in tests to verify behavior when additional information\n // is ferried in the future. Not set in production.\n readonly testSeqNum?: number | undefined;\n};\n\nexport interface ReplicaStateNotifier {\n /**\n * Creates a cancelable subscription of changes in the replica state.\n *\n * A `version-ready` message indicates that the replica is ready to be\n * read, and henceforth that a _new_ version is ready, i.e. whenever a\n * change is committed to the replica. The `version-ready` message itself\n * otherwise contains no other information; the subscriber queries the\n * replica for the current data.\n *\n * A `maintenance` state indicates that the replica should not be read from.\n * If a subscriber is holding any transaction locks, it should release them\n * until the next `version-ready` signal.\n *\n * Upon subscription, the current state of the replica is sent immediately\n * if known. If multiple notifications occur before the subscriber\n * can consume them, all but the last notification are discarded by the\n * Subscription object (i.e. not buffered). Thus, a subscriber only\n * ever consumes the current (i.e. known) state of the replica. This avoids\n * a buildup of \"work\" if a subscriber is too busy to consume all\n * notifications.\n */\n subscribe(): Source<ReplicaState>;\n}\n\nexport interface Replicator extends ReplicaStateNotifier {\n /**\n * Returns an opaque message for human-readable consumption. This is\n * purely for ensuring that the Replicator has started at least once to\n * bootstrap a new replica.\n */\n status(): Promise<ReadonlyJSONObject>;\n}\n\nexport type ReplicatorMode = 'backup' | 'serving';\n\nexport class ReplicatorService implements Replicator, Service {\n readonly id: string;\n readonly #lc: LogContext;\n readonly #incrementalSyncer: IncrementalSyncer;\n readonly #shouldPublishErrors: boolean;\n readonly #worker: WriteWorkerClient;\n #runPromise: Promise<void> | undefined;\n\n constructor(\n lc: LogContext,\n taskID: string,\n id: string,\n mode: ReplicatorMode,\n changeStreamer: ChangeStreamer,\n worker: WriteWorkerClient,\n statusPublisher: ReplicationStatusPublisher | null,\n ) {\n this.id = id;\n this.#lc = lc\n .withContext('component', 'replicator')\n .withContext('serviceID', this.id);\n this.#worker = worker;\n this.#shouldPublishErrors = statusPublisher !== null;\n\n this.#incrementalSyncer = new IncrementalSyncer(\n this.#lc,\n taskID,\n `${taskID}/${id}`,\n changeStreamer,\n worker,\n mode,\n statusPublisher,\n );\n }\n\n status() {\n return Promise.resolve({status: 'ok'});\n }\n\n run() {\n this.#runPromise = this.#incrementalSyncer.run().catch(async error => {\n if (this.#shouldPublishErrors) {\n await publishReplicationError(\n this.#lc,\n 'Replicating',\n 'Replication stopped because the replica writer failed',\n );\n }\n throw error;\n });\n return this.#runPromise;\n }\n\n subscribe(): Source<ReplicaState> {\n return this.#incrementalSyncer.subscribe();\n }\n\n async stop() {\n this.#incrementalSyncer.stop(this.#lc);\n // Wait for the syncer's run loop to finish so that any in-flight\n // worker.processMessage() call completes and clears #pending\n // before we send the 'stop' message to the worker.\n await this.#runPromise;\n await this.#worker.stop();\n }\n}\n"],"mappings":";;;AAmFA,IAAa,oBAAb,MAA8D;CAC5D;CACA;CACA;CACA;CACA;CACA;CAEA,YACE,IACA,QACA,IACA,MACA,gBACA,QACA,iBACA;EACA,KAAK,KAAK;EACV,KAAKA,MAAM,GACR,YAAY,aAAa,YAAY,EACrC,YAAY,aAAa,KAAK,EAAE;EACnC,KAAKG,UAAU;EACf,KAAKD,uBAAuB,oBAAoB;EAEhD,KAAKD,qBAAqB,IAAI,kBAC5B,KAAKD,KACL,QACA,GAAG,OAAO,GAAG,MACb,gBACA,QACA,MACA,eACF;CACF;CAEA,SAAS;EACP,OAAO,QAAQ,QAAQ,EAAC,QAAQ,KAAI,CAAC;CACvC;CAEA,MAAM;EACJ,KAAKI,cAAc,KAAKH,mBAAmB,IAAI,EAAE,MAAM,OAAM,UAAS;GACpE,IAAI,KAAKC,sBACP,MAAM,wBACJ,KAAKF,KACL,eACA,uDACF;GAEF,MAAM;EACR,CAAC;EACD,OAAO,KAAKI;CACd;CAEA,YAAkC;EAChC,OAAO,KAAKH,mBAAmB,UAAU;CAC3C;CAEA,MAAM,OAAO;EACX,KAAKA,mBAAmB,KAAK,KAAKD,GAAG;EAIrC,MAAM,KAAKI;EACX,MAAM,KAAKD,QAAQ,KAAK;CAC1B;AACF"}
1
+ {"version":3,"file":"replicator.js","names":["#lc","#incrementalSyncer","#shouldPublishErrors","#worker","#runPromise"],"sources":["../../../../../../zero-cache/src/services/replicator/replicator.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport type {ReadonlyJSONObject} from '../../../../shared/src/json.ts';\nimport type {Source} from '../../types/streams.ts';\nimport type {ChangeStreamer} from '../change-streamer/change-streamer.ts';\nimport type {Service} from '../service.ts';\nimport {IncrementalSyncer} from './incremental-sync.ts';\nimport {\n publishReplicationError,\n type ReplicationStatusPublisher,\n} from './replication-status.ts';\nimport type {WriteWorkerClient} from './write-worker-client.ts';\n\n/** See {@link ReplicaStateNotifier.subscribe()}. */\nexport type ReplicaState = {\n readonly state: 'version-ready';\n /**\n * The replica watermark that became ready. Omitted for the initial\n * \"current state is ready\" notification, which should not count as newly\n * unserved work for a freshly-started ViewSyncer.\n */\n readonly watermark?: string | undefined;\n /**\n * Millisecond epoch when `watermark` became ready to read from the replica.\n */\n readonly replicaReadyTimeMs?: number | undefined;\n\n /**\n * Millisecond epoch at which the transaction behind `watermark` committed\n * *upstream*, as reported by the ChangeSource. Unlike `replicaReadyTimeMs`,\n * which is stamped locally when the change lands in the replica, this is the\n * origin of the whole pipeline, so `now - upstreamCommitTimeMs` at the point\n * the change is poked to clients is the end-to-end serving lag.\n *\n * Note that this crosses a clock domain: it comes from the upstream\n * database, whereas it is subtracted from the local clock in the ViewSyncer.\n * The existing `zero.replication.total_lag` metric spans the same boundary.\n *\n * Undefined when the ChangeSource does not report a commit time, and for the\n * initial \"current state is ready\" notification.\n */\n readonly upstreamCommitTimeMs?: number | undefined;\n\n // Used in tests to verify behavior when additional information\n // is ferried in the future. Not set in production.\n readonly testSeqNum?: number | undefined;\n};\n\nexport interface ReplicaStateNotifier {\n /**\n * Creates a cancelable subscription of changes in the replica state.\n *\n * A `version-ready` message indicates that the replica is ready to be\n * read, and henceforth that a _new_ version is ready, i.e. whenever a\n * change is committed to the replica. The `version-ready` message itself\n * otherwise contains no other information; the subscriber queries the\n * replica for the current data.\n *\n * A `maintenance` state indicates that the replica should not be read from.\n * If a subscriber is holding any transaction locks, it should release them\n * until the next `version-ready` signal.\n *\n * Upon subscription, the current state of the replica is sent immediately\n * if known. If multiple notifications occur before the subscriber\n * can consume them, all but the last notification are discarded by the\n * Subscription object (i.e. not buffered). Thus, a subscriber only\n * ever consumes the current (i.e. known) state of the replica. This avoids\n * a buildup of \"work\" if a subscriber is too busy to consume all\n * notifications.\n */\n subscribe(): Source<ReplicaState>;\n}\n\nexport interface Replicator extends ReplicaStateNotifier {\n /**\n * Returns an opaque message for human-readable consumption. This is\n * purely for ensuring that the Replicator has started at least once to\n * bootstrap a new replica.\n */\n status(): Promise<ReadonlyJSONObject>;\n}\n\nexport type ReplicatorMode = 'backup' | 'serving';\n\nexport class ReplicatorService implements Replicator, Service {\n readonly id: string;\n readonly #lc: LogContext;\n readonly #incrementalSyncer: IncrementalSyncer;\n readonly #shouldPublishErrors: boolean;\n readonly #worker: WriteWorkerClient;\n #runPromise: Promise<void> | undefined;\n\n constructor(\n lc: LogContext,\n taskID: string,\n id: string,\n mode: ReplicatorMode,\n changeStreamer: ChangeStreamer,\n worker: WriteWorkerClient,\n statusPublisher: ReplicationStatusPublisher | null,\n ) {\n this.id = id;\n this.#lc = lc\n .withContext('component', 'replicator')\n .withContext('serviceID', this.id);\n this.#worker = worker;\n this.#shouldPublishErrors = statusPublisher !== null;\n\n this.#incrementalSyncer = new IncrementalSyncer(\n this.#lc,\n taskID,\n `${taskID}/${id}`,\n changeStreamer,\n worker,\n mode,\n statusPublisher,\n );\n }\n\n status() {\n return Promise.resolve({status: 'ok'});\n }\n\n run() {\n this.#runPromise = this.#incrementalSyncer.run().catch(async error => {\n if (this.#shouldPublishErrors) {\n await publishReplicationError(\n this.#lc,\n 'Replicating',\n 'Replication stopped because the replica writer failed',\n );\n }\n throw error;\n });\n return this.#runPromise;\n }\n\n subscribe(): Source<ReplicaState> {\n return this.#incrementalSyncer.subscribe();\n }\n\n async stop() {\n this.#incrementalSyncer.stop(this.#lc);\n // Wait for the syncer's run loop to finish so that any in-flight\n // worker.processMessages() call completes and clears #pending\n // before we send the 'stop' message to the worker.\n await this.#runPromise;\n await this.#worker.stop();\n }\n}\n"],"mappings":";;;AAmFA,IAAa,oBAAb,MAA8D;CAC5D;CACA;CACA;CACA;CACA;CACA;CAEA,YACE,IACA,QACA,IACA,MACA,gBACA,QACA,iBACA;EACA,KAAK,KAAK;EACV,KAAKA,MAAM,GACR,YAAY,aAAa,YAAY,EACrC,YAAY,aAAa,KAAK,EAAE;EACnC,KAAKG,UAAU;EACf,KAAKD,uBAAuB,oBAAoB;EAEhD,KAAKD,qBAAqB,IAAI,kBAC5B,KAAKD,KACL,QACA,GAAG,OAAO,GAAG,MACb,gBACA,QACA,MACA,eACF;CACF;CAEA,SAAS;EACP,OAAO,QAAQ,QAAQ,EAAC,QAAQ,KAAI,CAAC;CACvC;CAEA,MAAM;EACJ,KAAKI,cAAc,KAAKH,mBAAmB,IAAI,EAAE,MAAM,OAAM,UAAS;GACpE,IAAI,KAAKC,sBACP,MAAM,wBACJ,KAAKF,KACL,eACA,uDACF;GAEF,MAAM;EACR,CAAC;EACD,OAAO,KAAKI;CACd;CAEA,YAAkC;EAChC,OAAO,KAAKH,mBAAmB,UAAU;CAC3C;CAEA,MAAM,OAAO;EACX,KAAKA,mBAAmB,KAAK,KAAKD,GAAG;EAIrC,MAAM,KAAKI;EACX,MAAM,KAAKD,QAAQ,KAAK;CAC1B;AACF"}
@@ -33,7 +33,7 @@ type ErrorHandler = (err: Error) => void;
33
33
  */
34
34
  export interface WriteWorkerClient {
35
35
  getSubscriptionState(): Promise<SubscriptionState>;
36
- processMessage(downstream: ChangeStreamData): Promise<CommitResult | null>;
36
+ processMessages(downstream: readonly ChangeStreamData[]): Promise<CommitResult | null>;
37
37
  abort(): void;
38
38
  stop(): Promise<void>;
39
39
  onError(handler: ErrorHandler): void;
@@ -56,7 +56,7 @@ export type ArgsMap = {
56
56
  ForceCheckpointConfig | null
57
57
  ];
58
58
  getSubscriptionState: [];
59
- processMessage: [ChangeStreamData];
59
+ processMessages: [readonly ChangeStreamData[]];
60
60
  abort: [];
61
61
  stop: [];
62
62
  };
@@ -68,7 +68,7 @@ export type Request<M extends Method = Method> = {
68
68
  export type ResultMap = {
69
69
  init: void;
70
70
  getSubscriptionState: SubscriptionState;
71
- processMessage: CommitResult | null;
71
+ processMessages: CommitResult | null;
72
72
  abort: void;
73
73
  stop: void;
74
74
  };
@@ -94,7 +94,7 @@ export declare class ThreadWriteWorkerClient implements WriteWorkerClient {
94
94
  constructor();
95
95
  init(dbPath: string, mode: ChangeProcessorMode, pragmas: PragmaConfig, logConfig: LogConfig, checkpoint?: ForceCheckpointConfig | null): Promise<void>;
96
96
  getSubscriptionState(): Promise<SubscriptionState>;
97
- processMessage(downstream: ChangeStreamData): Promise<CommitResult | null>;
97
+ processMessages(downstream: readonly ChangeStreamData[]): Promise<CommitResult | null>;
98
98
  abort(): void;
99
99
  stop(): Promise<void>;
100
100
  onError(handler: ErrorHandler): void;
@@ -1 +1 @@
1
- {"version":3,"file":"write-worker-client.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/replicator/write-worker-client.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,mCAAmC,CAAC;AACjE,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,8BAA8B,CAAC;AAE3D,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,iDAAiD,CAAC;AACtF,OAAO,KAAK,EAAC,mBAAmB,EAAE,YAAY,EAAC,MAAM,uBAAuB,CAAC;AAC7E,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,+BAA+B,CAAC;AAErE,MAAM,MAAM,YAAY,GAAG;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,CAAC;IACtB,iBAAiB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACxC,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,wBAAwB,EAAE,MAAM,CAAC;IACjC,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAClC,CAAC;AAEF,KAAK,YAAY,GAAG,CAAC,GA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3,"file":"write-worker-client.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/replicator/write-worker-client.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,mCAAmC,CAAC;AACjE,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,8BAA8B,CAAC;AAE3D,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,iDAAiD,CAAC;AACtF,OAAO,KAAK,EAAC,mBAAmB,EAAE,YAAY,EAAC,MAAM,uBAAuB,CAAC;AAC7E,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,+BAA+B,CAAC;AAErE,MAAM,MAAM,YAAY,GAAG;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,CAAC;IACtB,iBAAiB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACxC,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,wBAAwB,EAAE,MAAM,CAAC;IACjC,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAClC,CAAC;AAEF,KAAK,YAAY,GAAG,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAC;AAEzC;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,oBAAoB,IAAI,OAAO,CAAC,iBAAiB,CAAC,CAAC;IACnD,eAAe,CACb,UAAU,EAAE,SAAS,gBAAgB,EAAE,GACtC,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC;IAChC,KAAK,IAAI,IAAI,CAAC;IACd,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACtB,OAAO,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAAC;CACtC;AAED,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC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E,eAAe,CAAC;IAAC,MAAM,CAAC,EAAE,SAAS,CAAA;CAAC,CAAC;AAE5D,MAAM,MAAM,UAAU,GAAG;IAAC,UAAU,EAAE,eAAe,CAAA;CAAC,CAAC;AAEvD,wBAAgB,YAAY,CAAC,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,YAAY,QAM/D;AAED;;;GAGG;AACH,qBAAa,uBAAwB,YAAW,iBAAiB;;IAM/D,cAiCC;IAkBD,IAAI,CACF,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,mBAAmB,EACzB,OAAO,EAAE,YAAY,EACrB,SAAS,EAAE,SAAS,EACpB,UAAU,GAAE,qBAAqB,GAAG,IAAW,GAC9C,OAAO,CAAC,IAAI,CAAC,CAEf;IAED,oBAAoB,IAAI,OAAO,CAAC,iBAAiB,CAAC,CAEjD;IAED,eAAe,CACb,UAAU,EAAE,SAAS,gBAAgB,EAAE,GACtC,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAE9B;IAED,KAAK,IAAI,IAAI,CAIZ;IAEK,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAK1B;IAED,OAAO,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAEnC;CACF"}
@@ -103,8 +103,8 @@ var ThreadWriteWorkerClient = class {
103
103
  getSubscriptionState() {
104
104
  return this.#call("getSubscriptionState", []);
105
105
  }
106
- processMessage(downstream) {
107
- return this.#call("processMessage", [downstream]);
106
+ processMessages(downstream) {
107
+ return this.#call("processMessages", [downstream]);
108
108
  }
109
109
  abort() {
110
110
  if (!this.#terminated) this.#worker.postMessage({
@@ -1 +1 @@
1
- {"version":3,"file":"write-worker-client.js","names":["#worker","#rejectAll","#errorHandler","#pending","#terminated","#call"],"sources":["../../../../../../zero-cache/src/services/replicator/write-worker-client.ts"],"sourcesContent":["import {Worker} from 'node:worker_threads';\nimport {resolver, type Resolver} from '@rocicorp/resolver';\nimport {assert} from '../../../../shared/src/asserts.ts';\nimport type {LogConfig} from '../../../../shared/src/logging.ts';\nimport type {Database} from '../../../../zqlite/src/db.ts';\nimport {WRITE_WORKER_URL} from '../../server/worker-urls.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport type {ChangeProcessorMode, CommitResult} from './change-processor.ts';\nimport type {SubscriptionState} from './schema/replication-state.ts';\n\nexport type PragmaConfig = {\n busyTimeout: number;\n analysisLimit: number;\n walAutocheckpoint?: number | undefined;\n};\n\n/**\n * Enables write-path checkpoint backpressure in the write worker. At each\n * commit boundary, if the WAL has grown to at least `checkpointThresholdPages`,\n * the worker forces an immediate litestream sync (sealing the WAL to LTX and\n * running litestream's checkpoint).\n *\n * The optional `walMaxPages` is an emergency break that pauses until the WAL drains,\n * rather than letting it exceed available disk space. This replaces litestream's\n * analogous `truncate-page-n` emergency break, which is more disruptive because of\n * https://github.com/benbjohnson/litestream/issues/1332. Note, however, this should\n * never been needed if non-initial snapshots are disabled (which is the default).\n *\n * Set only for the backup replicator when replicating with litestream v5; `null`\n * disables the feature entirely (no per-commit overhead).\n */\nexport type ForceCheckpointConfig = {\n checkpointThresholdPages: number;\n maxWalPages?: number | undefined;\n};\n\ntype ErrorHandler = (err: Error) => void;\n\n/**\n * Interface for a write worker that processes replication messages.\n */\nexport interface WriteWorkerClient {\n getSubscriptionState(): Promise<SubscriptionState>;\n processMessage(downstream: ChangeStreamData): Promise<CommitResult | null>;\n abort(): void;\n stop(): Promise<void>;\n onError(handler: ErrorHandler): void;\n}\n\nexport type SerializedError = {\n name: string;\n message: string;\n stack?: string | undefined;\n cause?: SerializedError | string | undefined;\n details?: Record<string, unknown> | undefined;\n};\n\nexport function serializeError(err: unknown): SerializedError {\n if (!(err instanceof Error)) {\n return {\n name: 'Error',\n message: String(err),\n details: err && typeof err === 'object' ? {...err} : undefined,\n };\n }\n\n // Error fields such as message, stack, and some native error details are\n // non-enumerable, so JSON.stringify(err) would usually return \"{}\".\n const details = Object.fromEntries(\n Object.getOwnPropertyNames(err)\n .filter(key => !['name', 'message', 'stack', 'cause'].includes(key))\n .map(key => [key, (err as unknown as Record<string, unknown>)[key]]),\n );\n const cause =\n err.cause instanceof Error\n ? serializeError(err.cause)\n : err.cause === undefined\n ? undefined\n : String(err.cause);\n\n return {\n name: err.name,\n message: err.message,\n stack: err.stack,\n cause,\n details: Object.keys(details).length ? details : undefined,\n };\n}\n\nexport function deserializeError(serialized: SerializedError): Error {\n const err = new Error(serialized.message);\n err.name = serialized.name;\n if (serialized.stack !== undefined) {\n err.stack = serialized.stack;\n }\n if (serialized.cause !== undefined) {\n err.cause =\n typeof serialized.cause === 'string'\n ? serialized.cause\n : deserializeError(serialized.cause);\n }\n if (serialized.details) {\n Object.assign(err, serialized.details);\n }\n return err;\n}\n\n// Wire protocol types.\nexport type ArgsMap = {\n init: [\n string,\n ChangeProcessorMode,\n PragmaConfig,\n LogConfig,\n ForceCheckpointConfig | null,\n ];\n getSubscriptionState: [];\n processMessage: [ChangeStreamData];\n abort: [];\n stop: [];\n};\n\nexport type Method = keyof ArgsMap;\n\nexport type Request<M extends Method = Method> = {method: M; args: ArgsMap[M]};\n\nexport type ResultMap = {\n init: void;\n getSubscriptionState: SubscriptionState;\n processMessage: CommitResult | null;\n abort: void;\n stop: void;\n};\n\nexport type Response<M extends Method = Method> =\n | {method: M; result: ResultMap[M]; error?: undefined}\n | {method: M; error: SerializedError; result?: undefined};\n\nexport type WriteError = {writeError: SerializedError};\n\nexport function applyPragmas(db: Database, pragmas: PragmaConfig) {\n db.pragma(`busy_timeout = ${pragmas.busyTimeout}`);\n db.pragma(`analysis_limit = ${pragmas.analysisLimit}`);\n if (pragmas.walAutocheckpoint !== undefined) {\n db.pragma(`wal_autocheckpoint = ${pragmas.walAutocheckpoint}`);\n }\n}\n\n/**\n * Delegates SQLite writes to a worker_thread,\n * keeping the main event loop free for WebSocket heartbeats and IPC.\n */\nexport class ThreadWriteWorkerClient implements WriteWorkerClient {\n readonly #worker: Worker;\n #pending: Resolver<unknown, Error> | null = null;\n #errorHandler: ErrorHandler = () => {};\n #terminated = false;\n\n constructor() {\n this.#worker = new Worker(WRITE_WORKER_URL);\n\n this.#worker.on('message', (msg: Response | WriteError) => {\n if ('writeError' in msg) {\n const error = deserializeError(msg.writeError);\n this.#rejectAll(error);\n this.#errorHandler(error);\n return;\n }\n const r = this.#pending;\n if (!r) return; // stale abort response\n this.#pending = null;\n if (msg.error !== undefined) {\n r.reject(deserializeError(msg.error));\n } else {\n r.resolve(msg.result);\n }\n });\n\n this.#worker.on('error', (err: Error) => {\n this.#rejectAll(err);\n this.#errorHandler(err);\n });\n\n this.#worker.on('exit', (code: number) => {\n this.#terminated = true;\n if (code !== 0) {\n const err = new Error(`Worker exited with code ${code}`);\n this.#rejectAll(err);\n this.#errorHandler(err);\n }\n });\n }\n\n #rejectAll(err: Error) {\n const r = this.#pending;\n if (r) {\n this.#pending = null;\n r.reject(err);\n }\n }\n\n #call<M extends Method>(method: M, args: ArgsMap[M]): Promise<ResultMap[M]> {\n assert(this.#pending === null, `concurrent call: ${method}`);\n const r = resolver<ResultMap[M]>();\n this.#pending = r as Resolver<unknown, Error>;\n this.#worker.postMessage({method, args} satisfies Request);\n return r.promise;\n }\n\n init(\n dbPath: string,\n mode: ChangeProcessorMode,\n pragmas: PragmaConfig,\n logConfig: LogConfig,\n checkpoint: ForceCheckpointConfig | null = null,\n ): Promise<void> {\n return this.#call('init', [dbPath, mode, pragmas, logConfig, checkpoint]);\n }\n\n getSubscriptionState(): Promise<SubscriptionState> {\n return this.#call('getSubscriptionState', []);\n }\n\n processMessage(downstream: ChangeStreamData): Promise<CommitResult | null> {\n return this.#call('processMessage', [downstream]);\n }\n\n abort(): void {\n if (!this.#terminated) {\n this.#worker.postMessage({method: 'abort', args: []} satisfies Request);\n }\n }\n\n async stop(): Promise<void> {\n await this.#call('stop', []);\n if (!this.#terminated) {\n await this.#worker.terminate();\n }\n }\n\n onError(handler: ErrorHandler): void {\n this.#errorHandler = handler;\n }\n}\n"],"mappings":";;;;;AAyDA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AC,UAAU,CAAC;CAClD;CAEA,QAAc;EACZ,IAAI,CAAC,KAAKD,aACR,KAAKJ,QAAQ,YAAY;GAAC,QAAQ;GAAS,MAAM,CAAC;EAAC,CAAmB;CAE1E;CAEA,MAAM,OAAsB;EAC1B,MAAM,KAAKK,MAAM,QAAQ,CAAC,CAAC;EAC3B,IAAI,CAAC,KAAKD,aACR,MAAM,KAAKJ,QAAQ,UAAU;CAEjC;CAEA,QAAQ,SAA6B;EACnC,KAAKE,gBAAgB;CACvB;AACF"}
1
+ {"version":3,"file":"write-worker-client.js","names":["#worker","#rejectAll","#errorHandler","#pending","#terminated","#call"],"sources":["../../../../../../zero-cache/src/services/replicator/write-worker-client.ts"],"sourcesContent":["import {Worker} from 'node:worker_threads';\nimport {resolver, type Resolver} from '@rocicorp/resolver';\nimport {assert} from '../../../../shared/src/asserts.ts';\nimport type {LogConfig} from '../../../../shared/src/logging.ts';\nimport type {Database} from '../../../../zqlite/src/db.ts';\nimport {WRITE_WORKER_URL} from '../../server/worker-urls.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport type {ChangeProcessorMode, CommitResult} from './change-processor.ts';\nimport type {SubscriptionState} from './schema/replication-state.ts';\n\nexport type PragmaConfig = {\n busyTimeout: number;\n analysisLimit: number;\n walAutocheckpoint?: number | undefined;\n};\n\n/**\n * Enables write-path checkpoint backpressure in the write worker. At each\n * commit boundary, if the WAL has grown to at least `checkpointThresholdPages`,\n * the worker forces an immediate litestream sync (sealing the WAL to LTX and\n * running litestream's checkpoint).\n *\n * The optional `walMaxPages` is an emergency break that pauses until the WAL drains,\n * rather than letting it exceed available disk space. This replaces litestream's\n * analogous `truncate-page-n` emergency break, which is more disruptive because of\n * https://github.com/benbjohnson/litestream/issues/1332. Note, however, this should\n * never been needed if non-initial snapshots are disabled (which is the default).\n *\n * Set only for the backup replicator when replicating with litestream v5; `null`\n * disables the feature entirely (no per-commit overhead).\n */\nexport type ForceCheckpointConfig = {\n checkpointThresholdPages: number;\n maxWalPages?: number | undefined;\n};\n\ntype ErrorHandler = (err: Error) => void;\n\n/**\n * Interface for a write worker that processes replication messages.\n */\nexport interface WriteWorkerClient {\n getSubscriptionState(): Promise<SubscriptionState>;\n processMessages(\n downstream: readonly ChangeStreamData[],\n ): Promise<CommitResult | null>;\n abort(): void;\n stop(): Promise<void>;\n onError(handler: ErrorHandler): void;\n}\n\nexport type SerializedError = {\n name: string;\n message: string;\n stack?: string | undefined;\n cause?: SerializedError | string | undefined;\n details?: Record<string, unknown> | undefined;\n};\n\nexport function serializeError(err: unknown): SerializedError {\n if (!(err instanceof Error)) {\n return {\n name: 'Error',\n message: String(err),\n details: err && typeof err === 'object' ? {...err} : undefined,\n };\n }\n\n // Error fields such as message, stack, and some native error details are\n // non-enumerable, so JSON.stringify(err) would usually return \"{}\".\n const details = Object.fromEntries(\n Object.getOwnPropertyNames(err)\n .filter(key => !['name', 'message', 'stack', 'cause'].includes(key))\n .map(key => [key, (err as unknown as Record<string, unknown>)[key]]),\n );\n const cause =\n err.cause instanceof Error\n ? serializeError(err.cause)\n : err.cause === undefined\n ? undefined\n : String(err.cause);\n\n return {\n name: err.name,\n message: err.message,\n stack: err.stack,\n cause,\n details: Object.keys(details).length ? details : undefined,\n };\n}\n\nexport function deserializeError(serialized: SerializedError): Error {\n const err = new Error(serialized.message);\n err.name = serialized.name;\n if (serialized.stack !== undefined) {\n err.stack = serialized.stack;\n }\n if (serialized.cause !== undefined) {\n err.cause =\n typeof serialized.cause === 'string'\n ? serialized.cause\n : deserializeError(serialized.cause);\n }\n if (serialized.details) {\n Object.assign(err, serialized.details);\n }\n return err;\n}\n\n// Wire protocol types.\nexport type ArgsMap = {\n init: [\n string,\n ChangeProcessorMode,\n PragmaConfig,\n LogConfig,\n ForceCheckpointConfig | null,\n ];\n getSubscriptionState: [];\n processMessages: [readonly ChangeStreamData[]];\n abort: [];\n stop: [];\n};\n\nexport type Method = keyof ArgsMap;\n\nexport type Request<M extends Method = Method> = {method: M; args: ArgsMap[M]};\n\nexport type ResultMap = {\n init: void;\n getSubscriptionState: SubscriptionState;\n processMessages: CommitResult | null;\n abort: void;\n stop: void;\n};\n\nexport type Response<M extends Method = Method> =\n | {method: M; result: ResultMap[M]; error?: undefined}\n | {method: M; error: SerializedError; result?: undefined};\n\nexport type WriteError = {writeError: SerializedError};\n\nexport function applyPragmas(db: Database, pragmas: PragmaConfig) {\n db.pragma(`busy_timeout = ${pragmas.busyTimeout}`);\n db.pragma(`analysis_limit = ${pragmas.analysisLimit}`);\n if (pragmas.walAutocheckpoint !== undefined) {\n db.pragma(`wal_autocheckpoint = ${pragmas.walAutocheckpoint}`);\n }\n}\n\n/**\n * Delegates SQLite writes to a worker_thread,\n * keeping the main event loop free for WebSocket heartbeats and IPC.\n */\nexport class ThreadWriteWorkerClient implements WriteWorkerClient {\n readonly #worker: Worker;\n #pending: Resolver<unknown, Error> | null = null;\n #errorHandler: ErrorHandler = () => {};\n #terminated = false;\n\n constructor() {\n this.#worker = new Worker(WRITE_WORKER_URL);\n\n this.#worker.on('message', (msg: Response | WriteError) => {\n if ('writeError' in msg) {\n const error = deserializeError(msg.writeError);\n this.#rejectAll(error);\n this.#errorHandler(error);\n return;\n }\n const r = this.#pending;\n if (!r) return; // stale abort response\n this.#pending = null;\n if (msg.error !== undefined) {\n r.reject(deserializeError(msg.error));\n } else {\n r.resolve(msg.result);\n }\n });\n\n this.#worker.on('error', (err: Error) => {\n this.#rejectAll(err);\n this.#errorHandler(err);\n });\n\n this.#worker.on('exit', (code: number) => {\n this.#terminated = true;\n if (code !== 0) {\n const err = new Error(`Worker exited with code ${code}`);\n this.#rejectAll(err);\n this.#errorHandler(err);\n }\n });\n }\n\n #rejectAll(err: Error) {\n const r = this.#pending;\n if (r) {\n this.#pending = null;\n r.reject(err);\n }\n }\n\n #call<M extends Method>(method: M, args: ArgsMap[M]): Promise<ResultMap[M]> {\n assert(this.#pending === null, `concurrent call: ${method}`);\n const r = resolver<ResultMap[M]>();\n this.#pending = r as Resolver<unknown, Error>;\n this.#worker.postMessage({method, args} satisfies Request);\n return r.promise;\n }\n\n init(\n dbPath: string,\n mode: ChangeProcessorMode,\n pragmas: PragmaConfig,\n logConfig: LogConfig,\n checkpoint: ForceCheckpointConfig | null = null,\n ): Promise<void> {\n return this.#call('init', [dbPath, mode, pragmas, logConfig, checkpoint]);\n }\n\n getSubscriptionState(): Promise<SubscriptionState> {\n return this.#call('getSubscriptionState', []);\n }\n\n processMessages(\n downstream: readonly ChangeStreamData[],\n ): Promise<CommitResult | null> {\n return this.#call('processMessages', [downstream]);\n }\n\n abort(): void {\n if (!this.#terminated) {\n this.#worker.postMessage({method: 'abort', args: []} satisfies Request);\n }\n }\n\n async stop(): Promise<void> {\n await this.#call('stop', []);\n if (!this.#terminated) {\n await this.#worker.terminate();\n }\n }\n\n onError(handler: ErrorHandler): void {\n this.#errorHandler = handler;\n }\n}\n"],"mappings":";;;;;AA2DA,SAAgB,eAAe,KAA+B;CAC5D,IAAI,EAAE,eAAe,QACnB,OAAO;EACL,MAAM;EACN,SAAS,OAAO,GAAG;EACnB,SAAS,OAAO,OAAO,QAAQ,WAAW,EAAC,GAAG,IAAG,IAAI,KAAA;CACvD;CAKF,MAAM,UAAU,OAAO,YACrB,OAAO,oBAAoB,GAAG,EAC3B,QAAO,QAAO,CAAC;EAAC;EAAQ;EAAW;EAAS;CAAO,EAAE,SAAS,GAAG,CAAC,EAClE,KAAI,QAAO,CAAC,KAAM,IAA2C,IAAI,CAAC,CACvE;CACA,MAAM,QACJ,IAAI,iBAAiB,QACjB,eAAe,IAAI,KAAK,IACxB,IAAI,UAAU,KAAA,IACZ,KAAA,IACA,OAAO,IAAI,KAAK;CAExB,OAAO;EACL,MAAM,IAAI;EACV,SAAS,IAAI;EACb,OAAO,IAAI;EACX;EACA,SAAS,OAAO,KAAK,OAAO,EAAE,SAAS,UAAU,KAAA;CACnD;AACF;AAEA,SAAgB,iBAAiB,YAAoC;CACnE,MAAM,MAAM,IAAI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AG;GACxB;EACF,CAAC;CACH;CAEA,WAAW,KAAY;EACrB,MAAM,IAAI,KAAKC;EACf,IAAI,GAAG;GACL,KAAKA,WAAW;GAChB,EAAE,OAAO,GAAG;EACd;CACF;CAEA,MAAwB,QAAW,MAAyC;EAC1E,OAAO,KAAKA,aAAa,MAAM,oBAAoB,QAAQ;EAC3D,MAAM,IAAI,SAAuB;EACjC,KAAKA,WAAW;EAChB,KAAKH,QAAQ,YAAY;GAAC;GAAQ;EAAI,CAAmB;EACzD,OAAO,EAAE;CACX;CAEA,KACE,QACA,MACA,SACA,WACA,aAA2C,MAC5B;EACf,OAAO,KAAKK,MAAM,QAAQ;GAAC;GAAQ;GAAM;GAAS;GAAW;EAAU,CAAC;CAC1E;CAEA,uBAAmD;EACjD,OAAO,KAAKA,MAAM,wBAAwB,CAAC,CAAC;CAC9C;CAEA,gBACE,YAC8B;EAC9B,OAAO,KAAKA,MAAM,mBAAmB,CAAC,UAAU,CAAC;CACnD;CAEA,QAAc;EACZ,IAAI,CAAC,KAAKD,aACR,KAAKJ,QAAQ,YAAY;GAAC,QAAQ;GAAS,MAAM,CAAC;EAAC,CAAmB;CAE1E;CAEA,MAAM,OAAsB;EAC1B,MAAM,KAAKK,MAAM,QAAQ,CAAC,CAAC;EAC3B,IAAI,CAAC,KAAKD,aACR,MAAM,KAAKJ,QAAQ,UAAU;CAEjC;CAEA,QAAQ,SAA6B;EACnC,KAAKE,gBAAgB;CACvB;AACF"}
@@ -80,11 +80,17 @@ function createAPI() {
80
80
  throw e;
81
81
  }
82
82
  },
83
- async processMessage(downstream) {
83
+ async processMessages(downstream) {
84
84
  try {
85
- const committed = must(processor).processMessage(must(lc), downstream);
86
- if (committed && checkpointer) await checkpointer.maybeCheckpoint();
87
- return committed;
85
+ let commitResult = null;
86
+ for (const message of downstream) {
87
+ const committed = must(processor).processMessage(must(lc), message);
88
+ if (committed) {
89
+ commitResult = committed;
90
+ if (checkpointer) await checkpointer.maybeCheckpoint();
91
+ }
92
+ }
93
+ return commitResult;
88
94
  } catch (e) {
89
95
  handleCorruptedDb(e);
90
96
  throw e;
@@ -1 +1 @@
1
- {"version":3,"file":"write-worker.js","names":[],"sources":["../../../../../../zero-cache/src/services/replicator/write-worker.ts"],"sourcesContent":["import {parentPort} from 'node:worker_threads';\nimport type {LogContext} from '@rocicorp/logger';\nimport {assert} from '../../../../shared/src/asserts.ts';\nimport type {LogConfig} from '../../../../shared/src/logging.ts';\nimport {must} from '../../../../shared/src/must.ts';\nimport {Database} from '../../../../zqlite/src/db.ts';\nimport {deleteLiteDB} from '../../db/delete-lite-db.ts';\nimport {\n isSQLiteCorruption,\n logSQLiteCorruptionDiagnostics,\n registerSQLiteCorruptionDiagnosticTarget,\n} from '../../db/sqlite-corruption.ts';\nimport {StatementRunner} from '../../db/statements.ts';\nimport {createLogContext} from '../../server/logging.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport {LitestreamCheckpointer} from '../litestream/litestream-checkpointer.ts';\nimport {LitestreamController} from '../litestream/litestream-controller.ts';\nimport {ChangeProcessor, type ChangeProcessorMode} from './change-processor.ts';\nimport {getSubscriptionState} from './schema/replication-state.ts';\nimport {\n applyPragmas,\n serializeError,\n type ArgsMap,\n type ForceCheckpointConfig,\n type Method,\n type PragmaConfig,\n type Request,\n type Response,\n type ResultMap,\n type WriteError,\n} from './write-worker-client.ts';\n\nif (!parentPort) {\n throw new Error('write-worker must be run as a worker thread');\n}\n\nconst port = parentPort;\n\ntype API = {\n [M in Method]: (...args: ArgsMap[M]) => ResultMap[M] | Promise<ResultMap[M]>;\n};\n\nfunction createAPI(): API {\n let db: Database | undefined;\n let runner: StatementRunner | undefined;\n let processor: ChangeProcessor | undefined;\n let mode: ChangeProcessorMode | undefined;\n let lc: LogContext | undefined;\n let replicaDbPath: string | undefined;\n let unregisterCorruptionDiagnosticTargets: (() => void)[] = [];\n\n // Set when write-path checkpoint backpressure is enabled (backup replicator\n // on litestream v5). `undefined` disables the feature.\n let checkpointerConfig: ForceCheckpointConfig | undefined;\n let checkpointer: LitestreamCheckpointer | undefined;\n\n function unregisterCorruptionDiagnostics() {\n unregisterCorruptionDiagnosticTargets.forEach(unregister => unregister());\n unregisterCorruptionDiagnosticTargets = [];\n }\n\n function handleCorruptedDb(err: unknown) {\n if (!lc || !replicaDbPath || !isSQLiteCorruption(err)) {\n return;\n }\n logSQLiteCorruptionDiagnostics(lc, 'write-worker', replicaDbPath, err);\n try {\n lc.warn?.(`deleting corrupted db at ${replicaDbPath}`);\n deleteLiteDB(replicaDbPath);\n } catch (e) {\n lc.warn?.(`error deleting corrupted db at ${replicaDbPath}`, e);\n }\n }\n\n function createProcessor() {\n processor = new ChangeProcessor(must(runner), must(mode), (_lc, err) => {\n handleCorruptedDb(err);\n port.postMessage({\n writeError: serializeError(err),\n } satisfies WriteError);\n });\n }\n\n function createCheckpointer() {\n if (checkpointerConfig) {\n assert(lc && db && replicaDbPath, `not initialized`);\n checkpointer = new LitestreamCheckpointer(\n lc,\n db,\n new LitestreamController(lc, replicaDbPath),\n checkpointerConfig,\n );\n }\n }\n\n return {\n init(\n dbPath: string,\n cpMode: ChangeProcessorMode,\n pragmas: PragmaConfig,\n logConfig: LogConfig,\n checkpointConfig: ForceCheckpointConfig | null,\n ): void {\n replicaDbPath = dbPath;\n lc = createLogContext({log: logConfig}, 'write-worker');\n unregisterCorruptionDiagnostics();\n unregisterCorruptionDiagnosticTargets.push(\n registerSQLiteCorruptionDiagnosticTarget({\n debugName: 'write-worker',\n dbPath,\n }),\n );\n try {\n db = new Database(lc, dbPath);\n applyPragmas(db, pragmas);\n runner = new StatementRunner(db);\n mode = cpMode;\n checkpointerConfig = checkpointConfig ?? undefined;\n createProcessor();\n createCheckpointer();\n } catch (e) {\n handleCorruptedDb(e);\n throw e;\n }\n },\n\n getSubscriptionState() {\n try {\n return getSubscriptionState(must(runner));\n } catch (e) {\n handleCorruptedDb(e);\n throw e;\n }\n },\n\n async processMessage(downstream: ChangeStreamData) {\n try {\n const committed = must(processor).processMessage(must(lc), downstream);\n if (committed && checkpointer) {\n await checkpointer.maybeCheckpoint();\n }\n return committed;\n } catch (e) {\n handleCorruptedDb(e);\n throw e;\n }\n },\n\n abort() {\n must(processor).abort(must(lc));\n checkpointer?.close();\n createProcessor();\n createCheckpointer();\n },\n\n stop() {\n checkpointer?.close();\n checkpointer = undefined;\n db?.close();\n db = undefined;\n runner = undefined;\n processor = undefined;\n replicaDbPath = undefined;\n unregisterCorruptionDiagnostics();\n },\n };\n}\n\nconst api = createAPI();\n\nport.on('message', async (msg: Request) => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- TS can't narrow msg.method + msg.args together\n const result = await (api[msg.method] as (...args: any[]) => unknown)(\n ...msg.args,\n );\n // abort is fire-and-forget — no pending slot on the client side.\n if (msg.method !== 'abort') {\n port.postMessage({method: msg.method, result} as Response);\n }\n } catch (e) {\n if (msg.method !== 'abort') {\n port.postMessage({\n method: msg.method,\n error: serializeError(e),\n } as Response);\n }\n }\n});\n"],"mappings":";;;;;;;;;;;;;;AAgCA,IAAI,CAAC,YACH,MAAM,IAAI,MAAM,6CAA6C;AAG/D,IAAM,OAAO;AAMb,SAAS,YAAiB;CACxB,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,wCAAwD,CAAC;CAI7D,IAAI;CACJ,IAAI;CAEJ,SAAS,kCAAkC;EACzC,sCAAsC,SAAQ,eAAc,WAAW,CAAC;EACxE,wCAAwC,CAAC;CAC3C;CAEA,SAAS,kBAAkB,KAAc;EACvC,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAAC,mBAAmB,GAAG,GAClD;EAEF,+BAA+B,IAAI,gBAAgB,eAAe,GAAG;EACrE,IAAI;GACF,GAAG,OAAO,4BAA4B,eAAe;GACrD,aAAa,aAAa;EAC5B,SAAS,GAAG;GACV,GAAG,OAAO,kCAAkC,iBAAiB,CAAC;EAChE;CACF;CAEA,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ACL,cAAc,MAAM;GACpB,eAAe,KAAA;GACf,IAAI,MAAM;GACV,KAAK,KAAA;GACL,SAAS,KAAA;GACT,YAAY,KAAA;GACZ,gBAAgB,KAAA;GAChB,gCAAgC;EAClC;CACF;AACF;AAEA,IAAM,MAAM,UAAU;AAEtB,KAAK,GAAG,WAAW,OAAO,QAAiB;CACzC,IAAI;EAEF,MAAM,SAAS,MAAO,IAAI,IAAI,QAC5B,GAAG,IAAI,IACT;EAEA,IAAI,IAAI,WAAW,SACjB,KAAK,YAAY;GAAC,QAAQ,IAAI;GAAQ;EAAM,CAAa;CAE7D,SAAS,GAAG;EACV,IAAI,IAAI,WAAW,SACjB,KAAK,YAAY;GACf,QAAQ,IAAI;GACZ,OAAO,eAAe,CAAC;EACzB,CAAa;CAEjB;AACF,CAAC"}
1
+ {"version":3,"file":"write-worker.js","names":[],"sources":["../../../../../../zero-cache/src/services/replicator/write-worker.ts"],"sourcesContent":["import {parentPort} from 'node:worker_threads';\nimport type {LogContext} from '@rocicorp/logger';\nimport {assert} from '../../../../shared/src/asserts.ts';\nimport type {LogConfig} from '../../../../shared/src/logging.ts';\nimport {must} from '../../../../shared/src/must.ts';\nimport {Database} from '../../../../zqlite/src/db.ts';\nimport {deleteLiteDB} from '../../db/delete-lite-db.ts';\nimport {\n isSQLiteCorruption,\n logSQLiteCorruptionDiagnostics,\n registerSQLiteCorruptionDiagnosticTarget,\n} from '../../db/sqlite-corruption.ts';\nimport {StatementRunner} from '../../db/statements.ts';\nimport {createLogContext} from '../../server/logging.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport {LitestreamCheckpointer} from '../litestream/litestream-checkpointer.ts';\nimport {LitestreamController} from '../litestream/litestream-controller.ts';\nimport {ChangeProcessor, type ChangeProcessorMode} from './change-processor.ts';\nimport {getSubscriptionState} from './schema/replication-state.ts';\nimport {\n applyPragmas,\n serializeError,\n type ArgsMap,\n type ForceCheckpointConfig,\n type Method,\n type PragmaConfig,\n type Request,\n type Response,\n type ResultMap,\n type WriteError,\n} from './write-worker-client.ts';\n\nif (!parentPort) {\n throw new Error('write-worker must be run as a worker thread');\n}\n\nconst port = parentPort;\n\ntype API = {\n [M in Method]: (...args: ArgsMap[M]) => ResultMap[M] | Promise<ResultMap[M]>;\n};\n\nfunction createAPI(): API {\n let db: Database | undefined;\n let runner: StatementRunner | undefined;\n let processor: ChangeProcessor | undefined;\n let mode: ChangeProcessorMode | undefined;\n let lc: LogContext | undefined;\n let replicaDbPath: string | undefined;\n let unregisterCorruptionDiagnosticTargets: (() => void)[] = [];\n\n // Set when write-path checkpoint backpressure is enabled (backup replicator\n // on litestream v5). `undefined` disables the feature.\n let checkpointerConfig: ForceCheckpointConfig | undefined;\n let checkpointer: LitestreamCheckpointer | undefined;\n\n function unregisterCorruptionDiagnostics() {\n unregisterCorruptionDiagnosticTargets.forEach(unregister => unregister());\n unregisterCorruptionDiagnosticTargets = [];\n }\n\n function handleCorruptedDb(err: unknown) {\n if (!lc || !replicaDbPath || !isSQLiteCorruption(err)) {\n return;\n }\n logSQLiteCorruptionDiagnostics(lc, 'write-worker', replicaDbPath, err);\n try {\n lc.warn?.(`deleting corrupted db at ${replicaDbPath}`);\n deleteLiteDB(replicaDbPath);\n } catch (e) {\n lc.warn?.(`error deleting corrupted db at ${replicaDbPath}`, e);\n }\n }\n\n function createProcessor() {\n processor = new ChangeProcessor(must(runner), must(mode), (_lc, err) => {\n handleCorruptedDb(err);\n port.postMessage({\n writeError: serializeError(err),\n } satisfies WriteError);\n });\n }\n\n function createCheckpointer() {\n if (checkpointerConfig) {\n assert(lc && db && replicaDbPath, `not initialized`);\n checkpointer = new LitestreamCheckpointer(\n lc,\n db,\n new LitestreamController(lc, replicaDbPath),\n checkpointerConfig,\n );\n }\n }\n\n return {\n init(\n dbPath: string,\n cpMode: ChangeProcessorMode,\n pragmas: PragmaConfig,\n logConfig: LogConfig,\n checkpointConfig: ForceCheckpointConfig | null,\n ): void {\n replicaDbPath = dbPath;\n lc = createLogContext({log: logConfig}, 'write-worker');\n unregisterCorruptionDiagnostics();\n unregisterCorruptionDiagnosticTargets.push(\n registerSQLiteCorruptionDiagnosticTarget({\n debugName: 'write-worker',\n dbPath,\n }),\n );\n try {\n db = new Database(lc, dbPath);\n applyPragmas(db, pragmas);\n runner = new StatementRunner(db);\n mode = cpMode;\n checkpointerConfig = checkpointConfig ?? undefined;\n createProcessor();\n createCheckpointer();\n } catch (e) {\n handleCorruptedDb(e);\n throw e;\n }\n },\n\n getSubscriptionState() {\n try {\n return getSubscriptionState(must(runner));\n } catch (e) {\n handleCorruptedDb(e);\n throw e;\n }\n },\n\n async processMessages(downstream: readonly ChangeStreamData[]) {\n try {\n let commitResult = null;\n for (const message of downstream) {\n const committed = must(processor).processMessage(must(lc), message);\n if (committed) {\n commitResult = committed;\n if (checkpointer) {\n await checkpointer.maybeCheckpoint();\n }\n }\n }\n return commitResult;\n } catch (e) {\n handleCorruptedDb(e);\n throw e;\n }\n },\n\n abort() {\n must(processor).abort(must(lc));\n checkpointer?.close();\n createProcessor();\n createCheckpointer();\n },\n\n stop() {\n checkpointer?.close();\n checkpointer = undefined;\n db?.close();\n db = undefined;\n runner = undefined;\n processor = undefined;\n replicaDbPath = undefined;\n unregisterCorruptionDiagnostics();\n },\n };\n}\n\nconst api = createAPI();\n\nport.on('message', async (msg: Request) => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- TS can't narrow msg.method + msg.args together\n const result = await (api[msg.method] as (...args: any[]) => unknown)(\n ...msg.args,\n );\n // abort is fire-and-forget — no pending slot on the client side.\n if (msg.method !== 'abort') {\n port.postMessage({method: msg.method, result} as Response);\n }\n } catch (e) {\n if (msg.method !== 'abort') {\n port.postMessage({\n method: msg.method,\n error: serializeError(e),\n } as Response);\n }\n }\n});\n"],"mappings":";;;;;;;;;;;;;;AAgCA,IAAI,CAAC,YACH,MAAM,IAAI,MAAM,6CAA6C;AAG/D,IAAM,OAAO;AAMb,SAAS,YAAiB;CACx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M;GACR;EACF;EAEA,uBAAuB;GACrB,IAAI;IACF,OAAO,qBAAqB,KAAK,MAAM,CAAC;GAC1C,SAAS,GAAG;IACV,kBAAkB,CAAC;IACnB,MAAM;GACR;EACF;EAEA,MAAM,gBAAgB,YAAyC;GAC7D,IAAI;IACF,IAAI,eAAe;IACnB,KAAK,MAAM,WAAW,YAAY;KAChC,MAAM,YAAY,KAAK,SAAS,EAAE,eAAe,KAAK,EAAE,GAAG,OAAO;KAClE,IAAI,WAAW;MACb,eAAe;MACf,IAAI,cACF,MAAM,aAAa,gBAAgB;KAEvC;IACF;IACA,OAAO;GACT,SAAS,GAAG;IACV,kBAAkB,CAAC;IACnB,MAAM;GACR;EACF;EAEA,QAAQ;GACN,KAAK,SAAS,EAAE,MAAM,KAAK,EAAE,CAAC;GAC9B,cAAc,MAAM;GACpB,gBAAgB;GAChB,mBAAmB;EACrB;EAEA,OAAO;GACL,cAAc,MAAM;GACpB,eAAe,KAAA;GACf,IAAI,MAAM;GACV,KAAK,KAAA;GACL,SAAS,KAAA;GACT,YAAY,KAAA;GACZ,gBAAgB,KAAA;GAChB,gCAAgC;EAClC;CACF;AACF;AAEA,IAAM,MAAM,UAAU;AAEtB,KAAK,GAAG,WAAW,OAAO,QAAiB;CACzC,IAAI;EAEF,MAAM,SAAS,MAAO,IAAI,IAAI,QAC5B,GAAG,IAAI,IACT;EAEA,IAAI,IAAI,WAAW,SACjB,KAAK,YAAY;GAAC,QAAQ,IAAI;GAAQ;EAAM,CAAa;CAE7D,SAAS,GAAG;EACV,IAAI,IAAI,WAAW,SACjB,KAAK,YAAY;GACf,QAAQ,IAAI;GACZ,OAAO,eAAe,CAAC;EACzB,CAAa;CAEjB;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"view-syncer.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/view-syncer/view-syncer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;A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