@rocicorp/zero 1.11.0-canary.8 → 1.11.0-canary.9

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 (268) hide show
  1. package/out/analyze-query/src/analyze-cli.js +2 -2
  2. package/out/analyze-query/src/analyze-cli.js.map +1 -1
  3. package/out/replicache/src/dag/gc.d.ts.map +1 -1
  4. package/out/replicache/src/dag/gc.js +2 -1
  5. package/out/replicache/src/dag/gc.js.map +1 -1
  6. package/out/replicache/src/dag/invalid-ref-count-error.d.ts +12 -0
  7. package/out/replicache/src/dag/invalid-ref-count-error.d.ts.map +1 -0
  8. package/out/replicache/src/dag/invalid-ref-count-error.js +19 -0
  9. package/out/replicache/src/dag/invalid-ref-count-error.js.map +1 -0
  10. package/out/replicache/src/dag/store-impl.d.ts +12 -2
  11. package/out/replicache/src/dag/store-impl.d.ts.map +1 -1
  12. package/out/replicache/src/dag/store-impl.js +22 -8
  13. package/out/replicache/src/dag/store-impl.js.map +1 -1
  14. package/out/replicache/src/db/rebase.d.ts +14 -2
  15. package/out/replicache/src/db/rebase.d.ts.map +1 -1
  16. package/out/replicache/src/db/rebase.js +27 -5
  17. package/out/replicache/src/db/rebase.js.map +1 -1
  18. package/out/replicache/src/persist/collect-idb-databases.d.ts +10 -5
  19. package/out/replicache/src/persist/collect-idb-databases.d.ts.map +1 -1
  20. package/out/replicache/src/persist/collect-idb-databases.js +16 -9
  21. package/out/replicache/src/persist/collect-idb-databases.js.map +1 -1
  22. package/out/replicache/src/persist/persist.d.ts.map +1 -1
  23. package/out/replicache/src/persist/persist.js +12 -5
  24. package/out/replicache/src/persist/persist.js.map +1 -1
  25. package/out/replicache/src/persist/refresh.js +6 -2
  26. package/out/replicache/src/persist/refresh.js.map +1 -1
  27. package/out/replicache/src/replicache-impl.d.ts +7 -3
  28. package/out/replicache/src/replicache-impl.d.ts.map +1 -1
  29. package/out/replicache/src/replicache-impl.js +98 -11
  30. package/out/replicache/src/replicache-impl.js.map +1 -1
  31. package/out/replicache/src/replicache-options.d.ts +9 -0
  32. package/out/replicache/src/replicache-options.d.ts.map +1 -1
  33. package/out/shared/src/iterables.d.ts +2 -0
  34. package/out/shared/src/iterables.d.ts.map +1 -1
  35. package/out/shared/src/iterables.js +18 -1
  36. package/out/shared/src/iterables.js.map +1 -1
  37. package/out/shared/src/ring-buffer.d.ts +8 -0
  38. package/out/shared/src/ring-buffer.d.ts.map +1 -1
  39. package/out/shared/src/ring-buffer.js +22 -1
  40. package/out/shared/src/ring-buffer.js.map +1 -1
  41. package/out/zero/package.js +2 -3
  42. package/out/zero/package.js.map +1 -1
  43. package/out/zero-cache/src/config/zero-config.js +2 -2
  44. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  45. package/out/zero-cache/src/server/change-streamer.js +1 -1
  46. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  47. package/out/zero-cache/src/server/inspector-delegate.d.ts +18 -2
  48. package/out/zero-cache/src/server/inspector-delegate.d.ts.map +1 -1
  49. package/out/zero-cache/src/server/inspector-delegate.js +20 -7
  50. package/out/zero-cache/src/server/inspector-delegate.js.map +1 -1
  51. package/out/zero-cache/src/services/change-source/custom/change-source.js +2 -2
  52. package/out/zero-cache/src/services/change-source/custom/change-source.js.map +1 -1
  53. package/out/zero-cache/src/services/change-source/pg/backfill-resume.d.ts +156 -0
  54. package/out/zero-cache/src/services/change-source/pg/backfill-resume.d.ts.map +1 -0
  55. package/out/zero-cache/src/services/change-source/pg/backfill-resume.js +15 -0
  56. package/out/zero-cache/src/services/change-source/pg/backfill-resume.js.map +1 -0
  57. package/out/zero-cache/src/services/change-source/pg/change-source-init.d.ts +15 -0
  58. package/out/zero-cache/src/services/change-source/pg/change-source-init.d.ts.map +1 -0
  59. package/out/zero-cache/src/services/change-source/pg/change-source-init.js +99 -0
  60. package/out/zero-cache/src/services/change-source/pg/change-source-init.js.map +1 -0
  61. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts +14 -16
  62. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
  63. package/out/zero-cache/src/services/change-source/pg/change-source.js +33 -126
  64. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  65. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +16 -1
  66. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
  67. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +8 -4
  68. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  69. package/out/zero-cache/src/services/change-source/pg/replication-slot-cleanup-monitor.d.ts +16 -0
  70. package/out/zero-cache/src/services/change-source/pg/replication-slot-cleanup-monitor.d.ts.map +1 -0
  71. package/out/zero-cache/src/services/change-source/pg/replication-slot-cleanup-monitor.js +113 -0
  72. package/out/zero-cache/src/services/change-source/pg/replication-slot-cleanup-monitor.js.map +1 -0
  73. package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts +1 -15
  74. package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts.map +1 -1
  75. package/out/zero-cache/src/services/change-source/pg/replication-slots.js +18 -21
  76. package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
  77. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +3 -3
  78. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  79. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +8 -9
  80. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  81. package/out/zero-cache/src/services/change-streamer/upstream-acker.d.ts +17 -1
  82. package/out/zero-cache/src/services/change-streamer/upstream-acker.d.ts.map +1 -1
  83. package/out/zero-cache/src/services/change-streamer/upstream-acker.js +19 -3
  84. package/out/zero-cache/src/services/change-streamer/upstream-acker.js.map +1 -1
  85. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.d.ts.map +1 -1
  86. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.js +1 -0
  87. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.js.map +1 -1
  88. package/out/zero-cache/src/services/replicator/change-processor.js +1 -0
  89. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  90. package/out/zero-cache/src/services/view-syncer/drain-coordinator.d.ts +14 -1
  91. package/out/zero-cache/src/services/view-syncer/drain-coordinator.d.ts.map +1 -1
  92. package/out/zero-cache/src/services/view-syncer/drain-coordinator.js +30 -4
  93. package/out/zero-cache/src/services/view-syncer/drain-coordinator.js.map +1 -1
  94. package/out/zero-cache/src/services/view-syncer/inspect-handler.d.ts +1 -1
  95. package/out/zero-cache/src/services/view-syncer/inspect-handler.d.ts.map +1 -1
  96. package/out/zero-cache/src/services/view-syncer/inspect-handler.js +2 -2
  97. package/out/zero-cache/src/services/view-syncer/inspect-handler.js.map +1 -1
  98. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
  99. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +6 -10
  100. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  101. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  102. package/out/zero-cache/src/services/view-syncer/view-syncer.js +14 -4
  103. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  104. package/out/zero-cache/src/types/streams.d.ts.map +1 -1
  105. package/out/zero-cache/src/types/streams.js +1 -1
  106. package/out/zero-cache/src/types/streams.js.map +1 -1
  107. package/out/zero-cache/src/workers/connection.js +3 -3
  108. package/out/zero-cache/src/workers/connection.js.map +1 -1
  109. package/out/zero-cache/src/workers/syncer.js +2 -2
  110. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  111. package/out/zero-client/src/client/connection-manager.d.ts +20 -0
  112. package/out/zero-client/src/client/connection-manager.d.ts.map +1 -1
  113. package/out/zero-client/src/client/connection-manager.js +32 -14
  114. package/out/zero-client/src/client/connection-manager.js.map +1 -1
  115. package/out/zero-client/src/client/connection-status-enum.d.ts +2 -0
  116. package/out/zero-client/src/client/connection-status-enum.d.ts.map +1 -1
  117. package/out/zero-client/src/client/connection-status-enum.js +3 -1
  118. package/out/zero-client/src/client/connection-status-enum.js.map +1 -1
  119. package/out/zero-client/src/client/connection.d.ts +6 -0
  120. package/out/zero-client/src/client/connection.d.ts.map +1 -1
  121. package/out/zero-client/src/client/connection.js +2 -1
  122. package/out/zero-client/src/client/connection.js.map +1 -1
  123. package/out/zero-client/src/client/context.d.ts +8 -11
  124. package/out/zero-client/src/client/context.d.ts.map +1 -1
  125. package/out/zero-client/src/client/context.js +11 -15
  126. package/out/zero-client/src/client/context.js.map +1 -1
  127. package/out/zero-client/src/client/custom.js +2 -2
  128. package/out/zero-client/src/client/custom.js.map +1 -1
  129. package/out/zero-client/src/client/error.js +1 -1
  130. package/out/zero-client/src/client/mutator-proxy.d.ts.map +1 -1
  131. package/out/zero-client/src/client/mutator-proxy.js +2 -1
  132. package/out/zero-client/src/client/mutator-proxy.js.map +1 -1
  133. package/out/zero-client/src/client/options.d.ts +3 -0
  134. package/out/zero-client/src/client/options.d.ts.map +1 -1
  135. package/out/zero-client/src/client/options.js.map +1 -1
  136. package/out/zero-client/src/client/query-manager.d.ts.map +1 -1
  137. package/out/zero-client/src/client/query-manager.js +42 -6
  138. package/out/zero-client/src/client/query-manager.js.map +1 -1
  139. package/out/zero-client/src/client/version.js +1 -1
  140. package/out/zero-client/src/client/zero-rep.d.ts +1 -0
  141. package/out/zero-client/src/client/zero-rep.d.ts.map +1 -1
  142. package/out/zero-client/src/client/zero-rep.js +7 -5
  143. package/out/zero-client/src/client/zero-rep.js.map +1 -1
  144. package/out/zero-client/src/client/zero.d.ts +9 -3
  145. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  146. package/out/zero-client/src/client/zero.js +48 -11
  147. package/out/zero-client/src/client/zero.js.map +1 -1
  148. package/out/zero-client/src/types/query-result.d.ts +2 -0
  149. package/out/zero-client/src/types/query-result.d.ts.map +1 -1
  150. package/out/zero-react/src/use-query.d.ts +5 -4
  151. package/out/zero-react/src/use-query.d.ts.map +1 -1
  152. package/out/zero-react/src/use-query.js +12 -1
  153. package/out/zero-react/src/use-query.js.map +1 -1
  154. package/out/zero-server/src/adapters/drizzle.d.ts +2 -1
  155. package/out/zero-server/src/adapters/drizzle.d.ts.map +1 -1
  156. package/out/zero-server/src/adapters/drizzle.js +12 -7
  157. package/out/zero-server/src/adapters/drizzle.js.map +1 -1
  158. package/out/zero-server/src/adapters/kysely.d.ts +2 -1
  159. package/out/zero-server/src/adapters/kysely.d.ts.map +1 -1
  160. package/out/zero-server/src/adapters/kysely.js +8 -2
  161. package/out/zero-server/src/adapters/kysely.js.map +1 -1
  162. package/out/zero-server/src/adapters/pg.d.ts +1 -0
  163. package/out/zero-server/src/adapters/pg.d.ts.map +1 -1
  164. package/out/zero-server/src/adapters/pg.js +8 -2
  165. package/out/zero-server/src/adapters/pg.js.map +1 -1
  166. package/out/zero-server/src/adapters/postgresjs.d.ts +1 -0
  167. package/out/zero-server/src/adapters/postgresjs.d.ts.map +1 -1
  168. package/out/zero-server/src/adapters/postgresjs.js +7 -1
  169. package/out/zero-server/src/adapters/postgresjs.js.map +1 -1
  170. package/out/zero-server/src/adapters/prisma.d.ts +3 -2
  171. package/out/zero-server/src/adapters/prisma.d.ts.map +1 -1
  172. package/out/zero-server/src/adapters/prisma.js +8 -2
  173. package/out/zero-server/src/adapters/prisma.js.map +1 -1
  174. package/out/zero-server/src/custom.d.ts +5 -1
  175. package/out/zero-server/src/custom.d.ts.map +1 -1
  176. package/out/zero-server/src/custom.js +6 -3
  177. package/out/zero-server/src/custom.js.map +1 -1
  178. package/out/zero-server/src/mod.d.ts +1 -1
  179. package/out/zero-server/src/mod.d.ts.map +1 -1
  180. package/out/zero-server/src/pg-query-executor.d.ts +2 -2
  181. package/out/zero-server/src/pg-query-executor.d.ts.map +1 -1
  182. package/out/zero-server/src/pg-query-executor.js +2 -2
  183. package/out/zero-server/src/pg-query-executor.js.map +1 -1
  184. package/out/zero-server/src/schema.d.ts +2 -2
  185. package/out/zero-server/src/schema.d.ts.map +1 -1
  186. package/out/zero-server/src/schema.js +2 -2
  187. package/out/zero-server/src/schema.js.map +1 -1
  188. package/out/zero-server/src/zql-database.d.ts +21 -1
  189. package/out/zero-server/src/zql-database.d.ts.map +1 -1
  190. package/out/zero-server/src/zql-database.js +33 -2
  191. package/out/zero-server/src/zql-database.js.map +1 -1
  192. package/out/zero-solid/src/solid-view.d.ts +10 -0
  193. package/out/zero-solid/src/solid-view.d.ts.map +1 -1
  194. package/out/zero-solid/src/solid-view.js +27 -0
  195. package/out/zero-solid/src/solid-view.js.map +1 -1
  196. package/out/zql/src/ivm/array-view.d.ts +10 -0
  197. package/out/zql/src/ivm/array-view.d.ts.map +1 -1
  198. package/out/zql/src/ivm/array-view.js +20 -8
  199. package/out/zql/src/ivm/array-view.js.map +1 -1
  200. package/out/zql/src/ivm/cap.d.ts.map +1 -1
  201. package/out/zql/src/ivm/cap.js +5 -3
  202. package/out/zql/src/ivm/cap.js.map +1 -1
  203. package/out/zql/src/ivm/deferred-input.d.ts.map +1 -1
  204. package/out/zql/src/ivm/deferred-input.js +3 -2
  205. package/out/zql/src/ivm/deferred-input.js.map +1 -1
  206. package/out/zql/src/ivm/exists.d.ts +1 -1
  207. package/out/zql/src/ivm/exists.d.ts.map +1 -1
  208. package/out/zql/src/ivm/exists.js.map +1 -1
  209. package/out/zql/src/ivm/fan-in.d.ts +2 -2
  210. package/out/zql/src/ivm/fan-in.d.ts.map +1 -1
  211. package/out/zql/src/ivm/fan-in.js +6 -5
  212. package/out/zql/src/ivm/fan-in.js.map +1 -1
  213. package/out/zql/src/ivm/fan-out.d.ts +2 -2
  214. package/out/zql/src/ivm/fan-out.d.ts.map +1 -1
  215. package/out/zql/src/ivm/fan-out.js.map +1 -1
  216. package/out/zql/src/ivm/filter-operators.d.ts +6 -6
  217. package/out/zql/src/ivm/filter-operators.d.ts.map +1 -1
  218. package/out/zql/src/ivm/filter-operators.js +10 -8
  219. package/out/zql/src/ivm/filter-operators.js.map +1 -1
  220. package/out/zql/src/ivm/filter.d.ts +2 -2
  221. package/out/zql/src/ivm/filter.d.ts.map +1 -1
  222. package/out/zql/src/ivm/filter.js +7 -4
  223. package/out/zql/src/ivm/filter.js.map +1 -1
  224. package/out/zql/src/ivm/flipped-join.js +2 -2
  225. package/out/zql/src/ivm/flipped-join.js.map +1 -1
  226. package/out/zql/src/ivm/maybe-split-and-push-edit-change.d.ts +1 -1
  227. package/out/zql/src/ivm/maybe-split-and-push-edit-change.d.ts.map +1 -1
  228. package/out/zql/src/ivm/maybe-split-and-push-edit-change.js +6 -4
  229. package/out/zql/src/ivm/maybe-split-and-push-edit-change.js.map +1 -1
  230. package/out/zql/src/ivm/memory-source.d.ts +2 -2
  231. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  232. package/out/zql/src/ivm/memory-source.js +9 -9
  233. package/out/zql/src/ivm/memory-source.js.map +1 -1
  234. package/out/zql/src/ivm/take.d.ts.map +1 -1
  235. package/out/zql/src/ivm/take.js +3 -4
  236. package/out/zql/src/ivm/take.js.map +1 -1
  237. package/out/zql/src/ivm/union-fan-in.d.ts.map +1 -1
  238. package/out/zql/src/ivm/union-fan-in.js +9 -7
  239. package/out/zql/src/ivm/union-fan-in.js.map +1 -1
  240. package/out/zql/src/ivm/view-apply-change.d.ts.map +1 -1
  241. package/out/zql/src/ivm/view-apply-change.js +3 -3
  242. package/out/zql/src/ivm/view-apply-change.js.map +1 -1
  243. package/out/zql/src/mutate/custom.d.ts +24 -1
  244. package/out/zql/src/mutate/custom.d.ts.map +1 -1
  245. package/out/zql/src/mutate/custom.js.map +1 -1
  246. package/out/zql/src/mutate/mutator-registry.d.ts.map +1 -1
  247. package/out/zql/src/mutate/mutator-registry.js +2 -2
  248. package/out/zql/src/mutate/mutator-registry.js.map +1 -1
  249. package/out/zql/src/query/query-delegate-base.d.ts +2 -0
  250. package/out/zql/src/query/query-delegate-base.d.ts.map +1 -1
  251. package/out/zql/src/query/query-delegate-base.js +55 -28
  252. package/out/zql/src/query/query-delegate-base.js.map +1 -1
  253. package/out/zql/src/query/query-delegate.d.ts +11 -1
  254. package/out/zql/src/query/query-delegate.d.ts.map +1 -1
  255. package/out/zql/src/query/query-impl.d.ts +1 -0
  256. package/out/zql/src/query/query-impl.d.ts.map +1 -1
  257. package/out/zql/src/query/query-impl.js.map +1 -1
  258. package/out/zql/src/query/query.d.ts +7 -1
  259. package/out/zql/src/query/query.d.ts.map +1 -1
  260. package/out/zql/src/query/runnable-query-impl.d.ts +1 -0
  261. package/out/zql/src/query/runnable-query-impl.d.ts.map +1 -1
  262. package/out/zql/src/query/runnable-query-impl.js.map +1 -1
  263. package/out/zql/src/query/typed-view.d.ts +1 -1
  264. package/out/zql/src/query/typed-view.d.ts.map +1 -1
  265. package/out/zqlite/src/table-source.d.ts.map +1 -1
  266. package/out/zqlite/src/table-source.js +7 -5
  267. package/out/zqlite/src/table-source.js.map +1 -1
  268. package/package.json +2 -3
