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

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 (384) 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/rebase.d.ts +14 -2
  6. package/out/replicache/src/db/rebase.d.ts.map +1 -1
  7. package/out/replicache/src/db/rebase.js +27 -5
  8. package/out/replicache/src/db/rebase.js.map +1 -1
  9. package/out/replicache/src/db/write.js.map +1 -1
  10. package/out/replicache/src/kv/expo-sqlite/store.d.ts.map +1 -1
  11. package/out/replicache/src/kv/expo-sqlite/store.js +27 -4
  12. package/out/replicache/src/kv/expo-sqlite/store.js.map +1 -1
  13. package/out/replicache/src/kv/sqlite-store.d.ts +11 -0
  14. package/out/replicache/src/kv/sqlite-store.d.ts.map +1 -1
  15. package/out/replicache/src/kv/sqlite-store.js +43 -3
  16. package/out/replicache/src/kv/sqlite-store.js.map +1 -1
  17. package/out/replicache/src/persist/persist.d.ts.map +1 -1
  18. package/out/replicache/src/persist/persist.js +12 -5
  19. package/out/replicache/src/persist/persist.js.map +1 -1
  20. package/out/replicache/src/persist/refresh.js +6 -2
  21. package/out/replicache/src/persist/refresh.js.map +1 -1
  22. package/out/replicache/src/replicache-impl.d.ts.map +1 -1
  23. package/out/replicache/src/replicache-impl.js +14 -2
  24. package/out/replicache/src/replicache-impl.js.map +1 -1
  25. package/out/replicache/src/replicache-options.d.ts +9 -0
  26. package/out/replicache/src/replicache-options.d.ts.map +1 -1
  27. package/out/replicache/src/transactions.d.ts.map +1 -1
  28. package/out/replicache/src/transactions.js +1 -1
  29. package/out/replicache/src/transactions.js.map +1 -1
  30. package/out/shared/src/error.d.ts +11 -0
  31. package/out/shared/src/error.d.ts.map +1 -1
  32. package/out/shared/src/error.js +35 -1
  33. package/out/shared/src/error.js.map +1 -1
  34. package/out/shared/src/hash.d.ts.map +1 -1
  35. package/out/shared/src/hash.js +105 -10
  36. package/out/shared/src/hash.js.map +1 -1
  37. package/out/shared/src/map.d.ts +7 -2
  38. package/out/shared/src/map.d.ts.map +1 -1
  39. package/out/shared/src/map.js.map +1 -1
  40. package/out/shared/src/promise-race.d.ts +14 -0
  41. package/out/shared/src/promise-race.d.ts.map +1 -1
  42. package/out/shared/src/promise-race.js +32 -1
  43. package/out/shared/src/promise-race.js.map +1 -1
  44. package/out/zero/package.js +2 -3
  45. package/out/zero/package.js.map +1 -1
  46. package/out/zero-cache/src/auth/write-authorizer.d.ts.map +1 -1
  47. package/out/zero-cache/src/auth/write-authorizer.js +8 -1
  48. package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
  49. package/out/zero-cache/src/config/normalize.d.ts +5 -0
  50. package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
  51. package/out/zero-cache/src/config/normalize.js +16 -3
  52. package/out/zero-cache/src/config/normalize.js.map +1 -1
  53. package/out/zero-cache/src/config/zero-config.d.ts +36 -7
  54. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  55. package/out/zero-cache/src/config/zero-config.js +121 -46
  56. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  57. package/out/zero-cache/src/db/create.d.ts.map +1 -1
  58. package/out/zero-cache/src/db/create.js +4 -1
  59. package/out/zero-cache/src/db/create.js.map +1 -1
  60. package/out/zero-cache/src/db/index-predicate.d.ts +4 -0
  61. package/out/zero-cache/src/db/index-predicate.d.ts.map +1 -0
  62. package/out/zero-cache/src/db/index-predicate.js +46 -0
  63. package/out/zero-cache/src/db/index-predicate.js.map +1 -0
  64. package/out/zero-cache/src/db/lite-tables.d.ts +10 -2
  65. package/out/zero-cache/src/db/lite-tables.d.ts.map +1 -1
  66. package/out/zero-cache/src/db/lite-tables.js +8 -3
  67. package/out/zero-cache/src/db/lite-tables.js.map +1 -1
  68. package/out/zero-cache/src/db/migration-lite.d.ts.map +1 -1
  69. package/out/zero-cache/src/db/migration-lite.js +5 -3
  70. package/out/zero-cache/src/db/migration-lite.js.map +1 -1
  71. package/out/zero-cache/src/db/specs.d.ts +41 -0
  72. package/out/zero-cache/src/db/specs.d.ts.map +1 -1
  73. package/out/zero-cache/src/db/specs.js +30 -3
  74. package/out/zero-cache/src/db/specs.js.map +1 -1
  75. package/out/zero-cache/src/db/transaction-pool.d.ts +5 -15
  76. package/out/zero-cache/src/db/transaction-pool.d.ts.map +1 -1
  77. package/out/zero-cache/src/db/transaction-pool.js +39 -73
  78. package/out/zero-cache/src/db/transaction-pool.js.map +1 -1
  79. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  80. package/out/zero-cache/src/server/change-streamer.js +27 -15
  81. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  82. package/out/zero-cache/src/server/main.d.ts.map +1 -1
  83. package/out/zero-cache/src/server/main.js +4 -4
  84. package/out/zero-cache/src/server/main.js.map +1 -1
  85. package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
  86. package/out/zero-cache/src/server/replicator.js +8 -4
  87. package/out/zero-cache/src/server/replicator.js.map +1 -1
  88. package/out/zero-cache/src/server/runner/run-worker.js +1 -1
  89. package/out/zero-cache/src/server/worker-urls.d.ts +0 -1
  90. package/out/zero-cache/src/server/worker-urls.d.ts.map +1 -1
  91. package/out/zero-cache/src/server/worker-urls.js +1 -2
  92. package/out/zero-cache/src/server/worker-urls.js.map +1 -1
  93. package/out/zero-cache/src/services/analyze.d.ts.map +1 -1
  94. package/out/zero-cache/src/services/analyze.js +1 -0
  95. package/out/zero-cache/src/services/analyze.js.map +1 -1
  96. package/out/zero-cache/src/services/change-source/common/backfill-manager.d.ts +12 -2
  97. package/out/zero-cache/src/services/change-source/common/backfill-manager.d.ts.map +1 -1
  98. package/out/zero-cache/src/services/change-source/common/backfill-manager.js +14 -3
  99. package/out/zero-cache/src/services/change-source/common/backfill-manager.js.map +1 -1
  100. package/out/zero-cache/src/services/change-source/common/replica-schema.d.ts.map +1 -1
  101. package/out/zero-cache/src/services/change-source/common/replica-schema.js +10 -41
  102. package/out/zero-cache/src/services/change-source/common/replica-schema.js.map +1 -1
  103. package/out/zero-cache/src/services/change-source/pg/backfill-stream.d.ts +3 -2
  104. package/out/zero-cache/src/services/change-source/pg/backfill-stream.d.ts.map +1 -1
  105. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +42 -16
  106. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
  107. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts +34 -2
  108. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
  109. package/out/zero-cache/src/services/change-source/pg/change-source.js +47 -19
  110. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  111. package/out/zero-cache/src/services/change-source/pg/decommission.d.ts.map +1 -1
  112. package/out/zero-cache/src/services/change-source/pg/decommission.js +20 -11
  113. package/out/zero-cache/src/services/change-source/pg/decommission.js.map +1 -1
  114. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +1 -0
  115. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
  116. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +58 -80
  117. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  118. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts +20 -0
  119. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts.map +1 -1
  120. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js +43 -3
  121. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js.map +1 -1
  122. package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts +24 -1
  123. package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts.map +1 -1
  124. package/out/zero-cache/src/services/change-source/pg/replication-slots.js +35 -5
  125. package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
  126. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +1513 -229
  127. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
  128. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +2 -2
  129. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
  130. package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.d.ts +19 -0
  131. package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.d.ts.map +1 -0
  132. package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.js +581 -0
  133. package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.js.map +1 -0
  134. package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts +1 -1
  135. package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts.map +1 -1
  136. package/out/zero-cache/src/services/change-source/pg/schema/init.js +15 -6
  137. package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
  138. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts +137 -20
  139. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts.map +1 -1
  140. package/out/zero-cache/src/services/change-source/pg/schema/published.js +82 -13
  141. package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
  142. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +128 -21
  143. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
  144. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +5 -5
  145. package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
  146. package/out/zero-cache/src/services/change-source/protocol/current/data.d.ts +2 -0
  147. package/out/zero-cache/src/services/change-source/protocol/current/data.d.ts.map +1 -1
  148. package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts +3 -0
  149. package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts.map +1 -1
  150. package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.d.ts +1 -4
  151. package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.d.ts.map +1 -1
  152. package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js +11 -18
  153. package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js.map +1 -1
  154. package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts.map +1 -1
  155. package/out/zero-cache/src/services/change-streamer/backup-monitor.js +8 -3
  156. package/out/zero-cache/src/services/change-streamer/backup-monitor.js.map +1 -1
  157. package/out/zero-cache/src/services/change-streamer/broadcast.d.ts.map +1 -1
  158. package/out/zero-cache/src/services/change-streamer/broadcast.js +4 -1
  159. package/out/zero-cache/src/services/change-streamer/broadcast.js.map +1 -1
  160. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.d.ts +34 -0
  161. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.d.ts.map +1 -0
  162. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js +67 -0
  163. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js.map +1 -0
  164. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +2 -4
  165. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  166. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +8 -2
  167. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  168. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +34 -13
  169. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
  170. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +165 -36
  171. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  172. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +4 -9
  173. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
  174. package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
  175. package/out/zero-cache/src/services/change-streamer/forwarder.d.ts.map +1 -1
  176. package/out/zero-cache/src/services/change-streamer/forwarder.js +12 -3
  177. package/out/zero-cache/src/services/change-streamer/forwarder.js.map +1 -1
  178. package/out/zero-cache/src/services/change-streamer/litestream3-prometheus-poller.d.ts.map +1 -1
  179. package/out/zero-cache/src/services/change-streamer/litestream3-prometheus-poller.js +11 -5
  180. package/out/zero-cache/src/services/change-streamer/litestream3-prometheus-poller.js.map +1 -1
  181. package/out/zero-cache/src/services/change-streamer/shard-sampling.d.ts +11 -0
  182. package/out/zero-cache/src/services/change-streamer/shard-sampling.d.ts.map +1 -0
  183. package/out/zero-cache/src/services/change-streamer/shard-sampling.js +19 -0
  184. package/out/zero-cache/src/services/change-streamer/shard-sampling.js.map +1 -0
  185. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.d.ts +11 -1
  186. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.d.ts.map +1 -1
  187. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +38 -5
  188. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -1
  189. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.d.ts +25 -1
  190. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.d.ts.map +1 -1
  191. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js +95 -12
  192. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js.map +1 -1
  193. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.d.ts +83 -0
  194. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.d.ts.map +1 -0
  195. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js +417 -0
  196. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js.map +1 -0
  197. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.d.ts +73 -0
  198. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.d.ts.map +1 -0
  199. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js +157 -0
  200. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js.map +1 -0
  201. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.d.ts +1 -1
  202. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.d.ts.map +1 -1
  203. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js +8 -3
  204. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js.map +1 -1
  205. package/out/zero-cache/src/services/change-streamer/storer.d.ts +63 -1
  206. package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
  207. package/out/zero-cache/src/services/change-streamer/storer.js +217 -49
  208. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  209. package/out/zero-cache/src/services/change-streamer/subscriber.d.ts +8 -1
  210. package/out/zero-cache/src/services/change-streamer/subscriber.d.ts.map +1 -1
  211. package/out/zero-cache/src/services/change-streamer/subscriber.js +10 -1
  212. package/out/zero-cache/src/services/change-streamer/subscriber.js.map +1 -1
  213. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.d.ts +29 -0
  214. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.d.ts.map +1 -0
  215. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.js +154 -0
  216. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.js.map +1 -0
  217. package/out/zero-cache/src/services/http-service.d.ts +1 -0
  218. package/out/zero-cache/src/services/http-service.d.ts.map +1 -1
  219. package/out/zero-cache/src/services/http-service.js +7 -3
  220. package/out/zero-cache/src/services/http-service.js.map +1 -1
  221. package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
  222. package/out/zero-cache/src/services/litestream/commands.js +16 -7
  223. package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
  224. package/out/zero-cache/src/services/litestream/config-v5.yml +15 -1
  225. package/out/zero-cache/src/services/litestream/litestream-checkpointer.js +131 -0
  226. package/out/zero-cache/src/services/litestream/litestream-checkpointer.js.map +1 -0
  227. package/out/zero-cache/src/services/litestream/litestream-controller.d.ts +70 -0
  228. package/out/zero-cache/src/services/litestream/litestream-controller.d.ts.map +1 -0
  229. package/out/zero-cache/src/services/litestream/litestream-controller.js +101 -0
  230. package/out/zero-cache/src/services/litestream/litestream-controller.js.map +1 -0
  231. package/out/zero-cache/src/services/litestream/metrics.d.ts +1 -0
  232. package/out/zero-cache/src/services/litestream/metrics.d.ts.map +1 -1
  233. package/out/zero-cache/src/services/litestream/metrics.js +4 -1
  234. package/out/zero-cache/src/services/litestream/metrics.js.map +1 -1
  235. package/out/zero-cache/src/services/mutagen/mutagen.d.ts.map +1 -1
  236. package/out/zero-cache/src/services/mutagen/mutagen.js +1 -1
  237. package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
  238. package/out/zero-cache/src/services/replicator/change-log-db.d.ts +10 -0
  239. package/out/zero-cache/src/services/replicator/change-log-db.d.ts.map +1 -1
  240. package/out/zero-cache/src/services/replicator/change-log-db.js +15 -1
  241. package/out/zero-cache/src/services/replicator/change-log-db.js.map +1 -1
  242. package/out/zero-cache/src/services/replicator/change-processor.d.ts.map +1 -1
  243. package/out/zero-cache/src/services/replicator/change-processor.js +18 -21
  244. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  245. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts +1 -1
  246. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
  247. package/out/zero-cache/src/services/replicator/incremental-sync.js +2 -6
  248. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  249. package/out/zero-cache/src/services/replicator/replicator.d.ts +1 -1
  250. package/out/zero-cache/src/services/replicator/replicator.d.ts.map +1 -1
  251. package/out/zero-cache/src/services/replicator/replicator.js +2 -2
  252. package/out/zero-cache/src/services/replicator/replicator.js.map +1 -1
  253. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.d.ts +3 -2
  254. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.d.ts.map +1 -1
  255. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js +8 -6
  256. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js.map +1 -1
  257. package/out/zero-cache/src/services/replicator/write-worker-client.d.ts +27 -2
  258. package/out/zero-cache/src/services/replicator/write-worker-client.d.ts.map +1 -1
  259. package/out/zero-cache/src/services/replicator/write-worker-client.js +3 -2
  260. package/out/zero-cache/src/services/replicator/write-worker-client.js.map +1 -1
  261. package/out/zero-cache/src/services/replicator/write-worker.js +24 -5
  262. package/out/zero-cache/src/services/replicator/write-worker.js.map +1 -1
  263. package/out/zero-cache/src/services/view-syncer/client-handler.d.ts +3 -2
  264. package/out/zero-cache/src/services/view-syncer/client-handler.d.ts.map +1 -1
  265. package/out/zero-cache/src/services/view-syncer/client-handler.js +25 -17
  266. package/out/zero-cache/src/services/view-syncer/client-handler.js.map +1 -1
  267. package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts.map +1 -1
  268. package/out/zero-cache/src/services/view-syncer/cvr-store.js +14 -1
  269. package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
  270. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts +3 -3
  271. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  272. package/out/zero-cache/src/services/view-syncer/view-syncer.js +6 -2
  273. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  274. package/out/zero-cache/src/types/downstream.d.ts +11 -0
  275. package/out/zero-cache/src/types/downstream.d.ts.map +1 -0
  276. package/out/zero-cache/src/types/pg.d.ts +15 -2
  277. package/out/zero-cache/src/types/pg.d.ts.map +1 -1
  278. package/out/zero-cache/src/types/pg.js +21 -8
  279. package/out/zero-cache/src/types/pg.js.map +1 -1
  280. package/out/zero-cache/src/types/poke-chunk.d.ts +18 -0
  281. package/out/zero-cache/src/types/poke-chunk.d.ts.map +1 -0
  282. package/out/zero-cache/src/types/poke-chunk.js +57 -0
  283. package/out/zero-cache/src/types/poke-chunk.js.map +1 -0
  284. package/out/zero-cache/src/types/processes.js +1 -4
  285. package/out/zero-cache/src/types/processes.js.map +1 -1
  286. package/out/zero-cache/src/types/streams.d.ts +4 -9
  287. package/out/zero-cache/src/types/streams.d.ts.map +1 -1
  288. package/out/zero-cache/src/types/streams.js.map +1 -1
  289. package/out/zero-cache/src/types/subscription.d.ts +2 -11
  290. package/out/zero-cache/src/types/subscription.d.ts.map +1 -1
  291. package/out/zero-cache/src/types/subscription.js +4 -25
  292. package/out/zero-cache/src/types/subscription.js.map +1 -1
  293. package/out/zero-cache/src/workers/connection.d.ts +22 -4
  294. package/out/zero-cache/src/workers/connection.d.ts.map +1 -1
  295. package/out/zero-cache/src/workers/connection.js +112 -14
  296. package/out/zero-cache/src/workers/connection.js.map +1 -1
  297. package/out/zero-cache/src/workers/replicator.d.ts +1 -0
  298. package/out/zero-cache/src/workers/replicator.d.ts.map +1 -1
  299. package/out/zero-cache/src/workers/replicator.js +4 -2
  300. package/out/zero-cache/src/workers/replicator.js.map +1 -1
  301. package/out/zero-client/src/client/connection-manager.d.ts.map +1 -1
  302. package/out/zero-client/src/client/connection-manager.js +46 -0
  303. package/out/zero-client/src/client/connection-manager.js.map +1 -1
  304. package/out/zero-client/src/client/context.d.ts +15 -0
  305. package/out/zero-client/src/client/context.d.ts.map +1 -1
  306. package/out/zero-client/src/client/context.js +44 -0
  307. package/out/zero-client/src/client/context.js.map +1 -1
  308. package/out/zero-client/src/client/inspector/lazy-inspector.d.ts.map +1 -1
  309. package/out/zero-client/src/client/inspector/lazy-inspector.js +19 -12
  310. package/out/zero-client/src/client/inspector/lazy-inspector.js.map +1 -1
  311. package/out/zero-client/src/client/ivm-branch.js.map +1 -1
  312. package/out/zero-client/src/client/version.js +1 -1
  313. package/out/zero-client/src/client/zero-poke-handler.d.ts +7 -2
  314. package/out/zero-client/src/client/zero-poke-handler.d.ts.map +1 -1
  315. package/out/zero-client/src/client/zero-poke-handler.js +52 -2
  316. package/out/zero-client/src/client/zero-poke-handler.js.map +1 -1
  317. package/out/zero-client/src/client/zero-rep.d.ts +1 -0
  318. package/out/zero-client/src/client/zero-rep.d.ts.map +1 -1
  319. package/out/zero-client/src/client/zero-rep.js +9 -6
  320. package/out/zero-client/src/client/zero-rep.js.map +1 -1
  321. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  322. package/out/zero-client/src/client/zero.js +98 -25
  323. package/out/zero-client/src/client/zero.js.map +1 -1
  324. package/out/zero-protocol/src/custom-queries.d.ts +1 -1
  325. package/out/zero-protocol/src/down.d.ts +1 -1
  326. package/out/zero-protocol/src/error.d.ts +4 -4
  327. package/out/zero-protocol/src/inspect-down.js +1 -1
  328. package/out/zero-protocol/src/mutate-server.d.ts +2 -2
  329. package/out/zero-protocol/src/poke.d.ts +89 -7
  330. package/out/zero-protocol/src/poke.d.ts.map +1 -1
  331. package/out/zero-protocol/src/poke.js +16 -8
  332. package/out/zero-protocol/src/poke.js.map +1 -1
  333. package/out/zero-protocol/src/protocol-version.d.ts +12 -7
  334. package/out/zero-protocol/src/protocol-version.d.ts.map +1 -1
  335. package/out/zero-protocol/src/protocol-version.js.map +1 -1
  336. package/out/zero-protocol/src/push.d.ts +1 -1
  337. package/out/zero-protocol/src/query-server.d.ts +2 -2
  338. package/out/zql/src/ivm/array-view.d.ts.map +1 -1
  339. package/out/zql/src/ivm/array-view.js +5 -3
  340. package/out/zql/src/ivm/array-view.js.map +1 -1
  341. package/out/zql/src/ivm/data.d.ts.map +1 -1
  342. package/out/zql/src/ivm/data.js +8 -3
  343. package/out/zql/src/ivm/data.js.map +1 -1
  344. package/out/zql/src/ivm/deferred-input.d.ts +44 -0
  345. package/out/zql/src/ivm/deferred-input.d.ts.map +1 -0
  346. package/out/zql/src/ivm/deferred-input.js +88 -0
  347. package/out/zql/src/ivm/deferred-input.js.map +1 -0
  348. package/out/zql/src/ivm/memory-source.d.ts +10 -2
  349. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  350. package/out/zql/src/ivm/memory-source.js +19 -16
  351. package/out/zql/src/ivm/memory-source.js.map +1 -1
  352. package/out/zql/src/ivm/stream.d.ts +0 -1
  353. package/out/zql/src/ivm/stream.d.ts.map +1 -1
  354. package/out/zql/src/ivm/stream.js +1 -7
  355. package/out/zql/src/ivm/stream.js.map +1 -1
  356. package/out/zql/src/ivm/union-fan-in.d.ts +1 -1
  357. package/out/zql/src/ivm/union-fan-in.d.ts.map +1 -1
  358. package/out/zql/src/ivm/union-fan-in.js +11 -2
  359. package/out/zql/src/ivm/union-fan-in.js.map +1 -1
  360. package/out/zql/src/ivm/view-apply-change.js +6 -1
  361. package/out/zql/src/ivm/view-apply-change.js.map +1 -1
  362. package/out/zql/src/query/query-delegate-base.d.ts +6 -0
  363. package/out/zql/src/query/query-delegate-base.d.ts.map +1 -1
  364. package/out/zql/src/query/query-delegate-base.js +73 -10
  365. package/out/zql/src/query/query-delegate-base.js.map +1 -1
  366. package/out/zql/src/query/query-delegate.d.ts +22 -0
  367. package/out/zql/src/query/query-delegate.d.ts.map +1 -1
  368. package/out/zqlite/src/query-builder.d.ts.map +1 -1
  369. package/out/zqlite/src/query-builder.js +2 -1
  370. package/out/zqlite/src/query-builder.js.map +1 -1
  371. package/out/zqlite/src/sqlite-stat-fanout.d.ts.map +1 -1
  372. package/out/zqlite/src/sqlite-stat-fanout.js +1 -0
  373. package/out/zqlite/src/sqlite-stat-fanout.js.map +1 -1
  374. package/out/zqlite/src/table-source.d.ts +1 -1
  375. package/out/zqlite/src/table-source.d.ts.map +1 -1
  376. package/out/zqlite/src/table-source.js +3 -2
  377. package/out/zqlite/src/table-source.js.map +1 -1
  378. package/package.json +2 -3
  379. package/out/zero-cache/src/server/backup-watermark-poller.js +0 -31
  380. package/out/zero-cache/src/server/backup-watermark-poller.js.map +0 -1
  381. package/out/zero-cache/src/services/litestream/vfs-watermark-poller.d.ts +0 -57
  382. package/out/zero-cache/src/services/litestream/vfs-watermark-poller.d.ts.map +0 -1
  383. package/out/zero-cache/src/services/litestream/vfs-watermark-poller.js +0 -137
  384. package/out/zero-cache/src/services/litestream/vfs-watermark-poller.js.map +0 -1