@@ -1 +1 @@
1
- {"version":3,"file":"initial-sync.js","names":[],"sources":["../../../../../../../zero-cache/src/services/change-source/pg/initial-sync.ts"],"sourcesContent":["import {mkdtemp, rm} from 'node:fs/promises';\nimport {platform, tmpdir} from 'node:os';\nimport {join} from 'node:path';\nimport {Writable, type Readable} from 'node:stream';\nimport {pipeline} from 'node:stream/promises';\nimport type {LogContext} from '@rocicorp/logger';\nimport {assert} from '../../../../../shared/src/asserts.ts';\nimport type {JSONObject} from '../../../../../shared/src/bigint-json.ts';\nimport {must} from '../../../../../shared/src/must.ts';\nimport {equals} from '../../../../../shared/src/set-utils.ts';\nimport type {DownloadStatus} from '../../../../../zero-events/src/status.ts';\nimport {Database} from '../../../../../zqlite/src/db.ts';\nimport {\n createLiteIndexStatement,\n createLiteTableStatement,\n} from '../../../db/create.ts';\nimport {listIndexes, listTables} from '../../../db/lite-tables.ts';\nimport * as Mode from '../../../db/mode-enum.ts';\nimport {\n BinaryCopyParser,\n hasBinaryDecoder,\n makeBinaryDecoder,\n textCastDecoder,\n} from '../../../db/pg-copy-binary.ts';\nimport {TsvParser} from '../../../db/pg-copy.ts';\nimport {\n mapPostgresToLite,\n mapPostgresToLiteIndex,\n} from '../../../db/pg-to-lite.ts';\nimport {getTypeParsers} from '../../../db/pg-type-parser.ts';\nimport {runTx} from '../../../db/run-transaction.ts';\nimport type {IndexSpec, PublishedTableSpec} from '../../../db/specs.ts';\nimport {importSnapshot, TransactionPool} from '../../../db/transaction-pool.ts';\nimport {\n getOrCreateCounter,\n getOrCreateHistogram,\n} from '../../../observability/metrics.ts';\nimport {\n JSON_STRINGIFIED,\n liteValue,\n type LiteValueType,\n} from '../../../types/lite.ts';\nimport {liteTableName} from '../../../types/names.ts';\nimport {PG_15, PG_17} from '../../../types/pg-versions.ts';\nimport {\n connectPgClient,\n type PostgresDB,\n type PostgresTransaction,\n type PostgresValueType,\n} from '../../../types/pg.ts';\nimport {CpuProfiler} from '../../../types/profiler.ts';\nimport type {ShardConfig} from '../../../types/shards.ts';\nimport {ALLOWED_APP_ID_CHARACTERS} from '../../../types/shards.ts';\nimport {id} from '../../../types/sql.ts';\nimport {ReplicationStatusPublisher} from '../../replicator/replication-status.ts';\nimport {ColumnMetadataStore} from '../../replicator/schema/column-metadata.ts';\nimport {initReplicationState} from '../../replicator/schema/replication-state.ts';\nimport {toStateVersionString} from './lsn.ts';\nimport {createReplicaAndSlot} from './replication-slots.ts';\nimport {ensureShardSchema} from './schema/init.ts';\nimport {getPublicationInfo, warnForSkippedIndexes} from './schema/published.ts';\nimport {\n dropShard,\n getInternalShardConfig,\n getReplicaState,\n initReplica,\n validatePublications,\n type ReplicaState,\n} from './schema/shard.ts';\n\nexport type InitialSyncOptions = {\n tableCopyWorkers: number;\n profileCopy?: boolean | undefined;\n textCopy?: boolean | undefined;\n replicationSlotFailover?: boolean | undefined;\n installPartialIndexTriggers?: boolean | undefined;\n /**\n * When set, run initial sync in \"shadow\" mode for verification: skip all\n * upstream mutations (no replication slot, no addReplica, no dropShard, no\n * slot drop on failure), suppress status events, and optionally sample\n * rows from each table via TABLESAMPLE BERNOULLI + LIMIT. The caller is\n * responsible for providing (and discarding) a throwaway SQLite `tx`.\n */\n shadow?:\n | {\n /** 0 < rate <= 1. When 1, no TABLESAMPLE clause is added. */\n sampleRate: number;\n /**\n * LIMIT N cap appended after TABLESAMPLE. Required: shadow sync is\n * for verification only, so every run must commit to a row budget.\n */\n maxRowsPerTable: number;\n }\n | undefined;\n};\n\nexport type ReplicaOptions = {\n backupV5: boolean;\n};\n\n/** Server context to store with the initial sync metadata for debugging. */\nexport type ServerContext = JSONObject;\n\n/**\n * @returns The {@link ReplicaState} of the initialized replica, or `undefined`\n * for a shadow sync.\n */\nexport async function initialSync(\n lc: LogContext,\n shard: ShardConfig,\n tx: Database,\n upstreamURI: string,\n syncOptions: InitialSyncOptions,\n context: ServerContext,\n {backupV5}: ReplicaOptions = {backupV5: true},\n): Promise<ReplicaState | undefined> {\n if (!ALLOWED_APP_ID_CHARACTERS.test(shard.appID)) {\n throw new Error(\n 'The App ID may only consist of lower-case letters, numbers, and the underscore character',\n );\n }\n const {\n tableCopyWorkers,\n profileCopy,\n textCopy = false,\n replicationSlotFailover = false,\n installPartialIndexTriggers = true,\n shadow,\n } = syncOptions;\n const syncMode: InitialSyncMode = shadow ? 'shadow' : 'initial';\n const copyFormat: CopyFormat = textCopy ? 'text' : 'binary';\n const start = performance.now();\n let sql: PostgresDB | undefined;\n const replicaID = Date.now().toString();\n let slotName: string | undefined; // undefined === shadow\n let slotSession: Readable | undefined; // undefined === shadow\n const statusPublisher = ReplicationStatusPublisher.forRunningTransaction(\n tx,\n shadow ? async () => {} : undefined,\n ).publish(lc, 'Initializing');\n try {\n const copyProfiler = profileCopy ? await CpuProfiler.connect() : null;\n sql = await connectPgClient(lc, upstreamURI, 'initial-sync');\n const pgVersion = await checkUpstreamConfig(sql);\n\n // In shadow mode we assume the shard is already initialized and just\n // read back the existing publications. `ensurePublishedTables` would\n // otherwise run DDL and potentially call `dropShard`, which must never\n // happen during a shadow run.\n const {publications} = shadow\n ? await getInternalShardConfig(sql, shard)\n : await ensurePublishedTables(\n lc,\n sql,\n shard,\n installPartialIndexTriggers,\n );\n lc.info?.(`Upstream is setup with publications [${publications}]`);\n\n const {database, host} = sql.options;\n lc.info?.(\n shadow\n ? `acquiring exported snapshot on ${database}@${host} (shadow mode)`\n : `opening replication session to ${database}@${host}`,\n );\n\n // Captures the necessary information from the consistent snapshot\n // created for the new replication slot (or a suitable equivalent\n // for shadow sync).\n async function captureSnapshot(snapshot: string) {\n // Run up to MAX_WORKERS to copy of tables at the replication slot's snapshot.\n // Retrieve the published schema at the consistent_point.\n const published = await runTx(\n must(sql),\n async tx => {\n await tx.unsafe(/* sql*/ `SET TRANSACTION SNAPSHOT '${snapshot}'`);\n return getPublicationInfo(tx, publications);\n },\n {mode: Mode.READONLY},\n );\n warnForSkippedIndexes(lc, published);\n // Note: If this throws, initial-sync is aborted.\n validatePublications(lc, published);\n\n // Now that tables have been validated, kick off the copiers.\n const {tables, indexes} = published;\n const numTables = tables.length;\n if (platform() === 'win32' && tableCopyWorkers < numTables) {\n lc.warn?.(\n `Increasing the number of copy workers from ${tableCopyWorkers} to ` +\n `${numTables} to work around a Node/Postgres connection bug`,\n );\n }\n const numWorkers =\n platform() === 'win32'\n ? numTables\n : Math.min(tableCopyWorkers, numTables);\n\n const copyPool = await connectPgClient(\n lc,\n upstreamURI,\n 'initial-sync-copy-worker',\n {\n max: numWorkers,\n ['max_lifetime']: 120 * 60, // set a long (2h) limit for COPY streaming\n },\n );\n const copiers = await startTableCopyWorkers(\n lc,\n copyPool,\n snapshot,\n numWorkers,\n numTables,\n );\n return {\n published,\n tables,\n indexes,\n numTables,\n copyPool,\n copiers,\n };\n }\n\n let lsn: string;\n let snapshotResult: Awaited<ReturnType<typeof captureSnapshot>>;\n\n if (shadow) {\n const exported = await acquireExportedSnapshotForShadowSync(\n lc,\n upstreamURI,\n captureSnapshot,\n );\n lsn = exported.lsn;\n snapshotResult = exported.result;\n } else {\n const replication = await createReplicaAndSlot(\n lc,\n sql,\n 'initial-sync-replication-session',\n shard,\n replicaID,\n replicationSlotFailover && pgVersion >= PG_17,\n {\n // When backing up with litestream v5, a unique backup path is\n // required since the LTX format does not tolerate multiple writers\n // (and there are no v3 \"generations\" to workaround it).\n backupPath: backupV5 ? replicaID : null,\n backupV5,\n },\n captureSnapshot,\n );\n lsn = replication.slot.consistent_point;\n slotName = replication.slot.slot_name;\n snapshotResult = replication.capturedSnapshot;\n slotSession = replication.initialSession;\n }\n\n const {published, tables, indexes, numTables, copyPool, copiers} =\n snapshotResult;\n\n const initialVersion = toStateVersionString(lsn);\n initReplicationState(tx, publications, initialVersion, context);\n try {\n createLiteTables(tx, tables, initialVersion);\n const sampleRate = shadow?.sampleRate;\n const maxRowsPerTable = shadow?.maxRowsPerTable;\n const downloads = await Promise.all(\n tables.map(spec =>\n copiers.processReadTask((db, lc) =>\n getInitialDownloadState(lc, db, spec, shadow !== undefined),\n ),\n ),\n );\n statusPublisher.publish(\n lc,\n 'Initializing',\n `Copying ${numTables} upstream tables at version ${initialVersion}`,\n 5000,\n () => ({downloadStatus: downloads.map(({status}) => status)}),\n );\n\n void copyProfiler?.start();\n const copyStart = performance.now();\n const copyResults = await Promise.all(\n downloads.map(table =>\n copiers.processReadTask((db, lc) =>\n copy(\n lc,\n table,\n copyPool,\n db,\n tx,\n textCopy,\n syncMode,\n sampleRate,\n maxRowsPerTable,\n ),\n ),\n ),\n );\n const copyElapsed = performance.now() - copyStart;\n void copyProfiler?.stopAndDispose(lc, 'initial-copy');\n copiers.setDone();\n\n const copySummary = initialSyncCopySummary(copyResults, copyElapsed);\n\n statusPublisher.publish(\n lc,\n 'Indexing',\n `Creating ${indexes.length} indexes`,\n 5000,\n );\n const indexStart = performance.now();\n createLiteIndices(lc, tx, indexes);\n const index = performance.now() - indexStart;\n lc.info?.(`Created indexes (${index.toFixed(3)} ms)`);\n\n if (slotName && replicaID) {\n await initReplica(sql, shard, replicaID, published, context);\n } else {\n assert(shadow, 'expected to be in shadow sync if there is no slotName');\n const rowsByTable = new Map<string, number>();\n for (let i = 0; i < downloads.length; i++) {\n rowsByTable.set(downloads[i].status.table, copyResults[i].rows);\n }\n verifyShadowReplica(lc, tx, published, rowsByTable);\n }\n\n const elapsed = performance.now() - start;\n const copyOtherMs = Math.max(0, elapsed - copySummary.flushMs - index);\n recordInitialSyncRunMetrics(\n {\n durationMs: elapsed,\n rows: copySummary.rows,\n copyBytes: copySummary.copyBytes,\n copyMs: copySummary.copyMs,\n copyOtherMs,\n flushMs: copySummary.flushMs,\n indexMs: index,\n },\n {\n result: 'success',\n syncMode,\n copyFormat,\n },\n );\n lc.info?.(\n `Synced ${copySummary.rows.toLocaleString()} rows of ${numTables} tables in ${publications} up to ${lsn} ` +\n `(flush: ${copySummary.flushMs.toFixed(3)}, index: ${index.toFixed(3)}, total: ${elapsed.toFixed(3)} ms)`,\n {\n syncMode,\n copyFormat,\n publications,\n lsn,\n ...copySummary,\n indexes: indexes.length,\n indexMs: index,\n copyOtherMs,\n totalMs: elapsed,\n },\n );\n\n return slotName && replicaID\n ? must(\n await getReplicaState(sql, shard, replicaID),\n `Missing replica with id ${replicaID}`,\n )\n : undefined; // shadow sync only\n } finally {\n // All meaningful errors are handled at the processReadTask() call site.\n void copyPool.end().catch(e => lc.warn?.(`Error closing copyPool`, e));\n }\n } catch (e) {\n recordInitialSyncRunMetrics(\n {durationMs: performance.now() - start},\n {\n result: 'error',\n syncMode,\n copyFormat,\n },\n );\n if (slotName && sql) {\n // If initial-sync did not succeed, make a best effort to drop the\n // orphaned replication slot to avoid running out of slots in\n // pathological cases that result in repeated failures.\n lc.warn?.(`dropping replication slot ${slotName}`, e);\n // release any initial replication session so the slot can be dropped\n slotSession?.destroy();\n await sql`\n SELECT pg_drop_replication_slot(slot_name) FROM pg_replication_slots\n WHERE slot_name = ${slotName};\n `.catch(e => lc.warn?.(`Unable to drop replication slot ${slotName}`, e));\n }\n throw await statusPublisher.publishAndThrowError(lc, 'Initializing', e);\n } finally {\n statusPublisher.stop();\n if (sql) {\n await sql.end();\n }\n }\n}\n\nexport type ShadowSyncOptions = {\n sampleRate: number;\n maxRowsPerTable: number;\n /**\n * Parent directory for the throwaway SQLite replica. Defaults to the OS\n * tmpdir. Primarily for tests that need to isolate the scratch directory.\n */\n parentDir?: string | undefined;\n};\n\n/**\n * Exercises the initial-sync code path against a sample of rows from every\n * published table, writing into a throwaway SQLite database that is deleted\n * when the run ends. Produces zero upstream mutations: no replication slot,\n * no `addReplica`, no `dropShard`, no status events.\n *\n * Intended to be invoked periodically so that if a customer ever needs a\n * full reset, we have recent confidence that `initialSync` still works.\n * The shard must already be initialized upstream.\n */\nexport async function shadowInitialSync(\n lc: LogContext,\n shard: ShardConfig,\n upstreamURI: string,\n shadow: ShadowSyncOptions,\n context: ServerContext,\n syncOptions?: Pick<InitialSyncOptions, 'textCopy'>,\n): Promise<void> {\n const dir = await mkdtemp(\n join(shadow.parentDir ?? tmpdir(), 'zero-shadow-sync-'),\n );\n const dbPath = join(dir, 'shadow-replica.db');\n const db = new Database(lc, dbPath);\n try {\n await initialSync(\n lc,\n shard,\n db,\n upstreamURI,\n {\n // Shadow sync copies small samples, so one worker is plenty —\n // no reason to burn additional upstream connections.\n tableCopyWorkers: 1,\n textCopy: syncOptions?.textCopy,\n shadow,\n },\n context,\n );\n } finally {\n try {\n db.close();\n } catch (e) {\n lc.warn?.(`Error closing shadow replica db`, e);\n }\n await rm(dir, {recursive: true, force: true}).catch(e =>\n lc.warn?.(`Error cleaning up shadow replica dir ${dir}`, e),\n );\n }\n}\n\nasync function checkUpstreamConfig(sql: PostgresDB) {\n const {walLevel, version} = (\n await sql<{walLevel: string; version: number}[]>`\n SELECT current_setting('wal_level') as \"walLevel\", \n current_setting('server_version_num') as \"version\";\n `\n )[0];\n\n if (walLevel !== 'logical') {\n throw new Error(\n `Postgres must be configured with \"wal_level = logical\" (currently: \"${walLevel})`,\n );\n }\n if (version < PG_15) {\n throw new Error(\n `Must be running Postgres 15 or higher (currently: \"${version}\")`,\n );\n }\n return version;\n}\n\nasync function ensurePublishedTables(\n lc: LogContext,\n sql: PostgresDB,\n shard: ShardConfig,\n installPartialIndexTriggers: boolean,\n validate = true,\n): Promise<{publications: string[]}> {\n const {database, host} = sql.options;\n lc.info?.(`Ensuring upstream PUBLICATION on ${database}@${host}`);\n\n // Technically, ensureShardSchema() is already called by\n // initializePostgresChangeSource, so the call here is redundant\n // but harmless. On the contrary, it makes initial sync more\n // self-contained (for test setup), and also plays a role in\n // recovering from corruption (below) after the shard is dropped.\n await ensureShardSchema(lc, sql, shard, installPartialIndexTriggers);\n const {publications} = await getInternalShardConfig(sql, shard);\n\n if (validate) {\n let valid = false;\n const nonInternalPublications = publications.filter(\n p => !p.startsWith('_'),\n );\n const exists = await sql`\n SELECT pubname FROM pg_publication WHERE pubname IN ${sql(publications)}\n `.values();\n if (exists.length !== publications.length) {\n lc.warn?.(\n `some configured publications [${publications}] are missing: ` +\n `[${exists.flat()}]. resyncing`,\n );\n } else if (\n !equals(new Set(shard.publications), new Set(nonInternalPublications))\n ) {\n lc.warn?.(\n `requested publications [${shard.publications}] differ from previous` +\n `publications [${nonInternalPublications}]. resyncing`,\n );\n } else {\n valid = true;\n }\n if (!valid) {\n await sql.unsafe(dropShard(shard.appID, shard.shardNum));\n return ensurePublishedTables(\n lc,\n sql,\n shard,\n installPartialIndexTriggers,\n false,\n );\n }\n }\n return {publications};\n}\n\nasync function startTableCopyWorkers(\n lc: LogContext,\n db: PostgresDB,\n snapshot: string,\n numWorkers: number,\n numTables: number,\n): Promise<TransactionPool> {\n const {init, imported} = importSnapshot(snapshot);\n const tableCopiers = new TransactionPool(lc, {\n mode: Mode.READONLY,\n init,\n initialWorkers: numWorkers,\n });\n tableCopiers.run(db);\n\n // Wait for all workers to run the importSnapshot() init task before\n // proceeding (to allow the snapshot to be released).\n for (let i = 0; i < numWorkers; i++) {\n await imported.dequeue();\n }\n\n lc.info?.(`Started ${numWorkers} workers to copy ${numTables} tables`);\n\n if (parseInt(process.versions.node) < 22) {\n lc.warn?.(\n `\\n\\n\\n` +\n `Older versions of Node have a bug that results in an unresponsive\\n` +\n `Postgres connection after running certain combinations of COPY commands.\\n` +\n `If initial sync hangs, run zero-cache with Node v22+. This has the additional\\n` +\n `benefit of being consistent with the Node version run in the production container image.` +\n `\\n\\n\\n`,\n );\n }\n return tableCopiers;\n}\n\n/**\n * Shadow-mode alternative to `createReplicationSlot`: opens a dedicated\n * READ ONLY REPEATABLE READ transaction on a normal connection, exports the\n * snapshot and captures the current WAL LSN. Note that the LSN and snapshot\n * are not guaranteed to be consistent but it this is fine for shadow sync\n * where the LSN is not actually relied on for anything.\n */\nasync function acquireExportedSnapshotForShadowSync<T>(\n lc: LogContext,\n upstreamURI: string,\n captureSnapshot: (snapshot: string) => Promise<T>,\n): Promise<{\n lsn: string;\n result: T;\n}> {\n const holder = await connectPgClient(\n lc,\n upstreamURI,\n 'shadow-initial-sync-snapshot',\n {max: 1},\n );\n return holder.begin(Mode.READONLY, async tx => {\n const [{lsn, snapshot}] = await tx<{snapshot: string; lsn: string}[]>`\n SELECT pg_export_snapshot() AS snapshot,\n pg_current_wal_lsn()::text AS lsn`;\n const result = await captureSnapshot(snapshot);\n return {lsn, result};\n });\n}\n\nfunction createLiteTables(\n tx: Database,\n tables: PublishedTableSpec[],\n initialVersion: string,\n) {\n // TODO: Figure out how to reuse the ChangeProcessor here to avoid\n // duplicating the ColumnMetadata logic.\n const columnMetadata = must(ColumnMetadataStore.getInstance(tx));\n for (const t of tables) {\n tx.exec(createLiteTableStatement(mapPostgresToLite(t, initialVersion)));\n const tableName = liteTableName(t);\n for (const [colName, colSpec] of Object.entries(t.columns)) {\n columnMetadata.insert(tableName, colName, colSpec);\n }\n }\n}\n\nfunction createLiteIndices(lc: LogContext, tx: Database, indices: IndexSpec[]) {\n for (const [i, index] of indices.entries()) {\n const stmt = createLiteIndexStatement(mapPostgresToLiteIndex(index));\n lc.info?.(`Creating index ${i + 1}/${indices.length}: ${stmt}`);\n const start = performance.now();\n tx.exec(stmt);\n lc.info?.(\n `Created index ${i + 1}/${indices.length} ` +\n `(${(performance.now() - start).toFixed(3)} ms): ${stmt}`,\n );\n }\n}\n\n/**\n * Runs structural assertions over a just-synced replica and throws if any\n * fail. Only called in shadow mode — a successful return means the replica\n * is schema-complete, row-count consistent, and its column metadata is in\n * sync with its lite schema.\n *\n * Note: this intentionally does NOT verify ZQL-queryability. Tables that\n * `computeZqlSpecs` drops (no PK / no all-NOT-NULL unique index, unsupported\n * column types, etc.) are silently skipped in production too — there's\n * nothing shadow-specific about them, so failing here would diverge from\n * prod over an upstream-schema condition prod accepts.\n *\n * Exported for testing.\n */\nexport function verifyShadowReplica(\n lc: LogContext,\n db: Database,\n published: {tables: PublishedTableSpec[]; indexes: IndexSpec[]},\n rowsByTable: ReadonlyMap<string, number>,\n): void {\n const issues: string[] = [];\n let columnsChecked = 0;\n let rowsChecked = 0;\n\n // 1. Schema completeness: every published table exists in the replica\n // with at least the expected column set.\n const liteTables = listTables(db);\n const liteTableByName = new Map(liteTables.map(t => [t.name, t]));\n for (const pt of published.tables) {\n const name = liteTableName(pt);\n const lite = liteTableByName.get(name);\n if (!lite) {\n issues.push(`missing table in replica: ${name}`);\n continue;\n }\n for (const col of Object.keys(pt.columns)) {\n columnsChecked++;\n if (!(col in lite.columns)) {\n issues.push(`column missing in replica table ${name}: ${col}`);\n }\n }\n }\n\n // Every published index exists in the replica.\n const liteIndexNames = new Set(listIndexes(db).map(i => i.name));\n for (const ix of published.indexes) {\n const mapped = mapPostgresToLiteIndex(ix);\n if (!liteIndexNames.has(mapped.name)) {\n issues.push(\n `missing index in replica: ${mapped.name} on ${mapped.tableName}`,\n );\n }\n }\n\n // 2. Row counts: SQLite COUNT(*) matches the in-memory copy counter.\n for (const [table, expected] of rowsByTable) {\n try {\n const [row] = db\n .prepare(`SELECT COUNT(*) as count FROM \"${table}\"`)\n .all<{count: number}>();\n if (row.count !== expected) {\n issues.push(\n `row count mismatch for table ${table}: ` +\n `copy counter reported ${expected}, replica has ${row.count}`,\n );\n } else {\n rowsChecked += row.count;\n }\n } catch (e) {\n issues.push(`could not count rows in table ${table}: ${String(e)}`);\n }\n }\n\n // 3. Column metadata: every published column has a _zero.column_metadata row.\n const meta = must(ColumnMetadataStore.getInstance(db));\n for (const pt of published.tables) {\n const name = liteTableName(pt);\n const rows = meta.getTable(name);\n for (const col of Object.keys(pt.columns)) {\n if (!rows.has(col)) {\n issues.push(`missing column_metadata row for ${name}.${col}`);\n }\n }\n }\n\n if (issues.length) {\n throw new Error(\n `Shadow replica verification failed (${issues.length} issue(s)):\\n` +\n issues.map(i => ` - ${i}`).join('\\n'),\n );\n }\n\n lc.info?.(\n `Shadow replica verification passed: ` +\n `${published.tables.length} tables, ` +\n `${published.indexes.length} indexes, ` +\n `${columnsChecked} columns, ` +\n `${rowsChecked.toLocaleString()} rows`,\n );\n}\n\n// Verified empirically that batches of 50 seem to be the sweet spot,\n// similar to the report in https://sqlite.org/forum/forumpost/8878a512d3652655\n//\n// Exported for testing.\nexport const INSERT_BATCH_SIZE = 50;\n\nconst MB = 1024 * 1024;\nconst MAX_BUFFERED_ROWS = 10_000;\nconst BUFFERED_SIZE_THRESHOLD = 8 * MB;\n\nexport type DownloadStatements = {\n select: string;\n getTotalRows: string;\n getTotalBytes: string;\n};\n\n/**\n * Produces ` TABLESAMPLE BERNOULLI(n)` when `sampleRate` is < 1, else `''`.\n * Row-level Bernoulli sampling is used (rather than SYSTEM) because it\n * produces a more uniform sample and, unlike SYSTEM, still returns rows\n * for small tables at low rates.\n */\nfunction tableSampleClause(sampleRate: number | undefined): string {\n if (sampleRate === undefined || sampleRate >= 1) {\n return '';\n }\n // Round away float noise (e.g. 0.3 * 100 = 30.000000000000004) while still\n // preserving sub-integer rates like 0.001 (= 0.1%).\n const pct = parseFloat((sampleRate * 100).toFixed(6));\n return /*sql*/ ` TABLESAMPLE BERNOULLI(${pct})`;\n}\n\nfunction limitClause(maxRowsPerTable: number | undefined): string {\n return maxRowsPerTable !== undefined\n ? /*sql*/ ` LIMIT ${maxRowsPerTable}`\n : '';\n}\n\n/**\n * Returns the SELECT column expressions for binary COPY, casting columns\n * without a known binary decoder to `::text`.\n */\nexport function makeBinarySelectExprs(\n table: PublishedTableSpec,\n cols: string[],\n): string[] {\n return cols.map(col => {\n const spec = table.columns[col];\n return hasBinaryDecoder(spec) ? id(col) : `${id(col)}::text`;\n });\n}\n\nexport function makeDownloadStatements(\n table: PublishedTableSpec,\n cols: string[],\n sampleRate?: number | undefined,\n maxRowsPerTable?: number | undefined,\n selectExprs?: string[] | undefined,\n): DownloadStatements {\n const filterConditions = Object.values(table.publications)\n .map(({rowFilter}) => rowFilter)\n .filter(f => !!f); // remove nulls\n const where =\n filterConditions.length === 0\n ? ''\n : /*sql*/ `WHERE ${filterConditions.join(' OR ')}`;\n const sample = tableSampleClause(sampleRate);\n const limit = limitClause(maxRowsPerTable);\n const fromTable = /*sql*/ `FROM ${id(table.schema)}.${id(table.name)}${sample} ${where}`;\n const select = /*sql*/ `SELECT ${(selectExprs ?? cols.map(id)).join(',')} ${fromTable}${limit}`;\n if (limit) {\n // With LIMIT, wrap counts/sums in a subquery so they reflect the\n // capped rowset rather than the full (sampled) table.\n const bytesExpr = cols\n .map(col => `COALESCE(pg_column_size(${id(col)}), 0)`)\n .join(' + ');\n return {\n select,\n getTotalRows: /*sql*/ `SELECT COUNT(*)::bigint AS \"totalRows\" FROM (SELECT 1 AS _ ${fromTable}${limit}) s`,\n getTotalBytes: /*sql*/ `SELECT COALESCE(SUM(b), 0)::bigint AS \"totalBytes\" FROM (SELECT (${bytesExpr}) AS b ${fromTable}${limit}) s`,\n };\n }\n const totalBytes = `(${cols.map(col => `SUM(COALESCE(pg_column_size(${id(col)}), 0))`).join(' + ')})`;\n return {\n select,\n getTotalRows: /*sql*/ `SELECT COUNT(*) AS \"totalRows\" ${fromTable}`,\n getTotalBytes: /*sql*/ `SELECT ${totalBytes} AS \"totalBytes\" ${fromTable}`,\n };\n}\n\ntype DownloadState = {\n spec: PublishedTableSpec;\n status: DownloadStatus;\n};\n\ntype CopyFormat = 'binary' | 'text';\ntype InitialSyncMode = 'initial' | 'shadow';\n\ntype InitialSyncMetricAttrs = {\n syncMode: InitialSyncMode;\n copyFormat: CopyFormat;\n};\n\ntype InitialSyncRunMetricAttrs = {\n syncMode: InitialSyncMode;\n copyFormat: CopyFormat;\n result: 'success' | 'error';\n};\n\ntype CopyResult = {\n schema: string;\n table: string;\n replicaTable: string;\n syncMode: InitialSyncMode;\n copyFormat: CopyFormat;\n columnCount: number;\n rows: number;\n estimatedRows: number;\n estimatedBytes: number | undefined;\n flushMs: number;\n elapsedMs: number;\n sourceWaitMs: number;\n processingMs: number;\n copyBytes: number;\n};\n\nconst INITIAL_SYNC_DURATION_HISTOGRAM_BOUNDARIES_S = [\n 1, 2, 5, 10, 30, 60, 120, 300, 600, 1200, 2400, 3600, 7200,\n];\nexport const COPY_METRIC_BATCH_BYTES = 8 * 1024 * 1024;\nconst SLOW_COPY_FLUSH_MS = 10_000;\n\n// change-streamer imports this module before startOtelAuto() runs, so create\n// instruments lazily to avoid binding them to OTel's no-op meter provider.\nfunction initialSyncRuns() {\n return getOrCreateCounter(\n 'replication',\n 'initial_sync_runs',\n 'Initial sync runs, labeled by result.',\n );\n}\n\nfunction initialSyncDuration() {\n return initialSyncDurationHistogram(\n 'initial_sync_duration',\n 'Wall-clock duration of an initial sync run, labeled by result.',\n );\n}\n\nfunction initialSyncCopyDuration() {\n return initialSyncDurationHistogram(\n 'initial_sync_copy_duration',\n 'Wall-clock duration of the COPY phase for a successful initial sync run.',\n );\n}\n\nfunction initialSyncCopyOtherDuration() {\n return initialSyncDurationHistogram(\n 'initial_sync_copy_other_duration',\n 'Initial sync total duration excluding SQLite flush and index time for a successful run.',\n );\n}\n\nfunction initialSyncFlushDuration() {\n return initialSyncDurationHistogram(\n 'initial_sync_flush_duration',\n 'Total SQLite flush time for a successful initial sync run.',\n );\n}\n\nfunction initialSyncIndexDuration() {\n return initialSyncDurationHistogram(\n 'initial_sync_index_duration',\n 'SQLite index creation time for a successful initial sync run.',\n );\n}\n\nfunction initialSyncRows() {\n return getOrCreateCounter(\n 'replication',\n 'initial_sync_rows',\n 'Rows copied during successful initial sync runs.',\n );\n}\n\nfunction initialSyncCopyStream() {\n return getOrCreateCounter('replication', 'initial_sync_copy_stream', {\n description:\n 'PostgreSQL COPY stream bytes processed during initial sync, including in-progress and failed runs.',\n unit: 'bytes',\n });\n}\n\nfunction initialSyncCompletedCopyStream() {\n return getOrCreateCounter(\n 'replication',\n 'initial_sync_completed_copy_stream',\n {\n description:\n 'PostgreSQL COPY stream bytes processed during successful initial sync runs.',\n unit: 'bytes',\n },\n );\n}\n\nfunction initialSyncCopyChunks() {\n return getOrCreateCounter(\n 'replication',\n 'initial_sync_copy_chunks',\n 'PostgreSQL COPY stream chunks processed during initial sync.',\n );\n}\n\nexport function createCopyMetricBatcher(\n record: (bytes: number, chunks: number) => void,\n) {\n let bytes = 0;\n let chunks = 0;\n\n function flush() {\n if (chunks === 0) {\n return;\n }\n record(bytes, chunks);\n bytes = 0;\n chunks = 0;\n }\n\n return {\n add(chunkBytes: number) {\n bytes += chunkBytes;\n chunks++;\n if (bytes >= COPY_METRIC_BATCH_BYTES) {\n flush();\n }\n },\n flush,\n };\n}\n\nexport function initialSyncCopyMetrics(attrs: InitialSyncMetricAttrs) {\n const labels = initialSyncMetricAttrs(attrs);\n const copyStreamMetric = initialSyncCopyStream();\n const copyChunksMetric = initialSyncCopyChunks();\n return createCopyMetricBatcher((bytes, chunks) => {\n copyStreamMetric.add(bytes, labels);\n copyChunksMetric.add(chunks, labels);\n });\n}\n\nfunction initialSyncDurationHistogram(name: string, description: string) {\n return getOrCreateHistogram('replication', name, {\n description,\n unit: 's',\n bucketBoundaries: INITIAL_SYNC_DURATION_HISTOGRAM_BOUNDARIES_S,\n });\n}\n\nfunction initialSyncMetricAttrs(attrs: InitialSyncMetricAttrs) {\n return {\n sync_mode: attrs.syncMode,\n copy_format: attrs.copyFormat,\n };\n}\n\nfunction initialSyncRunMetricAttrs(attrs: InitialSyncRunMetricAttrs) {\n return {\n ...initialSyncMetricAttrs(attrs),\n result: attrs.result,\n };\n}\n\nfunction recordInitialSyncRunMetrics(\n stats: {\n durationMs: number;\n rows?: number | undefined;\n copyBytes?: number | undefined;\n copyMs?: number | undefined;\n copyOtherMs?: number | undefined;\n flushMs?: number | undefined;\n indexMs?: number | undefined;\n },\n attrs: InitialSyncRunMetricAttrs,\n) {\n const labels = initialSyncRunMetricAttrs(attrs);\n initialSyncRuns().add(1, labels);\n initialSyncDuration().recordMs(stats.durationMs, labels);\n if (attrs.result === 'success') {\n if (stats.copyMs !== undefined) {\n initialSyncCopyDuration().recordMs(stats.copyMs, labels);\n }\n if (stats.copyOtherMs !== undefined) {\n initialSyncCopyOtherDuration().recordMs(stats.copyOtherMs, labels);\n }\n if (stats.flushMs !== undefined) {\n initialSyncFlushDuration().recordMs(stats.flushMs, labels);\n }\n if (stats.indexMs !== undefined) {\n initialSyncIndexDuration().recordMs(stats.indexMs, labels);\n }\n if (stats.rows !== undefined && stats.rows > 0) {\n initialSyncRows().add(stats.rows, labels);\n }\n if (stats.copyBytes !== undefined && stats.copyBytes > 0) {\n initialSyncCompletedCopyStream().add(stats.copyBytes, labels);\n }\n }\n}\n\nfunction initialSyncCopySummary(\n results: readonly CopyResult[],\n copyMs: number,\n) {\n const totals = results.reduce(\n (acc, curr) => {\n acc.rows += curr.rows;\n acc.flushMs += curr.flushMs;\n acc.copyBytes += curr.copyBytes;\n return acc;\n },\n {\n rows: 0,\n flushMs: 0,\n copyBytes: 0,\n },\n );\n return {\n tables: results.length,\n rows: totals.rows,\n copyMs,\n flushMs: totals.flushMs,\n copyBytes: totals.copyBytes,\n };\n}\n\nfunction logSlowCopyFlush(\n lc: LogContext,\n details: {\n schema: string;\n table: string;\n replicaTable: string;\n syncMode: InitialSyncMode;\n copyFormat: CopyFormat;\n elapsedMs: number;\n flushedRows: number;\n flushedBytes: number;\n rows: number;\n copyBytes: number;\n },\n) {\n if (details.elapsedMs < SLOW_COPY_FLUSH_MS || details.flushedRows === 0) {\n return;\n }\n lc.info?.('initial-sync table copy slow flush', details);\n}\n\n// Exported for testing.\nexport async function getInitialDownloadState(\n lc: LogContext,\n sql: PostgresDB,\n spec: PublishedTableSpec,\n skipTotals: boolean,\n): Promise<DownloadState> {\n const start = performance.now();\n const table = liteTableName(spec);\n const columns = Object.keys(spec.columns);\n if (skipTotals) {\n // Shadow sync suppresses status events, so the pg_class\n // estimates would be computed and thrown away.\n return {\n spec,\n status: {table, columns, rows: 0, totalRows: 0, totalBytes: 0},\n };\n }\n // Use pg_class estimates instead of expensive COUNT(*) and\n // SUM(pg_column_size(...)) full table scans. The exact values are only\n // used for progress reporting, so estimates are sufficient.\n const qualifiedName = `${id(spec.schema)}.${id(spec.name)}`;\n const estimateResult = await sql<\n {totalRows: number; totalBytes: number}[]\n >`SELECT GREATEST(reltuples, 0)::float8 AS \"totalRows\",\n pg_table_size(oid)::float8 AS \"totalBytes\"\n FROM pg_class\n WHERE oid = ${qualifiedName}::regclass`;\n\n const {totalRows, totalBytes} = estimateResult[0] ?? {\n totalRows: 0,\n totalBytes: 0,\n };\n\n const state: DownloadState = {\n spec,\n status: {\n table,\n columns,\n rows: 0,\n totalRows,\n totalBytes,\n },\n };\n const elapsed = (performance.now() - start).toFixed(3);\n lc.info?.(`Computed initial download state for ${table} (${elapsed} ms)`, {\n state: state.status,\n });\n return state;\n}\n\nfunction copy(\n lc: LogContext,\n {spec: table, status}: DownloadState,\n dbClient: PostgresDB,\n from: PostgresTransaction,\n to: Database,\n textCopy: boolean,\n syncMode: InitialSyncMode,\n sampleRate?: number | undefined,\n maxRowsPerTable?: number | undefined,\n): Promise<CopyResult> {\n if (textCopy) {\n return copyText(\n lc,\n table,\n status,\n dbClient,\n from,\n to,\n syncMode,\n sampleRate,\n maxRowsPerTable,\n );\n }\n return copyBinary(\n lc,\n table,\n status,\n from,\n to,\n syncMode,\n sampleRate,\n maxRowsPerTable,\n );\n}\n\nasync function copyBinary(\n lc: LogContext,\n table: PublishedTableSpec,\n status: DownloadStatus,\n from: PostgresTransaction,\n to: Database,\n syncMode: InitialSyncMode,\n sampleRate?: number | undefined,\n maxRowsPerTable?: number | undefined,\n): Promise<CopyResult> {\n const start = performance.now();\n const copyFormat: CopyFormat = 'binary';\n const copyMetrics = initialSyncCopyMetrics({syncMode, copyFormat});\n let flushMs = 0;\n let copyBytes = 0;\n let processingMs = 0;\n\n const tableName = liteTableName(table);\n const orderedColumns = Object.entries(table.columns);\n\n const columnNames = orderedColumns.map(([c]) => c);\n const columnSpecs = orderedColumns.map(([_name, spec]) => spec);\n const insertColumnList = columnNames.map(c => id(c)).join(',');\n\n const valuesSql =\n columnNames.length > 0 ? `(${'?,'.repeat(columnNames.length - 1)}?)` : '()';\n const insertSql = /*sql*/ `\n INSERT INTO \"${tableName}\" (${insertColumnList}) VALUES ${valuesSql}`;\n const insertStmt = to.prepare(insertSql);\n const insertBatchStmt = to.prepare(\n insertSql + `,${valuesSql}`.repeat(INSERT_BATCH_SIZE - 1),\n );\n\n // Build SELECT with ::text casts for columns without a known binary decoder.\n const select = makeDownloadStatements(\n table,\n columnNames,\n sampleRate,\n maxRowsPerTable,\n makeBinarySelectExprs(table, columnNames),\n ).select;\n\n const decoders = orderedColumns.map(([, spec]) =>\n hasBinaryDecoder(spec) ? makeBinaryDecoder(spec) : textCastDecoder,\n );\n\n const valuesPerRow = columnSpecs.length;\n const valuesPerBatch = valuesPerRow * INSERT_BATCH_SIZE;\n\n const pendingValues: LiteValueType[] = Array.from({\n length: MAX_BUFFERED_ROWS * valuesPerRow,\n });\n let pendingRows = 0;\n let pendingSize = 0;\n\n function flush() {\n const flushStart = performance.now();\n const flushedRows = pendingRows;\n const flushedSize = pendingSize;\n\n let l = 0;\n for (; pendingRows > INSERT_BATCH_SIZE; pendingRows -= INSERT_BATCH_SIZE) {\n insertBatchStmt.run(pendingValues.slice(l, (l += valuesPerBatch)));\n }\n for (; pendingRows > 0; pendingRows--) {\n insertStmt.run(pendingValues.slice(l, (l += valuesPerRow)));\n }\n const flushedValues = flushedRows * valuesPerRow;\n for (let i = 0; i < flushedValues; i++) {\n pendingValues[i] = undefined as unknown as LiteValueType;\n }\n pendingSize = 0;\n status.rows += flushedRows;\n\n const elapsed = performance.now() - flushStart;\n flushMs += elapsed;\n lc.debug?.(\n `flushed ${flushedRows} ${tableName} rows (${flushedSize} bytes) in ${elapsed.toFixed(3)} ms`,\n );\n logSlowCopyFlush(lc, {\n schema: table.schema,\n table: table.name,\n replicaTable: tableName,\n syncMode,\n copyFormat,\n elapsedMs: elapsed,\n flushedRows,\n flushedBytes: flushedSize,\n rows: status.rows,\n copyBytes,\n });\n }\n\n const binaryParser = new BinaryCopyParser();\n let col = 0;\n\n lc.info?.(`Starting binary copy stream of ${tableName}:`, select);\n\n const copyStreamStart = performance.now();\n await pipeline(\n await from\n .unsafe(`COPY (${select}) TO STDOUT WITH (FORMAT binary)`)\n .readable(),\n new Writable({\n highWaterMark: BUFFERED_SIZE_THRESHOLD,\n\n write(\n chunk: Buffer,\n _encoding: string,\n callback: (error?: Error) => void,\n ) {\n const processingStart = performance.now();\n try {\n copyBytes += chunk.length;\n copyMetrics.add(chunk.length);\n for (const fieldBuf of binaryParser.parse(chunk)) {\n const fieldSize = fieldBuf === null ? 4 : fieldBuf.length;\n pendingSize += fieldSize;\n pendingValues[pendingRows * valuesPerRow + col] =\n fieldBuf === null ? null : decoders[col](fieldBuf);\n\n if (++col === decoders.length) {\n col = 0;\n if (\n ++pendingRows >= MAX_BUFFERED_ROWS - valuesPerRow ||\n pendingSize >= BUFFERED_SIZE_THRESHOLD\n ) {\n flush();\n }\n }\n }\n processingMs += performance.now() - processingStart;\n callback();\n } catch (e) {\n processingMs += performance.now() - processingStart;\n callback(e instanceof Error ? e : new Error(String(e)));\n }\n },\n\n final: (callback: (error?: Error) => void) => {\n const processingStart = performance.now();\n try {\n copyMetrics.flush();\n flush();\n processingMs += performance.now() - processingStart;\n callback();\n } catch (e) {\n processingMs += performance.now() - processingStart;\n callback(e instanceof Error ? e : new Error(String(e)));\n }\n },\n\n destroy(error, callback) {\n copyMetrics.flush();\n callback(error);\n },\n }),\n );\n\n const sourceWaitMs = Math.max(\n 0,\n performance.now() - copyStreamStart - processingMs,\n );\n const elapsed = performance.now() - start;\n const result = {\n schema: table.schema,\n table: table.name,\n replicaTable: tableName,\n syncMode,\n copyFormat,\n columnCount: columnNames.length,\n rows: status.rows,\n estimatedRows: status.totalRows,\n estimatedBytes: status.totalBytes,\n flushMs,\n elapsedMs: elapsed,\n sourceWaitMs,\n processingMs,\n copyBytes,\n } satisfies CopyResult;\n\n lc.info?.(\n `Finished copying ${status.rows} rows into ${tableName} ` +\n `(flush: ${flushMs.toFixed(3)} ms) (total: ${elapsed.toFixed(3)} ms) `,\n result,\n );\n return result;\n}\n\nasync function copyText(\n lc: LogContext,\n table: PublishedTableSpec,\n status: DownloadStatus,\n dbClient: PostgresDB,\n from: PostgresTransaction,\n to: Database,\n syncMode: InitialSyncMode,\n sampleRate?: number | undefined,\n maxRowsPerTable?: number | undefined,\n): Promise<CopyResult> {\n const start = performance.now();\n const copyFormat: CopyFormat = 'text';\n const copyMetrics = initialSyncCopyMetrics({syncMode, copyFormat});\n let flushMs = 0;\n let copyBytes = 0;\n let processingMs = 0;\n\n const tableName = liteTableName(table);\n const orderedColumns = Object.entries(table.columns);\n\n const columnNames = orderedColumns.map(([c]) => c);\n const columnSpecs = orderedColumns.map(([_name, spec]) => spec);\n const insertColumnList = columnNames.map(c => id(c)).join(',');\n\n const valuesSql =\n columnNames.length > 0 ? `(${'?,'.repeat(columnNames.length - 1)}?)` : '()';\n const insertSql = /*sql*/ `\n INSERT INTO \"${tableName}\" (${insertColumnList}) VALUES ${valuesSql}`;\n const insertStmt = to.prepare(insertSql);\n const insertBatchStmt = to.prepare(\n insertSql + `,${valuesSql}`.repeat(INSERT_BATCH_SIZE - 1),\n );\n\n const {select} = makeDownloadStatements(\n table,\n columnNames,\n sampleRate,\n maxRowsPerTable,\n );\n const valuesPerRow = columnSpecs.length;\n const valuesPerBatch = valuesPerRow * INSERT_BATCH_SIZE;\n\n const pendingValues: LiteValueType[] = Array.from({\n length: MAX_BUFFERED_ROWS * valuesPerRow,\n });\n let pendingRows = 0;\n let pendingSize = 0;\n\n function flush() {\n const flushStart = performance.now();\n const flushedRows = pendingRows;\n const flushedSize = pendingSize;\n\n let l = 0;\n for (; pendingRows > INSERT_BATCH_SIZE; pendingRows -= INSERT_BATCH_SIZE) {\n insertBatchStmt.run(pendingValues.slice(l, (l += valuesPerBatch)));\n }\n for (; pendingRows > 0; pendingRows--) {\n insertStmt.run(pendingValues.slice(l, (l += valuesPerRow)));\n }\n const flushedValues = flushedRows * valuesPerRow;\n for (let i = 0; i < flushedValues; i++) {\n pendingValues[i] = undefined as unknown as LiteValueType;\n }\n pendingSize = 0;\n status.rows += flushedRows;\n\n const elapsed = performance.now() - flushStart;\n flushMs += elapsed;\n lc.debug?.(\n `flushed ${flushedRows} ${tableName} rows (${flushedSize} bytes) in ${elapsed.toFixed(3)} ms`,\n );\n logSlowCopyFlush(lc, {\n schema: table.schema,\n table: table.name,\n replicaTable: tableName,\n syncMode,\n copyFormat,\n elapsedMs: elapsed,\n flushedRows,\n flushedBytes: flushedSize,\n rows: status.rows,\n copyBytes,\n });\n }\n\n lc.info?.(`Starting text copy stream of ${tableName}:`, select);\n const pgParsers = await getTypeParsers(dbClient, {returnJsonAsString: true});\n const parsers = columnSpecs.map(c => {\n const pgParse = pgParsers.getTypeParser(c.typeOID);\n return (val: string) =>\n liteValue(\n pgParse(val) as PostgresValueType,\n c.dataType,\n JSON_STRINGIFIED,\n );\n });\n\n const tsvParser = new TsvParser();\n let col = 0;\n\n const copyStreamStart = performance.now();\n await pipeline(\n await from.unsafe(`COPY (${select}) TO STDOUT`).readable(),\n new Writable({\n highWaterMark: BUFFERED_SIZE_THRESHOLD,\n\n write(\n chunk: Buffer,\n _encoding: string,\n callback: (error?: Error) => void,\n ) {\n const processingStart = performance.now();\n try {\n copyBytes += chunk.length;\n copyMetrics.add(chunk.length);\n for (const text of tsvParser.parse(chunk)) {\n const fieldSize = text === null ? 4 : text.length;\n pendingSize += fieldSize;\n pendingValues[pendingRows * valuesPerRow + col] =\n text === null ? null : parsers[col](text);\n\n if (++col === parsers.length) {\n col = 0;\n if (\n ++pendingRows >= MAX_BUFFERED_ROWS - valuesPerRow ||\n pendingSize >= BUFFERED_SIZE_THRESHOLD\n ) {\n flush();\n }\n }\n }\n processingMs += performance.now() - processingStart;\n callback();\n } catch (e) {\n processingMs += performance.now() - processingStart;\n callback(e instanceof Error ? e : new Error(String(e)));\n }\n },\n\n final: (callback: (error?: Error) => void) => {\n const processingStart = performance.now();\n try {\n copyMetrics.flush();\n flush();\n processingMs += performance.now() - processingStart;\n callback();\n } catch (e) {\n processingMs += performance.now() - processingStart;\n callback(e instanceof Error ? e : new Error(String(e)));\n }\n },\n\n destroy(error, callback) {\n copyMetrics.flush();\n callback(error);\n },\n }),\n );\n\n const sourceWaitMs = Math.max(\n 0,\n performance.now() - copyStreamStart - processingMs,\n );\n const elapsed = performance.now() - start;\n const result = {\n schema: table.schema,\n table: table.name,\n replicaTable: tableName,\n syncMode,\n copyFormat,\n columnCount: columnNames.length,\n rows: status.rows,\n estimatedRows: status.totalRows,\n estimatedBytes: status.totalBytes,\n flushMs,\n elapsedMs: elapsed,\n sourceWaitMs,\n processingMs,\n copyBytes,\n } satisfies CopyResult;\n lc.info?.(\n `Finished copying ${status.rows} rows into ${tableName} ` +\n `(flush: ${flushMs.toFixed(3)} ms) (total: ${elapsed.toFixed(3)} ms) `,\n result,\n );\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2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MAAM,kBAAkB,YAAY,IAAI;GACxC,IAAI;IACF,YAAY,MAAM;IAClB,MAAM;IACN,gBAAgB,YAAY,IAAI,IAAI;IACpC,SAAS;GACX,SAAS,GAAG;IACV,gBAAgB,YAAY,IAAI,IAAI;IACpC,SAAS,aAAa,QAAQ,IAAI,IAAI,MAAM,OAAO,CAAC,CAAC,CAAC;GACxD;EACF;EAEA,QAAQ,OAAO,UAAU;GACvB,YAAY,MAAM;GAClB,SAAS,KAAK;EAChB;CACF,CAAC,CACH;CAEA,MAAM,eAAe,KAAK,IACxB,GACA,YAAY,IAAI,IAAI,kBAAkB,YACxC;CACA,MAAM,UAAU,YAAY,IAAI,IAAI;CACpC,MAAM,SAAS;EACb,QAAQ,MAAM;EACd,OAAO,MAAM;EACb,cAAc;EACd;EACA;EACA,aAAa,YAAY;EACzB,MAAM,OAAO;EACb,eAAe,OAAO;EACtB,gBAAgB,OAAO;EACvB;EACA,WAAW;EACX;EACA;EACA;CACF;CACA,GAAG,OACD,oBAAoB,OAAO,KAAK,aAAa,UAAU,WAC1C,QAAQ,QAAQ,CAAC,EAAE,eAAe,QAAQ,QAAQ,CAAC,EAAE,QAClE,MACF;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"initial-sync.js","names":[],"sources":["../../../../../../../zero-cache/src/services/change-source/pg/initial-sync.ts"],"sourcesContent":["import {mkdtemp, rm} from 'node:fs/promises';\nimport {platform, tmpdir} from 'node:os';\nimport {join} from 'node:path';\nimport {Writable, type Readable} from 'node:stream';\nimport {pipeline} from 'node:stream/promises';\nimport type {LogContext} from '@rocicorp/logger';\nimport {assert} from '../../../../../shared/src/asserts.ts';\nimport type {JSONObject} from '../../../../../shared/src/bigint-json.ts';\nimport {must} from '../../../../../shared/src/must.ts';\nimport {equals} from '../../../../../shared/src/set-utils.ts';\nimport type {DownloadStatus} from '../../../../../zero-events/src/status.ts';\nimport {Database} from '../../../../../zqlite/src/db.ts';\nimport {\n createLiteIndexStatement,\n createLiteTableStatement,\n} from '../../../db/create.ts';\nimport {listIndexes, listTables} from '../../../db/lite-tables.ts';\nimport * as Mode from '../../../db/mode-enum.ts';\nimport {\n BinaryCopyParser,\n hasBinaryDecoder,\n makeBinaryDecoder,\n textCastDecoder,\n} from '../../../db/pg-copy-binary.ts';\nimport {TsvParser} from '../../../db/pg-copy.ts';\nimport {\n mapPostgresToLite,\n mapPostgresToLiteIndex,\n} from '../../../db/pg-to-lite.ts';\nimport {getTypeParsers} from '../../../db/pg-type-parser.ts';\nimport {runTx} from '../../../db/run-transaction.ts';\nimport type {IndexSpec, PublishedTableSpec} from '../../../db/specs.ts';\nimport {importSnapshot, TransactionPool} from '../../../db/transaction-pool.ts';\nimport {\n getOrCreateCounter,\n getOrCreateHistogram,\n} from '../../../observability/metrics.ts';\nimport {\n JSON_STRINGIFIED,\n liteValue,\n type LiteValueType,\n} from '../../../types/lite.ts';\nimport {liteTableName} from '../../../types/names.ts';\nimport {PG_15, PG_17} from '../../../types/pg-versions.ts';\nimport {\n connectPgClient,\n type PostgresDB,\n type PostgresTransaction,\n type PostgresValueType,\n} from '../../../types/pg.ts';\nimport {CpuProfiler} from '../../../types/profiler.ts';\nimport type {ShardConfig} from '../../../types/shards.ts';\nimport {ALLOWED_APP_ID_CHARACTERS} from '../../../types/shards.ts';\nimport {id} from '../../../types/sql.ts';\nimport {ReplicationStatusPublisher} from '../../replicator/replication-status.ts';\nimport {ColumnMetadataStore} from '../../replicator/schema/column-metadata.ts';\nimport {initReplicationState} from '../../replicator/schema/replication-state.ts';\nimport {publicationRowFilter} from './backfill-resume.ts';\nimport {toStateVersionString} from './lsn.ts';\nimport {createReplicaAndSlot} from './replication-slots.ts';\nimport {ensureShardSchema} from './schema/init.ts';\nimport {getPublicationInfo, warnForSkippedIndexes} from './schema/published.ts';\nimport {\n dropShard,\n getInternalShardConfig,\n getReplicaState,\n initReplica,\n validatePublications,\n type ReplicaState,\n} from './schema/shard.ts';\n\nexport type InitialSyncOptions = {\n tableCopyWorkers: number;\n profileCopy?: boolean | undefined;\n textCopy?: boolean | undefined;\n replicationSlotFailover?: boolean | undefined;\n installPartialIndexTriggers?: boolean | undefined;\n /**\n * When set, run initial sync in \"shadow\" mode for verification: skip all\n * upstream mutations (no replication slot, no addReplica, no dropShard, no\n * slot drop on failure), suppress status events, and optionally sample\n * rows from each table via TABLESAMPLE BERNOULLI + LIMIT. The caller is\n * responsible for providing (and discarding) a throwaway SQLite `tx`.\n */\n shadow?:\n | {\n /** 0 < rate <= 1. When 1, no TABLESAMPLE clause is added. */\n sampleRate: number;\n /**\n * LIMIT N cap appended after TABLESAMPLE. Required: shadow sync is\n * for verification only, so every run must commit to a row budget.\n */\n maxRowsPerTable: number;\n }\n | undefined;\n};\n\nexport type ReplicaOptions = {\n backupV5: boolean;\n};\n\n/** Server context to store with the initial sync metadata for debugging. */\nexport type ServerContext = JSONObject;\n\n/**\n * @returns The {@link ReplicaState} of the initialized replica, or `undefined`\n * for a shadow sync.\n */\nexport async function initialSync(\n lc: LogContext,\n shard: ShardConfig,\n tx: Database,\n upstreamURI: string,\n syncOptions: InitialSyncOptions,\n context: ServerContext,\n {backupV5}: ReplicaOptions = {backupV5: true},\n): Promise<ReplicaState | undefined> {\n if (!ALLOWED_APP_ID_CHARACTERS.test(shard.appID)) {\n throw new Error(\n 'The App ID may only consist of lower-case letters, numbers, and the underscore character',\n );\n }\n const {\n tableCopyWorkers,\n profileCopy,\n textCopy = false,\n replicationSlotFailover = false,\n installPartialIndexTriggers = true,\n shadow,\n } = syncOptions;\n const syncMode: InitialSyncMode = shadow ? 'shadow' : 'initial';\n const copyFormat: CopyFormat = textCopy ? 'text' : 'binary';\n const start = performance.now();\n let sql: PostgresDB | undefined;\n const replicaID = Date.now().toString();\n let slotName: string | undefined; // undefined === shadow\n let slotSession: Readable | undefined; // undefined === shadow\n const statusPublisher = ReplicationStatusPublisher.forRunningTransaction(\n tx,\n shadow ? async () => {} : undefined,\n ).publish(lc, 'Initializing');\n try {\n const copyProfiler = profileCopy ? await CpuProfiler.connect() : null;\n sql = await connectPgClient(lc, upstreamURI, 'initial-sync');\n const pgVersion = await checkUpstreamConfig(sql);\n\n // In shadow mode we assume the shard is already initialized and just\n // read back the existing publications. `ensurePublishedTables` would\n // otherwise run DDL and potentially call `dropShard`, which must never\n // happen during a shadow run.\n const {publications} = shadow\n ? await getInternalShardConfig(sql, shard)\n : await ensurePublishedTables(\n lc,\n sql,\n shard,\n installPartialIndexTriggers,\n );\n lc.info?.(`Upstream is setup with publications [${publications}]`);\n\n const {database, host} = sql.options;\n lc.info?.(\n shadow\n ? `acquiring exported snapshot on ${database}@${host} (shadow mode)`\n : `opening replication session to ${database}@${host}`,\n );\n\n // Captures the necessary information from the consistent snapshot\n // created for the new replication slot (or a suitable equivalent\n // for shadow sync).\n async function captureSnapshot(snapshot: string) {\n // Run up to MAX_WORKERS to copy of tables at the replication slot's snapshot.\n // Retrieve the published schema at the consistent_point.\n const published = await runTx(\n must(sql),\n async tx => {\n await tx.unsafe(/* sql*/ `SET TRANSACTION SNAPSHOT '${snapshot}'`);\n return getPublicationInfo(tx, publications);\n },\n {mode: Mode.READONLY},\n );\n warnForSkippedIndexes(lc, published);\n // Note: If this throws, initial-sync is aborted.\n validatePublications(lc, published);\n\n // Now that tables have been validated, kick off the copiers.\n const {tables, indexes} = published;\n const numTables = tables.length;\n if (platform() === 'win32' && tableCopyWorkers < numTables) {\n lc.warn?.(\n `Increasing the number of copy workers from ${tableCopyWorkers} to ` +\n `${numTables} to work around a Node/Postgres connection bug`,\n );\n }\n const numWorkers =\n platform() === 'win32'\n ? numTables\n : Math.min(tableCopyWorkers, numTables);\n\n const copyPool = await connectPgClient(\n lc,\n upstreamURI,\n 'initial-sync-copy-worker',\n {\n max: numWorkers,\n ['max_lifetime']: 120 * 60, // set a long (2h) limit for COPY streaming\n },\n );\n const copiers = await startTableCopyWorkers(\n lc,\n copyPool,\n snapshot,\n numWorkers,\n numTables,\n );\n return {\n published,\n tables,\n indexes,\n numTables,\n copyPool,\n copiers,\n };\n }\n\n let lsn: string;\n let snapshotResult: Awaited<ReturnType<typeof captureSnapshot>>;\n\n if (shadow) {\n const exported = await acquireExportedSnapshotForShadowSync(\n lc,\n upstreamURI,\n captureSnapshot,\n );\n lsn = exported.lsn;\n snapshotResult = exported.result;\n } else {\n const replication = await createReplicaAndSlot(\n lc,\n sql,\n 'initial-sync-replication-session',\n shard,\n replicaID,\n replicationSlotFailover && pgVersion >= PG_17,\n {\n // When backing up with litestream v5, a unique backup path is\n // required since the LTX format does not tolerate multiple writers\n // (and there are no v3 \"generations\" to workaround it).\n backupPath: backupV5 ? replicaID : null,\n backupV5,\n },\n captureSnapshot,\n );\n lsn = replication.slot.consistent_point;\n slotName = replication.slot.slot_name;\n snapshotResult = replication.capturedSnapshot;\n slotSession = replication.initialSession;\n }\n\n const {published, tables, indexes, numTables, copyPool, copiers} =\n snapshotResult;\n\n const initialVersion = toStateVersionString(lsn);\n initReplicationState(tx, publications, initialVersion, context);\n try {\n createLiteTables(tx, tables, initialVersion);\n const sampleRate = shadow?.sampleRate;\n const maxRowsPerTable = shadow?.maxRowsPerTable;\n const downloads = await Promise.all(\n tables.map(spec =>\n copiers.processReadTask((db, lc) =>\n getInitialDownloadState(lc, db, spec, shadow !== undefined),\n ),\n ),\n );\n statusPublisher.publish(\n lc,\n 'Initializing',\n `Copying ${numTables} upstream tables at version ${initialVersion}`,\n 5000,\n () => ({downloadStatus: downloads.map(({status}) => status)}),\n );\n\n void copyProfiler?.start();\n const copyStart = performance.now();\n const copyResults = await Promise.all(\n downloads.map(table =>\n copiers.processReadTask((db, lc) =>\n copy(\n lc,\n table,\n copyPool,\n db,\n tx,\n textCopy,\n syncMode,\n sampleRate,\n maxRowsPerTable,\n ),\n ),\n ),\n );\n const copyElapsed = performance.now() - copyStart;\n void copyProfiler?.stopAndDispose(lc, 'initial-copy');\n copiers.setDone();\n\n const copySummary = initialSyncCopySummary(copyResults, copyElapsed);\n\n statusPublisher.publish(\n lc,\n 'Indexing',\n `Creating ${indexes.length} indexes`,\n 5000,\n );\n const indexStart = performance.now();\n createLiteIndices(lc, tx, indexes);\n const index = performance.now() - indexStart;\n lc.info?.(`Created indexes (${index.toFixed(3)} ms)`);\n\n if (slotName && replicaID) {\n await initReplica(sql, shard, replicaID, published, context);\n } else {\n assert(shadow, 'expected to be in shadow sync if there is no slotName');\n const rowsByTable = new Map<string, number>();\n for (let i = 0; i < downloads.length; i++) {\n rowsByTable.set(downloads[i].status.table, copyResults[i].rows);\n }\n verifyShadowReplica(lc, tx, published, rowsByTable);\n }\n\n const elapsed = performance.now() - start;\n const copyOtherMs = Math.max(0, elapsed - copySummary.flushMs - index);\n recordInitialSyncRunMetrics(\n {\n durationMs: elapsed,\n rows: copySummary.rows,\n copyBytes: copySummary.copyBytes,\n copyMs: copySummary.copyMs,\n copyOtherMs,\n flushMs: copySummary.flushMs,\n indexMs: index,\n },\n {\n result: 'success',\n syncMode,\n copyFormat,\n },\n );\n lc.info?.(\n `Synced ${copySummary.rows.toLocaleString()} rows of ${numTables} tables in ${publications} up to ${lsn} ` +\n `(flush: ${copySummary.flushMs.toFixed(3)}, index: ${index.toFixed(3)}, total: ${elapsed.toFixed(3)} ms)`,\n {\n syncMode,\n copyFormat,\n publications,\n lsn,\n ...copySummary,\n indexes: indexes.length,\n indexMs: index,\n copyOtherMs,\n totalMs: elapsed,\n },\n );\n\n return slotName && replicaID\n ? must(\n await getReplicaState(sql, shard, replicaID),\n `Missing replica with id ${replicaID}`,\n )\n : undefined; // shadow sync only\n } finally {\n // All meaningful errors are handled at the processReadTask() call site.\n void copyPool.end().catch(e => lc.warn?.(`Error closing copyPool`, e));\n }\n } catch (e) {\n recordInitialSyncRunMetrics(\n {durationMs: performance.now() - start},\n {\n result: 'error',\n syncMode,\n copyFormat,\n },\n );\n if (slotName && sql) {\n // If initial-sync did not succeed, make a best effort to drop the\n // orphaned replication slot to avoid running out of slots in\n // pathological cases that result in repeated failures.\n lc.warn?.(`dropping replication slot ${slotName}`, e);\n // release any initial replication session so the slot can be dropped\n slotSession?.destroy();\n await sql`\n SELECT pg_drop_replication_slot(slot_name) FROM pg_replication_slots\n WHERE slot_name = ${slotName};\n `.catch(e => lc.warn?.(`Unable to drop replication slot ${slotName}`, e));\n }\n throw await statusPublisher.publishAndThrowError(lc, 'Initializing', e);\n } finally {\n statusPublisher.stop();\n if (sql) {\n await sql.end();\n }\n }\n}\n\nexport type ShadowSyncOptions = {\n sampleRate: number;\n maxRowsPerTable: number;\n /**\n * Parent directory for the throwaway SQLite replica. Defaults to the OS\n * tmpdir. Primarily for tests that need to isolate the scratch directory.\n */\n parentDir?: string | undefined;\n};\n\n/**\n * Exercises the initial-sync code path against a sample of rows from every\n * published table, writing into a throwaway SQLite database that is deleted\n * when the run ends. Produces zero upstream mutations: no replication slot,\n * no `addReplica`, no `dropShard`, no status events.\n *\n * Intended to be invoked periodically so that if a customer ever needs a\n * full reset, we have recent confidence that `initialSync` still works.\n * The shard must already be initialized upstream.\n */\nexport async function shadowInitialSync(\n lc: LogContext,\n shard: ShardConfig,\n upstreamURI: string,\n shadow: ShadowSyncOptions,\n context: ServerContext,\n syncOptions?: Pick<InitialSyncOptions, 'textCopy'>,\n): Promise<void> {\n const dir = await mkdtemp(\n join(shadow.parentDir ?? tmpdir(), 'zero-shadow-sync-'),\n );\n const dbPath = join(dir, 'shadow-replica.db');\n const db = new Database(lc, dbPath);\n try {\n await initialSync(\n lc,\n shard,\n db,\n upstreamURI,\n {\n // Shadow sync copies small samples, so one worker is plenty —\n // no reason to burn additional upstream connections.\n tableCopyWorkers: 1,\n textCopy: syncOptions?.textCopy,\n shadow,\n },\n context,\n );\n } finally {\n try {\n db.close();\n } catch (e) {\n lc.warn?.(`Error closing shadow replica db`, e);\n }\n await rm(dir, {recursive: true, force: true}).catch(e =>\n lc.warn?.(`Error cleaning up shadow replica dir ${dir}`, e),\n );\n }\n}\n\nasync function checkUpstreamConfig(sql: PostgresDB) {\n const {walLevel, version} = (\n await sql<{walLevel: string; version: number}[]>`\n SELECT current_setting('wal_level') as \"walLevel\", \n current_setting('server_version_num') as \"version\";\n `\n )[0];\n\n if (walLevel !== 'logical') {\n throw new Error(\n `Postgres must be configured with \"wal_level = logical\" (currently: \"${walLevel})`,\n );\n }\n if (version < PG_15) {\n throw new Error(\n `Must be running Postgres 15 or higher (currently: \"${version}\")`,\n );\n }\n return version;\n}\n\nasync function ensurePublishedTables(\n lc: LogContext,\n sql: PostgresDB,\n shard: ShardConfig,\n installPartialIndexTriggers: boolean,\n validate = true,\n): Promise<{publications: string[]}> {\n const {database, host} = sql.options;\n lc.info?.(`Ensuring upstream PUBLICATION on ${database}@${host}`);\n\n // Technically, ensureShardSchema() is already called by\n // initializePostgresChangeSource, so the call here is redundant\n // but harmless. On the contrary, it makes initial sync more\n // self-contained (for test setup), and also plays a role in\n // recovering from corruption (below) after the shard is dropped.\n await ensureShardSchema(lc, sql, shard, installPartialIndexTriggers);\n const {publications} = await getInternalShardConfig(sql, shard);\n\n if (validate) {\n let valid = false;\n const nonInternalPublications = publications.filter(\n p => !p.startsWith('_'),\n );\n const exists = await sql`\n SELECT pubname FROM pg_publication WHERE pubname IN ${sql(publications)}\n `.values();\n if (exists.length !== publications.length) {\n lc.warn?.(\n `some configured publications [${publications}] are missing: ` +\n `[${exists.flat()}]. resyncing`,\n );\n } else if (\n !equals(new Set(shard.publications), new Set(nonInternalPublications))\n ) {\n lc.warn?.(\n `requested publications [${shard.publications}] differ from previous` +\n `publications [${nonInternalPublications}]. resyncing`,\n );\n } else {\n valid = true;\n }\n if (!valid) {\n await sql.unsafe(dropShard(shard.appID, shard.shardNum));\n return ensurePublishedTables(\n lc,\n sql,\n shard,\n installPartialIndexTriggers,\n false,\n );\n }\n }\n return {publications};\n}\n\nasync function startTableCopyWorkers(\n lc: LogContext,\n db: PostgresDB,\n snapshot: string,\n numWorkers: number,\n numTables: number,\n): Promise<TransactionPool> {\n const {init, imported} = importSnapshot(snapshot);\n const tableCopiers = new TransactionPool(lc, {\n mode: Mode.READONLY,\n init,\n initialWorkers: numWorkers,\n });\n tableCopiers.run(db);\n\n // Wait for all workers to run the importSnapshot() init task before\n // proceeding (to allow the snapshot to be released).\n for (let i = 0; i < numWorkers; i++) {\n await imported.dequeue();\n }\n\n lc.info?.(`Started ${numWorkers} workers to copy ${numTables} tables`);\n\n if (parseInt(process.versions.node) < 22) {\n lc.warn?.(\n `\\n\\n\\n` +\n `Older versions of Node have a bug that results in an unresponsive\\n` +\n `Postgres connection after running certain combinations of COPY commands.\\n` +\n `If initial sync hangs, run zero-cache with Node v22+. This has the additional\\n` +\n `benefit of being consistent with the Node version run in the production container image.` +\n `\\n\\n\\n`,\n );\n }\n return tableCopiers;\n}\n\n/**\n * Shadow-mode alternative to `createReplicationSlot`: opens a dedicated\n * READ ONLY REPEATABLE READ transaction on a normal connection, exports the\n * snapshot and captures the current WAL LSN. Note that the LSN and snapshot\n * are not guaranteed to be consistent but it this is fine for shadow sync\n * where the LSN is not actually relied on for anything.\n */\nasync function acquireExportedSnapshotForShadowSync<T>(\n lc: LogContext,\n upstreamURI: string,\n captureSnapshot: (snapshot: string) => Promise<T>,\n): Promise<{\n lsn: string;\n result: T;\n}> {\n const holder = await connectPgClient(\n lc,\n upstreamURI,\n 'shadow-initial-sync-snapshot',\n {max: 1},\n );\n return holder.begin(Mode.READONLY, async tx => {\n const [{lsn, snapshot}] = await tx<{snapshot: string; lsn: string}[]>`\n SELECT pg_export_snapshot() AS snapshot,\n pg_current_wal_lsn()::text AS lsn`;\n const result = await captureSnapshot(snapshot);\n return {lsn, result};\n });\n}\n\nfunction createLiteTables(\n tx: Database,\n tables: PublishedTableSpec[],\n initialVersion: string,\n) {\n // TODO: Figure out how to reuse the ChangeProcessor here to avoid\n // duplicating the ColumnMetadata logic.\n const columnMetadata = must(ColumnMetadataStore.getInstance(tx));\n for (const t of tables) {\n tx.exec(createLiteTableStatement(mapPostgresToLite(t, initialVersion)));\n const tableName = liteTableName(t);\n for (const [colName, colSpec] of Object.entries(t.columns)) {\n columnMetadata.insert(tableName, colName, colSpec);\n }\n }\n}\n\nfunction createLiteIndices(lc: LogContext, tx: Database, indices: IndexSpec[]) {\n for (const [i, index] of indices.entries()) {\n const stmt = createLiteIndexStatement(mapPostgresToLiteIndex(index));\n lc.info?.(`Creating index ${i + 1}/${indices.length}: ${stmt}`);\n const start = performance.now();\n tx.exec(stmt);\n lc.info?.(\n `Created index ${i + 1}/${indices.length} ` +\n `(${(performance.now() - start).toFixed(3)} ms): ${stmt}`,\n );\n }\n}\n\n/**\n * Runs structural assertions over a just-synced replica and throws if any\n * fail. Only called in shadow mode — a successful return means the replica\n * is schema-complete, row-count consistent, and its column metadata is in\n * sync with its lite schema.\n *\n * Note: this intentionally does NOT verify ZQL-queryability. Tables that\n * `computeZqlSpecs` drops (no PK / no all-NOT-NULL unique index, unsupported\n * column types, etc.) are silently skipped in production too — there's\n * nothing shadow-specific about them, so failing here would diverge from\n * prod over an upstream-schema condition prod accepts.\n *\n * Exported for testing.\n */\nexport function verifyShadowReplica(\n lc: LogContext,\n db: Database,\n published: {tables: PublishedTableSpec[]; indexes: IndexSpec[]},\n rowsByTable: ReadonlyMap<string, number>,\n): void {\n const issues: string[] = [];\n let columnsChecked = 0;\n let rowsChecked = 0;\n\n // 1. Schema completeness: every published table exists in the replica\n // with at least the expected column set.\n const liteTables = listTables(db);\n const liteTableByName = new Map(liteTables.map(t => [t.name, t]));\n for (const pt of published.tables) {\n const name = liteTableName(pt);\n const lite = liteTableByName.get(name);\n if (!lite) {\n issues.push(`missing table in replica: ${name}`);\n continue;\n }\n for (const col of Object.keys(pt.columns)) {\n columnsChecked++;\n if (!(col in lite.columns)) {\n issues.push(`column missing in replica table ${name}: ${col}`);\n }\n }\n }\n\n // Every published index exists in the replica.\n const liteIndexNames = new Set(listIndexes(db).map(i => i.name));\n for (const ix of published.indexes) {\n const mapped = mapPostgresToLiteIndex(ix);\n if (!liteIndexNames.has(mapped.name)) {\n issues.push(\n `missing index in replica: ${mapped.name} on ${mapped.tableName}`,\n );\n }\n }\n\n // 2. Row counts: SQLite COUNT(*) matches the in-memory copy counter.\n for (const [table, expected] of rowsByTable) {\n try {\n const [row] = db\n .prepare(`SELECT COUNT(*) as count FROM \"${table}\"`)\n .all<{count: number}>();\n if (row.count !== expected) {\n issues.push(\n `row count mismatch for table ${table}: ` +\n `copy counter reported ${expected}, replica has ${row.count}`,\n );\n } else {\n rowsChecked += row.count;\n }\n } catch (e) {\n issues.push(`could not count rows in table ${table}: ${String(e)}`);\n }\n }\n\n // 3. Column metadata: every published column has a _zero.column_metadata row.\n const meta = must(ColumnMetadataStore.getInstance(db));\n for (const pt of published.tables) {\n const name = liteTableName(pt);\n const rows = meta.getTable(name);\n for (const col of Object.keys(pt.columns)) {\n if (!rows.has(col)) {\n issues.push(`missing column_metadata row for ${name}.${col}`);\n }\n }\n }\n\n if (issues.length) {\n throw new Error(\n `Shadow replica verification failed (${issues.length} issue(s)):\\n` +\n issues.map(i => ` - ${i}`).join('\\n'),\n );\n }\n\n lc.info?.(\n `Shadow replica verification passed: ` +\n `${published.tables.length} tables, ` +\n `${published.indexes.length} indexes, ` +\n `${columnsChecked} columns, ` +\n `${rowsChecked.toLocaleString()} rows`,\n );\n}\n\n// Verified empirically that batches of 50 seem to be the sweet spot,\n// similar to the report in https://sqlite.org/forum/forumpost/8878a512d3652655\n//\n// Exported for testing.\nexport const INSERT_BATCH_SIZE = 50;\n\nconst MB = 1024 * 1024;\nconst MAX_BUFFERED_ROWS = 10_000;\nconst BUFFERED_SIZE_THRESHOLD = 8 * MB;\n\nexport type DownloadStatements = {\n select: string;\n getTotalRows: string;\n getTotalBytes: string;\n};\n\n/**\n * Produces ` TABLESAMPLE BERNOULLI(n)` when `sampleRate` is < 1, else `''`.\n * Row-level Bernoulli sampling is used (rather than SYSTEM) because it\n * produces a more uniform sample and, unlike SYSTEM, still returns rows\n * for small tables at low rates.\n */\nfunction tableSampleClause(sampleRate: number | undefined): string {\n if (sampleRate === undefined || sampleRate >= 1) {\n return '';\n }\n // Round away float noise (e.g. 0.3 * 100 = 30.000000000000004) while still\n // preserving sub-integer rates like 0.001 (= 0.1%).\n const pct = parseFloat((sampleRate * 100).toFixed(6));\n return /*sql*/ ` TABLESAMPLE BERNOULLI(${pct})`;\n}\n\nfunction limitClause(maxRowsPerTable: number | undefined): string {\n return maxRowsPerTable !== undefined\n ? /*sql*/ ` LIMIT ${maxRowsPerTable}`\n : '';\n}\n\n/**\n * Returns the SELECT column expressions for binary COPY, casting columns\n * without a known binary decoder to `::text`.\n */\nexport function makeBinarySelectExprs(\n table: PublishedTableSpec,\n cols: string[],\n): string[] {\n return cols.map(col => {\n const spec = table.columns[col];\n return hasBinaryDecoder(spec) ? id(col) : `${id(col)}::text`;\n });\n}\n\n/**\n * Orders the downloaded rows, and optionally restricts them to a suffix of\n * that order. Used by resumable backfills; see `backfill-resume.ts`.\n */\nexport type DownloadOrder = {\n /** The `ORDER BY` expression, e.g. from `orderByRowKey()`. */\n readonly by: string;\n\n /**\n * A boolean SQL expression restricting the download to rows after a mark,\n * e.g. from `resumeWhere()`. It is ANDed with the publication row filter,\n * and applies to the row and byte totals as well, so that a resumed run\n * reports the progress of what remains.\n */\n readonly after?: string | undefined;\n};\n\nexport function makeDownloadStatements(\n table: PublishedTableSpec,\n cols: string[],\n sampleRate?: number | undefined,\n maxRowsPerTable?: number | undefined,\n selectExprs?: string[] | undefined,\n order?: DownloadOrder | undefined,\n): DownloadStatements {\n const publicationFilter = publicationRowFilter(table);\n const after = order?.after;\n const conditions =\n after === undefined\n ? publicationFilter\n : [\n ...(publicationFilter === null ? [] : [publicationFilter]),\n after,\n ].join(' AND ');\n const where = conditions === null ? '' : /*sql*/ `WHERE ${conditions}`;\n const sample = tableSampleClause(sampleRate);\n const limit = limitClause(maxRowsPerTable);\n const orderBy = order ? /*sql*/ ` ORDER BY ${order.by}` : '';\n const fromTable = /*sql*/ `FROM ${id(table.schema)}.${id(table.name)}${sample} ${where}`;\n const select = /*sql*/ `SELECT ${(selectExprs ?? cols.map(id)).join(',')} ${fromTable}${orderBy}${limit}`;\n if (limit) {\n // With LIMIT, wrap counts/sums in a subquery so they reflect the\n // capped rowset rather than the full (sampled) table.\n const bytesExpr = cols\n .map(col => `COALESCE(pg_column_size(${id(col)}), 0)`)\n .join(' + ');\n return {\n select,\n getTotalRows: /*sql*/ `SELECT COUNT(*)::bigint AS \"totalRows\" FROM (SELECT 1 AS _ ${fromTable}${limit}) s`,\n getTotalBytes: /*sql*/ `SELECT COALESCE(SUM(b), 0)::bigint AS \"totalBytes\" FROM (SELECT (${bytesExpr}) AS b ${fromTable}${limit}) s`,\n };\n }\n const totalBytes = `(${cols.map(col => `SUM(COALESCE(pg_column_size(${id(col)}), 0))`).join(' + ')})`;\n return {\n select,\n getTotalRows: /*sql*/ `SELECT COUNT(*) AS \"totalRows\" ${fromTable}`,\n getTotalBytes: /*sql*/ `SELECT ${totalBytes} AS \"totalBytes\" ${fromTable}`,\n };\n}\n\ntype DownloadState = {\n spec: PublishedTableSpec;\n status: DownloadStatus;\n};\n\ntype CopyFormat = 'binary' | 'text';\ntype InitialSyncMode = 'initial' | 'shadow';\n\ntype InitialSyncMetricAttrs = {\n syncMode: InitialSyncMode;\n copyFormat: CopyFormat;\n};\n\ntype InitialSyncRunMetricAttrs = {\n syncMode: InitialSyncMode;\n copyFormat: CopyFormat;\n result: 'success' | 'error';\n};\n\ntype CopyResult = {\n schema: string;\n table: string;\n replicaTable: string;\n syncMode: InitialSyncMode;\n copyFormat: CopyFormat;\n columnCount: number;\n rows: number;\n estimatedRows: number;\n estimatedBytes: number | undefined;\n flushMs: number;\n elapsedMs: number;\n sourceWaitMs: number;\n processingMs: number;\n copyBytes: number;\n};\n\nconst INITIAL_SYNC_DURATION_HISTOGRAM_BOUNDARIES_S = [\n 1, 2, 5, 10, 30, 60, 120, 300, 600, 1200, 2400, 3600, 7200,\n];\nexport const COPY_METRIC_BATCH_BYTES = 8 * 1024 * 1024;\nconst SLOW_COPY_FLUSH_MS = 10_000;\n\n// change-streamer imports this module before startOtelAuto() runs, so create\n// instruments lazily to avoid binding them to OTel's no-op meter provider.\nfunction initialSyncRuns() {\n return getOrCreateCounter(\n 'replication',\n 'initial_sync_runs',\n 'Initial sync runs, labeled by result.',\n );\n}\n\nfunction initialSyncDuration() {\n return initialSyncDurationHistogram(\n 'initial_sync_duration',\n 'Wall-clock duration of an initial sync run, labeled by result.',\n );\n}\n\nfunction initialSyncCopyDuration() {\n return initialSyncDurationHistogram(\n 'initial_sync_copy_duration',\n 'Wall-clock duration of the COPY phase for a successful initial sync run.',\n );\n}\n\nfunction initialSyncCopyOtherDuration() {\n return initialSyncDurationHistogram(\n 'initial_sync_copy_other_duration',\n 'Initial sync total duration excluding SQLite flush and index time for a successful run.',\n );\n}\n\nfunction initialSyncFlushDuration() {\n return initialSyncDurationHistogram(\n 'initial_sync_flush_duration',\n 'Total SQLite flush time for a successful initial sync run.',\n );\n}\n\nfunction initialSyncIndexDuration() {\n return initialSyncDurationHistogram(\n 'initial_sync_index_duration',\n 'SQLite index creation time for a successful initial sync run.',\n );\n}\n\nfunction initialSyncRows() {\n return getOrCreateCounter(\n 'replication',\n 'initial_sync_rows',\n 'Rows copied during successful initial sync runs.',\n );\n}\n\nfunction initialSyncCopyStream() {\n return getOrCreateCounter('replication', 'initial_sync_copy_stream', {\n description:\n 'PostgreSQL COPY stream bytes processed during initial sync, including in-progress and failed runs.',\n unit: 'bytes',\n });\n}\n\nfunction initialSyncCompletedCopyStream() {\n return getOrCreateCounter(\n 'replication',\n 'initial_sync_completed_copy_stream',\n {\n description:\n 'PostgreSQL COPY stream bytes processed during successful initial sync runs.',\n unit: 'bytes',\n },\n );\n}\n\nfunction initialSyncCopyChunks() {\n return getOrCreateCounter(\n 'replication',\n 'initial_sync_copy_chunks',\n 'PostgreSQL COPY stream chunks processed during initial sync.',\n );\n}\n\nexport function createCopyMetricBatcher(\n record: (bytes: number, chunks: number) => void,\n) {\n let bytes = 0;\n let chunks = 0;\n\n function flush() {\n if (chunks === 0) {\n return;\n }\n record(bytes, chunks);\n bytes = 0;\n chunks = 0;\n }\n\n return {\n add(chunkBytes: number) {\n bytes += chunkBytes;\n chunks++;\n if (bytes >= COPY_METRIC_BATCH_BYTES) {\n flush();\n }\n },\n flush,\n };\n}\n\nexport function initialSyncCopyMetrics(attrs: InitialSyncMetricAttrs) {\n const labels = initialSyncMetricAttrs(attrs);\n const copyStreamMetric = initialSyncCopyStream();\n const copyChunksMetric = initialSyncCopyChunks();\n return createCopyMetricBatcher((bytes, chunks) => {\n copyStreamMetric.add(bytes, labels);\n copyChunksMetric.add(chunks, labels);\n });\n}\n\nfunction initialSyncDurationHistogram(name: string, description: string) {\n return getOrCreateHistogram('replication', name, {\n description,\n unit: 's',\n bucketBoundaries: INITIAL_SYNC_DURATION_HISTOGRAM_BOUNDARIES_S,\n });\n}\n\nfunction initialSyncMetricAttrs(attrs: InitialSyncMetricAttrs) {\n return {\n sync_mode: attrs.syncMode,\n copy_format: attrs.copyFormat,\n };\n}\n\nfunction initialSyncRunMetricAttrs(attrs: InitialSyncRunMetricAttrs) {\n return {\n ...initialSyncMetricAttrs(attrs),\n result: attrs.result,\n };\n}\n\nfunction recordInitialSyncRunMetrics(\n stats: {\n durationMs: number;\n rows?: number | undefined;\n copyBytes?: number | undefined;\n copyMs?: number | undefined;\n copyOtherMs?: number | undefined;\n flushMs?: number | undefined;\n indexMs?: number | undefined;\n },\n attrs: InitialSyncRunMetricAttrs,\n) {\n const labels = initialSyncRunMetricAttrs(attrs);\n initialSyncRuns().add(1, labels);\n initialSyncDuration().recordMs(stats.durationMs, labels);\n if (attrs.result === 'success') {\n if (stats.copyMs !== undefined) {\n initialSyncCopyDuration().recordMs(stats.copyMs, labels);\n }\n if (stats.copyOtherMs !== undefined) {\n initialSyncCopyOtherDuration().recordMs(stats.copyOtherMs, labels);\n }\n if (stats.flushMs !== undefined) {\n initialSyncFlushDuration().recordMs(stats.flushMs, labels);\n }\n if (stats.indexMs !== undefined) {\n initialSyncIndexDuration().recordMs(stats.indexMs, labels);\n }\n if (stats.rows !== undefined && stats.rows > 0) {\n initialSyncRows().add(stats.rows, labels);\n }\n if (stats.copyBytes !== undefined && stats.copyBytes > 0) {\n initialSyncCompletedCopyStream().add(stats.copyBytes, labels);\n }\n }\n}\n\nfunction initialSyncCopySummary(\n results: readonly CopyResult[],\n copyMs: number,\n) {\n const totals = results.reduce(\n (acc, curr) => {\n acc.rows += curr.rows;\n acc.flushMs += curr.flushMs;\n acc.copyBytes += curr.copyBytes;\n return acc;\n },\n {\n rows: 0,\n flushMs: 0,\n copyBytes: 0,\n },\n );\n return {\n tables: results.length,\n rows: totals.rows,\n copyMs,\n flushMs: totals.flushMs,\n copyBytes: totals.copyBytes,\n };\n}\n\nfunction logSlowCopyFlush(\n lc: LogContext,\n details: {\n schema: string;\n table: string;\n replicaTable: string;\n syncMode: InitialSyncMode;\n copyFormat: CopyFormat;\n elapsedMs: number;\n flushedRows: number;\n flushedBytes: number;\n rows: number;\n copyBytes: number;\n },\n) {\n if (details.elapsedMs < SLOW_COPY_FLUSH_MS || details.flushedRows === 0) {\n return;\n }\n lc.info?.('initial-sync table copy slow flush', details);\n}\n\n// Exported for testing.\nexport async function getInitialDownloadState(\n lc: LogContext,\n sql: PostgresDB,\n spec: PublishedTableSpec,\n skipTotals: boolean,\n): Promise<DownloadState> {\n const start = performance.now();\n const table = liteTableName(spec);\n const columns = Object.keys(spec.columns);\n if (skipTotals) {\n // Shadow sync suppresses status events, so the pg_class\n // estimates would be computed and thrown away.\n return {\n spec,\n status: {table, columns, rows: 0, totalRows: 0, totalBytes: 0},\n };\n }\n // Use pg_class estimates instead of expensive COUNT(*) and\n // SUM(pg_column_size(...)) full table scans. The exact values are only\n // used for progress reporting, so estimates are sufficient.\n const qualifiedName = `${id(spec.schema)}.${id(spec.name)}`;\n const estimateResult = await sql<\n {totalRows: number; totalBytes: number}[]\n >`SELECT GREATEST(reltuples, 0)::float8 AS \"totalRows\",\n pg_table_size(oid)::float8 AS \"totalBytes\"\n FROM pg_class\n WHERE oid = ${qualifiedName}::regclass`;\n\n const {totalRows, totalBytes} = estimateResult[0] ?? {\n totalRows: 0,\n totalBytes: 0,\n };\n\n const state: DownloadState = {\n spec,\n status: {\n table,\n columns,\n rows: 0,\n totalRows,\n totalBytes,\n },\n };\n const elapsed = (performance.now() - start).toFixed(3);\n lc.info?.(`Computed initial download state for ${table} (${elapsed} ms)`, {\n state: state.status,\n });\n return state;\n}\n\nfunction copy(\n lc: LogContext,\n {spec: table, status}: DownloadState,\n dbClient: PostgresDB,\n from: PostgresTransaction,\n to: Database,\n textCopy: boolean,\n syncMode: InitialSyncMode,\n sampleRate?: number | undefined,\n maxRowsPerTable?: number | undefined,\n): Promise<CopyResult> {\n if (textCopy) {\n return copyText(\n lc,\n table,\n status,\n dbClient,\n from,\n to,\n syncMode,\n sampleRate,\n maxRowsPerTable,\n );\n }\n return copyBinary(\n lc,\n table,\n status,\n from,\n to,\n syncMode,\n sampleRate,\n maxRowsPerTable,\n );\n}\n\nasync function copyBinary(\n lc: LogContext,\n table: PublishedTableSpec,\n status: DownloadStatus,\n from: PostgresTransaction,\n to: Database,\n syncMode: InitialSyncMode,\n sampleRate?: number | undefined,\n maxRowsPerTable?: number | undefined,\n): Promise<CopyResult> {\n const start = performance.now();\n const copyFormat: CopyFormat = 'binary';\n const copyMetrics = initialSyncCopyMetrics({syncMode, copyFormat});\n let flushMs = 0;\n let copyBytes = 0;\n let processingMs = 0;\n\n const tableName = liteTableName(table);\n const orderedColumns = Object.entries(table.columns);\n\n const columnNames = orderedColumns.map(([c]) => c);\n const columnSpecs = orderedColumns.map(([_name, spec]) => spec);\n const insertColumnList = columnNames.map(c => id(c)).join(',');\n\n const valuesSql =\n columnNames.length > 0 ? `(${'?,'.repeat(columnNames.length - 1)}?)` : '()';\n const insertSql = /*sql*/ `\n INSERT INTO \"${tableName}\" (${insertColumnList}) VALUES ${valuesSql}`;\n const insertStmt = to.prepare(insertSql);\n const insertBatchStmt = to.prepare(\n insertSql + `,${valuesSql}`.repeat(INSERT_BATCH_SIZE - 1),\n );\n\n // Build SELECT with ::text casts for columns without a known binary decoder.\n const select = makeDownloadStatements(\n table,\n columnNames,\n sampleRate,\n maxRowsPerTable,\n makeBinarySelectExprs(table, columnNames),\n ).select;\n\n const decoders = orderedColumns.map(([, spec]) =>\n hasBinaryDecoder(spec) ? makeBinaryDecoder(spec) : textCastDecoder,\n );\n\n const valuesPerRow = columnSpecs.length;\n const valuesPerBatch = valuesPerRow * INSERT_BATCH_SIZE;\n\n const pendingValues: LiteValueType[] = Array.from({\n length: MAX_BUFFERED_ROWS * valuesPerRow,\n });\n let pendingRows = 0;\n let pendingSize = 0;\n\n function flush() {\n const flushStart = performance.now();\n const flushedRows = pendingRows;\n const flushedSize = pendingSize;\n\n let l = 0;\n for (; pendingRows > INSERT_BATCH_SIZE; pendingRows -= INSERT_BATCH_SIZE) {\n insertBatchStmt.run(pendingValues.slice(l, (l += valuesPerBatch)));\n }\n for (; pendingRows > 0; pendingRows--) {\n insertStmt.run(pendingValues.slice(l, (l += valuesPerRow)));\n }\n const flushedValues = flushedRows * valuesPerRow;\n for (let i = 0; i < flushedValues; i++) {\n pendingValues[i] = undefined as unknown as LiteValueType;\n }\n pendingSize = 0;\n status.rows += flushedRows;\n\n const elapsed = performance.now() - flushStart;\n flushMs += elapsed;\n lc.debug?.(\n `flushed ${flushedRows} ${tableName} rows (${flushedSize} bytes) in ${elapsed.toFixed(3)} ms`,\n );\n logSlowCopyFlush(lc, {\n schema: table.schema,\n table: table.name,\n replicaTable: tableName,\n syncMode,\n copyFormat,\n elapsedMs: elapsed,\n flushedRows,\n flushedBytes: flushedSize,\n rows: status.rows,\n copyBytes,\n });\n }\n\n const binaryParser = new BinaryCopyParser();\n let col = 0;\n\n lc.info?.(`Starting binary copy stream of ${tableName}:`, select);\n\n const copyStreamStart = performance.now();\n await pipeline(\n await from\n .unsafe(`COPY (${select}) TO STDOUT WITH (FORMAT binary)`)\n .readable(),\n new Writable({\n highWaterMark: BUFFERED_SIZE_THRESHOLD,\n\n write(\n chunk: Buffer,\n _encoding: string,\n callback: (error?: Error) => void,\n ) {\n const processingStart = performance.now();\n try {\n copyBytes += chunk.length;\n copyMetrics.add(chunk.length);\n for (const fieldBuf of binaryParser.parse(chunk)) {\n const fieldSize = fieldBuf === null ? 4 : fieldBuf.length;\n pendingSize += fieldSize;\n pendingValues[pendingRows * valuesPerRow + col] =\n fieldBuf === null ? null : decoders[col](fieldBuf);\n\n if (++col === decoders.length) {\n col = 0;\n if (\n ++pendingRows >= MAX_BUFFERED_ROWS - valuesPerRow ||\n pendingSize >= BUFFERED_SIZE_THRESHOLD\n ) {\n flush();\n }\n }\n }\n processingMs += performance.now() - processingStart;\n callback();\n } catch (e) {\n processingMs += performance.now() - processingStart;\n callback(e instanceof Error ? e : new Error(String(e)));\n }\n },\n\n final: (callback: (error?: Error) => void) => {\n const processingStart = performance.now();\n try {\n copyMetrics.flush();\n flush();\n processingMs += performance.now() - processingStart;\n callback();\n } catch (e) {\n processingMs += performance.now() - processingStart;\n callback(e instanceof Error ? e : new Error(String(e)));\n }\n },\n\n destroy(error, callback) {\n copyMetrics.flush();\n callback(error);\n },\n }),\n );\n\n const sourceWaitMs = Math.max(\n 0,\n performance.now() - copyStreamStart - processingMs,\n );\n const elapsed = performance.now() - start;\n const result = {\n schema: table.schema,\n table: table.name,\n replicaTable: tableName,\n syncMode,\n copyFormat,\n columnCount: columnNames.length,\n rows: status.rows,\n estimatedRows: status.totalRows,\n estimatedBytes: status.totalBytes,\n flushMs,\n elapsedMs: elapsed,\n sourceWaitMs,\n processingMs,\n copyBytes,\n } satisfies CopyResult;\n\n lc.info?.(\n `Finished copying ${status.rows} rows into ${tableName} ` +\n `(flush: ${flushMs.toFixed(3)} ms) (total: ${elapsed.toFixed(3)} ms) `,\n result,\n );\n return result;\n}\n\nasync function copyText(\n lc: LogContext,\n table: PublishedTableSpec,\n status: DownloadStatus,\n dbClient: PostgresDB,\n from: PostgresTransaction,\n to: Database,\n syncMode: InitialSyncMode,\n sampleRate?: number | undefined,\n maxRowsPerTable?: number | undefined,\n): Promise<CopyResult> {\n const start = performance.now();\n const copyFormat: CopyFormat = 'text';\n const copyMetrics = initialSyncCopyMetrics({syncMode, copyFormat});\n let flushMs = 0;\n let copyBytes = 0;\n let processingMs = 0;\n\n const tableName = liteTableName(table);\n const orderedColumns = Object.entries(table.columns);\n\n const columnNames = orderedColumns.map(([c]) => c);\n const columnSpecs = orderedColumns.map(([_name, spec]) => spec);\n const insertColumnList = columnNames.map(c => id(c)).join(',');\n\n const valuesSql =\n columnNames.length > 0 ? `(${'?,'.repeat(columnNames.length - 1)}?)` : '()';\n const insertSql = /*sql*/ `\n INSERT INTO \"${tableName}\" (${insertColumnList}) VALUES ${valuesSql}`;\n const insertStmt = to.prepare(insertSql);\n const insertBatchStmt = to.prepare(\n insertSql + `,${valuesSql}`.repeat(INSERT_BATCH_SIZE - 1),\n );\n\n const {select} = makeDownloadStatements(\n table,\n columnNames,\n sampleRate,\n maxRowsPerTable,\n );\n const valuesPerRow = columnSpecs.length;\n const valuesPerBatch = valuesPerRow * INSERT_BATCH_SIZE;\n\n const pendingValues: LiteValueType[] = Array.from({\n length: MAX_BUFFERED_ROWS * valuesPerRow,\n });\n let pendingRows = 0;\n let pendingSize = 0;\n\n function flush() {\n const flushStart = performance.now();\n const flushedRows = pendingRows;\n const flushedSize = pendingSize;\n\n let l = 0;\n for (; pendingRows > INSERT_BATCH_SIZE; pendingRows -= INSERT_BATCH_SIZE) {\n insertBatchStmt.run(pendingValues.slice(l, (l += valuesPerBatch)));\n }\n for (; pendingRows > 0; pendingRows--) {\n insertStmt.run(pendingValues.slice(l, (l += valuesPerRow)));\n }\n const flushedValues = flushedRows * valuesPerRow;\n for (let i = 0; i < flushedValues; i++) {\n pendingValues[i] = undefined as unknown as LiteValueType;\n }\n pendingSize = 0;\n status.rows += flushedRows;\n\n const elapsed = performance.now() - flushStart;\n flushMs += elapsed;\n lc.debug?.(\n `flushed ${flushedRows} ${tableName} rows (${flushedSize} bytes) in ${elapsed.toFixed(3)} ms`,\n );\n logSlowCopyFlush(lc, {\n schema: table.schema,\n table: table.name,\n replicaTable: tableName,\n syncMode,\n copyFormat,\n elapsedMs: elapsed,\n flushedRows,\n flushedBytes: flushedSize,\n rows: status.rows,\n copyBytes,\n });\n }\n\n lc.info?.(`Starting text copy stream of ${tableName}:`, select);\n const pgParsers = await getTypeParsers(dbClient, {returnJsonAsString: true});\n const parsers = columnSpecs.map(c => {\n const pgParse = pgParsers.getTypeParser(c.typeOID);\n return (val: string) =>\n liteValue(\n pgParse(val) as PostgresValueType,\n c.dataType,\n JSON_STRINGIFIED,\n );\n });\n\n const tsvParser = new TsvParser();\n let col = 0;\n\n const copyStreamStart = performance.now();\n await pipeline(\n await from.unsafe(`COPY (${select}) TO STDOUT`).readable(),\n new Writable({\n highWaterMark: BUFFERED_SIZE_THRESHOLD,\n\n write(\n chunk: Buffer,\n _encoding: string,\n callback: (error?: Error) => void,\n ) {\n const processingStart = performance.now();\n try {\n copyBytes += chunk.length;\n copyMetrics.add(chunk.length);\n for (const text of tsvParser.parse(chunk)) {\n const fieldSize = text === null ? 4 : text.length;\n pendingSize += fieldSize;\n pendingValues[pendingRows * valuesPerRow + col] =\n text === null ? null : parsers[col](text);\n\n if (++col === parsers.length) {\n col = 0;\n if (\n ++pendingRows >= MAX_BUFFERED_ROWS - valuesPerRow ||\n pendingSize >= BUFFERED_SIZE_THRESHOLD\n ) {\n flush();\n }\n }\n }\n processingMs += performance.now() - processingStart;\n callback();\n } catch (e) {\n processingMs += performance.now() - processingStart;\n callback(e instanceof Error ? e : new Error(String(e)));\n }\n },\n\n final: (callback: (error?: Error) => void) => {\n const processingStart = performance.now();\n try {\n copyMetrics.flush();\n flush();\n processingMs += performance.now() - processingStart;\n callback();\n } catch (e) {\n processingMs += performance.now() - processingStart;\n callback(e instanceof Error ? e : new Error(String(e)));\n }\n },\n\n destroy(error, callback) {\n copyMetrics.flush();\n callback(error);\n },\n }),\n );\n\n const sourceWaitMs = Math.max(\n 0,\n performance.now() - copyStreamStart - processingMs,\n );\n const elapsed = performance.now() - start;\n const result = {\n schema: table.schema,\n table: table.name,\n replicaTable: tableName,\n syncMode,\n copyFormat,\n columnCount: columnNames.length,\n rows: status.rows,\n estimatedRows: status.totalRows,\n estimatedBytes: status.totalBytes,\n flushMs,\n elapsedMs: elapsed,\n sourceWaitMs,\n processingMs,\n copyBytes,\n } satisfies CopyResult;\n lc.info?.(\n `Finished copying ${status.rows} rows into ${tableName} ` +\n `(flush: ${flushMs.toFixed(3)} ms) (total: ${elapsed.toFixed(3)} ms) `,\n result,\n );\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,eAAsB,YACpB,IACA,OACA,IACA,aACA,aACA,SACA,EAAC,aAA4B,EAAC,UAAU,KAAI,GACT;CACnC,IAAI,CAAC,0BAA0B,KAAK,MAAM,KAAK,GAC7C,MAAM,IAAI,MACR,0FACF;CAEF,MAAM,EACJ,kBACA,aACA,WAAW,OACX,0BAA0B,OAC1B,8BAA8B,MAC9B,WACE;CACJ,MAAM,WAA4B,SAAS,WAAW;CACtD,MAAM,aAAyB,WAAW,SAAS;CACnD,MAAM,QAAQ,YAAY,IAAI;CAC9B,IAAI;CACJ,MAAM,YAAY,KAAK,IAAI,EAAE,SAAS;CACtC,IAAI;CACJ,IAAI;CACJ,MAAM,kBAAkB,2BAA2B,sBACjD,IACA,SAAS,YAAY,CAAC,IAAI,KAAA,CAC5B,EAAE,QAAQ,IAAI,cAAc;CAC5B,IAAI;EACF,MAAM,eAAe,cAAc,MAAM,YAAY,QAAQ,IAAI;EACjE,MAAM,MAAM,gBAAgB,IAAI,aAAa,cAAc;EAC3D,MAAM,YAAY,MAAM,oBAAoB,GAAG;EAM/C,MAAM,EAAC,iBAAgB,SACnB,MAAM,uBAAuB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;CACA,GAAG,OACD,oBAAoB,OAAO,KAAK,aAAa,UAAU,WAC1C,QAAQ,QAAQ,CAAC,EAAE,eAAe,QAAQ,QAAQ,CAAC,EAAE,QAClE,MACF;CACA,OAAO;AACT"}
@@ -0,0 +1,16 @@
1
+ import type { LogContext } from '@rocicorp/logger';
2
+ import type { PostgresDB } from '../../../types/pg.ts';
3
+ import type { ShardID } from '../../../types/shards.ts';
4
+ type Options = {
5
+ inactiveSlotCleanupTimeoutMs?: number | undefined;
6
+ pollIntervalMs?: number | undefined;
7
+ };
8
+ export declare class ReplicationSlotCleanupMonitor {
9
+ #private;
10
+ constructor(lc: LogContext, shard: ShardID, upstream: PostgresDB, upstreamPgServerVersionNum: number, currentSlot: string, { inactiveSlotCleanupTimeoutMs, pollIntervalMs }?: Options);
11
+ start(): void;
12
+ stop(): void;
13
+ getSlotsToCleanup(now: Date): Promise<string[]>;
14
+ }
15
+ export {};
16
+ //# sourceMappingURL=replication-slot-cleanup-monitor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replication-slot-cleanup-monitor.d.ts","sourceRoot":"","sources":["../../../../../../../zero-cache/src/services/change-source/pg/replication-slot-cleanup-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,sBAAsB,CAAC;AACrD,OAAO,KAAK,EAAC,OAAO,EAAC,MAAM,0BAA0B,CAAC;AAItD,KAAK,OAAO,GAAG;IACb,4BAA4B,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAClD,cAAc,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC,CAAC;AAKF,qBAAa,6BAA6B;;IAkCxC,YACE,EAAE,EAAE,UAAU,EACd,KAAK,EAAE,OAAO,EACd,QAAQ,EAAE,UAAU,EACpB,0BAA0B,EAAE,MAAM,EAClC,WAAW,EAAE,MAAM,EACnB,EAAC,4BAA4B,EAAE,cAAc,EAAC,GAAE,OAAY,EAW7D;IAED,KAAK,SAYJ;IAED,IAAI,SAIH;IAiBK,iBAAiB,CAAC,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAqEpD;CACF"}
@@ -0,0 +1,113 @@
1
+ import { replicationSlotPrefix } from "./schema/shard.js";
2
+ import "../../../types/pg-versions.js";
3
+ import { dropInactiveSlotsAndReplicas } from "./replication-slots.js";
4
+ //#region ../zero-cache/src/services/change-source/pg/replication-slot-cleanup-monitor.ts
5
+ var DEFAULT_INACTIVE_SLOT_CLEANUP_TIMEOUT_MS = 300 * 1e3;
6
+ var DEFAULT_POLL_INTERVAL_MS = 60 * 1e3;
7
+ var ReplicationSlotCleanupMonitor = class {
8
+ #lc;
9
+ /** The shard constrains which slots are monitored (e.g. zero_0_*). */
10
+ #shard;
11
+ #upstream;
12
+ /**
13
+ * This slot that this task is using. Cleanup of slots is predicated on
14
+ * this slot remaining active, in order to guarantee at least one healthy
15
+ * slot in the shard.
16
+ */
17
+ #currentSlot;
18
+ /**
19
+ * How long a slot is inactive (while the currentSlot is active) before it
20
+ * is eligible to be cleaned up. Because new slots are immediately connected
21
+ * to, even while an initial-sync or replica-restore is in progress, slots
22
+ * should only be inactive if no server is using it, or if a server was
23
+ * disconnected (e.g. a pg restart) and is in the process of reconnecting
24
+ * to it (see `keepSlotActiveUntilTakenOver`).
25
+ *
26
+ * As such, this timeout should be long enough to account for a server
27
+ * reconnecting to upstream. Note again that the cleanup monitor only runs
28
+ * while at least one replication slot is active, guaranteeing that upstream
29
+ * replication is working.
30
+ */
31
+ #inactiveSlotCleanupTimeoutMs;
32
+ #pollIntervalMs;
33
+ /** Manually tracked inactive times for PG < 17. null for PG 17+ */
34
+ #firstInactiveTimes;
35
+ #pollTimer;
36
+ constructor(lc, shard, upstream, upstreamPgServerVersionNum, currentSlot, { inactiveSlotCleanupTimeoutMs, pollIntervalMs } = {}) {
37
+ this.#lc = lc.withContext("component", "replication-slot-cleanup-monitor");
38
+ this.#shard = shard;
39
+ this.#upstream = upstream;
40
+ this.#currentSlot = currentSlot;
41
+ this.#inactiveSlotCleanupTimeoutMs = inactiveSlotCleanupTimeoutMs ?? DEFAULT_INACTIVE_SLOT_CLEANUP_TIMEOUT_MS;
42
+ this.#pollIntervalMs = pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
43
+ this.#firstInactiveTimes = upstreamPgServerVersionNum >= 17e4 ? null : /* @__PURE__ */ new Map();
44
+ }
45
+ start() {
46
+ if (this.#pollTimer) {
47
+ this.#lc.warn?.(`monitor already started`);
48
+ return;
49
+ }
50
+ this.#pollTimer = setInterval(() => this.#poll(/* @__PURE__ */ new Date()).catch((e) => this.#lc.warn?.(`error checking replication slots`, e)), this.#pollIntervalMs);
51
+ }
52
+ stop() {
53
+ clearInterval(this.#pollTimer);
54
+ this.#pollTimer = void 0;
55
+ this.#firstInactiveTimes?.clear();
56
+ }
57
+ async #poll(now) {
58
+ if (!this.#pollTimer) return;
59
+ const slots = await this.getSlotsToCleanup(now);
60
+ if (slots.length) await dropInactiveSlotsAndReplicas(this.#lc, this.#upstream, this.#shard, slots);
61
+ }
62
+ async getSlotsToCleanup(now) {
63
+ const slotPoolPrefix = replicationSlotPrefix(this.#shard);
64
+ const slotsToCleanUp = [];
65
+ const trackedInactiveTimes = this.#firstInactiveTimes;
66
+ if (trackedInactiveTimes) {
67
+ const shardSlots = await this.#upstream`
68
+ SELECT slot_name AS slot, active FROM pg_replication_slots
69
+ WHERE slot_name LIKE ${slotPoolPrefix + "%"};
70
+ `;
71
+ for (const { slot, active } of shardSlots) {
72
+ if (slot === this.#currentSlot && !active) {
73
+ this.#lc.warn?.(`current slot ${this.#currentSlot} is not active. disabling cleanup.`);
74
+ this.stop();
75
+ return [];
76
+ }
77
+ if (active) trackedInactiveTimes.delete(slot);
78
+ else {
79
+ const inactiveSince = trackedInactiveTimes.get(slot);
80
+ if (!inactiveSince) trackedInactiveTimes.set(slot, now);
81
+ else if (now.getTime() - inactiveSince.getTime() >= this.#inactiveSlotCleanupTimeoutMs) {
82
+ this.#lc.info?.(`slot ${slot} has been inactive since ${inactiveSince.toISOString()} and is eligible for cleanup`);
83
+ slotsToCleanUp.push(slot);
84
+ }
85
+ }
86
+ }
87
+ } else {
88
+ const expiration = now.getTime() - this.#inactiveSlotCleanupTimeoutMs;
89
+ const inactiveSlots = await this.#upstream`
90
+ SELECT slot_name AS slot, inactive_since AS "inactiveSince" FROM pg_replication_slots
91
+ WHERE slot_name LIKE ${slotPoolPrefix + "%"}
92
+ AND active = false
93
+ AND inactive_since IS NOT NULL;
94
+ `;
95
+ for (const { slot, inactiveSince } of inactiveSlots) {
96
+ if (slot === this.#currentSlot) {
97
+ this.#lc.warn?.(`current slot ${this.#currentSlot} is not active. disabling cleanup.`);
98
+ this.stop();
99
+ return [];
100
+ }
101
+ if (inactiveSince <= expiration) {
102
+ this.#lc.info?.(`slot ${slot} has been inactive since ${new Date(inactiveSince).toISOString()} and is eligible for cleanup`);
103
+ slotsToCleanUp.push(slot);
104
+ }
105
+ }
106
+ }
107
+ return slotsToCleanUp;
108
+ }
109
+ };
110
+ //#endregion
111
+ export { ReplicationSlotCleanupMonitor };
112
+
113
+ //# sourceMappingURL=replication-slot-cleanup-monitor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replication-slot-cleanup-monitor.js","names":["#lc","#shard","#upstream","#currentSlot","#inactiveSlotCleanupTimeoutMs","#pollIntervalMs","#firstInactiveTimes","#pollTimer","#poll"],"sources":["../../../../../../../zero-cache/src/services/change-source/pg/replication-slot-cleanup-monitor.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {PG_17} from '../../../types/pg-versions.ts';\nimport type {PostgresDB} from '../../../types/pg.ts';\nimport type {ShardID} from '../../../types/shards.ts';\nimport {dropInactiveSlotsAndReplicas} from './replication-slots.ts';\nimport {replicationSlotPrefix} from './schema/shard.ts';\n\ntype Options = {\n inactiveSlotCleanupTimeoutMs?: number | undefined;\n pollIntervalMs?: number | undefined;\n};\n\nconst DEFAULT_INACTIVE_SLOT_CLEANUP_TIMEOUT_MS = 5 * 60 * 1000;\nconst DEFAULT_POLL_INTERVAL_MS = 60 * 1000;\n\nexport class ReplicationSlotCleanupMonitor {\n readonly #lc: LogContext;\n\n /** The shard constrains which slots are monitored (e.g. zero_0_*). */\n readonly #shard: ShardID;\n readonly #upstream: PostgresDB;\n /**\n * This slot that this task is using. Cleanup of slots is predicated on\n * this slot remaining active, in order to guarantee at least one healthy\n * slot in the shard.\n */\n readonly #currentSlot: string;\n\n /**\n * How long a slot is inactive (while the currentSlot is active) before it\n * is eligible to be cleaned up. Because new slots are immediately connected\n * to, even while an initial-sync or replica-restore is in progress, slots\n * should only be inactive if no server is using it, or if a server was\n * disconnected (e.g. a pg restart) and is in the process of reconnecting\n * to it (see `keepSlotActiveUntilTakenOver`).\n *\n * As such, this timeout should be long enough to account for a server\n * reconnecting to upstream. Note again that the cleanup monitor only runs\n * while at least one replication slot is active, guaranteeing that upstream\n * replication is working.\n */\n readonly #inactiveSlotCleanupTimeoutMs: number;\n readonly #pollIntervalMs: number;\n\n /** Manually tracked inactive times for PG < 17. null for PG 17+ */\n readonly #firstInactiveTimes: Map<string, Date> | null;\n\n #pollTimer: NodeJS.Timeout | undefined;\n\n constructor(\n lc: LogContext,\n shard: ShardID,\n upstream: PostgresDB,\n upstreamPgServerVersionNum: number,\n currentSlot: string,\n {inactiveSlotCleanupTimeoutMs, pollIntervalMs}: Options = {},\n ) {\n this.#lc = lc.withContext('component', 'replication-slot-cleanup-monitor');\n this.#shard = shard;\n this.#upstream = upstream;\n this.#currentSlot = currentSlot;\n this.#inactiveSlotCleanupTimeoutMs =\n inactiveSlotCleanupTimeoutMs ?? DEFAULT_INACTIVE_SLOT_CLEANUP_TIMEOUT_MS;\n this.#pollIntervalMs = pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n this.#firstInactiveTimes =\n upstreamPgServerVersionNum >= PG_17 ? null : new Map();\n }\n\n start() {\n if (this.#pollTimer) {\n this.#lc.warn?.(`monitor already started`);\n return;\n }\n this.#pollTimer = setInterval(\n () =>\n this.#poll(new Date()).catch(e =>\n this.#lc.warn?.(`error checking replication slots`, e),\n ),\n this.#pollIntervalMs,\n );\n }\n\n stop() {\n clearInterval(this.#pollTimer);\n this.#pollTimer = undefined;\n this.#firstInactiveTimes?.clear();\n }\n\n async #poll(now: Date) {\n if (!this.#pollTimer) {\n return; // concurrently stopped\n }\n const slots = await this.getSlotsToCleanup(now);\n if (slots.length) {\n await dropInactiveSlotsAndReplicas(\n this.#lc,\n this.#upstream,\n this.#shard,\n slots,\n );\n }\n }\n\n async getSlotsToCleanup(now: Date): Promise<string[]> {\n const slotPoolPrefix = replicationSlotPrefix(this.#shard);\n\n const slotsToCleanUp: string[] = [];\n const trackedInactiveTimes = this.#firstInactiveTimes;\n\n if (trackedInactiveTimes) {\n // For PG <17, each poll tracks and updates earliest time the slot was\n // observed to be inactive.\n const shardSlots = await this.#upstream<{slot: string; active: boolean}[]>\n /*sql*/ `\n SELECT slot_name AS slot, active FROM pg_replication_slots\n WHERE slot_name LIKE ${slotPoolPrefix + '%'};\n `;\n for (const {slot, active} of shardSlots) {\n if (slot === this.#currentSlot && !active) {\n this.#lc.warn?.(\n `current slot ${this.#currentSlot} is not active. disabling cleanup.`,\n );\n this.stop();\n return [];\n }\n if (active) {\n trackedInactiveTimes.delete(slot);\n } else {\n const inactiveSince = trackedInactiveTimes.get(slot);\n if (!inactiveSince) {\n trackedInactiveTimes.set(slot, now);\n } else if (\n now.getTime() - inactiveSince.getTime() >=\n this.#inactiveSlotCleanupTimeoutMs\n ) {\n this.#lc.info?.(\n `slot ${slot} has been inactive since ${inactiveSince.toISOString()} and is eligible for cleanup`,\n );\n slotsToCleanUp.push(slot);\n }\n }\n }\n } else {\n // PG 17+ is simpler as inactivity time is tracked in the table.\n const expiration = now.getTime() - this.#inactiveSlotCleanupTimeoutMs;\n const inactiveSlots = await this.#upstream<\n {slot: string; inactiveSince: number}[]\n > /*sql*/ `\n SELECT slot_name AS slot, inactive_since AS \"inactiveSince\" FROM pg_replication_slots\n WHERE slot_name LIKE ${slotPoolPrefix + '%'}\n AND active = false\n AND inactive_since IS NOT NULL;\n `;\n for (const {slot, inactiveSince} of inactiveSlots) {\n if (slot === this.#currentSlot) {\n this.#lc.warn?.(\n `current slot ${this.#currentSlot} is not active. disabling cleanup.`,\n );\n this.stop();\n return [];\n }\n // The slot has been inactive since at or before the expiration cutoff\n // (now - timeout), i.e. inactive for at least the timeout duration.\n if (inactiveSince <= expiration) {\n this.#lc.info?.(\n `slot ${slot} has been inactive since ${new Date(inactiveSince).toISOString()} and is eligible for cleanup`,\n );\n slotsToCleanUp.push(slot);\n }\n }\n }\n return slotsToCleanUp;\n }\n}\n"],"mappings":";;;;AAYA,IAAM,2CAA2C,MAAS;AAC1D,IAAM,2BAA2B,KAAK;AAEtC,IAAa,gCAAb,MAA2C;CACzC;;CAGA;CACA;;;;;;CAMA;;;;;;;;;;;;;;CAeA;CACA;;CAGA;CAEA;CAEA,YACE,IACA,OACA,UACA,4BACA,aACA,EAAC,8BAA8B,mBAA2B,CAAC,GAC3D;EACA,KAAKA,MAAM,GAAG,YAAY,aAAa,kCAAkC;EACzE,KAAKC,SAAS;EACd,KAAKC,YAAY;EACjB,KAAKC,eAAe;EACpB,KAAKC,gCACH,gCAAgC;EAClC,KAAKC,kBAAkB,kBAAkB;EACzC,KAAKC,sBACH,8BAAA,OAAsC,uBAAO,IAAI,IAAI;CACzD;CAEA,QAAQ;EACN,IAAI,KAAKC,YAAY;GACnB,KAAKP,IAAI,OAAO,yBAAyB;GACzC;EACF;EACA,KAAKO,aAAa,kBAEd,KAAKC,sBAAM,IAAI,KAAK,CAAC,EAAE,OAAM,MAC3B,KAAKR,IAAI,OAAO,oCAAoC,CAAC,CACvD,GACF,KAAKK,eACP;CACF;CAEA,OAAO;EACL,cAAc,KAAKE,UAAU;EAC7B,K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A,IAAI,iBAAiB,YAAY;KAC/B,KAAKH,IAAI,OACP,QAAQ,KAAK,2BAA2B,IAAI,KAAK,aAAa,EAAE,YAAY,EAAE,6BAChF;KACA,eAAe,KAAK,IAAI;IAC1B;GACF;EACF;EACA,OAAO;CACT;AACF"}
@@ -63,20 +63,6 @@ export declare function createReplicationSlot(lc: LogContext, session: postgres.
63
63
  * in unit tests).
64
64
  */
65
65
  export declare function createReplicaAndSlot<T>(lc: LogContext, sql: PostgresDB, sessionName: string, shard: ShardID, replicaID: string, failover: boolean, backupOptions: BackupOptions, captureSnapshot: (snapshot: string) => Promise<T>): Promise<ReplicationSlotResult<T>>;
66
- /**
67
- * Deletes "old" replicas (i.e. those with a lower rank than the current)
68
- * and attempts to drop replication slots that are not associated with any
69
- * replica.
70
- *
71
- * If a slot could not be dropped because there is still an active subscriber,
72
- * it will be reflected in the `draining` count that is returned. When there
73
- * are draining slots, the method should be retried until all orphaned slots
74
- * have been dropped.
75
- */
76
- export declare function dropOldReplicasAndSlots(lc: LogContext, sql: PostgresDB, shard: ShardID, beforeRank: bigint): Promise<{
77
- dropped: number;
78
- active: number;
79
- draining: number;
80
- }>;
66
+ export declare function dropInactiveSlotsAndReplicas(lc: LogContext, sql: PostgresDB, shard: ShardID, slots: string[]): Promise<void>;
81
67
  export declare function slotPoolSuffix(n: number): string;
82
68
  //# sourceMappingURL=replication-slots.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"replication-slots.d.ts","sourceRoot":"","sources":["../../../../../../../zero-cache/src/services/change-source/pg/replication-slots.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,aAAa,CAAC;AAK1C,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,QAAQ,MAAM,UAAU,CAAC;AAErC,OAAO,EAAkB,KAAK,UAAU,EAAC,MAAM,sBAAsB,CAAC;AACtE,OAAO,EAAiB,KAAK,OAAO,EAAC,M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U,EACd,GAAG,EAAE,UAAU,EACf,KAAK,EAAE,OAAO,EACd,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAC,CAAC,CAY9D;AA+DD,wBAAgB,cAAc,CAAC,CAAC,EAAE,MAAM,UAUvC"}
1
+ {"version":3,"file":"replication-slots.d.ts","sourceRoot":"","sources":["../../../../../../../zero-cache/src/services/change-source/pg/replication-slots.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,aAAa,CAAC;AAK1C,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,QAAQ,MAAM,UAAU,CAAC;AAErC,OAAO,EAAkB,KAAK,UAAU,EAAC,MAAM,sBAAsB,CAAC;AACtE,OAAO,EAAiB,KAAK,OAAO,EAAC,MAAM,0BAA0B,CAAC;AAOtE,OAAO,EAKL,KAAK,aAAa,EACnB,MAAM,mBAAmB,CAAC;AAG3B,MAAM,MAAM,eAAe,GAAG;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,gBAAgB,EAAE,MAAM,CAAC;IACzB,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,qBAAqB,CAAC,CAAC,IAAI;IACrC,IAAI,EAAE,eAAe,CAAC;IACtB,gBAAgB,EAAE,CAAC,CAAC;IACpB,cAAc,EAAE,QAAQ,CAAC;CAC1B,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAC3B,QAAQ,EAAE,MAAM,CAAC;IAGjB,QAAQ,CAAC,EAAE,OAAO,CAAC;IAInB,SAAS,CAAC,EAAE,OAAO,CAAC;IAGpB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAoBF,wBAAsB,qBAAqB,CACzC,EAAE,EAAE,UAAU,EACd,OAAO,EAAE,QAAQ,CAAC,GAAG,EACrB,EACE,QAAQ,EACR,QAAQ,EACR,SAAS,EACT,WAAoC,GACrC,EAAE,cAAc,GAChB,OAAO,CAAC,eAAe,CAAC,CAwC1B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAsB,oBAAoB,CAAC,CAAC,EAC1C,EAAE,EAAE,UAAU,EACd,GAAG,EAAE,UAAU,EACf,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE,OAAO,EACd,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,OAAO,EACjB,aAAa,EAAE,aAAa,EAC5B,eAAe,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,GAChD,OAAO,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,CAuFnC;AAED,wBAAgB,4BAA4B,CAC1C,EAAE,EAAE,UAAU,EACd,GAAG,EAAE,UAAU,EACf,KAAK,EAAE,OAAO,EACd,KAAK,EAAE,MAAM,EAAE,iBA+BhB;AA+DD,wBAAgB,cAAc,CAAC,CAAC,EAAE,MAAM,UAUvC"}
@@ -120,27 +120,24 @@ async function createReplicaAndSlot(lc, sql, sessionName, shard, replicaID, fail
120
120
  }
121
121
  }
122
122
  }
123
- /**
124
- * Deletes "old" replicas (i.e. those with a lower rank than the current)
125
- * and attempts to drop replication slots that are not associated with any
126
- * replica.
127
- *
128
- * If a slot could not be dropped because there is still an active subscriber,
129
- * it will be reflected in the `draining` count that is returned. When there
130
- * are draining slots, the method should be retried until all orphaned slots
131
- * have been dropped.
132
- */
133
- async function dropOldReplicasAndSlots(lc, sql, shard, beforeRank) {
123
+ function dropInactiveSlotsAndReplicas(lc, sql, shard, slots) {
124
+ const lockName = replicationSlotManagementLock(shard);
134
125
  const replicasTable = `${upstreamSchema(shard)}.replicas`;
135
- const oldReplicas = await sql`
136
- SELECT id, rank::float8, slot, version, "initialSyncContext", "subscriberContext"
137
- FROM ${sql(replicasTable)} WHERE rank < ${beforeRank};
138
- `;
139
- if (oldReplicas.length) {
140
- lc.info?.(`Deleting ${oldReplicas.length} old replica(s)`, { oldReplicas });
141
- await sql`DELETE FROM ${sql(replicasTable)} WHERE rank < ${beforeRank}`;
142
- }
143
- return dropUnclaimedSlots(lc, sql, shard);
126
+ return runTx(sql, async (tx) => {
127
+ await tx`SELECT pg_advisory_xact_lock(hashtext(${lockName}))`;
128
+ const dropped = await tx`
129
+ SELECT slot_name as slot, replica.id as "replicaID", pg_drop_replication_slot(slot_name)
130
+ FROM pg_replication_slots
131
+ LEFT JOIN ${tx(replicasTable)} replica on slot_name = slot
132
+ WHERE slot_name IN ${tx(slots)} AND NOT active;
133
+ `;
134
+ if (dropped.length) lc.info?.(`dropped ${dropped.length} inactive replication slot(s)`, { dropped });
135
+ const replicas = dropped.map(({ replicaID }) => replicaID).filter((id) => id !== null);
136
+ if (replicas.length) {
137
+ await tx`DELETE FROM ${tx(replicasTable)} WHERE id IN ${tx(replicas)}`;
138
+ lc.info?.(`deleted ${replicas.length} old replica(s)`, { replicas });
139
+ }
140
+ });
144
141
  }
145
142
  function dropUnclaimedSlots(lc, sql, shard) {
146
143
  const lockName = replicationSlotManagementLock(shard);
@@ -190,6 +187,6 @@ function replicationSlotManagementLock(shard) {
190
187
  return `replication-slot-management:${shard.appID}_${shard.shardNum}`;
191
188
  }
192
189
  //#endregion
193
- export { createReplicaAndSlot, createReplicationSlot, dropOldReplicasAndSlots };
190
+ export { createReplicaAndSlot, createReplicationSlot, dropInactiveSlotsAndReplicas };
194
191
 
195
192
  //# sourceMappingURL=replication-slots.js.map