@@ -1,7 +1,6 @@
1
1
  import { AbortError } from "../../../../shared/src/abort-error.js";
2
2
  import { getOrCreateCounter } from "../../observability/metrics.js";
3
3
  import { RunningState } from "../running-state.js";
4
- import { deleteLiteDB } from "../../db/delete-lite-db.js";
5
4
  import { errorTypeToReadableName } from "../change-streamer/change-streamer.js";
6
5
  import { Notifier } from "./notifier.js";
7
6
  import { ReplicationReportRecorder } from "./reporter/recorder.js";
@@ -20,20 +19,18 @@ var IncrementalSyncer = class {
20
19
  #changeStreamer;
21
20
  #worker;
22
21
  #mode;
23
- #replicaDbPath;
24
22
  #statusPublisher;
25
23
  #notifier;
26
24
  #reporter;
27
25
  #state = new RunningState("IncrementalSyncer");
28
26
  #replicationEvents = getOrCreateCounter("replication", "events", "Number of replication events processed");
29
- constructor(lc, taskID, id, changeStreamer, worker, mode, replicaDbPath, statusPublisher) {
27
+ constructor(lc, taskID, id, changeStreamer, worker, mode, statusPublisher) {
30
28
  this.#lc = lc;
31
29
  this.#taskID = taskID;
32
30
  this.#id = id;
33
31
  this.#changeStreamer = changeStreamer;
34
32
  this.#worker = worker;
35
33
  this.#mode = mode;
36
- this.#replicaDbPath = replicaDbPath;
37
34
  this.#statusPublisher = statusPublisher;
38
35
  this.#notifier = new Notifier();
39
36
  this.#reporter = new ReplicationReportRecorder(lc);
@@ -88,8 +85,6 @@ var IncrementalSyncer = class {
88
85
  }
89
86
  case "error": {
90
87
  const { type, message: msg } = message[1];
91
- lc.warn?.(`received error from change-streamer. deleting replica file`, { error: message[1] });
92
- deleteLiteDB(this.#replicaDbPath);
93
88
  this.stop(lc, new AbortError(`${errorTypeToReadableName(type)}: ${msg}`));
94
89
  break;
95
90
  }
@@ -147,6 +142,7 @@ var IncrementalSyncer = class {
147
142
  }
148
143
  stop(lc, err) {
149
144
  this.#state.stop(lc, err);
145
+ this.#worker.abort();
150
146
  }
151
147
  };
152
148
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"incremental-sync.js","names":["#lc","#taskID","#id","#changeStreamer","#worker","#mode","#replicaDbPath","#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 {deleteLiteDB} from '../../db/delete-lite-db.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 #replicaDbPath: string;\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 replicaDbPath: string,\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.#replicaDbPath = replicaDbPath;\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 // Explicit errors from the change-streamer (e.g. watermark too\n // old) often indicate a problem with the replica. As a\n // conservative measure, delete the replica before shutting down\n // so that the process restarts from scratch even if reusing the\n // same volume.\n lc.warn?.(\n `received error from change-streamer. deleting replica file`,\n {error: message[1]},\n );\n deleteLiteDB(this.#replicaDbPath);\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 }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiCA,IAAa,oBAAb,MAA+B;CAC7B;CACA;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,eACA,iBACA;EACA,KAAKA,MAAM;EACX,KAAKC,UAAU;EACf,KAAKC,MAAM;EACX,KAAKC,kBAAkB;EACvB,KAAKC,UAAU;EACf,KAAKC,QAAQ;EACb,KAAKC,iBAAiB;EACtB,KAAKC,mBAAmB;EACxB,KAAKC,YAAY,IAAI,SAAS;EAC9B,KAAKC,YAAY,IAAI,0BAA0B,EAAE;CACnD;CAEA,MAAM,MAAM;EACV,MAAM,KAAK,KAAKT;EAChB,IAAI;EACJ,KAAKI,QAAQ,SAAQ,QAAO;GAC1B,gBAAgB;GAChB,KAAKM,OAAO,KAAK,IAAI,GAAG;EAC1B,CAAC;EACD,GAAG,OAAO,4BAA4B;EACtC,MAAM,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AAe;EAClC,KAAKE,OAAO,KAAK,IAAI,GAAG;CAC1B;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 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,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,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AKF,QAAQ,eAAe,IAAI;OAErD,KAAKO,cAAc,IAAI,MAAM;OAC7B,IAAI,QAAQ,mBACV,iBAAiB,KAAA;OAEnB;MACF;KACF;IACF;IACA,KAAKP,QAAQ,MAAM;GACrB,SAAS,GAAG;IACV,MAAM;IACN,KAAKA,QAAQ,MAAM;GACrB,UAAU;IACR,YAAY,OAAO;IACnB,WAAW;IACX,KAAKE,kBAAkB,KAAK;GAC9B;GACA,MAAM,KAAKG,OAAO,QAAQ,IAAI,GAAG;EACnC;EACA,GAAG,OAAO,2BAA2B;EACrC,IAAI,aACF,MAAM;CAEV;CAEA,cAAc,IAAgB,QAA6B;EACzD,IAAI,CAAC,QACH;EAEF,IAAI,OAAO,mBAAmB;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"}
@@ -71,7 +71,7 @@ export type ReplicatorMode = 'backup' | 'serving';
71
71
  export declare class ReplicatorService implements Replicator, Service {
72
72
  #private;
73
73
  readonly id: string;
74
- constructor(lc: LogContext, taskID: string, id: string, mode: ReplicatorMode, replicaDbPath: string, changeStreamer: ChangeStreamer, worker: WriteWorkerClient, statusPublisher: ReplicationStatusPublisher | null);
74
+ constructor(lc: LogContext, taskID: string, id: string, mode: ReplicatorMode, changeStreamer: ChangeStreamer, worker: WriteWorkerClient, statusPublisher: ReplicationStatusPublisher | null);
75
75
  status(): Promise<{
76
76
  status: string;
77
77
  }>;
@@ -1 +1 @@
1
- {"version":3,"file":"replicator.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/replicator/replicator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAC,kBAAkB,EAAC,MAAM,gCAAgC,CAAC;AACvE,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,wBAAwB,CAAC;AACnD,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,uCAAuC,CAAC;AAC1E,OAAO,KAAK,EAAC,OAAO,EAAC,MAAM,eAAe,CAAC;AAE3C,OAAO,EAEL,KAAK,0BAA0B,EAChC,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,0BAA0B,CAAC;AAEhE,oDAAoD;AACpD,MAAM,MAAM,YAAY,GAAG;IACzB,QAAQ,CAAC,KAAK,EAAE,eAAe,CAAC;IAChC;;;;OAIG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACxC;;OAEG;IACH,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAEjD;;;;;;;;;;;;;OAaG;IACH,QAAQ,CAAC,oBAAoB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAInD,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1C,CAAC;AAEF,MAAM,WAAW,oBAAoB;IACnC;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,SAAS,IAAI,MAAM,CAAC,YAAY,CAAC,CAAC;CACnC;AAED,MAAM,WAAW,UAAW,SAAQ,oBAAoB;IACtD;;;;OAIG;IACH,MAAM,IAAI,OAAO,CAAC,kBAAkB,CAAC,C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CAAC,oBAAoB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAInD,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1C,CAAC;AAEF,MAAM,WAAW,oBAAoB;IACnC;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,SAAS,IAAI,MAAM,CAAC,YAAY,CAAC,CAAC;CACnC;AAED,MAAM,WAAW,UAAW,SAAQ,oBAAoB;IACtD;;;;OAIG;IACH,MAAM,IAAI,OAAO,CAAC,kBAAkB,CAAC,CAAC;CACvC;AAED,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,SAAS,CAAC;AAElD,qBAAa,iBAAkB,YAAW,UAAU,EAAE,OAAO;;IAC3D,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;gBAQlB,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,MAAM,EACd,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,cAAc,EACpB,cAAc,EAAE,cAAc,EAC9B,MAAM,EAAE,iBAAiB,EACzB,eAAe,EAAE,0BAA0B,GAAG,IAAI;IAoBpD,MAAM;;;IAIN,GAAG;IAcH,SAAS,IAAI,MAAM,CAAC,YAAY,CAAC;IAI3B,IAAI;CAQX"}
@@ -8,12 +8,12 @@ var ReplicatorService = class {
8
8
  #shouldPublishErrors;
9
9
  #worker;
10
10
  #runPromise;
11
- constructor(lc, taskID, id, mode, replicaDbPath, changeStreamer, worker, statusPublisher) {
11
+ constructor(lc, taskID, id, mode, changeStreamer, worker, statusPublisher) {
12
12
  this.id = id;
13
13
  this.#lc = lc.withContext("component", "replicator").withContext("serviceID", this.id);
14
14
  this.#worker = worker;
15
15
  this.#shouldPublishErrors = statusPublisher !== null;
16
- this.#incrementalSyncer = new IncrementalSyncer(this.#lc, taskID, `${taskID}/${id}`, changeStreamer, worker, mode, replicaDbPath, statusPublisher);
16
+ this.#incrementalSyncer = new IncrementalSyncer(this.#lc, taskID, `${taskID}/${id}`, changeStreamer, worker, mode, statusPublisher);
17
17
  }
18
18
  status() {
19
19
  return Promise.resolve({ status: "ok" });
@@ -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 replicaDbPath: string,\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 replicaDbPath,\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,eACA,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,eACA,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.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"}
@@ -34,6 +34,7 @@ export declare function recordSQLiteChangeLogReconcile(lc: LogContext, result: R
34
34
  * consequence of this log rather than a fact about it.
35
35
  */
36
36
  export type SQLiteChangeLogStartupInfo = ChangeLogMeta & {
37
+ readonly minWatermark: string;
37
38
  readonly headWatermark: string;
38
39
  };
39
40
  export type SQLiteChangeLogInfo = SQLiteChangeLogStartupInfo & {
@@ -42,8 +43,8 @@ export type SQLiteChangeLogInfo = SQLiteChangeLogStartupInfo & {
42
43
  readonly cookieRows: CookieRowCounts;
43
44
  };
44
45
  /**
45
- * Reads the meta row and the head. The head is an index-optimized `max()`, so
46
- * unlike {@link getSQLiteChangeLogInfo} this does not scan the log.
46
+ * Reads the meta row and covered range. Unlike {@link getSQLiteChangeLogInfo}
47
+ * this does not scan the log; see {@link readChangeLogBounds}.
47
48
  *
48
49
  * Call this after reconciliation, which is the only point at which the head is
49
50
  * known to be the resume watermark.
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-change-log-observability.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/replicator/sqlite-change-log-observability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,8BAA8B,CAAC;AAQ3D,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,iDAAiD,CAAC;AAGtF,OAAO,EAEL,KAAK,WAAW,EAChB,KAAK,eAAe,EACrB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAIL,KAAK,aAAa,EAClB,KAAK,eAAe,EACrB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAC,+BAA+B,EAAC,MAAM,+BAA+B,CAAC;AAEnF;;;;;;;;;;;GAWG;AACH,wBAAgB,8BAA8B,CAC5C,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,eAAe,GACtB,IAAI,CAsCN;AAED;;;;GAIG;AACH,MAAM,MAAM,0BAA0B,GAAG,aAAa,GAAG;IACvD,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;CAChC,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG,0BAA0B,GAAG;IAC7D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,UAAU,EAAE,eAAe,CAAC;CACtC,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,6BAA6B,CAC3C,SAAS,EAAE,QAAQ,GAClB,0BAA0B,CAO5B;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,SAAS,EAAE,QAAQ,GAClB,mBAAmB,CAgBr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C5D,gBAAgB,CACd,IAAI,EAAE,gBAAgB,EACtB,MAAM,EAAE,eAAe,GAAG,IAAI,EAC9B,UAAU,EAAE,MAAM,GACjB,IAAI;IAiEP,aAAa,CACX,IAAI,EAAE,gBAAgB,EACtB,KAAK,EAAE,OAAO,EACd,UAAU,EAAE,MAAM,GACjB,IAAI;IAsBP;;;;OAIG;IACH,cAAc,CAAC,GAAG,EAAE,SAAS,WAAW,EAAE,EAAE,IAAI,EAAE,eAAe,GAAG,IAAI;IAQxE;;;;;OAKG;IACH,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IAI1E,yDAAyD;IACzD,KAAK,IAAI,IAAI;IAQb,4EAA4E;IAC5E,UAAU,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI;IAU3C,KAAK,IAAI,iCAAiC;CA0E3C"}
1
+ {"version":3,"file":"sqlite-change-log-observability.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/replicator/sqlite-change-log-observability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,8BAA8B,CAAC;AAQ3D,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,iDAAiD,CAAC;AAGtF,OAAO,EAEL,KAAK,WAAW,EAChB,KAAK,eAAe,EACrB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAIL,KAAK,aAAa,EAClB,KAAK,eAAe,EACrB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAC,+BAA+B,EAAC,MAAM,+BAA+B,CAAC;AAEnF;;;;;;;;;;;GAWG;AACH,wBAAgB,8BAA8B,CAC5C,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,eAAe,GACtB,IAAI,CAsCN;AAED;;;;GAIG;AAC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U,EAAE,eAAe,CAAC;IACrC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;CAC/B,CAAC;AAIF;;;;;GAKG;AACH,qBAAa,uBAAuB;;gBAuEtB,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,mBAAmB;IAsDrD;;;;OAIG;IACH,eAAe,CAAC,IAAI,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI;IAwD3D,4DAA4D;IAC5D,gBAAgB,CACd,IAAI,EAAE,gBAAgB,EACtB,MAAM,EAAE,eAAe,GAAG,IAAI,EAC9B,UAAU,EAAE,MAAM,GACjB,IAAI;IAiEP,aAAa,CACX,IAAI,EAAE,gBAAgB,EACtB,KAAK,EAAE,OAAO,EACd,UAAU,EAAE,MAAM,GACjB,IAAI;IAsBP;;;;OAIG;IACH,cAAc,CAAC,GAAG,EAAE,SAAS,WAAW,EAAE,EAAE,IAAI,EAAE,eAAe,GAAG,IAAI;IAQxE;;;;;OAKG;IACH,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IAI1E,yDAAyD;IACzD,KAAK,IAAI,IAAI;IAQb,4EAA4E;IAC5E,UAAU,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI;IAU3C,KAAK,IAAI,iCAAiC;CA0E3C"}
@@ -2,7 +2,7 @@ import { unreachable } from "../../../../shared/src/asserts.js";
2
2
  import { getOrCreateCounter, getOrCreateGauge, getOrCreateLatencyHistogram, getOrCreateValueHistogram } from "../../observability/metrics.js";
3
3
  import { readCookieRowCounts } from "./change-log-cookies.js";
4
4
  import { versionFromLexi } from "../../types/lexi-version.js";
5
- import { CHANGE_LOG_STREAM_TABLE, readChangeLogHead, readChangeLogMeta } from "./change-log-db.js";
5
+ import { CHANGE_LOG_STREAM_TABLE, readChangeLogBounds, readChangeLogMeta } from "./change-log-db.js";
6
6
  import { extractChangeSubstring } from "../change-streamer/change-log-codec.js";
7
7
  import { ChangeLogTransactionHasher } from "../change-streamer/change-log-transaction-hash.js";
8
8
  import { stat } from "node:fs/promises";
@@ -45,19 +45,20 @@ function recordSQLiteChangeLogReconcile(lc, result) {
45
45
  lc.debug?.("SQLite change-log reconciliation", { sqliteChangeLogReconcile: result });
46
46
  }
47
47
  /**
48
- * Reads the meta row and the head. The head is an index-optimized `max()`, so
49
- * unlike {@link getSQLiteChangeLogInfo} this does not scan the log.
48
+ * Reads the meta row and covered range. Unlike {@link getSQLiteChangeLogInfo}
49
+ * this does not scan the log; see {@link readChangeLogBounds}.
50
50
  *
51
51
  * Call this after reconciliation, which is the only point at which the head is
52
52
  * known to be the resume watermark.
53
53
  */
54
54
  function getSQLiteChangeLogStartupInfo(changeLog) {
55
55
  const meta = readChangeLogMeta(changeLog);
56
- const head = readChangeLogHead(changeLog);
57
- if (head === null) throw new Error("the SQLite change log must contain its seed transaction");
56
+ const { minWatermark, headWatermark } = readChangeLogBounds(changeLog);
57
+ if (minWatermark === null || headWatermark === null) throw new Error("the SQLite change log must contain its seed transaction");
58
58
  return {
59
59
  ...meta,
60
- headWatermark: head
60
+ minWatermark,
61
+ headWatermark
61
62
  };
62
63
  }
63
64
  /**
@@ -89,6 +90,7 @@ function logSQLiteChangeLogStartup(lc, file, info) {
89
90
  schemaVersion: info.schemaVersion,
90
91
  seedWatermark: info.seedWatermark,
91
92
  seededAtMs: info.seededAtMs,
93
+ minWatermark: info.minWatermark,
92
94
  headWatermark: info.headWatermark
93
95
  } });
94
96
  }
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-change-log-observability.js","names":["#lc","#messageProcessing","#logCommitDuration","#transactionRows","#rollbackCounter","#invariantFailureCounter","#hashComparisonCounter","#hashUnpairedCounter","#cookieMutationCounter","#receivedHead","#sqliteHead","#rows","#estimatedBytes","#cookieRows","#sourceHasher","#invariantFailure","#sourcePos","#sourceCommitHash","#resetSourceHash","#transactionWatermark","#recordRollback","#recordUnpaired","#compareHashes","#cookieMutations","#rollbacks","#invariantFailures","#hashMatches","#hashMismatches","#hashUnpaired"],"sources":["../../../../../../zero-cache/src/services/replicator/sqlite-change-log-observability.ts"],"sourcesContent":["/**\n * Observability for the SQLite change log.\n *\n * Everything here now runs in the **change-streamer** process, which is where\n * the writer lives. The module stays beside the rest of the change-log code\n * under `services/replicator/` for the same reason `change-log-db.ts` and\n * `change-log-stream-writer.ts` do: moving files would obscure the topology\n * diff, and the writer's home is a property of who calls it rather than of\n * where it sits. Metric names are unchanged from 7H — only their emitting\n * process, and therefore their resource attributes, moved.\n */\n\nimport {stat} from 'node:fs/promises';\nimport type {LogContext} from '@rocicorp/logger';\nimport {unreachable} from '../../../../shared/src/asserts.ts';\nimport type {Database} from '../../../../zqlite/src/db.ts';\nimport {\n getOrCreateCounter,\n getOrCreateGauge,\n getOrCreateLatencyHistogram,\n getOrCreateValueHistogram,\n} from '../../observability/metrics.ts';\nimport {versionFromLexi} from '../../types/lexi-version.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport {extractChangeSubstring} from '../change-streamer/change-log-codec.ts';\nimport {ChangeLogTransactionHasher} from '../change-streamer/change-log-transaction-hash.ts';\nimport {\n readCookieRowCounts,\n type CookieOpTag,\n type CookieRowCounts,\n} from './change-log-cookies.ts';\nimport {\n CHANGE_LOG_STREAM_TABLE,\n readChangeLogHead,\n readChangeLogMeta,\n type ChangeLogMeta,\n type ReconcileResult,\n} from './change-log-db.ts';\nimport type {ChangeLogStreamTransactionStats} from './change-log-stream-writer.ts';\n\n/**\n * Reports the reconciliation of the change-log database against the watermark\n * the stream connection resumes from. This runs once per stream connection, so\n * a reconnect storm is visible here as well as a restart.\n *\n * A wipe is not an error — it is how every abnormal change-log state is\n * collapsed into a correct one — but each wipe costs the retention window, so\n * every reconnecting subscriber below the head gets `too-old`. The `gap` reason\n * in particular means the log neither held the resume watermark nor could be\n * truncated to it, so a nonzero rate in steady state is an alert, not a\n * statistic.\n */\nexport function recordSQLiteChangeLogReconcile(\n lc: LogContext,\n result: ReconcileResult,\n): void {\n switch (result.action) {\n case 'truncated':\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.reconcile_truncated_rows',\n 'Phantom change-log rows removed at reconciliation, i.e. rows above ' +\n 'the watermark the change stream resumed from.',\n ).add(result.rows);\n break;\n case 'reseeded':\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.reconcile_wipes',\n 'Change-log wipes at reconciliation, by reason. Each one resets the ' +\n 'retention window, so subscribers below the head get `too-old`.',\n ).add(1, {reason: result.reason});\n break;\n case 'none':\n break;\n default:\n unreachable(result);\n }\n if (result.cookiesStale) {\n // The invariant-17 counter: after any reconcile that moved the head, the\n // log's cookie set has to be replaced with the one that belongs to the\n // resume watermark. A nonzero `truncated` series in steady state means\n // phantom truncation is happening on a shard where it should not.\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.cookie_reseed',\n 'Change-log cookie sets invalidated at reconciliation, by the ' +\n 'reconcile action that invalidated them.',\n ).add(1, {action: result.action});\n }\n lc.debug?.('SQLite change-log reconciliation', {\n sqliteChangeLogReconcile: result,\n });\n}\n\n/**\n * What the log says about itself. Nothing here reads the replica: after the\n * writer moved to the change-streamer, the replica's state version is a\n * consequence of this log rather than a fact about it.\n */\nexport type SQLiteChangeLogStartupInfo = ChangeLogMeta & {\n readonly headWatermark: string;\n};\n\nexport type SQLiteChangeLogInfo = SQLiteChangeLogStartupInfo & {\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly cookieRows: CookieRowCounts;\n};\n\n/**\n * Reads the meta row and the head. The head is an index-optimized `max()`, so\n * unlike {@link getSQLiteChangeLogInfo} this does not scan the log.\n *\n * Call this after reconciliation, which is the only point at which the head is\n * known to be the resume watermark.\n */\nexport function getSQLiteChangeLogStartupInfo(\n changeLog: Database,\n): SQLiteChangeLogStartupInfo {\n const meta = readChangeLogMeta(changeLog);\n const head = readChangeLogHead(changeLog);\n if (head === null) {\n throw new Error('the SQLite change log must contain its seed transaction');\n }\n return {...meta, headWatermark: head};\n}\n\n/**\n * Extends {@link getSQLiteChangeLogStartupInfo} with the retained row and\n * estimated byte totals. Computing these scans the entire change-log table, so\n * only call it when the totals are consumed, i.e. when the writer (and thus the\n * observer) is enabled.\n */\nexport function getSQLiteChangeLogInfo(\n changeLog: Database,\n): SQLiteChangeLogInfo {\n const startup = getSQLiteChangeLogStartupInfo(changeLog);\n const aggregate = changeLog\n .prepare(/*sql*/ `\n SELECT count(*) AS \"rows\",\n coalesce(sum(\"estimatedBytes\"), 0) AS \"estimatedBytes\"\n FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n `)\n .get<{rows: number; estimatedBytes: number}>();\n\n return {\n ...startup,\n rows: aggregate.rows,\n estimatedBytes: aggregate.estimatedBytes,\n cookieRows: readCookieRowCounts(changeLog),\n };\n}\n\nexport function logSQLiteChangeLogStartup(\n lc: LogContext,\n file: string,\n info: SQLiteChangeLogStartupInfo,\n): void {\n lc.info?.('SQLite change-log startup', {\n sqliteChangeLog: {\n file,\n epoch: info.epoch,\n generation: info.generation,\n replicaID: info.replicaID,\n schemaVersion: info.schemaVersion,\n seedWatermark: info.seedWatermark,\n seededAtMs: info.seededAtMs,\n headWatermark: info.headWatermark,\n },\n });\n}\n\n/**\n * The on-disk footprint of a SQLite database: its main file plus its `-wal` and\n * `-wal2` sidecars, whichever exist. `-shm` is excluded — it is a\n * shared-memory index rather than retained bytes.\n *\n * A missing file counts as zero rather than warning. Which sidecars exist\n * depends on the journal mode, and the change-log database is absent entirely\n * until the writer creates it.\n */\nexport async function sqliteFileBytes(\n lc: LogContext,\n file: string,\n): Promise<number> {\n const sizes = await Promise.all(\n [file, `${file}-wal`, `${file}-wal2`].map(async path => {\n try {\n return (await stat(path)).size;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {\n lc.warn?.(`unable to stat ${path} for size metrics`, e);\n }\n return 0;\n }\n }),\n );\n return sizes.reduce((total, size) => total + size, 0);\n}\n\n/** What the writer reports back for a committed transaction. */\nexport type ChangeLogCommit = {\n readonly watermark: string;\n readonly stats: ChangeLogStreamTransactionStats;\n /**\n * Appending the commit row and committing the log's transaction. This is the\n * cost that sits on the forward path, once per upstream transaction.\n */\n readonly logCommitMs: number;\n};\n\nexport type SQLiteChangeLogObservabilityState = {\n readonly receivedHead: string;\n readonly sqliteHead: string;\n readonly headLag: number | undefined;\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly cookieRows: CookieRowCounts;\n readonly cookieMutations: number;\n readonly rollbacks: number;\n readonly invariantFailures: number;\n readonly hashMatches: number;\n readonly hashMismatches: number;\n readonly hashUnpaired: number;\n};\n\nconst TRANSACTION_ROW_BUCKETS = [2, 3, 5, 10, 25, 50, 100, 250, 1000, 5000];\n\n/**\n * Records writer metrics in the change-streamer process. State changes only\n * after the corresponding write succeeds, except receivedHead, which advances\n * when a commit message arrives so that transient lag behind the log is\n * observable.\n */\nexport class SQLiteChangeLogObserver {\n readonly #lc: LogContext;\n readonly #messageProcessing = getOrCreateLatencyHistogram(\n 'replica',\n 'sqlite_change_log.message_processing_duration',\n 'Time to write a replication message to the SQLite change log.',\n );\n // The commit that sits on the forward path. There is no second commit to\n // order against any more: the replica's belongs to a subscriber downstream of\n // this loop, so `sqlite_change_log.replica_commit_duration` and the phantom\n // window it measured are gone. A failed commit is still timed, by\n // `message_processing_duration` keyed `tag=\"commit\"`.\n readonly #logCommitDuration = getOrCreateLatencyHistogram(\n 'replica',\n 'sqlite_change_log.log_commit_duration',\n 'Time to append the commit row to the SQLite change log and commit its ' +\n 'transaction. This is on the forward path: it precedes the forward of ' +\n \"that transaction's commit message.\",\n );\n readonly #transactionRows = getOrCreateValueHistogram(\n 'replica',\n 'sqlite_change_log.transaction_rows',\n {\n description: 'Rows stored per committed SQLite change-log transaction.',\n unit: '{row}',\n bucketBoundaries: TRANSACTION_ROW_BUCKETS,\n },\n );\n readonly #rollbackCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.rollbacks',\n 'SQLite change-log transactions rolled back before commit.',\n );\n readonly #invariantFailureCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.invariant_failures',\n 'Detected SQLite change-log writer invariant failures.',\n );\n readonly #hashComparisonCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.hash_comparisons',\n 'Ephemeral transaction hash comparisons between the received change stream and SQLite change-log writes.',\n );\n readonly #hashUnpairedCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.hash_unpaired',\n 'Committed change-log transactions without both ephemeral hashes available for comparison.',\n );\n // Near zero at steady state: cookie state only moves on schema changes.\n readonly #cookieMutationCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.cookie_mutations',\n 'Change-log cookie mutations folded from schema changes, by operation.',\n );\n\n #receivedHead: string;\n #sqliteHead: string;\n #rows: number;\n #estimatedBytes: number;\n #cookieRows: CookieRowCounts;\n #cookieMutations = 0;\n #transactionWatermark: string | undefined;\n #sourceHasher: ChangeLogTransactionHasher | undefined;\n #sourcePos = 0;\n #sourceCommitHash: string | undefined;\n #rollbacks = 0;\n #invariantFailures = 0;\n #hashMatches = 0;\n #hashMismatches = 0;\n #hashUnpaired = 0;\n\n constructor(lc: LogContext, info: SQLiteChangeLogInfo) {\n this.#lc = lc.withContext('component', 'sqlite-change-log-observer');\n // Reconciliation has just put the head at the resume watermark, which is\n // also the point the stream is about to be received from.\n this.#receivedHead = info.headWatermark;\n this.#sqliteHead = info.headWatermark;\n this.#rows = info.rows;\n this.#estimatedBytes = info.estimatedBytes;\n this.#cookieRows = info.cookieRows;\n\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.rows',\n 'Rows retained in the SQLite change log.',\n ).addCallback(result => result.observe(this.#rows));\n // Nonzero with no backfill in flight is a leaked cookie, i.e. a backfill\n // that will be re-requested forever.\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.cookie_rows',\n 'Cookie rows retained in the SQLite change log, by cookie table.',\n ).addCallback(result => {\n result.observe(this.#cookieRows.tableMetadata, {table: 'tableMetadata'});\n result.observe(this.#cookieRows.backfilling, {table: 'backfilling'});\n });\n getOrCreateGauge('replica', 'sqlite_change_log.retained_bytes', {\n description:\n 'Estimated UTF-8 payload bytes retained in the SQLite change log.',\n unit: 'By',\n }).addCallback(result => result.observe(this.#estimatedBytes));\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.head',\n 'SQLite change-log head converted from its lexicographic watermark.',\n ).addCallback(result => {\n const head = watermarkValue(this.#sqliteHead);\n if (head !== undefined) {\n result.observe(head);\n }\n });\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.head_lag',\n 'Distance from the latest received commit to the SQLite change-log ' +\n 'head. The log commits before the forward, so this is zero except ' +\n 'within a transaction.',\n ).addCallback(result => {\n const lag = watermarkDistance(this.#receivedHead, this.#sqliteHead);\n if (lag !== undefined) {\n result.observe(lag);\n }\n });\n }\n\n /**\n * Called as each message arrives, before it is written. Hashes the *received*\n * stream, which is compared against the hash the writer computes over what it\n * *stored*.\n */\n messageReceived(data: ChangeStreamData, json: string): void {\n const tag = data[1].tag;\n if (data[0] === 'begin') {\n if (this.#sourceHasher !== undefined) {\n this.#invariantFailure(\n 'Received change-log begin while a source hash is already open',\n {receivedWatermark: data[2].commitWatermark},\n );\n }\n const watermark = data[2].commitWatermark;\n this.#sourceHasher = new ChangeLogTransactionHasher();\n this.#sourcePos = 0;\n this.#sourceCommitHash = undefined;\n this.#sourceHasher.add({\n watermark,\n pos: this.#sourcePos,\n tag,\n change: extractChangeSubstring(json, tag),\n precommit: null,\n });\n return;\n }\n\n if (tag === 'rollback') {\n this.#resetSourceHash();\n return;\n }\n\n if (data[0] === 'commit') {\n this.#receivedHead = data[2].watermark;\n }\n\n const watermark = this.#transactionWatermark;\n if (this.#sourceHasher === undefined || watermark === undefined) {\n this.#invariantFailure(\n 'Received change-log message without an observed transaction',\n {tag},\n );\n return;\n }\n\n const commitWatermark =\n data[0] === 'commit' ? data[2].watermark : watermark;\n this.#sourceHasher.add({\n watermark: commitWatermark,\n pos: ++this.#sourcePos,\n tag,\n change: extractChangeSubstring(json, tag),\n precommit: data[0] === 'commit' ? watermark : null,\n });\n if (data[0] === 'commit') {\n this.#sourceCommitHash = this.#sourceHasher.digest();\n this.#sourceHasher = undefined;\n }\n }\n\n /** Called after the message has been written to the log. */\n messageProcessed(\n data: ChangeStreamData,\n commit: ChangeLogCommit | null,\n durationMs: number,\n ): void {\n const tag = data[1].tag;\n this.#messageProcessing.recordMs(durationMs, {tag, outcome: 'success'});\n\n if (data[0] === 'begin') {\n if (this.#transactionWatermark !== undefined) {\n this.#invariantFailure('SQLite change-log transaction already open', {\n openWatermark: this.#transactionWatermark,\n receivedWatermark: data[2].commitWatermark,\n });\n }\n this.#transactionWatermark = data[2].commitWatermark;\n return;\n }\n\n if (tag === 'rollback') {\n this.#recordRollback('upstream');\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n return;\n }\n\n if (data[0] !== 'commit') {\n return;\n }\n\n const watermark = data[2].watermark;\n if (commit !== null) {\n this.#logCommitDuration.recordMs(commit.logCommitMs);\n }\n if (this.#transactionWatermark !== watermark) {\n this.#invariantFailure(\n 'SQLite change-log commit does not match the observed begin',\n {openWatermark: this.#transactionWatermark, commitWatermark: watermark},\n );\n }\n if (commit === null) {\n this.#invariantFailure(\n 'SQLite change-log commit result is missing writer statistics',\n {commitWatermark: watermark},\n );\n this.#recordUnpaired(watermark, 'missing-sqlite-hash');\n } else {\n if (commit.watermark !== watermark) {\n this.#invariantFailure(\n 'SQLite change-log commit result has an unexpected watermark',\n {commitWatermark: watermark, resultWatermark: commit.watermark},\n );\n }\n this.#rows += commit.stats.rows;\n this.#estimatedBytes += commit.stats.estimatedBytes;\n this.#transactionRows.record(commit.stats.rows);\n this.#compareHashes(watermark, this.#sourceCommitHash, commit.stats.hash);\n }\n if (watermark < this.#sqliteHead) {\n this.#invariantFailure('SQLite change-log head regressed', {\n previousHead: this.#sqliteHead,\n commitWatermark: watermark,\n });\n }\n this.#sqliteHead = watermark;\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n messageFailed(\n data: ChangeStreamData,\n error: unknown,\n durationMs: number,\n ): void {\n const tag = data[1].tag;\n this.#messageProcessing.recordMs(durationMs, {tag, outcome: 'error'});\n if (data[0] === 'commit') {\n // No commit duration here: a failed commit produces no statistics, so\n // there is nothing to attribute. The attempt is timed by\n // `message_processing_duration{tag=\"commit\",outcome=\"error\"}` above.\n this.#recordUnpaired(data[2].watermark, 'sqlite-commit-failed');\n }\n if (\n error instanceof Error &&\n error.name === 'ChangeLogStreamInvariantError'\n ) {\n this.#invariantFailure(error.message);\n }\n if (this.#transactionWatermark !== undefined || data[0] === 'begin') {\n this.#recordRollback('processing-error');\n }\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n /**\n * A committed transaction folded schema changes into the cookie jar. Reported\n * separately from {@link messageProcessed} because it costs a read of the\n * cookie tables, which is only worth taking when they actually moved.\n */\n cookiesMutated(ops: readonly CookieOpTag[], rows: CookieRowCounts): void {\n for (const op of ops) {\n this.#cookieMutations++;\n this.#cookieMutationCounter.add(1, {op});\n }\n this.#cookieRows = rows;\n }\n\n /**\n * A missed truncate-above surfaces as a constraint violation on the writer's\n * plain `INSERT`, which the fail-soft policy would otherwise absorb quietly.\n * Classifying it as an invariant failure is what keeps a reconciliation bug\n * from looking like a lost cache.\n */\n invariantFailure(message: string, details?: Record<string, unknown>): void {\n this.#invariantFailure(message, details);\n }\n\n /** The source interrupted the stream mid-transaction. */\n abort(): void {\n if (this.#transactionWatermark !== undefined) {\n this.#recordRollback('source-interruption');\n this.#transactionWatermark = undefined;\n }\n this.#resetSourceHash();\n }\n\n /** Reconciliation moved the head, so the observer's totals are restated. */\n reconciled(info: SQLiteChangeLogInfo): void {\n this.#receivedHead = info.headWatermark;\n this.#sqliteHead = info.headWatermark;\n this.#rows = info.rows;\n this.#estimatedBytes = info.estimatedBytes;\n this.#cookieRows = info.cookieRows;\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n state(): SQLiteChangeLogObservabilityState {\n return {\n receivedHead: this.#receivedHead,\n sqliteHead: this.#sqliteHead,\n headLag: watermarkDistance(this.#receivedHead, this.#sqliteHead),\n rows: this.#rows,\n estimatedBytes: this.#estimatedBytes,\n cookieRows: this.#cookieRows,\n cookieMutations: this.#cookieMutations,\n rollbacks: this.#rollbacks,\n invariantFailures: this.#invariantFailures,\n hashMatches: this.#hashMatches,\n hashMismatches: this.#hashMismatches,\n hashUnpaired: this.#hashUnpaired,\n };\n }\n\n #recordRollback(\n reason: 'upstream' | 'processing-error' | 'source-interruption',\n ) {\n this.#rollbacks++;\n this.#rollbackCounter.add(1, {reason});\n }\n\n #invariantFailure(message: string, details?: Record<string, unknown>) {\n this.#invariantFailures++;\n this.#invariantFailureCounter.add(1);\n this.#lc.error?.(message, details);\n }\n\n #compareHashes(\n watermark: string,\n sourceHash: string | undefined,\n sqliteHash: string,\n ): void {\n if (sourceHash === undefined) {\n this.#recordUnpaired(watermark, 'missing-source-hash');\n return;\n }\n if (sourceHash === sqliteHash) {\n this.#hashMatches++;\n this.#hashComparisonCounter.add(1, {outcome: 'match'});\n return;\n }\n this.#hashMismatches++;\n this.#hashComparisonCounter.add(1, {outcome: 'mismatch'});\n this.#lc.error?.('SQLite change-log transaction hash mismatch', {\n sqliteChangeLogHashComparison: {\n watermark,\n sourceHash: sourceHash.slice(0, 16),\n sqliteHash: sqliteHash.slice(0, 16),\n },\n });\n }\n\n #recordUnpaired(\n watermark: string,\n reason:\n | 'missing-source-hash'\n | 'missing-sqlite-hash'\n | 'sqlite-commit-failed',\n ): void {\n this.#hashUnpaired++;\n this.#hashUnpairedCounter.add(1, {reason});\n this.#lc.warn?.('SQLite change-log transaction hash was not compared', {\n sqliteChangeLogHashComparison: {watermark, reason},\n });\n }\n\n #resetSourceHash(): void {\n this.#sourceHasher = undefined;\n this.#sourcePos = 0;\n this.#sourceCommitHash = undefined;\n }\n}\n\nfunction watermarkValue(watermark: string): number | undefined {\n try {\n const value = Number(versionFromLexi(watermark));\n return Number.isFinite(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction watermarkDistance(\n receivedHead: string,\n sqliteHead: string,\n): number | undefined {\n if (receivedHead <= sqliteHead) {\n return 0;\n }\n try {\n const distance =\n versionFromLexi(receivedHead) - versionFromLexi(sqliteHead);\n const value = Number(distance);\n return Number.isFinite(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAgB,+BACd,IACA,QACM;CACN,QAAQ,OAAO,QAAf;EACE,KAAK;GACH,mBACE,WACA,8CACA,kHAEF,EAAE,IAAI,OAAO,IAAI;GACjB;EACF,KAAK;GACH,mBACE,WACA,qCACA,mIAEF,EAAE,IAAI,GAAG,EAAC,QAAQ,OAAO,OAAM,CAAC;GAChC;EACF,KAAK,QACH;EACF,SACE,YAAY,MAAM;CACtB;CACA,IAAI,OAAO,cAKT,mBACE,WACA,mCACA,sGAEF,EAAE,IAAI,GAAG,EAAC,QAAQ,OAAO,OAAM,CAAC;CAElC,GAAG,QAAQ,oCAAoC,EAC7C,0BAA0B,OAC5B,CAAC;AACH;;;;;;;;AAwBA,SAAgB,8BACd,WAC4B;CAC5B,MAAM,OAAO,kBAAkB,SAAS;CACxC,MAAM,OAAO,kBAAkB,SAAS;CACxC,IAAI,SAAS,MACX,MAAM,IAAI,MAAM,yDAAyD;CAE3E,OAAO;EAAC,GAAG;EAAM,eAAe;CAAI;AACtC;;;;;;;AAQA,SAAgB,uBACd,WACqB;CACrB,M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GAC7B,KAAKK;GACL,KAAKpB,uBAAuB,IAAI,GAAG,EAAC,SAAS,QAAO,CAAC;GACrD;EACF;EACA,KAAKqB;EACL,KAAKrB,uBAAuB,IAAI,GAAG,EAAC,SAAS,WAAU,CAAC;EACxD,KAAKN,IAAI,QAAQ,+CAA+C,EAC9D,+BAA+B;GAC7B;GACA,YAAY,WAAW,MAAM,GAAG,EAAE;GAClC,YAAY,WAAW,MAAM,GAAG,EAAE;EACpC,EACF,CAAC;CACH;CAEA,gBACE,WACA,QAIM;EACN,KAAK4B;EACL,KAAKrB,qBAAqB,IAAI,GAAG,EAAC,OAAM,CAAC;EACzC,KAAKP,IAAI,OAAO,uDAAuD,EACrE,+BAA+B;GAAC;GAAW;EAAM,EACnD,CAAC;CACH;CAEA,mBAAyB;EACvB,KAAKc,gBAAgB,KAAA;EACrB,KAAKE,aAAa;EAClB,KAAKC,oBAAoB,KAAA;CAC3B;AACF;AAEA,SAAS,eAAe,WAAuC;CAC7D,IAAI;EACF,MAAM,QAAQ,OAAO,gBAAgB,SAAS,CAAC;EAC/C,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;CAC1C,QAAQ;EACN;CACF;AACF;AAEA,SAAS,kBACP,cACA,YACoB;CACpB,IAAI,gBAAgB,YAClB,OAAO;CAET,IAAI;EACF,MAAM,WACJ,gBAAgB,YAAY,IAAI,gBAAgB,UAAU;EAC5D,MAAM,QAAQ,OAAO,QAAQ;EAC7B,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;CAC1C,QAAQ;EACN;CACF;AACF"}
1
+ {"version":3,"file":"sqlite-change-log-observability.js","names":["#lc","#messageProcessing","#logCommitDuration","#transactionRows","#rollbackCounter","#invariantFailureCounter","#hashComparisonCounter","#hashUnpairedCounter","#cookieMutationCounter","#receivedHead","#sqliteHead","#rows","#estimatedBytes","#cookieRows","#sourceHasher","#invariantFailure","#sourcePos","#sourceCommitHash","#resetSourceHash","#transactionWatermark","#recordRollback","#recordUnpaired","#compareHashes","#cookieMutations","#rollbacks","#invariantFailures","#hashMatches","#hashMismatches","#hashUnpaired"],"sources":["../../../../../../zero-cache/src/services/replicator/sqlite-change-log-observability.ts"],"sourcesContent":["/**\n * Observability for the SQLite change log.\n *\n * Everything here now runs in the **change-streamer** process, which is where\n * the writer lives. The module stays beside the rest of the change-log code\n * under `services/replicator/` for the same reason `change-log-db.ts` and\n * `change-log-stream-writer.ts` do: moving files would obscure the topology\n * diff, and the writer's home is a property of who calls it rather than of\n * where it sits. Metric names are unchanged from 7H — only their emitting\n * process, and therefore their resource attributes, moved.\n */\n\nimport {stat} from 'node:fs/promises';\nimport type {LogContext} from '@rocicorp/logger';\nimport {unreachable} from '../../../../shared/src/asserts.ts';\nimport type {Database} from '../../../../zqlite/src/db.ts';\nimport {\n getOrCreateCounter,\n getOrCreateGauge,\n getOrCreateLatencyHistogram,\n getOrCreateValueHistogram,\n} from '../../observability/metrics.ts';\nimport {versionFromLexi} from '../../types/lexi-version.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport {extractChangeSubstring} from '../change-streamer/change-log-codec.ts';\nimport {ChangeLogTransactionHasher} from '../change-streamer/change-log-transaction-hash.ts';\nimport {\n readCookieRowCounts,\n type CookieOpTag,\n type CookieRowCounts,\n} from './change-log-cookies.ts';\nimport {\n CHANGE_LOG_STREAM_TABLE,\n readChangeLogBounds,\n readChangeLogMeta,\n type ChangeLogMeta,\n type ReconcileResult,\n} from './change-log-db.ts';\nimport type {ChangeLogStreamTransactionStats} from './change-log-stream-writer.ts';\n\n/**\n * Reports the reconciliation of the change-log database against the watermark\n * the stream connection resumes from. This runs once per stream connection, so\n * a reconnect storm is visible here as well as a restart.\n *\n * A wipe is not an error — it is how every abnormal change-log state is\n * collapsed into a correct one — but each wipe costs the retention window, so\n * every reconnecting subscriber below the head gets `too-old`. The `gap` reason\n * in particular means the log neither held the resume watermark nor could be\n * truncated to it, so a nonzero rate in steady state is an alert, not a\n * statistic.\n */\nexport function recordSQLiteChangeLogReconcile(\n lc: LogContext,\n result: ReconcileResult,\n): void {\n switch (result.action) {\n case 'truncated':\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.reconcile_truncated_rows',\n 'Phantom change-log rows removed at reconciliation, i.e. rows above ' +\n 'the watermark the change stream resumed from.',\n ).add(result.rows);\n break;\n case 'reseeded':\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.reconcile_wipes',\n 'Change-log wipes at reconciliation, by reason. Each one resets the ' +\n 'retention window, so subscribers below the head get `too-old`.',\n ).add(1, {reason: result.reason});\n break;\n case 'none':\n break;\n default:\n unreachable(result);\n }\n if (result.cookiesStale) {\n // The invariant-17 counter: after any reconcile that moved the head, the\n // log's cookie set has to be replaced with the one that belongs to the\n // resume watermark. A nonzero `truncated` series in steady state means\n // phantom truncation is happening on a shard where it should not.\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.cookie_reseed',\n 'Change-log cookie sets invalidated at reconciliation, by the ' +\n 'reconcile action that invalidated them.',\n ).add(1, {action: result.action});\n }\n lc.debug?.('SQLite change-log reconciliation', {\n sqliteChangeLogReconcile: result,\n });\n}\n\n/**\n * What the log says about itself. Nothing here reads the replica: after the\n * writer moved to the change-streamer, the replica's state version is a\n * consequence of this log rather than a fact about it.\n */\nexport type SQLiteChangeLogStartupInfo = ChangeLogMeta & {\n readonly minWatermark: string;\n readonly headWatermark: string;\n};\n\nexport type SQLiteChangeLogInfo = SQLiteChangeLogStartupInfo & {\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly cookieRows: CookieRowCounts;\n};\n\n/**\n * Reads the meta row and covered range. Unlike {@link getSQLiteChangeLogInfo}\n * this does not scan the log; see {@link readChangeLogBounds}.\n *\n * Call this after reconciliation, which is the only point at which the head is\n * known to be the resume watermark.\n */\nexport function getSQLiteChangeLogStartupInfo(\n changeLog: Database,\n): SQLiteChangeLogStartupInfo {\n const meta = readChangeLogMeta(changeLog);\n const {minWatermark, headWatermark} = readChangeLogBounds(changeLog);\n if (minWatermark === null || headWatermark === null) {\n throw new Error('the SQLite change log must contain its seed transaction');\n }\n return {...meta, minWatermark, headWatermark};\n}\n\n/**\n * Extends {@link getSQLiteChangeLogStartupInfo} with the retained row and\n * estimated byte totals. Computing these scans the entire change-log table, so\n * only call it when the totals are consumed, i.e. when the writer (and thus the\n * observer) is enabled.\n */\nexport function getSQLiteChangeLogInfo(\n changeLog: Database,\n): SQLiteChangeLogInfo {\n const startup = getSQLiteChangeLogStartupInfo(changeLog);\n const aggregate = changeLog\n .prepare(/*sql*/ `\n SELECT count(*) AS \"rows\",\n coalesce(sum(\"estimatedBytes\"), 0) AS \"estimatedBytes\"\n FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n `)\n .get<{rows: number; estimatedBytes: number}>();\n\n return {\n ...startup,\n rows: aggregate.rows,\n estimatedBytes: aggregate.estimatedBytes,\n cookieRows: readCookieRowCounts(changeLog),\n };\n}\n\nexport function logSQLiteChangeLogStartup(\n lc: LogContext,\n file: string,\n info: SQLiteChangeLogStartupInfo,\n): void {\n lc.info?.('SQLite change-log startup', {\n sqliteChangeLog: {\n file,\n epoch: info.epoch,\n generation: info.generation,\n replicaID: info.replicaID,\n schemaVersion: info.schemaVersion,\n seedWatermark: info.seedWatermark,\n seededAtMs: info.seededAtMs,\n minWatermark: info.minWatermark,\n headWatermark: info.headWatermark,\n },\n });\n}\n\n/**\n * The on-disk footprint of a SQLite database: its main file plus its `-wal` and\n * `-wal2` sidecars, whichever exist. `-shm` is excluded — it is a\n * shared-memory index rather than retained bytes.\n *\n * A missing file counts as zero rather than warning. Which sidecars exist\n * depends on the journal mode, and the change-log database is absent entirely\n * until the writer creates it.\n */\nexport async function sqliteFileBytes(\n lc: LogContext,\n file: string,\n): Promise<number> {\n const sizes = await Promise.all(\n [file, `${file}-wal`, `${file}-wal2`].map(async path => {\n try {\n return (await stat(path)).size;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {\n lc.warn?.(`unable to stat ${path} for size metrics`, e);\n }\n return 0;\n }\n }),\n );\n return sizes.reduce((total, size) => total + size, 0);\n}\n\n/** What the writer reports back for a committed transaction. */\nexport type ChangeLogCommit = {\n readonly watermark: string;\n readonly stats: ChangeLogStreamTransactionStats;\n /**\n * Appending the commit row and committing the log's transaction. This is the\n * cost that sits on the forward path, once per upstream transaction.\n */\n readonly logCommitMs: number;\n};\n\nexport type SQLiteChangeLogObservabilityState = {\n readonly receivedHead: string;\n readonly sqliteHead: string;\n readonly headLag: number | undefined;\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly cookieRows: CookieRowCounts;\n readonly cookieMutations: number;\n readonly rollbacks: number;\n readonly invariantFailures: number;\n readonly hashMatches: number;\n readonly hashMismatches: number;\n readonly hashUnpaired: number;\n};\n\nconst TRANSACTION_ROW_BUCKETS = [2, 3, 5, 10, 25, 50, 100, 250, 1000, 5000];\n\n/**\n * Records writer metrics in the change-streamer process. State changes only\n * after the corresponding write succeeds, except receivedHead, which advances\n * when a commit message arrives so that transient lag behind the log is\n * observable.\n */\nexport class SQLiteChangeLogObserver {\n readonly #lc: LogContext;\n readonly #messageProcessing = getOrCreateLatencyHistogram(\n 'replica',\n 'sqlite_change_log.message_processing_duration',\n 'Time to write a replication message to the SQLite change log.',\n );\n // The commit that sits on the forward path. There is no second commit to\n // order against any more: the replica's belongs to a subscriber downstream of\n // this loop, so `sqlite_change_log.replica_commit_duration` and the phantom\n // window it measured are gone. A failed commit is still timed, by\n // `message_processing_duration` keyed `tag=\"commit\"`.\n readonly #logCommitDuration = getOrCreateLatencyHistogram(\n 'replica',\n 'sqlite_change_log.log_commit_duration',\n 'Time to append the commit row to the SQLite change log and commit its ' +\n 'transaction. This is on the forward path: it precedes the forward of ' +\n \"that transaction's commit message.\",\n );\n readonly #transactionRows = getOrCreateValueHistogram(\n 'replica',\n 'sqlite_change_log.transaction_rows',\n {\n description: 'Rows stored per committed SQLite change-log transaction.',\n unit: '{row}',\n bucketBoundaries: TRANSACTION_ROW_BUCKETS,\n },\n );\n readonly #rollbackCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.rollbacks',\n 'SQLite change-log transactions rolled back before commit.',\n );\n readonly #invariantFailureCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.invariant_failures',\n 'Detected SQLite change-log writer invariant failures.',\n );\n readonly #hashComparisonCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.hash_comparisons',\n 'Ephemeral transaction hash comparisons between the received change stream and SQLite change-log writes.',\n );\n readonly #hashUnpairedCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.hash_unpaired',\n 'Committed change-log transactions without both ephemeral hashes available for comparison.',\n );\n // Near zero at steady state: cookie state only moves on schema changes.\n readonly #cookieMutationCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.cookie_mutations',\n 'Change-log cookie mutations folded from schema changes, by operation.',\n );\n\n #receivedHead: string;\n #sqliteHead: string;\n #rows: number;\n #estimatedBytes: number;\n #cookieRows: CookieRowCounts;\n #cookieMutations = 0;\n #transactionWatermark: string | undefined;\n #sourceHasher: ChangeLogTransactionHasher | undefined;\n #sourcePos = 0;\n #sourceCommitHash: string | undefined;\n #rollbacks = 0;\n #invariantFailures = 0;\n #hashMatches = 0;\n #hashMismatches = 0;\n #hashUnpaired = 0;\n\n constructor(lc: LogContext, info: SQLiteChangeLogInfo) {\n this.#lc = lc.withContext('component', 'sqlite-change-log-observer');\n // Reconciliation has just put the head at the resume watermark, which is\n // also the point the stream is about to be received from.\n this.#receivedHead = info.headWatermark;\n this.#sqliteHead = info.headWatermark;\n this.#rows = info.rows;\n this.#estimatedBytes = info.estimatedBytes;\n this.#cookieRows = info.cookieRows;\n\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.rows',\n 'Rows retained in the SQLite change log.',\n ).addCallback(result => result.observe(this.#rows));\n // Nonzero with no backfill in flight is a leaked cookie, i.e. a backfill\n // that will be re-requested forever.\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.cookie_rows',\n 'Cookie rows retained in the SQLite change log, by cookie table.',\n ).addCallback(result => {\n result.observe(this.#cookieRows.tableMetadata, {table: 'tableMetadata'});\n result.observe(this.#cookieRows.backfilling, {table: 'backfilling'});\n });\n getOrCreateGauge('replica', 'sqlite_change_log.retained_bytes', {\n description:\n 'Estimated UTF-8 payload bytes retained in the SQLite change log.',\n unit: 'By',\n }).addCallback(result => result.observe(this.#estimatedBytes));\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.head',\n 'SQLite change-log head converted from its lexicographic watermark.',\n ).addCallback(result => {\n const head = watermarkValue(this.#sqliteHead);\n if (head !== undefined) {\n result.observe(head);\n }\n });\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.head_lag',\n 'Distance from the latest received commit to the SQLite change-log ' +\n 'head. The log commits before the forward, so this is zero except ' +\n 'within a transaction.',\n ).addCallback(result => {\n const lag = watermarkDistance(this.#receivedHead, this.#sqliteHead);\n if (lag !== undefined) {\n result.observe(lag);\n }\n });\n }\n\n /**\n * Called as each message arrives, before it is written. Hashes the *received*\n * stream, which is compared against the hash the writer computes over what it\n * *stored*.\n */\n messageReceived(data: ChangeStreamData, json: string): void {\n const tag = data[1].tag;\n if (data[0] === 'begin') {\n if (this.#sourceHasher !== undefined) {\n this.#invariantFailure(\n 'Received change-log begin while a source hash is already open',\n {receivedWatermark: data[2].commitWatermark},\n );\n }\n const watermark = data[2].commitWatermark;\n this.#sourceHasher = new ChangeLogTransactionHasher();\n this.#sourcePos = 0;\n this.#sourceCommitHash = undefined;\n this.#sourceHasher.add({\n watermark,\n pos: this.#sourcePos,\n tag,\n change: extractChangeSubstring(json, tag),\n precommit: null,\n });\n return;\n }\n\n if (tag === 'rollback') {\n this.#resetSourceHash();\n return;\n }\n\n if (data[0] === 'commit') {\n this.#receivedHead = data[2].watermark;\n }\n\n const watermark = this.#transactionWatermark;\n if (this.#sourceHasher === undefined || watermark === undefined) {\n this.#invariantFailure(\n 'Received change-log message without an observed transaction',\n {tag},\n );\n return;\n }\n\n const commitWatermark =\n data[0] === 'commit' ? data[2].watermark : watermark;\n this.#sourceHasher.add({\n watermark: commitWatermark,\n pos: ++this.#sourcePos,\n tag,\n change: extractChangeSubstring(json, tag),\n precommit: data[0] === 'commit' ? watermark : null,\n });\n if (data[0] === 'commit') {\n this.#sourceCommitHash = this.#sourceHasher.digest();\n this.#sourceHasher = undefined;\n }\n }\n\n /** Called after the message has been written to the log. */\n messageProcessed(\n data: ChangeStreamData,\n commit: ChangeLogCommit | null,\n durationMs: number,\n ): void {\n const tag = data[1].tag;\n this.#messageProcessing.recordMs(durationMs, {tag, outcome: 'success'});\n\n if (data[0] === 'begin') {\n if (this.#transactionWatermark !== undefined) {\n this.#invariantFailure('SQLite change-log transaction already open', {\n openWatermark: this.#transactionWatermark,\n receivedWatermark: data[2].commitWatermark,\n });\n }\n this.#transactionWatermark = data[2].commitWatermark;\n return;\n }\n\n if (tag === 'rollback') {\n this.#recordRollback('upstream');\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n return;\n }\n\n if (data[0] !== 'commit') {\n return;\n }\n\n const watermark = data[2].watermark;\n if (commit !== null) {\n this.#logCommitDuration.recordMs(commit.logCommitMs);\n }\n if (this.#transactionWatermark !== watermark) {\n this.#invariantFailure(\n 'SQLite change-log commit does not match the observed begin',\n {openWatermark: this.#transactionWatermark, commitWatermark: watermark},\n );\n }\n if (commit === null) {\n this.#invariantFailure(\n 'SQLite change-log commit result is missing writer statistics',\n {commitWatermark: watermark},\n );\n this.#recordUnpaired(watermark, 'missing-sqlite-hash');\n } else {\n if (commit.watermark !== watermark) {\n this.#invariantFailure(\n 'SQLite change-log commit result has an unexpected watermark',\n {commitWatermark: watermark, resultWatermark: commit.watermark},\n );\n }\n this.#rows += commit.stats.rows;\n this.#estimatedBytes += commit.stats.estimatedBytes;\n this.#transactionRows.record(commit.stats.rows);\n this.#compareHashes(watermark, this.#sourceCommitHash, commit.stats.hash);\n }\n if (watermark < this.#sqliteHead) {\n this.#invariantFailure('SQLite change-log head regressed', {\n previousHead: this.#sqliteHead,\n commitWatermark: watermark,\n });\n }\n this.#sqliteHead = watermark;\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n messageFailed(\n data: ChangeStreamData,\n error: unknown,\n durationMs: number,\n ): void {\n const tag = data[1].tag;\n this.#messageProcessing.recordMs(durationMs, {tag, outcome: 'error'});\n if (data[0] === 'commit') {\n // No commit duration here: a failed commit produces no statistics, so\n // there is nothing to attribute. The attempt is timed by\n // `message_processing_duration{tag=\"commit\",outcome=\"error\"}` above.\n this.#recordUnpaired(data[2].watermark, 'sqlite-commit-failed');\n }\n if (\n error instanceof Error &&\n error.name === 'ChangeLogStreamInvariantError'\n ) {\n this.#invariantFailure(error.message);\n }\n if (this.#transactionWatermark !== undefined || data[0] === 'begin') {\n this.#recordRollback('processing-error');\n }\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n /**\n * A committed transaction folded schema changes into the cookie jar. Reported\n * separately from {@link messageProcessed} because it costs a read of the\n * cookie tables, which is only worth taking when they actually moved.\n */\n cookiesMutated(ops: readonly CookieOpTag[], rows: CookieRowCounts): void {\n for (const op of ops) {\n this.#cookieMutations++;\n this.#cookieMutationCounter.add(1, {op});\n }\n this.#cookieRows = rows;\n }\n\n /**\n * A missed truncate-above surfaces as a constraint violation on the writer's\n * plain `INSERT`, which the fail-soft policy would otherwise absorb quietly.\n * Classifying it as an invariant failure is what keeps a reconciliation bug\n * from looking like a lost cache.\n */\n invariantFailure(message: string, details?: Record<string, unknown>): void {\n this.#invariantFailure(message, details);\n }\n\n /** The source interrupted the stream mid-transaction. */\n abort(): void {\n if (this.#transactionWatermark !== undefined) {\n this.#recordRollback('source-interruption');\n this.#transactionWatermark = undefined;\n }\n this.#resetSourceHash();\n }\n\n /** Reconciliation moved the head, so the observer's totals are restated. */\n reconciled(info: SQLiteChangeLogInfo): void {\n this.#receivedHead = info.headWatermark;\n this.#sqliteHead = info.headWatermark;\n this.#rows = info.rows;\n this.#estimatedBytes = info.estimatedBytes;\n this.#cookieRows = info.cookieRows;\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n state(): SQLiteChangeLogObservabilityState {\n return {\n receivedHead: this.#receivedHead,\n sqliteHead: this.#sqliteHead,\n headLag: watermarkDistance(this.#receivedHead, this.#sqliteHead),\n rows: this.#rows,\n estimatedBytes: this.#estimatedBytes,\n cookieRows: this.#cookieRows,\n cookieMutations: this.#cookieMutations,\n rollbacks: this.#rollbacks,\n invariantFailures: this.#invariantFailures,\n hashMatches: this.#hashMatches,\n hashMismatches: this.#hashMismatches,\n hashUnpaired: this.#hashUnpaired,\n };\n }\n\n #recordRollback(\n reason: 'upstream' | 'processing-error' | 'source-interruption',\n ) {\n this.#rollbacks++;\n this.#rollbackCounter.add(1, {reason});\n }\n\n #invariantFailure(message: string, details?: Record<string, unknown>) {\n this.#invariantFailures++;\n this.#invariantFailureCounter.add(1);\n this.#lc.error?.(message, details);\n }\n\n #compareHashes(\n watermark: string,\n sourceHash: string | undefined,\n sqliteHash: string,\n ): void {\n if (sourceHash === undefined) {\n this.#recordUnpaired(watermark, 'missing-source-hash');\n return;\n }\n if (sourceHash === sqliteHash) {\n this.#hashMatches++;\n this.#hashComparisonCounter.add(1, {outcome: 'match'});\n return;\n }\n this.#hashMismatches++;\n this.#hashComparisonCounter.add(1, {outcome: 'mismatch'});\n this.#lc.error?.('SQLite change-log transaction hash mismatch', {\n sqliteChangeLogHashComparison: {\n watermark,\n sourceHash: sourceHash.slice(0, 16),\n sqliteHash: sqliteHash.slice(0, 16),\n },\n });\n }\n\n #recordUnpaired(\n watermark: string,\n reason:\n | 'missing-source-hash'\n | 'missing-sqlite-hash'\n | 'sqlite-commit-failed',\n ): void {\n this.#hashUnpaired++;\n this.#hashUnpairedCounter.add(1, {reason});\n this.#lc.warn?.('SQLite change-log transaction hash was not compared', {\n sqliteChangeLogHashComparison: {watermark, reason},\n });\n }\n\n #resetSourceHash(): void {\n this.#sourceHasher = undefined;\n this.#sourcePos = 0;\n this.#sourceCommitHash = undefined;\n }\n}\n\nfunction watermarkValue(watermark: string): number | undefined {\n try {\n const value = Number(versionFromLexi(watermark));\n return Number.isFinite(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction watermarkDistance(\n receivedHead: string,\n sqliteHead: string,\n): number | undefined {\n if (receivedHead <= sqliteHead) {\n return 0;\n }\n try {\n const distance =\n versionFromLexi(receivedHead) - versionFromLexi(sqliteHead);\n const value = Number(distance);\n return Number.isFinite(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAgB,+BACd,IACA,QACM;CACN,QAAQ,OAAO,QAAf;EACE,KAAK;GACH,mBACE,WACA,8CACA,kHAEF,EAAE,IAAI,OAAO,IAAI;GACjB;EACF,KAAK;GACH,mBACE,WACA,qCACA,mIAEF,EAAE,IAAI,GAAG,EAAC,QAAQ,OAAO,OAAM,CAAC;GAChC;EACF,KAAK,QACH;EACF,SACE,YAAY,MAAM;CACtB;CACA,IAAI,OAAO,cAKT,mBACE,WACA,mCACA,sGAEF,EAAE,IAAI,GAAG,EAAC,QAAQ,OAAO,OAAM,CAAC;CAElC,GAAG,QAAQ,oCAAoC,EAC7C,0BAA0B,OAC5B,CAAC;AACH;;;;;;;;AAyBA,SAAgB,8BACd,WAC4B;CAC5B,MAAM,OAAO,kBAAkB,SAAS;CACxC,MAAM,EAAC,cAAc,kBAAiB,oBAAoB,SAAS;CACnE,IAAI,iBAAiB,QAAQ,kBAAkB,MAC7C,MAAM,IAAI,MAAM,yDAAyD;CAE3E,OAAO;EAAC,GAAG;EAAM;EAAc;CAAa;AAC9C;;;;;;;AAQA,SAAgB,uBACd,WACqB;CACrB,MAAM,UAAU,8BAA8B,SAAS;CACvD,MAAM,YAAY,UACf,QAAgB;;;gBAGL,wBAAwB;KACnC,EACA,IAA4C;CAE/C,OAA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ACA,KAAKqB;EACL,KAAKrB,uBAAuB,IAAI,GAAG,EAAC,SAAS,WAAU,CAAC;EACxD,KAAKN,IAAI,QAAQ,+CAA+C,EAC9D,+BAA+B;GAC7B;GACA,YAAY,WAAW,MAAM,GAAG,EAAE;GAClC,YAAY,WAAW,MAAM,GAAG,EAAE;EACpC,EACF,CAAC;CACH;CAEA,gBACE,WACA,QAIM;EACN,KAAK4B;EACL,KAAKrB,qBAAqB,IAAI,GAAG,EAAC,OAAM,CAAC;EACzC,KAAKP,IAAI,OAAO,uDAAuD,EACrE,+BAA+B;GAAC;GAAW;EAAM,EACnD,CAAC;CACH;CAEA,mBAAyB;EACvB,KAAKc,gBAAgB,KAAA;EACrB,KAAKE,aAAa;EAClB,KAAKC,oBAAoB,KAAA;CAC3B;AACF;AAEA,SAAS,eAAe,WAAuC;CAC7D,IAAI;EACF,MAAM,QAAQ,OAAO,gBAAgB,SAAS,CAAC;EAC/C,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;CAC1C,QAAQ;EACN;CACF;AACF;AAEA,SAAS,kBACP,cACA,YACoB;CACpB,IAAI,gBAAgB,YAClB,OAAO;CAET,IAAI;EACF,MAAM,WACJ,gBAAgB,YAAY,IAAI,gBAAgB,UAAU;EAC5D,MAAM,QAAQ,OAAO,QAAQ;EAC7B,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;CAC1C,QAAQ;EACN;CACF;AACF"}
@@ -8,6 +8,25 @@ export type PragmaConfig = {
8
8
  analysisLimit: number;
9
9
  walAutocheckpoint?: number | undefined;
10
10
  };
11
+ /**
12
+ * Enables write-path checkpoint backpressure in the write worker. At each
13
+ * commit boundary, if the WAL has grown to at least `checkpointThresholdPages`,
14
+ * the worker forces an immediate litestream sync (sealing the WAL to LTX and
15
+ * running litestream's checkpoint).
16
+ *
17
+ * The optional `walMaxPages` is an emergency break that pauses until the WAL drains,
18
+ * rather than letting it exceed available disk space. This replaces litestream's
19
+ * analogous `truncate-page-n` emergency break, which is more disruptive because of
20
+ * https://github.com/benbjohnson/litestream/issues/1332. Note, however, this should
21
+ * never been needed if non-initial snapshots are disabled (which is the default).
22
+ *
23
+ * Set only for the backup replicator when replicating with litestream v5; `null`
24
+ * disables the feature entirely (no per-commit overhead).
25
+ */
26
+ export type ForceCheckpointConfig = {
27
+ checkpointThresholdPages: number;
28
+ maxWalPages?: number | undefined;
29
+ };
11
30
  type ErrorHandler = (err: Error) => void;
12
31
  /**
13
32
  * Interface for a write worker that processes replication messages.
@@ -29,7 +48,13 @@ export type SerializedError = {
29
48
  export declare function serializeError(err: unknown): SerializedError;
30
49
  export declare function deserializeError(serialized: SerializedError): Error;
31
50
  export type ArgsMap = {
32
- init: [string, ChangeProcessorMode, PragmaConfig, LogConfig];
51
+ init: [
52
+ string,
53
+ ChangeProcessorMode,
54
+ PragmaConfig,
55
+ LogConfig,
56
+ ForceCheckpointConfig | null
57
+ ];
33
58
  getSubscriptionState: [];
34
59
  processMessage: [ChangeStreamData];
35
60
  abort: [];
@@ -67,7 +92,7 @@ export declare function applyPragmas(db: Database, pragmas: PragmaConfig): void;
67
92
  export declare class ThreadWriteWorkerClient implements WriteWorkerClient {
68
93
  #private;
69
94
  constructor();
70
- init(dbPath: string, mode: ChangeProcessorMode, pragmas: PragmaConfig, logConfig: LogConfig): Promise<void>;
95
+ init(dbPath: string, mode: ChangeProcessorMode, pragmas: PragmaConfig, logConfig: LogConfig, checkpoint?: ForceCheckpointConfig | null): Promise<void>;
71
96
  getSubscriptionState(): Promise<SubscriptionState>;
72
97
  processMessage(downstream: ChangeStreamData): Promise<CommitResult | null>;
73
98
  abort(): 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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,IAAI,CAAC;IAIhB,oBAAoB,IAAI,OAAO,CAAC,iBAAiB,CAAC;IAIlD,cAAc,CAAC,UAAU,EAAE,gBAAgB,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAI1E,KAAK,IAAI,IAAI;IAMP,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAO3B,OAAO,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI;CAGrC"}
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,GAAG,EAAE,KAAK,KAAK,IAAI,CAAC;AAEzC;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,oBAAoB,IAAI,OAAO,CAAC,iBAAiB,CAAC,CAAC;IACnD,cAAc,CAAC,UAAU,EAAE,gBAAgB,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC;IAC3E,KA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AC;CACZ,CAAC;AAEF,MAAM,MAAM,QAAQ,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,IAC1C;IAAC,MAAM,EAAE,CAAC,CAAC;IAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;IAAC,KAAK,CAAC,EAAE,SAAS,CAAA;CAAC,GACpD;IAAC,MAAM,EAAE,CAAC,CAAC;IAAC,KAAK,EAAE,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;;;IAyD/D,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;IAIhB,oBAAoB,IAAI,OAAO,CAAC,iBAAiB,CAAC;IAIlD,cAAc,CAAC,UAAU,EAAE,gBAAgB,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAI1E,KAAK,IAAI,IAAI;IAMP,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAO3B,OAAO,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI;CAGrC"}
@@ -91,12 +91,13 @@ var ThreadWriteWorkerClient = class {
91
91
  });
92
92
  return r.promise;
93
93
  }
94
- init(dbPath, mode, pragmas, logConfig) {
94
+ init(dbPath, mode, pragmas, logConfig, checkpoint = null) {
95
95
  return this.#call("init", [
96
96
  dbPath,
97
97
  mode,
98
98
  pragmas,
99
- logConfig
99
+ logConfig,
100
+ checkpoint
100
101
  ]);
101
102
  }
102
103
  getSubscriptionState() {
@@ -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\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: [string, ChangeProcessorMode, PragmaConfig, LogConfig];\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 ): Promise<void> {\n return this.#call('init', [dbPath, mode, pragmas, logConfig]);\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":";;;;;AAqCA,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;C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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 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,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,MAAM,WAAW,OAAO;CACxC,IAAI,OAAO,WAAW;CACtB,IAAI,WAAW,UAAU,KAAA,GACvB,IAAI,QAAQ,WAAW;CAEzB,IAAI,WAAW,UAAU,KAAA,GACvB,IAAI,QACF,OAAO,WAAW,UAAU,WACxB,WAAW,QACX,iBAAiB,WAAW,KAAK;CAEzC,IAAI,WAAW,SACb,OAAO,OAAO,KAAK,WAAW,OAAO;CAEvC,OAAO;AACT;AAmCA,SAAgB,aAAa,IAAc,SAAuB;CAChE,GAAG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