@opendatalabs/personal-server-ts-core 1.37.0 → 1.38.1

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 (793) hide show
  1. package/contracts/host-contract.json +115 -0
  2. package/contracts/raw-end.json +2360 -0
  3. package/contracts/replace-conformance.json +729 -0
  4. package/contracts/routes.json +349 -0
  5. package/contracts/run-finish-plan.json +3238 -0
  6. package/contracts/run-saved.json +1308 -0
  7. package/contracts/scope-delete-receipt.json +616 -0
  8. package/dist/api/account-storage-mode.d.ts +77 -0
  9. package/dist/api/account-storage-mode.d.ts.map +1 -0
  10. package/dist/api/account-storage-mode.js +72 -0
  11. package/dist/api/account-storage-mode.js.map +1 -0
  12. package/dist/api/index.d.ts +139 -3
  13. package/dist/api/index.d.ts.map +1 -1
  14. package/dist/api/index.js +973 -191
  15. package/dist/api/index.js.map +1 -1
  16. package/dist/api/legacy-write-gate.d.ts +51 -0
  17. package/dist/api/legacy-write-gate.d.ts.map +1 -0
  18. package/dist/api/legacy-write-gate.js +88 -0
  19. package/dist/api/legacy-write-gate.js.map +1 -0
  20. package/dist/api/owner-connector-delete.d.ts +103 -0
  21. package/dist/api/owner-connector-delete.d.ts.map +1 -0
  22. package/dist/api/owner-connector-delete.js +158 -0
  23. package/dist/api/owner-connector-delete.js.map +1 -0
  24. package/dist/api/pdpp-record-query.d.ts +25 -0
  25. package/dist/api/pdpp-record-query.d.ts.map +1 -0
  26. package/dist/api/pdpp-record-query.js +72 -0
  27. package/dist/api/pdpp-record-query.js.map +1 -0
  28. package/dist/api/pdpp-records-list.d.ts +133 -0
  29. package/dist/api/pdpp-records-list.d.ts.map +1 -0
  30. package/dist/api/pdpp-records-list.js +380 -0
  31. package/dist/api/pdpp-records-list.js.map +1 -0
  32. package/dist/api/scope-delete-verdict.d.ts +107 -0
  33. package/dist/api/scope-delete-verdict.d.ts.map +1 -0
  34. package/dist/api/scope-delete-verdict.js +92 -0
  35. package/dist/api/scope-delete-verdict.js.map +1 -0
  36. package/dist/api/switched-delete-refusal.d.ts +16 -0
  37. package/dist/api/switched-delete-refusal.d.ts.map +1 -0
  38. package/dist/api/switched-delete-refusal.js +30 -0
  39. package/dist/api/switched-delete-refusal.js.map +1 -0
  40. package/dist/client.d.ts +29 -0
  41. package/dist/client.d.ts.map +1 -1
  42. package/dist/client.js +34 -2
  43. package/dist/client.js.map +1 -1
  44. package/dist/contracts/access-logs.d.ts +1 -0
  45. package/dist/contracts/access-logs.d.ts.map +1 -1
  46. package/dist/contracts/access-logs.js +7 -1
  47. package/dist/contracts/access-logs.js.map +1 -1
  48. package/dist/contracts/data.d.ts +12 -0
  49. package/dist/contracts/data.d.ts.map +1 -1
  50. package/dist/contracts/data.js +30 -1
  51. package/dist/contracts/data.js.map +1 -1
  52. package/dist/contracts/grants.d.ts.map +1 -1
  53. package/dist/contracts/grants.js +9 -0
  54. package/dist/contracts/grants.js.map +1 -1
  55. package/dist/contracts/index.d.ts +1 -1
  56. package/dist/contracts/index.d.ts.map +1 -1
  57. package/dist/contracts/index.js +1 -1
  58. package/dist/contracts/index.js.map +1 -1
  59. package/dist/contracts/sync.d.ts +9 -1
  60. package/dist/contracts/sync.d.ts.map +1 -1
  61. package/dist/contracts/sync.js +6 -2
  62. package/dist/contracts/sync.js.map +1 -1
  63. package/dist/derivatives/compute.d.ts.map +1 -1
  64. package/dist/derivatives/compute.js +19 -0
  65. package/dist/derivatives/compute.js.map +1 -1
  66. package/dist/encoding/base64url.d.ts +6 -0
  67. package/dist/encoding/base64url.d.ts.map +1 -0
  68. package/dist/encoding/base64url.js +29 -0
  69. package/dist/encoding/base64url.js.map +1 -0
  70. package/dist/errors/pdpp-catalog.d.ts +1 -1
  71. package/dist/errors/pdpp-catalog.d.ts.map +1 -1
  72. package/dist/errors/pdpp-catalog.js +6 -0
  73. package/dist/errors/pdpp-catalog.js.map +1 -1
  74. package/dist/keys/index.d.ts +1 -0
  75. package/dist/keys/index.d.ts.map +1 -1
  76. package/dist/keys/index.js +1 -0
  77. package/dist/keys/index.js.map +1 -1
  78. package/dist/keys/owner-master-key.d.ts +37 -0
  79. package/dist/keys/owner-master-key.d.ts.map +1 -0
  80. package/dist/keys/owner-master-key.js +45 -0
  81. package/dist/keys/owner-master-key.js.map +1 -0
  82. package/dist/legacy-projection/bindings.d.ts.map +1 -1
  83. package/dist/legacy-projection/bindings.js +10 -4
  84. package/dist/legacy-projection/bindings.js.map +1 -1
  85. package/dist/legacy-projection/erase-connector.d.ts +18 -0
  86. package/dist/legacy-projection/erase-connector.d.ts.map +1 -0
  87. package/dist/legacy-projection/erase-connector.js +29 -0
  88. package/dist/legacy-projection/erase-connector.js.map +1 -0
  89. package/dist/legacy-projection/index.d.ts +17 -0
  90. package/dist/legacy-projection/index.d.ts.map +1 -1
  91. package/dist/legacy-projection/index.js +41 -0
  92. package/dist/legacy-projection/index.js.map +1 -1
  93. package/dist/legacy-projection/types.d.ts +12 -2
  94. package/dist/legacy-projection/types.d.ts.map +1 -1
  95. package/dist/lineage/gateway.d.ts +3 -1
  96. package/dist/lineage/gateway.d.ts.map +1 -1
  97. package/dist/lineage/gateway.js +2 -1
  98. package/dist/lineage/gateway.js.map +1 -1
  99. package/dist/localdb/admit.d.ts +138 -0
  100. package/dist/localdb/admit.d.ts.map +1 -0
  101. package/dist/localdb/admit.js +344 -0
  102. package/dist/localdb/admit.js.map +1 -0
  103. package/dist/localdb/apply-meter.d.ts +14 -0
  104. package/dist/localdb/apply-meter.d.ts.map +1 -0
  105. package/dist/localdb/apply-meter.js +31 -0
  106. package/dist/localdb/apply-meter.js.map +1 -0
  107. package/dist/localdb/apply-progress.d.ts +10 -0
  108. package/dist/localdb/apply-progress.d.ts.map +1 -0
  109. package/dist/localdb/apply-progress.js +39 -0
  110. package/dist/localdb/apply-progress.js.map +1 -0
  111. package/dist/localdb/apply.d.ts +17 -0
  112. package/dist/localdb/apply.d.ts.map +1 -0
  113. package/dist/localdb/apply.js +291 -0
  114. package/dist/localdb/apply.js.map +1 -0
  115. package/dist/localdb/batch-commit.d.ts +70 -0
  116. package/dist/localdb/batch-commit.d.ts.map +1 -0
  117. package/dist/localdb/batch-commit.js +91 -0
  118. package/dist/localdb/batch-commit.js.map +1 -0
  119. package/dist/localdb/batch-contract.d.ts +19 -0
  120. package/dist/localdb/batch-contract.d.ts.map +1 -0
  121. package/dist/localdb/batch-contract.js +24 -0
  122. package/dist/localdb/batch-contract.js.map +1 -0
  123. package/dist/localdb/blobs.d.ts +71 -0
  124. package/dist/localdb/blobs.d.ts.map +1 -0
  125. package/dist/localdb/blobs.js +306 -0
  126. package/dist/localdb/blobs.js.map +1 -0
  127. package/dist/localdb/bootstrap-copy.d.ts +6 -0
  128. package/dist/localdb/bootstrap-copy.d.ts.map +1 -0
  129. package/dist/localdb/bootstrap-copy.js +79 -0
  130. package/dist/localdb/bootstrap-copy.js.map +1 -0
  131. package/dist/localdb/bootstrap-keys.d.ts +33 -0
  132. package/dist/localdb/bootstrap-keys.d.ts.map +1 -0
  133. package/dist/localdb/bootstrap-keys.js +89 -0
  134. package/dist/localdb/bootstrap-keys.js.map +1 -0
  135. package/dist/localdb/bootstrap-swap.d.ts +17 -0
  136. package/dist/localdb/bootstrap-swap.d.ts.map +1 -0
  137. package/dist/localdb/bootstrap-swap.js +78 -0
  138. package/dist/localdb/bootstrap-swap.js.map +1 -0
  139. package/dist/localdb/bootstrap.d.ts +55 -0
  140. package/dist/localdb/bootstrap.d.ts.map +1 -0
  141. package/dist/localdb/bootstrap.js +195 -0
  142. package/dist/localdb/bootstrap.js.map +1 -0
  143. package/dist/localdb/complete-read.d.ts +77 -0
  144. package/dist/localdb/complete-read.d.ts.map +1 -0
  145. package/dist/localdb/complete-read.js +136 -0
  146. package/dist/localdb/complete-read.js.map +1 -0
  147. package/dist/localdb/connection-link.d.ts +12 -0
  148. package/dist/localdb/connection-link.d.ts.map +1 -0
  149. package/dist/localdb/connection-link.js +79 -0
  150. package/dist/localdb/connection-link.js.map +1 -0
  151. package/dist/localdb/cursor.d.ts +61 -0
  152. package/dist/localdb/cursor.d.ts.map +1 -0
  153. package/dist/localdb/cursor.js +178 -0
  154. package/dist/localdb/cursor.js.map +1 -0
  155. package/dist/localdb/cycle.d.ts +69 -0
  156. package/dist/localdb/cycle.d.ts.map +1 -0
  157. package/dist/localdb/cycle.js +189 -0
  158. package/dist/localdb/cycle.js.map +1 -0
  159. package/dist/localdb/delete-batch.d.ts +29 -0
  160. package/dist/localdb/delete-batch.d.ts.map +1 -0
  161. package/dist/localdb/delete-batch.js +84 -0
  162. package/dist/localdb/delete-batch.js.map +1 -0
  163. package/dist/localdb/delete-lifetime.d.ts +24 -0
  164. package/dist/localdb/delete-lifetime.d.ts.map +1 -0
  165. package/dist/localdb/delete-lifetime.js +83 -0
  166. package/dist/localdb/delete-lifetime.js.map +1 -0
  167. package/dist/localdb/delete.d.ts +88 -0
  168. package/dist/localdb/delete.d.ts.map +1 -0
  169. package/dist/localdb/delete.js +521 -0
  170. package/dist/localdb/delete.js.map +1 -0
  171. package/dist/localdb/delta-apply.d.ts +4 -0
  172. package/dist/localdb/delta-apply.d.ts.map +1 -0
  173. package/dist/localdb/delta-apply.js +253 -0
  174. package/dist/localdb/delta-apply.js.map +1 -0
  175. package/dist/localdb/deps.d.ts +87 -0
  176. package/dist/localdb/deps.d.ts.map +1 -0
  177. package/dist/localdb/deps.js +10 -0
  178. package/dist/localdb/deps.js.map +1 -0
  179. package/dist/localdb/driver.d.ts +51 -0
  180. package/dist/localdb/driver.d.ts.map +1 -0
  181. package/dist/localdb/driver.js +3 -0
  182. package/dist/localdb/driver.js.map +1 -0
  183. package/dist/localdb/fence.d.ts +31 -0
  184. package/dist/localdb/fence.d.ts.map +1 -0
  185. package/dist/localdb/fence.js +69 -0
  186. package/dist/localdb/fence.js.map +1 -0
  187. package/dist/localdb/history.d.ts +76 -0
  188. package/dist/localdb/history.d.ts.map +1 -0
  189. package/dist/localdb/history.js +256 -0
  190. package/dist/localdb/history.js.map +1 -0
  191. package/dist/localdb/import-fingerprint.d.ts +8 -0
  192. package/dist/localdb/import-fingerprint.d.ts.map +1 -0
  193. package/dist/localdb/import-fingerprint.js +35 -0
  194. package/dist/localdb/import-fingerprint.js.map +1 -0
  195. package/dist/localdb/import-ledger.d.ts +27 -0
  196. package/dist/localdb/import-ledger.d.ts.map +1 -0
  197. package/dist/localdb/import-ledger.js +197 -0
  198. package/dist/localdb/import-ledger.js.map +1 -0
  199. package/dist/localdb/import-readback.d.ts +8 -0
  200. package/dist/localdb/import-readback.d.ts.map +1 -0
  201. package/dist/localdb/import-readback.js +69 -0
  202. package/dist/localdb/import-readback.js.map +1 -0
  203. package/dist/localdb/import-snapshot.d.ts +21 -0
  204. package/dist/localdb/import-snapshot.d.ts.map +1 -0
  205. package/dist/localdb/import-snapshot.js +94 -0
  206. package/dist/localdb/import-snapshot.js.map +1 -0
  207. package/dist/localdb/index.d.ts +42 -0
  208. package/dist/localdb/index.d.ts.map +1 -0
  209. package/dist/localdb/index.js +40 -0
  210. package/dist/localdb/index.js.map +1 -0
  211. package/dist/localdb/legacy-import-types.d.ts +112 -0
  212. package/dist/localdb/legacy-import-types.d.ts.map +1 -0
  213. package/dist/localdb/legacy-import-types.js +2 -0
  214. package/dist/localdb/legacy-import-types.js.map +1 -0
  215. package/dist/localdb/legacy-import.d.ts +67 -0
  216. package/dist/localdb/legacy-import.d.ts.map +1 -0
  217. package/dist/localdb/legacy-import.js +320 -0
  218. package/dist/localdb/legacy-import.js.map +1 -0
  219. package/dist/localdb/legacy-retire.d.ts +26 -0
  220. package/dist/localdb/legacy-retire.d.ts.map +1 -0
  221. package/dist/localdb/legacy-retire.js +93 -0
  222. package/dist/localdb/legacy-retire.js.map +1 -0
  223. package/dist/localdb/lifetime.d.ts +29 -0
  224. package/dist/localdb/lifetime.d.ts.map +1 -0
  225. package/dist/localdb/lifetime.js +64 -0
  226. package/dist/localdb/lifetime.js.map +1 -0
  227. package/dist/localdb/listing.d.ts +70 -0
  228. package/dist/localdb/listing.d.ts.map +1 -0
  229. package/dist/localdb/listing.js +345 -0
  230. package/dist/localdb/listing.js.map +1 -0
  231. package/dist/localdb/log-apply.d.ts +46 -0
  232. package/dist/localdb/log-apply.d.ts.map +1 -0
  233. package/dist/localdb/log-apply.js +827 -0
  234. package/dist/localdb/log-apply.js.map +1 -0
  235. package/dist/localdb/log-batch.d.ts +204 -0
  236. package/dist/localdb/log-batch.d.ts.map +1 -0
  237. package/dist/localdb/log-batch.js +418 -0
  238. package/dist/localdb/log-batch.js.map +1 -0
  239. package/dist/localdb/log-bodies.d.ts +27 -0
  240. package/dist/localdb/log-bodies.d.ts.map +1 -0
  241. package/dist/localdb/log-bodies.js +142 -0
  242. package/dist/localdb/log-bodies.js.map +1 -0
  243. package/dist/localdb/log-bootstrap-stage.d.ts +5 -0
  244. package/dist/localdb/log-bootstrap-stage.d.ts.map +1 -0
  245. package/dist/localdb/log-bootstrap-stage.js +60 -0
  246. package/dist/localdb/log-bootstrap-stage.js.map +1 -0
  247. package/dist/localdb/log-bootstrap.d.ts +23 -0
  248. package/dist/localdb/log-bootstrap.d.ts.map +1 -0
  249. package/dist/localdb/log-bootstrap.js +399 -0
  250. package/dist/localdb/log-bootstrap.js.map +1 -0
  251. package/dist/localdb/log-compact.d.ts +28 -0
  252. package/dist/localdb/log-compact.d.ts.map +1 -0
  253. package/dist/localdb/log-compact.js +83 -0
  254. package/dist/localdb/log-compact.js.map +1 -0
  255. package/dist/localdb/log-keyed.d.ts +118 -0
  256. package/dist/localdb/log-keyed.d.ts.map +1 -0
  257. package/dist/localdb/log-keyed.js +640 -0
  258. package/dist/localdb/log-keyed.js.map +1 -0
  259. package/dist/localdb/log-progressive.d.ts +18 -0
  260. package/dist/localdb/log-progressive.d.ts.map +1 -0
  261. package/dist/localdb/log-progressive.js +58 -0
  262. package/dist/localdb/log-progressive.js.map +1 -0
  263. package/dist/localdb/log-publish-phases.d.ts +31 -0
  264. package/dist/localdb/log-publish-phases.d.ts.map +1 -0
  265. package/dist/localdb/log-publish-phases.js +40 -0
  266. package/dist/localdb/log-publish-phases.js.map +1 -0
  267. package/dist/localdb/log-publish.d.ts +16 -0
  268. package/dist/localdb/log-publish.d.ts.map +1 -0
  269. package/dist/localdb/log-publish.js +1745 -0
  270. package/dist/localdb/log-publish.js.map +1 -0
  271. package/dist/localdb/log-rebase.d.ts +12 -0
  272. package/dist/localdb/log-rebase.d.ts.map +1 -0
  273. package/dist/localdb/log-rebase.js +74 -0
  274. package/dist/localdb/log-rebase.js.map +1 -0
  275. package/dist/localdb/log-recommit.d.ts +15 -0
  276. package/dist/localdb/log-recommit.d.ts.map +1 -0
  277. package/dist/localdb/log-recommit.js +88 -0
  278. package/dist/localdb/log-recommit.js.map +1 -0
  279. package/dist/localdb/log-seed.d.ts +25 -0
  280. package/dist/localdb/log-seed.d.ts.map +1 -0
  281. package/dist/localdb/log-seed.js +129 -0
  282. package/dist/localdb/log-seed.js.map +1 -0
  283. package/dist/localdb/log-state.d.ts +34 -0
  284. package/dist/localdb/log-state.d.ts.map +1 -0
  285. package/dist/localdb/log-state.js +79 -0
  286. package/dist/localdb/log-state.js.map +1 -0
  287. package/dist/localdb/merge.d.ts +122 -0
  288. package/dist/localdb/merge.d.ts.map +1 -0
  289. package/dist/localdb/merge.js +339 -0
  290. package/dist/localdb/merge.js.map +1 -0
  291. package/dist/localdb/migrate.d.ts +10 -0
  292. package/dist/localdb/migrate.d.ts.map +1 -0
  293. package/dist/localdb/migrate.js +27 -0
  294. package/dist/localdb/migrate.js.map +1 -0
  295. package/dist/localdb/name.d.ts +10 -0
  296. package/dist/localdb/name.d.ts.map +1 -0
  297. package/dist/localdb/name.js +15 -0
  298. package/dist/localdb/name.js.map +1 -0
  299. package/dist/localdb/open.d.ts +33 -0
  300. package/dist/localdb/open.d.ts.map +1 -0
  301. package/dist/localdb/open.js +46 -0
  302. package/dist/localdb/open.js.map +1 -0
  303. package/dist/localdb/part-layout.d.ts +6 -0
  304. package/dist/localdb/part-layout.d.ts.map +1 -0
  305. package/dist/localdb/part-layout.js +6 -0
  306. package/dist/localdb/part-layout.js.map +1 -0
  307. package/dist/localdb/part-readahead.d.ts +87 -0
  308. package/dist/localdb/part-readahead.d.ts.map +1 -0
  309. package/dist/localdb/part-readahead.js +130 -0
  310. package/dist/localdb/part-readahead.js.map +1 -0
  311. package/dist/localdb/partial-load.d.ts +42 -0
  312. package/dist/localdb/partial-load.d.ts.map +1 -0
  313. package/dist/localdb/partial-load.js +120 -0
  314. package/dist/localdb/partial-load.js.map +1 -0
  315. package/dist/localdb/partial-read.d.ts +64 -0
  316. package/dist/localdb/partial-read.d.ts.map +1 -0
  317. package/dist/localdb/partial-read.js +110 -0
  318. package/dist/localdb/partial-read.js.map +1 -0
  319. package/dist/localdb/plan-inputs.d.ts +31 -0
  320. package/dist/localdb/plan-inputs.d.ts.map +1 -0
  321. package/dist/localdb/plan-inputs.js +26 -0
  322. package/dist/localdb/plan-inputs.js.map +1 -0
  323. package/dist/localdb/publication-work.d.ts +20 -0
  324. package/dist/localdb/publication-work.d.ts.map +1 -0
  325. package/dist/localdb/publication-work.js +60 -0
  326. package/dist/localdb/publication-work.js.map +1 -0
  327. package/dist/localdb/publish-meter.d.ts +32 -0
  328. package/dist/localdb/publish-meter.d.ts.map +1 -0
  329. package/dist/localdb/publish-meter.js +36 -0
  330. package/dist/localdb/publish-meter.js.map +1 -0
  331. package/dist/localdb/publish.d.ts +153 -0
  332. package/dist/localdb/publish.d.ts.map +1 -0
  333. package/dist/localdb/publish.js +329 -0
  334. package/dist/localdb/publish.js.map +1 -0
  335. package/dist/localdb/purge.d.ts +40 -0
  336. package/dist/localdb/purge.d.ts.map +1 -0
  337. package/dist/localdb/purge.js +159 -0
  338. package/dist/localdb/purge.js.map +1 -0
  339. package/dist/localdb/query.d.ts +77 -0
  340. package/dist/localdb/query.d.ts.map +1 -0
  341. package/dist/localdb/query.js +330 -0
  342. package/dist/localdb/query.js.map +1 -0
  343. package/dist/localdb/queue.d.ts +10 -0
  344. package/dist/localdb/queue.d.ts.map +1 -0
  345. package/dist/localdb/queue.js +31 -0
  346. package/dist/localdb/queue.js.map +1 -0
  347. package/dist/localdb/raw-end-evidence.d.ts +16 -0
  348. package/dist/localdb/raw-end-evidence.d.ts.map +1 -0
  349. package/dist/localdb/raw-end-evidence.js +27 -0
  350. package/dist/localdb/raw-end-evidence.js.map +1 -0
  351. package/dist/localdb/read-selection.d.ts +182 -0
  352. package/dist/localdb/read-selection.d.ts.map +1 -0
  353. package/dist/localdb/read-selection.js +290 -0
  354. package/dist/localdb/read-selection.js.map +1 -0
  355. package/dist/localdb/registered-read.d.ts +15 -0
  356. package/dist/localdb/registered-read.d.ts.map +1 -0
  357. package/dist/localdb/registered-read.js +62 -0
  358. package/dist/localdb/registered-read.js.map +1 -0
  359. package/dist/localdb/replace.d.ts +33 -0
  360. package/dist/localdb/replace.d.ts.map +1 -0
  361. package/dist/localdb/replace.js +22 -0
  362. package/dist/localdb/replace.js.map +1 -0
  363. package/dist/localdb/requirements.d.ts +35 -0
  364. package/dist/localdb/requirements.d.ts.map +1 -0
  365. package/dist/localdb/requirements.js +66 -0
  366. package/dist/localdb/requirements.js.map +1 -0
  367. package/dist/localdb/resolve.d.ts +69 -0
  368. package/dist/localdb/resolve.d.ts.map +1 -0
  369. package/dist/localdb/resolve.js +436 -0
  370. package/dist/localdb/resolve.js.map +1 -0
  371. package/dist/localdb/run-end.d.ts +35 -0
  372. package/dist/localdb/run-end.d.ts.map +1 -0
  373. package/dist/localdb/run-end.js +520 -0
  374. package/dist/localdb/run-end.js.map +1 -0
  375. package/dist/localdb/run-intake.d.ts +17 -0
  376. package/dist/localdb/run-intake.d.ts.map +1 -0
  377. package/dist/localdb/run-intake.js +662 -0
  378. package/dist/localdb/run-intake.js.map +1 -0
  379. package/dist/localdb/run-receipts.d.ts +19 -0
  380. package/dist/localdb/run-receipts.d.ts.map +1 -0
  381. package/dist/localdb/run-receipts.js +151 -0
  382. package/dist/localdb/run-receipts.js.map +1 -0
  383. package/dist/localdb/schema.d.ts +7 -0
  384. package/dist/localdb/schema.d.ts.map +1 -0
  385. package/dist/localdb/schema.js +686 -0
  386. package/dist/localdb/schema.js.map +1 -0
  387. package/dist/localdb/seed.d.ts +39 -0
  388. package/dist/localdb/seed.d.ts.map +1 -0
  389. package/dist/localdb/seed.js +188 -0
  390. package/dist/localdb/seed.js.map +1 -0
  391. package/dist/localdb/slot.d.ts +9 -0
  392. package/dist/localdb/slot.d.ts.map +1 -0
  393. package/dist/localdb/slot.js +15 -0
  394. package/dist/localdb/slot.js.map +1 -0
  395. package/dist/localdb/stream-digest.d.ts +35 -0
  396. package/dist/localdb/stream-digest.d.ts.map +1 -0
  397. package/dist/localdb/stream-digest.js +50 -0
  398. package/dist/localdb/stream-digest.js.map +1 -0
  399. package/dist/localdb/sync.d.ts +75 -0
  400. package/dist/localdb/sync.d.ts.map +1 -0
  401. package/dist/localdb/sync.js +339 -0
  402. package/dist/localdb/sync.js.map +1 -0
  403. package/dist/localdb/system-stream-descriptor.d.ts +22 -0
  404. package/dist/localdb/system-stream-descriptor.d.ts.map +1 -0
  405. package/dist/localdb/system-stream-descriptor.js +24 -0
  406. package/dist/localdb/system-stream-descriptor.js.map +1 -0
  407. package/dist/localdb/system-stream-page.d.ts +15 -0
  408. package/dist/localdb/system-stream-page.d.ts.map +1 -0
  409. package/dist/localdb/system-stream-page.js +98 -0
  410. package/dist/localdb/system-stream-page.js.map +1 -0
  411. package/dist/localdb/system-streams.d.ts +35 -0
  412. package/dist/localdb/system-streams.d.ts.map +1 -0
  413. package/dist/localdb/system-streams.js +350 -0
  414. package/dist/localdb/system-streams.js.map +1 -0
  415. package/dist/localdb/transfer-memory.d.ts +17 -0
  416. package/dist/localdb/transfer-memory.d.ts.map +1 -0
  417. package/dist/localdb/transfer-memory.js +17 -0
  418. package/dist/localdb/transfer-memory.js.map +1 -0
  419. package/dist/localdb/unwrite.d.ts +28 -0
  420. package/dist/localdb/unwrite.d.ts.map +1 -0
  421. package/dist/localdb/unwrite.js +62 -0
  422. package/dist/localdb/unwrite.js.map +1 -0
  423. package/dist/localdb/update-required.d.ts +10 -0
  424. package/dist/localdb/update-required.d.ts.map +1 -0
  425. package/dist/localdb/update-required.js +27 -0
  426. package/dist/localdb/update-required.js.map +1 -0
  427. package/dist/localdb/view-changes.d.ts +58 -0
  428. package/dist/localdb/view-changes.d.ts.map +1 -0
  429. package/dist/localdb/view-changes.js +174 -0
  430. package/dist/localdb/view-changes.js.map +1 -0
  431. package/dist/logging/access-log.d.ts +2 -2
  432. package/dist/logging/access-log.d.ts.map +1 -1
  433. package/dist/logging/access-reader.d.ts +4 -1
  434. package/dist/logging/access-reader.d.ts.map +1 -1
  435. package/dist/logging/activity-stream.d.ts +37 -0
  436. package/dist/logging/activity-stream.d.ts.map +1 -0
  437. package/dist/logging/activity-stream.js +86 -0
  438. package/dist/logging/activity-stream.js.map +1 -0
  439. package/dist/mcp/approval-url.d.ts +32 -0
  440. package/dist/mcp/approval-url.d.ts.map +1 -1
  441. package/dist/mcp/approval-url.js +76 -0
  442. package/dist/mcp/approval-url.js.map +1 -1
  443. package/dist/mcp/connection-api.d.ts +54 -27
  444. package/dist/mcp/connection-api.d.ts.map +1 -1
  445. package/dist/mcp/connection-api.js +267 -77
  446. package/dist/mcp/connection-api.js.map +1 -1
  447. package/dist/mcp/grant-registration.d.ts +15 -0
  448. package/dist/mcp/grant-registration.d.ts.map +1 -0
  449. package/dist/mcp/grant-registration.js +44 -0
  450. package/dist/mcp/grant-registration.js.map +1 -0
  451. package/dist/mcp/index.d.ts +1 -0
  452. package/dist/mcp/index.d.ts.map +1 -1
  453. package/dist/mcp/index.js +1 -0
  454. package/dist/mcp/index.js.map +1 -1
  455. package/dist/mcp/read-client.d.ts +32 -10
  456. package/dist/mcp/read-client.d.ts.map +1 -1
  457. package/dist/mcp/read-client.js +299 -15
  458. package/dist/mcp/read-client.js.map +1 -1
  459. package/dist/mcp/resources.d.ts +3 -1
  460. package/dist/mcp/resources.d.ts.map +1 -1
  461. package/dist/mcp/resources.js +11 -2
  462. package/dist/mcp/resources.js.map +1 -1
  463. package/dist/mcp/server.d.ts +17 -0
  464. package/dist/mcp/server.d.ts.map +1 -1
  465. package/dist/mcp/server.js +54 -7
  466. package/dist/mcp/server.js.map +1 -1
  467. package/dist/mcp/session.d.ts +2 -0
  468. package/dist/mcp/session.d.ts.map +1 -1
  469. package/dist/mcp/session.js +41 -8
  470. package/dist/mcp/session.js.map +1 -1
  471. package/dist/mcp/store.d.ts +14 -1
  472. package/dist/mcp/store.d.ts.map +1 -1
  473. package/dist/mcp/store.js +31 -2
  474. package/dist/mcp/store.js.map +1 -1
  475. package/dist/mcp/tools.d.ts +62 -0
  476. package/dist/mcp/tools.d.ts.map +1 -1
  477. package/dist/mcp/tools.js +186 -64
  478. package/dist/mcp/tools.js.map +1 -1
  479. package/dist/mcp/types.d.ts +3 -1
  480. package/dist/mcp/types.d.ts.map +1 -1
  481. package/dist/oura/index.d.ts +1 -1
  482. package/dist/oura/index.d.ts.map +1 -1
  483. package/dist/oura/index.js +15 -0
  484. package/dist/oura/index.js.map +1 -1
  485. package/dist/payment/x402.d.ts +6 -3
  486. package/dist/payment/x402.d.ts.map +1 -1
  487. package/dist/payment/x402.js +35 -0
  488. package/dist/payment/x402.js.map +1 -1
  489. package/dist/pdpp/pkce.d.ts +1 -22
  490. package/dist/pdpp/pkce.d.ts.map +1 -1
  491. package/dist/pdpp/pkce.js +3 -2
  492. package/dist/pdpp/pkce.js.map +1 -1
  493. package/dist/policy/reserved-scopes.d.ts +3 -0
  494. package/dist/policy/reserved-scopes.d.ts.map +1 -1
  495. package/dist/policy/reserved-scopes.js +12 -1
  496. package/dist/policy/reserved-scopes.js.map +1 -1
  497. package/dist/ports/index.d.ts +61 -9
  498. package/dist/ports/index.d.ts.map +1 -1
  499. package/dist/ports/index.js.map +1 -1
  500. package/dist/publication/publish.d.ts +31 -1
  501. package/dist/publication/publish.d.ts.map +1 -1
  502. package/dist/publication/publish.js +30 -14
  503. package/dist/publication/publish.js.map +1 -1
  504. package/dist/replication/copies.d.ts +1 -1
  505. package/dist/replication/dpv2.d.ts.map +1 -1
  506. package/dist/replication/dpv2.js +33 -0
  507. package/dist/replication/dpv2.js.map +1 -1
  508. package/dist/schemas/server-config.d.ts +16 -0
  509. package/dist/schemas/server-config.d.ts.map +1 -1
  510. package/dist/schemas/server-config.js +49 -0
  511. package/dist/schemas/server-config.js.map +1 -1
  512. package/dist/storage/adapters/interface.d.ts +12 -2
  513. package/dist/storage/adapters/interface.d.ts.map +1 -1
  514. package/dist/storage/adapters/interface.js.map +1 -1
  515. package/dist/storage/adapters/rate-limit-policy.d.ts +71 -0
  516. package/dist/storage/adapters/rate-limit-policy.d.ts.map +1 -0
  517. package/dist/storage/adapters/rate-limit-policy.js +107 -0
  518. package/dist/storage/adapters/rate-limit-policy.js.map +1 -0
  519. package/dist/storage/adapters/sdk.d.ts +7 -0
  520. package/dist/storage/adapters/sdk.d.ts.map +1 -1
  521. package/dist/storage/adapters/sdk.js +12 -6
  522. package/dist/storage/adapters/sdk.js.map +1 -1
  523. package/dist/storage/adapters/throttle.d.ts +30 -0
  524. package/dist/storage/adapters/throttle.d.ts.map +1 -0
  525. package/dist/storage/adapters/throttle.js +94 -0
  526. package/dist/storage/adapters/throttle.js.map +1 -0
  527. package/dist/storage/adapters/vana-audience.d.ts +4 -1
  528. package/dist/storage/adapters/vana-audience.d.ts.map +1 -1
  529. package/dist/storage/adapters/vana-audience.js +23 -11
  530. package/dist/storage/adapters/vana-audience.js.map +1 -1
  531. package/dist/storage/adapters/vana.d.ts +5 -0
  532. package/dist/storage/adapters/vana.d.ts.map +1 -1
  533. package/dist/storage/adapters/vana.js +82 -18
  534. package/dist/storage/adapters/vana.js.map +1 -1
  535. package/dist/storage/blocks/cursor.d.ts.map +1 -1
  536. package/dist/storage/blocks/cursor.js +3 -13
  537. package/dist/storage/blocks/cursor.js.map +1 -1
  538. package/dist/storage/canonical-legacy-projection.d.ts +13 -1
  539. package/dist/storage/canonical-legacy-projection.d.ts.map +1 -1
  540. package/dist/storage/canonical-legacy-projection.js +92 -24
  541. package/dist/storage/canonical-legacy-projection.js.map +1 -1
  542. package/dist/storage/hierarchy/paths.d.ts.map +1 -1
  543. package/dist/storage/hierarchy/paths.js +9 -2
  544. package/dist/storage/hierarchy/paths.js.map +1 -1
  545. package/dist/storage/index/manager.d.ts +19 -5
  546. package/dist/storage/index/manager.d.ts.map +1 -1
  547. package/dist/storage/legacy-scope-view.d.ts +4 -6
  548. package/dist/storage/legacy-scope-view.d.ts.map +1 -1
  549. package/dist/storage/legacy-scope-view.js +50 -57
  550. package/dist/storage/legacy-scope-view.js.map +1 -1
  551. package/dist/storage/legacy-write-seal.d.ts +73 -0
  552. package/dist/storage/legacy-write-seal.d.ts.map +1 -0
  553. package/dist/storage/legacy-write-seal.js +74 -0
  554. package/dist/storage/legacy-write-seal.js.map +1 -0
  555. package/dist/storage/pdpp-records/cursor.d.ts.map +1 -1
  556. package/dist/storage/pdpp-records/cursor.js +3 -29
  557. package/dist/storage/pdpp-records/cursor.js.map +1 -1
  558. package/dist/storage/pdpp-records/declaration-witness.d.ts.map +1 -1
  559. package/dist/storage/pdpp-records/declaration-witness.js +4 -3
  560. package/dist/storage/pdpp-records/declaration-witness.js.map +1 -1
  561. package/dist/storage/pdpp-records/types.d.ts +2 -0
  562. package/dist/storage/pdpp-records/types.d.ts.map +1 -1
  563. package/dist/storage/pdpp-records/types.js.map +1 -1
  564. package/dist/stream-sync/artifacts.d.ts +38 -0
  565. package/dist/stream-sync/artifacts.d.ts.map +1 -0
  566. package/dist/stream-sync/artifacts.js +179 -0
  567. package/dist/stream-sync/artifacts.js.map +1 -0
  568. package/dist/stream-sync/blobs.d.ts +18 -0
  569. package/dist/stream-sync/blobs.d.ts.map +1 -0
  570. package/dist/stream-sync/blobs.js +83 -0
  571. package/dist/stream-sync/blobs.js.map +1 -0
  572. package/dist/stream-sync/crypto-port.d.ts +30 -0
  573. package/dist/stream-sync/crypto-port.d.ts.map +1 -0
  574. package/dist/stream-sync/crypto-port.js +29 -0
  575. package/dist/stream-sync/crypto-port.js.map +1 -0
  576. package/dist/stream-sync/crypto.d.ts +27 -0
  577. package/dist/stream-sync/crypto.d.ts.map +1 -0
  578. package/dist/stream-sync/crypto.js +67 -0
  579. package/dist/stream-sync/crypto.js.map +1 -0
  580. package/dist/stream-sync/delete-metadata.d.ts +23 -0
  581. package/dist/stream-sync/delete-metadata.d.ts.map +1 -0
  582. package/dist/stream-sync/delete-metadata.js +40 -0
  583. package/dist/stream-sync/delete-metadata.js.map +1 -0
  584. package/dist/stream-sync/design-flags.d.ts +31 -0
  585. package/dist/stream-sync/design-flags.d.ts.map +1 -0
  586. package/dist/stream-sync/design-flags.js +44 -0
  587. package/dist/stream-sync/design-flags.js.map +1 -0
  588. package/dist/stream-sync/host-contract.d.ts +50 -0
  589. package/dist/stream-sync/host-contract.d.ts.map +1 -0
  590. package/dist/stream-sync/host-contract.js +80 -0
  591. package/dist/stream-sync/host-contract.js.map +1 -0
  592. package/dist/stream-sync/index.d.ts +19 -0
  593. package/dist/stream-sync/index.d.ts.map +1 -0
  594. package/dist/stream-sync/index.js +19 -0
  595. package/dist/stream-sync/index.js.map +1 -0
  596. package/dist/stream-sync/intake.d.ts +319 -0
  597. package/dist/stream-sync/intake.d.ts.map +1 -0
  598. package/dist/stream-sync/intake.js +62 -0
  599. package/dist/stream-sync/intake.js.map +1 -0
  600. package/dist/stream-sync/memory-registry.d.ts +85 -0
  601. package/dist/stream-sync/memory-registry.d.ts.map +1 -0
  602. package/dist/stream-sync/memory-registry.js +293 -0
  603. package/dist/stream-sync/memory-registry.js.map +1 -0
  604. package/dist/stream-sync/normalize-raw-end.d.ts +25 -0
  605. package/dist/stream-sync/normalize-raw-end.d.ts.map +1 -0
  606. package/dist/stream-sync/normalize-raw-end.js +177 -0
  607. package/dist/stream-sync/normalize-raw-end.js.map +1 -0
  608. package/dist/stream-sync/ports.d.ts +486 -0
  609. package/dist/stream-sync/ports.d.ts.map +1 -0
  610. package/dist/stream-sync/ports.js +91 -0
  611. package/dist/stream-sync/ports.js.map +1 -0
  612. package/dist/stream-sync/publish-plan.d.ts +129 -0
  613. package/dist/stream-sync/publish-plan.d.ts.map +1 -0
  614. package/dist/stream-sync/publish-plan.js +134 -0
  615. package/dist/stream-sync/publish-plan.js.map +1 -0
  616. package/dist/stream-sync/raw-end.d.ts +59 -0
  617. package/dist/stream-sync/raw-end.d.ts.map +1 -0
  618. package/dist/stream-sync/raw-end.js +113 -0
  619. package/dist/stream-sync/raw-end.js.map +1 -0
  620. package/dist/stream-sync/registry.d.ts +31 -0
  621. package/dist/stream-sync/registry.d.ts.map +1 -0
  622. package/dist/stream-sync/registry.js +645 -0
  623. package/dist/stream-sync/registry.js.map +1 -0
  624. package/dist/stream-sync/run-finish-plan.d.ts +61 -0
  625. package/dist/stream-sync/run-finish-plan.d.ts.map +1 -0
  626. package/dist/stream-sync/run-finish-plan.js +373 -0
  627. package/dist/stream-sync/run-finish-plan.js.map +1 -0
  628. package/dist/stream-sync/run-saved.d.ts +51 -0
  629. package/dist/stream-sync/run-saved.d.ts.map +1 -0
  630. package/dist/stream-sync/run-saved.js +83 -0
  631. package/dist/stream-sync/run-saved.js.map +1 -0
  632. package/dist/stream-sync/scope-routing.d.ts +17 -0
  633. package/dist/stream-sync/scope-routing.d.ts.map +1 -0
  634. package/dist/stream-sync/scope-routing.js +24 -0
  635. package/dist/stream-sync/scope-routing.js.map +1 -0
  636. package/dist/stream-sync/seed-staging.d.ts +85 -0
  637. package/dist/stream-sync/seed-staging.d.ts.map +1 -0
  638. package/dist/stream-sync/seed-staging.js +325 -0
  639. package/dist/stream-sync/seed-staging.js.map +1 -0
  640. package/dist/stream-sync/semver.d.ts +3 -0
  641. package/dist/stream-sync/semver.d.ts.map +1 -0
  642. package/dist/stream-sync/semver.js +49 -0
  643. package/dist/stream-sync/semver.js.map +1 -0
  644. package/dist/stream-sync/send-gate.d.ts +149 -0
  645. package/dist/stream-sync/send-gate.d.ts.map +1 -0
  646. package/dist/stream-sync/send-gate.js +382 -0
  647. package/dist/stream-sync/send-gate.js.map +1 -0
  648. package/dist/stream-sync/storage-retry.d.ts +216 -0
  649. package/dist/stream-sync/storage-retry.d.ts.map +1 -0
  650. package/dist/stream-sync/storage-retry.js +315 -0
  651. package/dist/stream-sync/storage-retry.js.map +1 -0
  652. package/dist/stream-sync/stream-aead.d.ts +33 -0
  653. package/dist/stream-sync/stream-aead.d.ts.map +1 -0
  654. package/dist/stream-sync/stream-aead.js +183 -0
  655. package/dist/stream-sync/stream-aead.js.map +1 -0
  656. package/dist/stream-sync/timer.d.ts +3 -0
  657. package/dist/stream-sync/timer.d.ts.map +1 -0
  658. package/dist/stream-sync/timer.js +3 -0
  659. package/dist/stream-sync/timer.js.map +1 -0
  660. package/dist/stream-sync-read/index.d.ts +4 -0
  661. package/dist/stream-sync-read/index.d.ts.map +1 -0
  662. package/dist/stream-sync-read/index.js +3 -0
  663. package/dist/stream-sync-read/index.js.map +1 -0
  664. package/dist/stream-sync-read/routing.d.ts +27 -0
  665. package/dist/stream-sync-read/routing.d.ts.map +1 -0
  666. package/dist/stream-sync-read/routing.js +49 -0
  667. package/dist/stream-sync-read/routing.js.map +1 -0
  668. package/dist/stream-sync-read/service.d.ts +281 -0
  669. package/dist/stream-sync-read/service.d.ts.map +1 -0
  670. package/dist/stream-sync-read/service.js +18 -0
  671. package/dist/stream-sync-read/service.js.map +1 -0
  672. package/dist/sync/account-mode/authority.d.ts +121 -0
  673. package/dist/sync/account-mode/authority.d.ts.map +1 -0
  674. package/dist/sync/account-mode/authority.js +446 -0
  675. package/dist/sync/account-mode/authority.js.map +1 -0
  676. package/dist/sync/account-mode/evidence-wire.d.ts +42 -0
  677. package/dist/sync/account-mode/evidence-wire.d.ts.map +1 -0
  678. package/dist/sync/account-mode/evidence-wire.js +76 -0
  679. package/dist/sync/account-mode/evidence-wire.js.map +1 -0
  680. package/dist/sync/account-mode/import-waker.d.ts +36 -0
  681. package/dist/sync/account-mode/import-waker.d.ts.map +1 -0
  682. package/dist/sync/account-mode/import-waker.js +55 -0
  683. package/dist/sync/account-mode/import-waker.js.map +1 -0
  684. package/dist/sync/account-mode/index.d.ts +10 -0
  685. package/dist/sync/account-mode/index.d.ts.map +1 -0
  686. package/dist/sync/account-mode/index.js +10 -0
  687. package/dist/sync/account-mode/index.js.map +1 -0
  688. package/dist/sync/account-mode/port.d.ts +11 -0
  689. package/dist/sync/account-mode/port.d.ts.map +1 -0
  690. package/dist/sync/account-mode/port.js +21 -0
  691. package/dist/sync/account-mode/port.js.map +1 -0
  692. package/dist/sync/account-mode/record.d.ts +54 -0
  693. package/dist/sync/account-mode/record.d.ts.map +1 -0
  694. package/dist/sync/account-mode/record.js +62 -0
  695. package/dist/sync/account-mode/record.js.map +1 -0
  696. package/dist/sync/account-mode/rw-lock.d.ts +14 -0
  697. package/dist/sync/account-mode/rw-lock.d.ts.map +1 -0
  698. package/dist/sync/account-mode/rw-lock.js +59 -0
  699. package/dist/sync/account-mode/rw-lock.js.map +1 -0
  700. package/dist/sync/cancellable-gateway.d.ts +25 -0
  701. package/dist/sync/cancellable-gateway.d.ts.map +1 -0
  702. package/dist/sync/cancellable-gateway.js +64 -0
  703. package/dist/sync/cancellable-gateway.js.map +1 -0
  704. package/dist/sync/engine/change-probe.d.ts +49 -0
  705. package/dist/sync/engine/change-probe.d.ts.map +1 -0
  706. package/dist/sync/engine/change-probe.js +84 -0
  707. package/dist/sync/engine/change-probe.js.map +1 -0
  708. package/dist/sync/engine/change-push.d.ts +56 -0
  709. package/dist/sync/engine/change-push.d.ts.map +1 -0
  710. package/dist/sync/engine/change-push.js +176 -0
  711. package/dist/sync/engine/change-push.js.map +1 -0
  712. package/dist/sync/engine/sync-manager.d.ts +208 -1
  713. package/dist/sync/engine/sync-manager.d.ts.map +1 -1
  714. package/dist/sync/engine/sync-manager.js +1005 -34
  715. package/dist/sync/engine/sync-manager.js.map +1 -1
  716. package/dist/sync/index.d.ts +6 -2
  717. package/dist/sync/index.d.ts.map +1 -1
  718. package/dist/sync/index.js +5 -1
  719. package/dist/sync/index.js.map +1 -1
  720. package/dist/sync/pdpp-import.d.ts +12 -2
  721. package/dist/sync/pdpp-import.d.ts.map +1 -1
  722. package/dist/sync/pdpp-import.js +32 -7
  723. package/dist/sync/pdpp-import.js.map +1 -1
  724. package/dist/sync/tombstone-resubmits.d.ts +7 -4
  725. package/dist/sync/tombstone-resubmits.d.ts.map +1 -1
  726. package/dist/sync/tombstone-resubmits.js.map +1 -1
  727. package/dist/sync/types.d.ts +29 -0
  728. package/dist/sync/types.d.ts.map +1 -1
  729. package/dist/sync/upload-attempts.d.ts +244 -0
  730. package/dist/sync/upload-attempts.d.ts.map +1 -0
  731. package/dist/sync/upload-attempts.js +548 -0
  732. package/dist/sync/upload-attempts.js.map +1 -0
  733. package/dist/sync/upload-state.d.ts +163 -0
  734. package/dist/sync/upload-state.d.ts.map +1 -0
  735. package/dist/sync/upload-state.js +239 -0
  736. package/dist/sync/upload-state.js.map +1 -0
  737. package/dist/sync/workers/delete.d.ts +33 -1
  738. package/dist/sync/workers/delete.d.ts.map +1 -1
  739. package/dist/sync/workers/delete.js +83 -11
  740. package/dist/sync/workers/delete.js.map +1 -1
  741. package/dist/sync/workers/download.d.ts +3 -0
  742. package/dist/sync/workers/download.d.ts.map +1 -1
  743. package/dist/sync/workers/download.js +67 -12
  744. package/dist/sync/workers/download.js.map +1 -1
  745. package/dist/sync/workers/upload.d.ts +70 -2
  746. package/dist/sync/workers/upload.d.ts.map +1 -1
  747. package/dist/sync/workers/upload.js +354 -23
  748. package/dist/sync/workers/upload.js.map +1 -1
  749. package/dist/test-support/memory-oracle.calibration.d.ts +16 -0
  750. package/dist/test-support/memory-oracle.calibration.d.ts.map +1 -0
  751. package/dist/test-support/memory-oracle.calibration.js +43 -0
  752. package/dist/test-support/memory-oracle.calibration.js.map +1 -0
  753. package/dist/test-support/memory-oracle.d.ts +82 -0
  754. package/dist/test-support/memory-oracle.d.ts.map +1 -0
  755. package/dist/test-support/memory-oracle.js +104 -0
  756. package/dist/test-support/memory-oracle.js.map +1 -0
  757. package/dist/test-utils/account-mode.d.ts +36 -0
  758. package/dist/test-utils/account-mode.d.ts.map +1 -0
  759. package/dist/test-utils/account-mode.js +78 -0
  760. package/dist/test-utils/account-mode.js.map +1 -0
  761. package/dist/test-utils/index.d.ts +3 -0
  762. package/dist/test-utils/index.d.ts.map +1 -1
  763. package/dist/test-utils/index.js +3 -0
  764. package/dist/test-utils/index.js.map +1 -1
  765. package/dist/test-utils/legacy-write-seal.d.ts +16 -0
  766. package/dist/test-utils/legacy-write-seal.d.ts.map +1 -0
  767. package/dist/test-utils/legacy-write-seal.js +20 -0
  768. package/dist/test-utils/legacy-write-seal.js.map +1 -0
  769. package/dist/test-utils/live-grants.d.ts +24 -0
  770. package/dist/test-utils/live-grants.d.ts.map +1 -0
  771. package/dist/test-utils/live-grants.js +6 -0
  772. package/dist/test-utils/live-grants.js.map +1 -0
  773. package/dist/test-utils/memory-storage.d.ts +17 -1
  774. package/dist/test-utils/memory-storage.d.ts.map +1 -1
  775. package/dist/test-utils/memory-storage.js +94 -46
  776. package/dist/test-utils/memory-storage.js.map +1 -1
  777. package/dist/test-utils/run-end.d.ts +27 -0
  778. package/dist/test-utils/run-end.d.ts.map +1 -0
  779. package/dist/test-utils/run-end.js +44 -0
  780. package/dist/test-utils/run-end.js.map +1 -0
  781. package/dist/test-utils/wallet.d.ts +0 -4
  782. package/dist/test-utils/wallet.d.ts.map +1 -1
  783. package/dist/test-utils/wallet.js +3 -12
  784. package/dist/test-utils/wallet.js.map +1 -1
  785. package/dist/write/attribution.d.ts.map +1 -1
  786. package/dist/write/attribution.js +2 -4
  787. package/dist/write/attribution.js.map +1 -1
  788. package/dist-test/localdb/conformance.d.ts +13 -0
  789. package/dist-test/localdb/conformance.d.ts.map +1 -0
  790. package/dist-test/localdb/conformance.js +372 -0
  791. package/dist-test/localdb/conformance.js.map +1 -0
  792. package/dist-test/tsconfig.tsbuildinfo +1 -0
  793. package/package.json +60 -5
@@ -0,0 +1,1745 @@
1
+ // The writer of the stream-sync log (stream-sync/src/log.ts).
2
+ //
3
+ // One round publishes one batch: the changes of every stream that has work,
4
+ // as ONE immutable segment object (one PUT) and ONE registry commit that
5
+ // advances the connection's log position, so request count does not grow with
6
+ // stream count. It is the only way a connection publishes.
7
+ //
8
+ // SNAPSHOT (slot) Decide, for each stream, what its publish is: apply the
9
+ // retained runs' plan (`planStream`), select the changes since the stream's
10
+ // watermark, read the changed records, and, for a stream whose newest
11
+ // replacing run still applies, list the keys that run dropped. Build the
12
+ // segment, encode, hash, encrypt. Read nothing from the registry unless the
13
+ // connection's control row is not yet known to be active here.
14
+ // TRANSFER (no slot) Upload the attachments, then the segment.
15
+ // COMMIT (slot) Re-read the basis. Post one row for the log scope at
16
+ // version position+1 with a condition on the control row, in one
17
+ // all-or-nothing request. A new connection's first save also carries the
18
+ // control row's creation (version 1): the segment's PUT needs no control
19
+ // row (objects are content addressed and authorize nothing until a commit
20
+ // names them), so the creation waits for the commit and costs no round
21
+ // trip of its own. A lost log row applies the winner and starts the round
22
+ // over; a lost control row reads the control row; a failed control
23
+ // condition purges or defers. On success one local batch: replace
24
+ // deletes, each touched stream's local head, watermarks, run evidence, the
25
+ // log position, and compaction of `record_changes`.
26
+ //
27
+ // A batch is bounded by the part target: a round takes the changes of streams
28
+ // in order until the target is reached and leaves the rest for the next round,
29
+ // except that a stream whose replacing run applies goes whole (its omission
30
+ // completion and its changes are one unit) when the whole fits one segment.
31
+ // A larger one goes in rounds, and only the round with its completion says
32
+ // the stream is complete. A completion larger than what a round has left goes
33
+ // in pieces, each naming a range of the dropped keys in hash order. A single
34
+ // record larger than the target goes alone, its body out of line.
35
+ //
36
+ // Runs it cannot place (refused, fenced, from another lifetime) are cleaned up
37
+ // and the round starts over; runs it cannot order yet (deferred) hold only
38
+ // their own stream.
39
+ //
40
+ // Compaction rides the batch's own commit (log-compact.ts): when the cost rule
41
+ // or the head's bound says so, the segment carries a snapshot pointer, a new
42
+ // `base`, and no refs at or below it.
43
+ import { sha256 } from "@noble/hashes/sha2";
44
+ import { LOG_FORMAT, DEFAULT_PART_TARGET_BYTES, classifyControl, compactionRequired, controlHashes, controlScope, deriveKeyCheck, digestSegment, encodeSegment, segmentRemoves, deletionKeyMatchesHash, firstDeletionKeyMismatch, keyFromRecordKey, logScope, primaryKeyValues, streamScope, verifySegment, } from "@opendatalabs/personal-server-ts-stream-sync";
45
+ import { RegistryBatchRouteMissingError, RegistryRefusedError, } from "../stream-sync/ports.js";
46
+ import { StorageDeferredError } from "../stream-sync/storage-retry.js";
47
+ import { sameHead } from "../stream-sync/publish-plan.js";
48
+ import { keccakOf } from "../stream-sync/crypto-port.js";
49
+ import { putBodiesOutOfLine } from "./log-bodies.js";
50
+ import { seedFromRecords } from "./log-seed.js";
51
+ import { applyConnection } from "./apply.js";
52
+ import { listStreamBlobs, uploadBlobs } from "./blobs.js";
53
+ import { batchBounds, checkBatchRoom, settleRequirementFailure, settleRow, } from "./batch-commit.js";
54
+ import { tombstoneOmissions } from "./admit.js";
55
+ import { planCompaction } from "./log-compact.js";
56
+ import { logPublishPhases, openPhases, } from "./log-publish-phases.js";
57
+ import { readLogState, writeLogState } from "./log-apply.js";
58
+ import { rowsPerStatement } from "./log-batch.js";
59
+ import { replaceDelete, seenBeforeParams, SEEN_BEFORE, withOrigin, } from "./merge.js";
60
+ import { discardFencedRuns, discardForeignLifetimeRuns, excludeSeedsIfAny, hasDeleteIntent, lifetimeHolds, metadataHashFor, planStream, postBatchOnce, runPublicationStatements, retainedRuns, } from "./publish.js";
61
+ import { BODY_BYTES } from "./part-layout.js";
62
+ import { adoptDelete, connectionLifetime } from "./purge.js";
63
+ import { ELIGIBLE_CHANGE, PENDING_RUN, readPublicationWork, pendingChangeReasons, } from "./publication-work.js";
64
+ import { readPublicationStatus } from "./run-receipts.js";
65
+ import { insideQueue } from "./slot.js";
66
+ import { unwriteRefusedRun } from "./unwrite.js";
67
+ /**
68
+ * A transfer page holds at most `PAGE_BYTES` of bodies when two or more rows
69
+ * fit; a row larger than that is a page of its own (a body is encoded whole).
70
+ * Row sizes are read `META_ROWS` at a time and cut into pages; a page also
71
+ * holds at most `META_ROWS` rows.
72
+ */
73
+ const META_ROWS = 2048;
74
+ export const PAGE_BYTES = 2 * 1024 * 1024;
75
+ const MAX_ATTEMPTS = 5;
76
+ /** Keys a query binds: the delete lookup binds a connection, a stream and two positions beside them. */
77
+ const KEYS_PER_QUERY = rowsPerStatement(1, 4);
78
+ /**
79
+ * The stream as the log last described it: the base a plan starts from. A
80
+ * stream with no head was never described, so its own state is the base.
81
+ */
82
+ function asPublished(row) {
83
+ if (row.head_version === 0)
84
+ return row;
85
+ if (row.published_primary_key === null || row.published_complete === null)
86
+ throw new Error(`publish: stream ${row.stream} has head version ${row.head_version} and no meta for it`);
87
+ return {
88
+ ...row,
89
+ primary_key: row.published_primary_key,
90
+ profile_key: row.published_profile_key,
91
+ profile_version: row.published_profile_version,
92
+ complete: row.published_complete,
93
+ };
94
+ }
95
+ /**
96
+ * Publish a connection through the log. Every commit is a batch request:
97
+ * throws `RegistryBatchRouteMissingError` when the registry serves none.
98
+ */
99
+ export async function publishLog(deps, connectionId) {
100
+ if (!deps.registry.postBatch)
101
+ throw new RegistryBatchRouteMissingError("this registry has no batch port");
102
+ // One publish of a connection at a time. A publish releases the queue slot
103
+ // while it uploads, and what it sends is chosen at its snapshot and leaves
104
+ // the pending set only at its local commit. A second publish that took its
105
+ // snapshot in between would choose the same changes: it would encode and
106
+ // upload the same segment again and commit nothing. It waits for the first
107
+ // instead, then publishes what is left, which is usually nothing; the
108
+ // completion read covers the work pending when each caller arrived, even
109
+ // if the preceding publish was the one that acknowledged it.
110
+ const earlier = inFlight.get(deps.db)?.get(connectionId);
111
+ const own = (async () => {
112
+ // The earlier publish's own failure is its caller's; this one starts over.
113
+ // Order the call's initial read after intake already queued by its caller.
114
+ const work = await deps.queue.run(connectionId, "publish", () => readPublicationWork(deps.db, connectionId));
115
+ if (earlier)
116
+ await earlier.catch(() => null);
117
+ const clock = openPhases(deps);
118
+ try {
119
+ await publishRounds(deps, connectionId, clock);
120
+ return deps.queue.run(connectionId, "publish", () => completedResults(insideQueue(deps, connectionId), connectionId, work));
121
+ }
122
+ finally {
123
+ logPublishPhases(deps, connectionId, clock);
124
+ }
125
+ })();
126
+ const chain = inFlightOf(deps.db);
127
+ chain.set(connectionId, own);
128
+ try {
129
+ return await own;
130
+ }
131
+ finally {
132
+ if (chain.get(connectionId) === own)
133
+ chain.delete(connectionId);
134
+ }
135
+ }
136
+ /** Publishes in flight, by database and connection (see `publishLog`). */
137
+ const inFlight = new WeakMap();
138
+ function inFlightOf(db) {
139
+ let chain = inFlight.get(db);
140
+ if (!chain)
141
+ inFlight.set(db, (chain = new Map()));
142
+ return chain;
143
+ }
144
+ /** Attempt outcomes describe blocked work, never the caller's completion. */
145
+ const blockedOrder = [
146
+ "deferred",
147
+ "backoff",
148
+ "discarded",
149
+ "purged",
150
+ "refused",
151
+ ];
152
+ async function recordBlocked(deps, id, results) {
153
+ for (const result of results) {
154
+ const rank = blockedOrder.indexOf(result.outcome);
155
+ if (rank < 0)
156
+ continue;
157
+ // Each row records its latest attempt. Severity orders rows at completion,
158
+ // never attempts over time.
159
+ await deps.db.batch([
160
+ {
161
+ sql: `UPDATE record_changes SET publish_blocked_reason=?
162
+ WHERE connection_id=? AND stream=?
163
+ AND seq > (SELECT publish_watermark FROM stream_state WHERE connection_id=? AND stream=?)
164
+ AND ${ELIGIBLE_CHANGE}`,
165
+ params: [result.outcome, id, result.stream, id, result.stream],
166
+ },
167
+ {
168
+ sql: `UPDATE run_streams SET publish_blocked_reason=? WHERE stream=?
169
+ AND run_id IN (SELECT r.run_id FROM runs r JOIN run_streams rs ON rs.run_id=r.run_id
170
+ WHERE r.connection_id=? AND rs.stream=? AND ${PENDING_RUN})`,
171
+ params: [result.outcome, result.stream, id, result.stream],
172
+ },
173
+ ]);
174
+ }
175
+ }
176
+ /** Completion is read after all work, independently of the order of attempts. */
177
+ async function completedResults(deps, id, work) {
178
+ const [connection] = await deps.db.query("SELECT connector, ns, generation, control_state FROM connections WHERE connection_id=?", [id]);
179
+ const deleting = connection
180
+ ? await hasDeleteIntent(deps, connection.connector)
181
+ : false;
182
+ const log = await readLogState(deps, id);
183
+ const remaining = await readPublicationWork(deps.db, id);
184
+ const results = [];
185
+ for (const item of work) {
186
+ const [state] = await deps.db.query("SELECT publish_watermark, head_generation, head_data_hash FROM stream_state WHERE connection_id=? AND stream=?", [id, item.stream]);
187
+ const statuses = await Promise.all(item.runIds.map((runId) => readPublicationStatus(deps.db, runId)));
188
+ const streams = statuses.map((status) => status.streams.find((s) => s.name === item.stream));
189
+ const changeReasons = await pendingChangeReasons(deps.db, id, item);
190
+ const rest = remaining.find((w) => w.stream === item.stream);
191
+ const pending = changeReasons.length > 0 || streams.some((s) => s.state === "pending");
192
+ const reasons = new Set([
193
+ ...changeReasons,
194
+ ...item.runIds
195
+ .filter((_, i) => streams[i].state === "pending")
196
+ .map((runId) => rest?.runReasons.get(runId)),
197
+ ]);
198
+ const blocked = [...blockedOrder].reverse().find((reason) => reasons.has(reason)) ??
199
+ "deferred";
200
+ const superseded = streams.some((s) => s.state === "superseded" && !s.reason?.startsWith("replaced_by:"));
201
+ const runIds = item.runIds.filter((_, i) => streams[i].publication !== undefined);
202
+ const evidence = streams
203
+ .flatMap((s) => (s.publication ? [s.publication] : []))
204
+ .sort((a, b) => b.version - a.version)[0];
205
+ const hadWork = item.hadChanges || item.runIds.length > 0;
206
+ const lifetimeEnded = item.lifetime !== connectionLifetime(deps.db, id) ||
207
+ connection?.generation !== item.generation;
208
+ const outcome = lifetimeEnded
209
+ ? // A deleted connection adopted its tombstone: settled. A lifetime a
210
+ // newer live generation replaced was not deleted: its work is owed
211
+ // still, and the caller is told it is unconfirmed.
212
+ connection?.control_state === "deleted"
213
+ ? "purged"
214
+ : "replaced"
215
+ : deleting
216
+ ? "deferred"
217
+ : // A deleted connection owes nothing once its purge settled the work:
218
+ // only a stream that still held work reports the purge.
219
+ connection?.control_state === "deleted" && hadWork
220
+ ? "purged"
221
+ : pending
222
+ ? blocked
223
+ : superseded
224
+ ? "discarded"
225
+ : hadWork
226
+ ? "published"
227
+ : "noop";
228
+ results.push({
229
+ stream: item.stream,
230
+ outcome,
231
+ watermark: state?.publish_watermark ?? null,
232
+ ...(outcome === "published" &&
233
+ connection &&
234
+ state?.head_data_hash && {
235
+ publication: {
236
+ connectionId: id,
237
+ connector: connection.connector,
238
+ ns: connection.ns,
239
+ stream: item.stream,
240
+ head: {
241
+ version: evidence?.version ??
242
+ log.refs.find((r) => r.dataHash === state.head_data_hash)
243
+ ?.position ??
244
+ log.position,
245
+ generation: evidence?.generation ??
246
+ state.head_generation ??
247
+ connection.generation,
248
+ dataHash: evidence?.dataHash ?? state.head_data_hash,
249
+ },
250
+ watermark: evidence?.watermark ?? state.publish_watermark,
251
+ runIds,
252
+ },
253
+ }),
254
+ });
255
+ }
256
+ return results;
257
+ }
258
+ const pendingCommits = new WeakMap();
259
+ function pendingOf(db) {
260
+ let pending = pendingCommits.get(db);
261
+ if (!pending)
262
+ pendingCommits.set(db, (pending = new Map()));
263
+ return pending;
264
+ }
265
+ function isInvalidated(entry) {
266
+ return entry.state.kind === "invalidated";
267
+ }
268
+ function hasAmbiguousCommit(entry) {
269
+ return ((entry.state.kind === "uploaded" || entry.state.kind === "invalidated") &&
270
+ entry.state.ambiguous);
271
+ }
272
+ function transition(entry, event) {
273
+ const state = entry.state;
274
+ if (event === "invalidated") {
275
+ entry.state = { kind: "invalidated", ambiguous: hasAmbiguousCommit(entry) };
276
+ }
277
+ else if (event === "reconciled" && state.kind === "committed") {
278
+ return;
279
+ }
280
+ else if (event === "reconciled" &&
281
+ (state.kind === "uploaded" || state.kind === "invalidated")) {
282
+ entry.state = { kind: state.kind, ambiguous: false };
283
+ }
284
+ else if (event === "uploaded" && state.kind === "uploading") {
285
+ entry.state = { kind: "uploaded", ambiguous: false };
286
+ }
287
+ else if (event === "ambiguous" && state.kind === "uploaded") {
288
+ entry.state = { kind: "uploaded", ambiguous: true };
289
+ }
290
+ else if (event === "committed" &&
291
+ (state.kind === "uploaded" || state.kind === "committed")) {
292
+ entry.state = { kind: "committed" };
293
+ }
294
+ else if (event === "refused" &&
295
+ state.kind === "uploaded" &&
296
+ !state.ambiguous) {
297
+ entry.state = { kind: "refused" };
298
+ }
299
+ else {
300
+ throw new Error(`publish: invalid candidate transition ${state.kind} -> ${event}`);
301
+ }
302
+ }
303
+ function releaseCandidate(pending, id, entry) {
304
+ if (hasAmbiguousCommit(entry) ||
305
+ entry.state.kind === "uploading" ||
306
+ entry.state.kind === "uploaded")
307
+ throw new Error("publish: cannot release an unsettled candidate");
308
+ pending.delete(id);
309
+ }
310
+ async function invalidateExpiredCandidate(held, id, entry) {
311
+ const [row] = await held.db.query("SELECT generation, control_state FROM connections WHERE connection_id = ?", [id]);
312
+ if (entry.candidate.lifetime !== connectionLifetime(held.db, id) ||
313
+ !row ||
314
+ row.generation !== entry.candidate.generation ||
315
+ // A first save's control row is created by its commit, so its connection
316
+ // is still absent here; it is active once another path (an apply after a
317
+ // lost reply) has seen the row. Either way the candidate stands.
318
+ !(entry.candidate.createControl
319
+ ? row.control_state === "absent" || row.control_state === "active"
320
+ : row.control_state === "active") ||
321
+ (await hasDeleteIntent(held, entry.candidate.connector)))
322
+ transition(entry, "invalidated");
323
+ }
324
+ async function publishRounds(deps, connectionId, clock) {
325
+ const record = (list) => recordBlocked(deps, connectionId, list);
326
+ let attempts = 0;
327
+ const pending = pendingOf(deps.db);
328
+ for (;;) {
329
+ let retained = pending.get(connectionId);
330
+ if (retained) {
331
+ const entry = retained;
332
+ const recovered = await deps.queue.run(connectionId, "publish", async () => {
333
+ const held = insideQueue(deps, connectionId);
334
+ await invalidateExpiredCandidate(held, connectionId, entry);
335
+ if (hasAmbiguousCommit(entry) || entry.state.kind === "committed")
336
+ return reconcileCandidate(held, connectionId, entry);
337
+ if (!isInvalidated(entry) &&
338
+ (await basisOf(held, connectionId, entry.candidate.planned, await readLogState(held, connectionId))) !== entry.candidate.basis)
339
+ transition(entry, "invalidated");
340
+ return null;
341
+ });
342
+ if (recovered)
343
+ await record(recovered);
344
+ if (entry.state.kind === "invalidated" ||
345
+ entry.state.kind === "committed" ||
346
+ entry.state.kind === "refused") {
347
+ releaseCandidate(pending, connectionId, entry);
348
+ retained = undefined;
349
+ }
350
+ }
351
+ const turn = retained
352
+ ? { kind: "candidate", candidate: retained.candidate }
353
+ : await clock.time("snapshot", () => deps.queue.run(connectionId, "publish", async () => {
354
+ const held = insideQueue(deps, connectionId);
355
+ return snapshotRound(held, connectionId, clock);
356
+ }));
357
+ if (turn.kind === "done") {
358
+ // Bytes that arrived after their records were published still go up.
359
+ if (turn.attachments && turn.attachments.length > 0) {
360
+ const attachments = turn.attachments;
361
+ await clock.time("attachments", () => uploadBlobs(deps, attachments));
362
+ }
363
+ await record(turn.results);
364
+ break;
365
+ }
366
+ if (turn.kind === "retry") {
367
+ if (++attempts >= MAX_ATTEMPTS) {
368
+ await record(await backoff(deps, connectionId));
369
+ break;
370
+ }
371
+ continue;
372
+ }
373
+ const { candidate } = turn;
374
+ const transfer = retained ?? {
375
+ candidate,
376
+ state: { kind: "uploading" },
377
+ };
378
+ pending.set(connectionId, transfer);
379
+ // TRANSFER: no slot. Objects are content addressed and authorize nothing
380
+ // until the registry commit, so nothing orders one PUT before another:
381
+ // the attachments, the snapshot parts and the segment that names them go
382
+ // at once and the commit waits for all of them. The commit's one
383
+ // dependency is the objects it names.
384
+ const scope = logScope(candidate.connector, candidate.ns);
385
+ try {
386
+ if (transfer.state.kind === "uploading") {
387
+ await allTransferred([
388
+ candidate.attachments.length > 0
389
+ ? clock.time("attachments", () => uploadBlobs(deps, candidate.attachments))
390
+ : undefined,
391
+ clock.time("segment-put", () => allTransferred([
392
+ ...candidate.objects.map((object) => putIfMissing(deps, `${scope}/${object.name}`, object.cipher, retained !== undefined || attempts > 0)),
393
+ putIfMissing(deps, `${scope}/${candidate.blobName}`, candidate.cipher, retained !== undefined || attempts > 0),
394
+ ])),
395
+ ]);
396
+ transition(transfer, "uploaded");
397
+ }
398
+ }
399
+ catch (error) {
400
+ // Storage kept refusing past its retry budget. Nothing is wrong with the
401
+ // data: nothing was committed, so the changes stay queued and the next
402
+ // cycle sends them again.
403
+ if (!(error instanceof StorageDeferredError))
404
+ throw error;
405
+ deps.logger.info({ connectionId, error: error.message }, "stream sync: storage unavailable, publish left in the queue");
406
+ await record(await backoff(deps, connectionId));
407
+ break;
408
+ }
409
+ let committed;
410
+ try {
411
+ committed = await clock.time("commit", () => deps.queue.run(connectionId, "publish", () => commitRound(insideQueue(deps, connectionId), connectionId, transfer, clock)));
412
+ }
413
+ catch (error) {
414
+ if ((error instanceof RegistryRefusedError ||
415
+ error instanceof RegistryBatchRouteMissingError) &&
416
+ transfer.state.kind === "uploaded" &&
417
+ !hasAmbiguousCommit(transfer)) {
418
+ transition(transfer, "refused");
419
+ releaseCandidate(pending, connectionId, transfer);
420
+ }
421
+ throw error;
422
+ }
423
+ releaseCandidate(pending, connectionId, transfer);
424
+ if (committed.kind === "retry") {
425
+ if (++attempts >= MAX_ATTEMPTS) {
426
+ await record(await backoff(deps, connectionId));
427
+ break;
428
+ }
429
+ continue;
430
+ }
431
+ await record(committed.results);
432
+ attempts = 0;
433
+ if (!committed.more)
434
+ break;
435
+ }
436
+ }
437
+ /**
438
+ * Probe retries only. Storage must publish complete objects atomically:
439
+ * existence proves the whole immutable object is available.
440
+ */
441
+ async function putIfMissing(deps, key, bytes, checkExisting) {
442
+ if (!checkExisting || !(await deps.blobs.exists(key)))
443
+ await deps.blobs.put(key, bytes);
444
+ }
445
+ // A failed transfer must not leave another PUT running into the next retry.
446
+ async function allTransferred(transfers) {
447
+ const results = await Promise.allSettled(transfers);
448
+ const failed = results.find((r) => r.status === "rejected");
449
+ if (failed)
450
+ throw failed.reason;
451
+ }
452
+ async function backoff(deps, connectionId) {
453
+ const streams = await deps.db.query("SELECT stream FROM stream_state WHERE connection_id = ? ORDER BY stream", [connectionId]);
454
+ return streams.map(({ stream }) => ({
455
+ stream,
456
+ outcome: "backoff",
457
+ watermark: null,
458
+ }));
459
+ }
460
+ const chunked = (items, size) => {
461
+ const out = [];
462
+ for (let i = 0; i < items.length; i += size)
463
+ out.push(items.slice(i, i + size));
464
+ return out;
465
+ };
466
+ /**
467
+ * What this process already warned about, by database and connection: a held
468
+ * stream's warned state, so one held state warns once however many publish
469
+ * passes meet it.
470
+ */
471
+ const heldWarnings = new WeakMap();
472
+ function warnedHolds(db, connectionId) {
473
+ let byConnection = heldWarnings.get(db);
474
+ if (!byConnection)
475
+ heldWarnings.set(db, (byConnection = new Map()));
476
+ let streams = byConnection.get(connectionId);
477
+ if (!streams)
478
+ byConnection.set(connectionId, (streams = new Map()));
479
+ return streams;
480
+ }
481
+ async function snapshotRound(held, connectionId, clock) {
482
+ const [connection] = await held.db.query("SELECT connector, ns, generation, control_state FROM connections WHERE connection_id = ?", [connectionId]);
483
+ if (!connection)
484
+ throw new Error(`publish: unknown connection ${connectionId}`);
485
+ const streams = await held.db.query(`SELECT s.stream, s.primary_key, s.profile_key, s.profile_version, s.complete,
486
+ s.floor_version, s.floor_o, s.floor_r, s.last_delete_version,
487
+ s.head_version, s.head_generation, s.head_data_hash, s.publish_watermark,
488
+ v.complete AS published_complete, v.primary_key AS published_primary_key,
489
+ v.profile_key AS published_profile_key,
490
+ v.profile_version AS published_profile_version
491
+ FROM stream_state s
492
+ LEFT JOIN stream_versions v
493
+ ON v.connection_id = s.connection_id AND v.stream = s.stream
494
+ AND v.version = s.head_version
495
+ WHERE s.connection_id = ? ORDER BY s.stream`, [connectionId]);
496
+ const all = (outcome) => ({
497
+ kind: "done",
498
+ results: streams.map(({ stream }) => ({
499
+ stream,
500
+ outcome,
501
+ watermark: null,
502
+ })),
503
+ });
504
+ if (await hasDeleteIntent(held, connection.connector))
505
+ return all("deferred");
506
+ if (streams.length === 0)
507
+ return { kind: "done", results: [] };
508
+ const keyCheck = await deriveKeyCheck(held.keys.namespaceHmac);
509
+ const hashes = await controlHashes(keccakOf(held.streamCrypto), keyCheck);
510
+ // Control. A connection this device already holds as active is confirmed by
511
+ // the commit's own condition; only an unknown one is read here. A first
512
+ // save creates the row with its commit.
513
+ const controlDataHash = hashes.activeData;
514
+ let createControl = false;
515
+ if (connection.control_state !== "active") {
516
+ const settled = await clock.time("control", () => establishControl(held, connectionId, connection, hashes));
517
+ if (settled === "create")
518
+ createControl = true;
519
+ else if (settled !== "active")
520
+ return all(settled);
521
+ }
522
+ if (await discardForeignLifetimeRuns(held, connectionId, connection.generation)) {
523
+ await applyConnection(held, connectionId);
524
+ return { kind: "retry" };
525
+ }
526
+ await held.db.batch([
527
+ ...(createControl ? [] : [markControlActive(connectionId, connection)]),
528
+ {
529
+ sql: "UPDATE runs SET generation=? WHERE connection_id=? AND generation IS NULL AND state='ended'",
530
+ params: [connection.generation, connectionId],
531
+ },
532
+ ]);
533
+ const planStart = clock.now();
534
+ const log = await readLogState(held, connectionId);
535
+ // A connection with no log yet starts it with everything this device holds
536
+ // (a device that applied a log first seeded when it did, `applyLog`).
537
+ const seeded = log.position === 0
538
+ ? await seedFromRecords(held, connectionId)
539
+ : new Set();
540
+ const planned = [];
541
+ const target = held.partTargetBytes ?? DEFAULT_PART_TARGET_BYTES;
542
+ let budget = 0;
543
+ let first = true;
544
+ // Streams this pass holds back, and streams it did not examine for it.
545
+ const heldNow = new Set();
546
+ const unexamined = new Set();
547
+ eachStream: for (const row of streams) {
548
+ const { stream } = row;
549
+ if (await discardFencedRuns(held, connectionId, stream)) {
550
+ await applyConnection(held, connectionId);
551
+ return { kind: "retry" };
552
+ }
553
+ if (connection.generation !== 1)
554
+ await excludeSeedsIfAny(held, connectionId, stream);
555
+ // The plan's base is what the log last said, not what the run's end wrote.
556
+ const published = asPublished(row);
557
+ const plan = await planStream(held, connectionId, connection, stream, published, null, row.head_version, row.head_data_hash);
558
+ if (plan.refused) {
559
+ await unwriteRefusedRun(held, {
560
+ connectionId,
561
+ stream,
562
+ runId: plan.refused.runId,
563
+ reason: plan.refused.reason,
564
+ });
565
+ await applyConnection(held, connectionId);
566
+ return { kind: "retry" };
567
+ }
568
+ const [wRow] = await held.db.query("SELECT MAX(seq) AS w FROM record_changes WHERE connection_id = ? AND stream = ?", [connectionId, stream]);
569
+ const watermark = wRow?.w ?? row.publish_watermark;
570
+ const base = {
571
+ stream,
572
+ local: row,
573
+ plan,
574
+ watermark,
575
+ ack: watermark,
576
+ included: false,
577
+ rest: false,
578
+ operations: [],
579
+ meta: null,
580
+ runIds: plan.steps.map((step) => step.runId),
581
+ replace: null,
582
+ replacing: null,
583
+ omitting: null,
584
+ omitted: [],
585
+ bytes: 0,
586
+ cursor: null,
587
+ };
588
+ if (plan.deferred) {
589
+ unexamined.add(stream);
590
+ planned.push({ ...base, ack: row.publish_watermark });
591
+ continue;
592
+ }
593
+ // The stream's local head stands for the log's last segment that touched
594
+ // it (see `applySegmentOperations`): a replacing run applies only if no
595
+ // segment touched the stream since the run began.
596
+ const replace = plan.replaceBelow ?? null;
597
+ const omitted = replace
598
+ ? await omittedBy(held, connectionId, stream, plan.finalHead?.primaryKey ?? JSON.parse(row.primary_key), replace)
599
+ : [];
600
+ const groups = await changedKeys(held, connectionId, stream, row.publish_watermark, watermark);
601
+ // A stream with no head yet (a first collection that publishes while it
602
+ // collects) is described by its local state.
603
+ const head = plan.finalHead ??
604
+ (groups.length > 0
605
+ ? {
606
+ generation: row.head_generation ?? connection.generation,
607
+ primaryKey: JSON.parse(row.primary_key),
608
+ profile: {
609
+ key: row.profile_key ?? connection.connector,
610
+ version: row.profile_version ?? row.floor_version ?? "0",
611
+ },
612
+ // A seeded stream is what this device holds, head and all: its
613
+ // completeness is its own. Other changes with no run to describe
614
+ // them belong to a first collection that is still filling.
615
+ complete: seeded.has(stream) && row.complete === 1,
616
+ }
617
+ : null);
618
+ const metaChanged = head !== null &&
619
+ (row.head_version === 0 ||
620
+ !sameHead(head, {
621
+ generation: row.head_generation ?? head.generation,
622
+ primaryKey: JSON.parse(published.primary_key),
623
+ profile: {
624
+ key: published.profile_key ?? connection.connector,
625
+ version: published.profile_version ?? "0",
626
+ },
627
+ complete: published.complete === 1,
628
+ }));
629
+ const metaPublishes = metaChanged && plan.steps.some((s) => s.decision.kind === "publish");
630
+ const hasWork = groups.length > 0 || replace !== null || metaPublishes;
631
+ if (!hasWork || head === null) {
632
+ planned.push({ ...base, runIds: base.runIds });
633
+ continue;
634
+ }
635
+ // Changes go in the order they were made, until the segment reaches the
636
+ // part target, measured on the operations themselves. The first thing in
637
+ // a segment always goes, however large, so a round always progresses.
638
+ //
639
+ // A replacing stream whose rows and completion fit one segment goes whole
640
+ // (a reader sees the replace at once), or waits for the next round if
641
+ // this segment is full. One larger than a segment goes like any other
642
+ // changes, over as many rounds as it needs. Its completion (the keys it
643
+ // dropped) goes in the round that takes its last rows, or alone in the
644
+ // next. A completion larger than what is left of the segment goes in
645
+ // pieces over as many rounds as it needs: each is a completion at the
646
+ // run's cutoff for the next keys in hash order, an omission per key like
647
+ // any other. Only the round with the last piece says the stream is
648
+ // complete: an earlier round says it is not, so a reader never takes a
649
+ // replace that is half published for a complete stream. Every operation
650
+ // merges per key by stamp, so rounds from other writers in between
651
+ // interleave as they would with any other changes.
652
+ const room = (size) => first || budget + size <= target;
653
+ const sizeOf = (op) => opSize(op, target);
654
+ const selected = [];
655
+ const taken = [];
656
+ let bytes = 100;
657
+ let rest = false;
658
+ let whole = false;
659
+ // A stream with a change the log cannot say stops here: nothing of it is
660
+ // published or acknowledged this round (`plan.deferred`, as for a stream
661
+ // that waits on its runs), so no change is lost without a trace.
662
+ const wasFirst = first;
663
+ const stop = (untyped) => {
664
+ first = wasFirst;
665
+ heldNow.add(stream);
666
+ // One warning per held state, not per pass: a cycle publishes more than
667
+ // once and a held stream is met again on every poll until its keys are
668
+ // known. The state is the set of changes held; a different set warns.
669
+ const state = [...untyped].sort().join(",");
670
+ const warned = warnedHolds(held.db, connectionId);
671
+ if (warned.get(stream) !== state) {
672
+ warned.set(stream, state);
673
+ held.logger.warn({ connectionId, stream, pkHashes: untyped.slice(0, 5) }, `stream sync: the log holds back stream "${stream}": an explicit delete made before typed keys were kept cannot be written to it, and the stream's declared key types do not give its key back`);
674
+ }
675
+ planned.push({
676
+ ...base,
677
+ plan: { ...plan, deferred: true },
678
+ ack: row.publish_watermark,
679
+ });
680
+ };
681
+ if (replace !== null) {
682
+ const { ops: found, untyped } = await operationsFor(held, connectionId, stream, groups.map((g) => g.pk), row.publish_watermark, watermark);
683
+ if (untyped.length > 0) {
684
+ stop(untyped);
685
+ continue;
686
+ }
687
+ let size = bytes + 100 + omittedSize(omitted);
688
+ for (const op of found.values())
689
+ size += sizeOf(op);
690
+ if (size <= target) {
691
+ if (!room(size)) {
692
+ planned.push({ ...base, ack: row.publish_watermark, rest: true });
693
+ continue;
694
+ }
695
+ // A stream can hold more keys than a call takes as arguments (a
696
+ // spread of ~125k overflows the stack), so these go one by one.
697
+ for (const group of groups)
698
+ selected.push(group);
699
+ for (const op of found.values())
700
+ taken.push(op);
701
+ bytes = size;
702
+ whole = true;
703
+ }
704
+ }
705
+ if (!whole)
706
+ scan: for (const batch of chunked(groups, KEYS_PER_QUERY)) {
707
+ const { ops: found, untyped } = await operationsFor(held, connectionId, stream, batch.map((g) => g.pk), row.publish_watermark, watermark);
708
+ if (untyped.length > 0) {
709
+ stop(untyped);
710
+ continue eachStream;
711
+ }
712
+ for (const group of batch) {
713
+ const op = found.get(group.pk);
714
+ const size = op ? sizeOf(op) : 0;
715
+ if (!room(bytes + size)) {
716
+ rest = true;
717
+ break scan;
718
+ }
719
+ selected.push(group);
720
+ if (op)
721
+ taken.push(op);
722
+ bytes += size;
723
+ first = false;
724
+ }
725
+ }
726
+ if (selected.length === 0 && groups.length > 0) {
727
+ planned.push({ ...base, ack: row.publish_watermark, rest: true });
728
+ continue;
729
+ }
730
+ // Rows of the stream wait for a later round; its completion waits with them.
731
+ const rowsRest = rest;
732
+ let completes = whole;
733
+ let piece = [];
734
+ if (replace !== null && !whole && !rowsRest) {
735
+ // An empty segment takes at least one key, so a round always progresses.
736
+ const fit = omissionsThatFit(omitted, target - budget - bytes - 100);
737
+ const take = fit === 0 && first ? 1 : fit;
738
+ if (take >= omitted.length) {
739
+ completes = true;
740
+ bytes += 100 + omittedSize(omitted);
741
+ }
742
+ else {
743
+ rest = true;
744
+ piece = omitted.slice(0, take);
745
+ if (piece.length > 0)
746
+ bytes += 100 + omittedSize(piece);
747
+ }
748
+ }
749
+ // A replace whose completion waits, with no rows or piece of its
750
+ // completion in this round, waits whole.
751
+ if (replace !== null &&
752
+ !completes &&
753
+ taken.length === 0 &&
754
+ piece.length === 0) {
755
+ planned.push({ ...base, ack: row.publish_watermark, rest: true });
756
+ continue;
757
+ }
758
+ // Changes that carry no operation are nothing to publish: the rows a
759
+ // replacing run dropped are deleted locally in the commit that publishes
760
+ // its completion, and those deletions are changes above that commit's
761
+ // watermark. Counted as work they would cost a segment that says nothing.
762
+ if (!completes && !rest && taken.length === 0 && !metaPublishes) {
763
+ planned.push({ ...base });
764
+ continue;
765
+ }
766
+ budget += bytes;
767
+ first = false;
768
+ const ack = rowsRest ? selected.at(-1).seq : watermark;
769
+ planned.push({
770
+ ...base,
771
+ included: true,
772
+ rest,
773
+ ack,
774
+ operations: [
775
+ ...orderedOperations(taken),
776
+ ...(replace && (completes || piece.length > 0)
777
+ ? [
778
+ {
779
+ kind: "complete",
780
+ stream,
781
+ cutoff: { o: replace.o, r: replace.r },
782
+ omitted: completes ? omitted : piece,
783
+ },
784
+ ]
785
+ : []),
786
+ ],
787
+ meta: {
788
+ stream,
789
+ primaryKey: head.primaryKey,
790
+ profile: head.profile,
791
+ complete: replace !== null && !completes ? false : head.complete,
792
+ },
793
+ replace: completes ? replace : null,
794
+ replacing: replace !== null && !completes ? replace : null,
795
+ omitting: piece.length > 0
796
+ ? { from: piece[0].pkHash, to: piece.at(-1).pkHash }
797
+ : null,
798
+ omitted: completes ? omitted : piece,
799
+ bytes,
800
+ });
801
+ }
802
+ await carryCursors(held, connectionId, connection.connector, streams, planned);
803
+ // A stream that is no longer held warns again if it is held again.
804
+ const warned = warnedHolds(held.db, connectionId);
805
+ for (const stream of [...warned.keys()])
806
+ if (!heldNow.has(stream) && !unexamined.has(stream))
807
+ warned.delete(stream);
808
+ const included = planned.filter((p) => p.included);
809
+ const settle = (outcomeFor) => planned.map((p) => ({
810
+ stream: p.stream,
811
+ outcome: outcomeFor(p),
812
+ watermark: p.watermark,
813
+ }));
814
+ // Attachments named by any stream's records, published or not yet: bytes can
815
+ // arrive after the records that name them were published.
816
+ clock.record("plan", planStart);
817
+ const attachments = [];
818
+ for (const p of planned)
819
+ if (!p.plan.deferred)
820
+ attachments.push(...(await listStreamBlobs(held, {
821
+ connectionId,
822
+ stream: p.stream,
823
+ scope: streamScope(connection.connector, connection.ns, p.stream),
824
+ generation: connection.generation,
825
+ })));
826
+ if (included.length === 0) {
827
+ // Nothing to publish. A new connection's control row is still created, as
828
+ // a request of its own. Record that every covered run was already saved
829
+ // by what the log holds, move the watermarks, and compact.
830
+ if (createControl) {
831
+ const created = await clock.time("control", () => commitControl(held, connectionId, connection, hashes));
832
+ if (created === "retry")
833
+ return { kind: "retry" };
834
+ if (created !== "active")
835
+ return all(created);
836
+ }
837
+ await commitIdle(held, connectionId, planned, log);
838
+ return {
839
+ kind: "done",
840
+ results: settle((p) => (p.plan.deferred ? "deferred" : "noop")),
841
+ attachments,
842
+ };
843
+ }
844
+ const scope = logScope(connection.connector, connection.ns);
845
+ // The log is folded into a snapshot when that is cheaper than replaying it
846
+ // (or it is at the head's bound), and this segment carries the result.
847
+ const compaction = await planCompaction(held, {
848
+ connector: connection.connector,
849
+ ns: connection.ns,
850
+ generation: connection.generation,
851
+ keyCheck,
852
+ scope,
853
+ log,
854
+ });
855
+ const base = compaction ? log.position : log.base;
856
+ const refs = compaction ? [] : log.refs;
857
+ const snapshot = compaction ? compaction.snapshot : log.snapshot;
858
+ if (compactionRequired(refs.length, snapshot?.parts.length ?? 0)) {
859
+ held.logger.warn({ connectionId, refs: refs.length, parts: snapshot?.parts.length ?? 0 }, "stream sync: the log head is full even after compaction");
860
+ return all("deferred");
861
+ }
862
+ const position = log.position + 1;
863
+ const observedAt = Math.max(...included.map((p) => p.plan.newestRunObservedAt ?? 0), 0);
864
+ const segment = {
865
+ format: LOG_FORMAT,
866
+ connector: connection.connector,
867
+ ns: connection.ns,
868
+ generation: connection.generation,
869
+ keyCheck,
870
+ position,
871
+ observedAt: observedAt || held.now(),
872
+ base,
873
+ snapshot,
874
+ refs,
875
+ streams: included.map((p) => p.meta),
876
+ operations: included.flatMap((p) => p.operations),
877
+ };
878
+ // A deletion's key is the one its hash covers, or the segment is not written.
879
+ const mismatch = await firstDeletionKeyMismatch(async (bytes) => sha256(bytes), segment.streams, segment.operations);
880
+ if (mismatch)
881
+ throw new Error(`publish: a deletion's key does not match its hash (${mismatch.stream}/${mismatch.pkHash})`);
882
+ const encodeStart = clock.now();
883
+ // A body larger than one object goes out of line (stream-sync `log.ts`).
884
+ const outOfLine = await putBodiesOutOfLine(held, scope, segment.operations, target);
885
+ const clear = encodeSegment({ ...segment, operations: outOfLine.ops });
886
+ const { dataHash, blobName } = await digestSegment(keccakOf(held.streamCrypto), clear);
887
+ // A segment that would not verify is never uploaded or posted.
888
+ const verified = await verifySegment(keccakOf(held.streamCrypto), clear, {
889
+ dataHash,
890
+ connector: connection.connector,
891
+ ns: connection.ns,
892
+ keyCheck,
893
+ position,
894
+ });
895
+ if (verified.kind !== "ok")
896
+ throw new Error(`publish: the log segment failed verification: ${verified.kind}`);
897
+ const cipher = await held.keys.encrypt(scope, clear);
898
+ clock.record("encode", encodeStart);
899
+ return {
900
+ kind: "candidate",
901
+ candidate: {
902
+ lifetime: connectionLifetime(held.db, connectionId),
903
+ connector: connection.connector,
904
+ ns: connection.ns,
905
+ basis: await basisOf(held, connectionId, planned, log),
906
+ state: log,
907
+ base,
908
+ refs,
909
+ snapshot,
910
+ objects: [...(compaction?.objects ?? []), ...outOfLine.pieces],
911
+ position,
912
+ generation: connection.generation,
913
+ dataHash,
914
+ blobName,
915
+ cipher,
916
+ clearBytes: clear.length,
917
+ removes: segmentRemoves(segment.operations),
918
+ observedAt: segment.observedAt,
919
+ planned,
920
+ attachments,
921
+ controlDataHash,
922
+ createControl,
923
+ prevHash: log.refs.at(-1)?.dataHash ?? null,
924
+ },
925
+ };
926
+ }
927
+ /**
928
+ * A stream's unpublished cursor rides this round only when no row it covers
929
+ * is left for a later round: the stream publishes all its changes through the
930
+ * run end's `cursor_seq`, and every stream that lists it in `state_parents`,
931
+ * transitively, has nothing left either and is not deferred. A cursor on an
932
+ * earlier round of a publication that a crash cuts short would claim rows no
933
+ * device holds. A parent's cursor claims its children's rows too (a run reads
934
+ * them through it), so a round that closes the parent but leaves a child's
935
+ * rows for later, or a child the publisher defers, holds the parent's cursor
936
+ * back; the parent's rows still go. A stream whose rows are all published
937
+ * already carries its cursor in a meta of its own, with no operation.
938
+ */
939
+ async function carryCursors(held, connectionId, connector, rows, planned) {
940
+ const pending = await held.db.query(`SELECT stream, cursor_unpublished, cursor_seq, cursor_children, cursor_write FROM stream_state
941
+ WHERE connection_id = ? AND cursor_unpublished IS NOT NULL`, [connectionId]);
942
+ if (pending.length === 0)
943
+ return;
944
+ const at = new Map(planned.map((p, i) => [p.stream, i]));
945
+ const closed = (stream) => {
946
+ const i = at.get(stream);
947
+ if (i === undefined)
948
+ return true;
949
+ const p = planned[i];
950
+ return !p.plan.deferred && !p.rest;
951
+ };
952
+ for (const row of pending) {
953
+ const i = at.get(row.stream);
954
+ if (i === undefined)
955
+ continue;
956
+ const p = planned[i];
957
+ const children = JSON.parse(row.cursor_children ?? "[]");
958
+ if (!closed(row.stream) ||
959
+ p.watermark < (row.cursor_seq ?? 0) ||
960
+ !children.every(closed))
961
+ continue;
962
+ const cursor = JSON.parse(row.cursor_unpublished);
963
+ planned[i] = {
964
+ ...p,
965
+ included: true,
966
+ meta: {
967
+ ...(p.meta ?? cursorOnlyMeta(p, rows, connector)),
968
+ cursor,
969
+ },
970
+ cursor: { saved: row.cursor_unpublished, write: row.cursor_write },
971
+ };
972
+ }
973
+ }
974
+ /** The meta of a stream that carries only its cursor: what the log last said of it. */
975
+ function cursorOnlyMeta(p, rows, connector) {
976
+ const head = p.plan.finalHead;
977
+ if (head)
978
+ return {
979
+ stream: p.stream,
980
+ primaryKey: head.primaryKey,
981
+ profile: head.profile,
982
+ complete: head.complete,
983
+ };
984
+ const row = rows.find((r) => r.stream === p.stream);
985
+ const published = asPublished(row);
986
+ return {
987
+ stream: p.stream,
988
+ primaryKey: JSON.parse(published.primary_key),
989
+ profile: {
990
+ key: published.profile_key ?? connector,
991
+ version: published.profile_version ?? published.floor_version ?? "0",
992
+ },
993
+ // Never claimed complete without a head that said so.
994
+ complete: row.head_version > 0 && published.complete === 1,
995
+ };
996
+ }
997
+ /**
998
+ * What `op` adds to a segment. A body longer than `target` goes out of line
999
+ * (`log-bodies.ts`): the segment carries only its piece hashes.
1000
+ */
1001
+ function opSize(op, target) {
1002
+ if (op.kind === "upsert") {
1003
+ const length = JSON.stringify(op.value).length;
1004
+ return length > target
1005
+ ? 260 + 70 * Math.ceil(length / target)
1006
+ : 160 + length;
1007
+ }
1008
+ return op.kind === "delete"
1009
+ ? 160 + JSON.stringify(op.key).length
1010
+ : 100 + omittedSize(op.omitted);
1011
+ }
1012
+ /** An omission lists its hash and its typed key. */
1013
+ function omissionSize(o) {
1014
+ return 70 + JSON.stringify(o.key).length;
1015
+ }
1016
+ function omittedSize(omitted) {
1017
+ return omitted.reduce((n, o) => n + omissionSize(o), 0);
1018
+ }
1019
+ /** How many of `omitted`, from the first, fit in `room` bytes. */
1020
+ function omissionsThatFit(omitted, room) {
1021
+ let n = 0;
1022
+ for (let used = 0; n < omitted.length; n += 1) {
1023
+ used += omissionSize(omitted[n]);
1024
+ if (used > room)
1025
+ break;
1026
+ }
1027
+ return n;
1028
+ }
1029
+ /**
1030
+ * Whether the connection's control row is active here, for a connection this
1031
+ * device does not already hold as active.
1032
+ *
1033
+ * A connection this device has only ever seen absent, at its first generation,
1034
+ * is the first save of a new connection: `create`, with no read. The commit
1035
+ * creates the row in its own request, as a compare-and-set at version 1, and
1036
+ * the request's control condition is judged on what it commits. A row another
1037
+ * device wrote makes the creation lose, and the row is then read and
1038
+ * classified as for any other connection (`readControl`).
1039
+ */
1040
+ async function establishControl(held, connectionId, connection, hashes) {
1041
+ if (connection.control_state === "absent" && connection.generation === 1)
1042
+ return "create";
1043
+ return readControl(held, connectionId, connection, hashes);
1044
+ }
1045
+ /** Read the control row and say what it means for this connection. */
1046
+ async function readControl(held, connectionId, connection, hashes) {
1047
+ const control = controlScope(connection.connector, connection.ns);
1048
+ const state = classifyControl(await held.registry.read(control), hashes);
1049
+ // Absence creates the row only for a connection this device never saved. A
1050
+ // connection this device deleted is absent from the registry too (a delete
1051
+ // of a never-saved connection fences nothing), and only an explicit connect
1052
+ // starts it again: creating its row here would undo the delete.
1053
+ if (state.kind === "absent")
1054
+ return connection.control_state === "absent" && connection.generation === 1
1055
+ ? "create"
1056
+ : "deferred";
1057
+ if (state.kind === "deleted") {
1058
+ await adoptDelete(held, connectionId, { controlVersion: state.version });
1059
+ return "purged";
1060
+ }
1061
+ if (state.kind !== "active")
1062
+ return "deferred";
1063
+ if (state.generation !== connection.generation) {
1064
+ await applyConnection(held, connectionId);
1065
+ return "deferred";
1066
+ }
1067
+ return "active";
1068
+ }
1069
+ function markControlActive(connectionId, connection) {
1070
+ return {
1071
+ sql: "UPDATE connections SET control_state='active',control_version=? WHERE connection_id=?",
1072
+ params: [connection.generation, connectionId],
1073
+ };
1074
+ }
1075
+ /** The control row of a new connection: active, version 1. */
1076
+ async function controlCreation(held, control, hashes) {
1077
+ return {
1078
+ scope: control,
1079
+ dataHash: hashes.activeData,
1080
+ metadataHash: hashes.activeMetadata,
1081
+ expectedVersion: "1",
1082
+ signature: await held.signer.signAddData({
1083
+ ownerAddress: held.ownerAddress,
1084
+ scope: control,
1085
+ dataHash: hashes.activeData,
1086
+ metadataHash: hashes.activeMetadata,
1087
+ expectedVersion: 1n,
1088
+ }),
1089
+ };
1090
+ }
1091
+ /**
1092
+ * The condition every commit carries: the control row is this connection's
1093
+ * lifetime, active. Judged on what the request commits, so it also holds a
1094
+ * control row the same request creates, and refuses a stored one (a replay)
1095
+ * that a delete has since tombstoned.
1096
+ */
1097
+ function controlCondition(control, connection, hashes) {
1098
+ return {
1099
+ scope: control,
1100
+ expectedVersion: String(connection.generation),
1101
+ notDeleted: true,
1102
+ expectedDataHash: hashes.activeData,
1103
+ };
1104
+ }
1105
+ /** What a failed control condition means for the connection. */
1106
+ async function controlFailed(held, connectionId, control, failure) {
1107
+ const verdict = failure ? settleRequirementFailure(failure, control) : null;
1108
+ if (verdict?.kind !== "purge")
1109
+ return "deferred";
1110
+ await adoptDelete(held, connectionId, {
1111
+ controlVersion: verdict.controlVersion,
1112
+ });
1113
+ return "purged";
1114
+ }
1115
+ /**
1116
+ * Create a new connection's control row in a request of its own: the first
1117
+ * save of a connection with nothing to publish yet.
1118
+ */
1119
+ async function commitControl(held, connectionId, connection, hashes) {
1120
+ const control = controlScope(connection.connector, connection.ns);
1121
+ const answer = await postBatchOnce(held.registry, {
1122
+ ownerAddress: held.ownerAddress,
1123
+ rows: [await controlCreation(held, control, hashes)],
1124
+ requires: [controlCondition(control, connection, hashes)],
1125
+ });
1126
+ if (answer.kind === "precondition_failed")
1127
+ return controlFailed(held, connectionId, control, answer.failure);
1128
+ const state = answer.kind === "committed"
1129
+ ? "active"
1130
+ : await readControl(held, connectionId, connection, hashes);
1131
+ if (state === "create")
1132
+ return "retry";
1133
+ if (state === "active")
1134
+ await held.db.batch([markControlActive(connectionId, connection)]);
1135
+ return state;
1136
+ }
1137
+ /**
1138
+ * The keys a replacing run dropped: held rows last observed before it. Each
1139
+ * names its typed primary-key values from the row it drops, which is held until
1140
+ * the run deletes it: the row's data holds them with their types, and a
1141
+ * deletion's key is exactly what its hash was computed from.
1142
+ *
1143
+ * The bodies are read a page at a time (`PAGE_BYTES` of bodies, or one row), after reading the rows' sizes alone (`META_ROWS` at a
1144
+ * time): the shared SQL cannot return just the key fields of a body (a phone's
1145
+ * SQLite 3.22 has no JSON1), and a pass that drops many large records must not
1146
+ * hold them all at once. Only the small keys are kept.
1147
+ */
1148
+ async function omittedBy(deps, connectionId, stream, primaryKey, replace) {
1149
+ const scope = `connection_id = ? AND stream = ? AND ${SEEN_BEFORE}`;
1150
+ const scopeParams = [
1151
+ connectionId,
1152
+ stream,
1153
+ ...seenBeforeParams(replace.o, replace.r),
1154
+ ];
1155
+ const omitted = [];
1156
+ let after;
1157
+ for (;;) {
1158
+ const meta = await deps.db.query(`SELECT pk_hash, COALESCE(body_bytes, ${BODY_BYTES}) AS n FROM records
1159
+ WHERE ${scope}${after === undefined ? "" : " AND pk_hash > ?"}
1160
+ ORDER BY pk_hash LIMIT ${META_ROWS}`, after === undefined ? scopeParams : [...scopeParams, after]);
1161
+ for (let at = 0; at < meta.length;) {
1162
+ let take = 0;
1163
+ let bytes = 0;
1164
+ while (at + take < meta.length &&
1165
+ (take === 0 || bytes + Number(meta[at + take].n) <= PAGE_BYTES)) {
1166
+ bytes += Number(meta[at + take].n);
1167
+ take += 1;
1168
+ }
1169
+ const page = await deps.db.query(`SELECT pk_hash, body FROM records
1170
+ WHERE ${scope} AND pk_hash >= ? AND pk_hash <= ? ORDER BY pk_hash`, [...scopeParams, meta[at].pk_hash, meta[at + take - 1].pk_hash]);
1171
+ for (const row of page)
1172
+ omitted.push({
1173
+ pkHash: row.pk_hash,
1174
+ key: primaryKeyValues(JSON.parse(row.body), primaryKey),
1175
+ });
1176
+ at += take;
1177
+ }
1178
+ if (meta.length < META_ROWS)
1179
+ return omitted;
1180
+ after = meta[meta.length - 1].pk_hash;
1181
+ }
1182
+ }
1183
+ /** The hashes `omittedBy` names, for a comparison that needs no key. */
1184
+ async function omittedHashes(deps, connectionId, stream, replace, keys) {
1185
+ const rows = await deps.db.query(`SELECT pk_hash FROM records WHERE connection_id = ? AND stream = ?
1186
+ AND ${SEEN_BEFORE}${keys ? " AND pk_hash >= ? AND pk_hash <= ?" : ""}
1187
+ ORDER BY pk_hash`, [
1188
+ connectionId,
1189
+ stream,
1190
+ ...seenBeforeParams(replace.o, replace.r),
1191
+ ...(keys ? [keys.from, keys.to] : []),
1192
+ ]);
1193
+ return rows.map((row) => row.pk_hash);
1194
+ }
1195
+ /** Changed keys since the watermark, oldest change first. */
1196
+ async function changedKeys(deps, connectionId, stream, from, to) {
1197
+ const rows = await deps.db.query(`SELECT pk_hash, MAX(seq) AS seq FROM record_changes
1198
+ WHERE connection_id = ? AND stream = ? AND seq > ? AND seq <= ?
1199
+ AND ${ELIGIBLE_CHANGE}
1200
+ GROUP BY pk_hash ORDER BY MAX(seq)`, [connectionId, stream, from, to]);
1201
+ return rows.map((row) => ({ pk: row.pk_hash, seq: row.seq }));
1202
+ }
1203
+ /**
1204
+ * Local publication debt, independent of publishRounds' aggregate receipt.
1205
+ * Read under the connection queue using the same changed-key and retained-run
1206
+ * eligibility queries as snapshotRound/planStream. Pending runs also cover a
1207
+ * metadata-only completion or an omission round after its records were sent.
1208
+ */
1209
+ export async function hasPendingLogPublication(deps, connectionId) {
1210
+ return deps.queue.run(connectionId, "publish", async () => {
1211
+ const streams = await deps.db.query("SELECT stream, publish_watermark FROM stream_state WHERE connection_id=?", [connectionId]);
1212
+ const [last] = await deps.db.query("SELECT MAX(seq) AS seq FROM record_changes WHERE connection_id=?", [connectionId]);
1213
+ for (const row of streams) {
1214
+ if ((await retainedRuns(deps, connectionId, row.stream)).length > 0)
1215
+ return true;
1216
+ if ((await changedKeys(deps, connectionId, row.stream, row.publish_watermark, last?.seq ?? row.publish_watermark)).length > 0)
1217
+ return true;
1218
+ }
1219
+ return false;
1220
+ });
1221
+ }
1222
+ /**
1223
+ * The operations for these keys: a held row is an upsert at its stamp; a key
1224
+ * with no row and an explicit delete in the window is a delete at the stamp of
1225
+ * that delete. A key with no row and no explicit delete is nothing to say: a
1226
+ * replacing run's drop travels as its completion, and a refused run's rows
1227
+ * were never published.
1228
+ */
1229
+ async function operationsFor(deps, connectionId, stream, keys, from, to) {
1230
+ // A remove change carries its typed key only from an explicit delete
1231
+ // (`explicit_delete`) or from a seeded omission (`seedFromHistory`), which
1232
+ // goes as the completion of that one key at its cutoff.
1233
+ const ops = new Map();
1234
+ const untyped = [];
1235
+ for (const group of chunked(keys, KEYS_PER_QUERY)) {
1236
+ const marks = group.map(() => "?").join(",");
1237
+ const rows = await deps.db.query(`SELECT pk_hash, stamp_o, stamp_r, stamp_n, first_o, body FROM records
1238
+ WHERE connection_id = ? AND stream = ? AND pk_hash IN (${marks})`, [connectionId, stream, ...group]);
1239
+ const held = new Set(rows.map((row) => row.pk_hash));
1240
+ for (const row of rows)
1241
+ ops.set(row.pk_hash, {
1242
+ kind: "upsert",
1243
+ stream,
1244
+ pkHash: row.pk_hash,
1245
+ stamp: { o: row.stamp_o, r: row.stamp_r },
1246
+ // Absent for the run's first batch and for rows from before the column.
1247
+ ...(row.stamp_n > 0 ? { ordinal: row.stamp_n } : {}),
1248
+ firstSeen: row.first_o,
1249
+ value: JSON.parse(row.body),
1250
+ });
1251
+ const gone = group.filter((pk) => !held.has(pk));
1252
+ if (gone.length === 0)
1253
+ continue;
1254
+ const goneMarks = gone.map(() => "?").join(",");
1255
+ const deletes = await deps.db.query(`SELECT pk_hash, pk_values, record_key, stamp_o, stamp_r, explicit_delete, MAX(seq) FROM record_changes
1256
+ WHERE connection_id = ? AND stream = ? AND seq > ? AND seq <= ?
1257
+ AND op = 'remove' AND (explicit_delete = 1 OR pk_values IS NOT NULL)
1258
+ AND pk_hash IN (${goneMarks})
1259
+ GROUP BY pk_hash`, [connectionId, stream, from, to, ...gone]);
1260
+ for (const row of deletes) {
1261
+ if (row.explicit_delete === 0) {
1262
+ ops.set(row.pk_hash, {
1263
+ kind: "complete",
1264
+ stream,
1265
+ cutoff: { o: row.stamp_o, r: row.stamp_r },
1266
+ omitted: [
1267
+ { pkHash: row.pk_hash, key: JSON.parse(row.pk_values) },
1268
+ ],
1269
+ });
1270
+ continue;
1271
+ }
1272
+ // A delete made before `pk_values` existed has only the lossy string
1273
+ // key. The stream's declared key types give the typed key back from it,
1274
+ // if the rebuilt tuple hashes to the record's hash; otherwise the log
1275
+ // cannot name the deletion, and the caller must not acknowledge it.
1276
+ const key = row.pk_values !== null
1277
+ ? JSON.parse(row.pk_values)
1278
+ : await declaredKey(deps, connectionId, stream, row);
1279
+ if (key === null) {
1280
+ untyped.push(row.pk_hash);
1281
+ continue;
1282
+ }
1283
+ ops.set(row.pk_hash, {
1284
+ kind: "delete",
1285
+ stream,
1286
+ pkHash: row.pk_hash,
1287
+ key,
1288
+ stamp: { o: row.stamp_o, r: row.stamp_r },
1289
+ });
1290
+ }
1291
+ }
1292
+ return { ops, untyped };
1293
+ }
1294
+ /**
1295
+ * The typed key of a delete made before typed keys were kept: its record key
1296
+ * read with the types the stream's schema declares for its key fields, and
1297
+ * accepted only if it hashes to the delete's hash. `null` when the schema does
1298
+ * not determine it (no declared types yet, a union, or data that disagrees
1299
+ * with the schema).
1300
+ */
1301
+ async function declaredKey(deps, connectionId, stream, row) {
1302
+ const [state] = await deps.db.query("SELECT primary_key, key_types FROM stream_state WHERE connection_id = ? AND stream = ?", [connectionId, stream]);
1303
+ if (!state || state.key_types === null)
1304
+ return null;
1305
+ const primaryKey = JSON.parse(state.primary_key);
1306
+ const key = keyFromRecordKey(primaryKey, JSON.parse(state.key_types), row.record_key);
1307
+ return key !== null &&
1308
+ (await deletionKeyMatchesHash(async (bytes) => sha256(bytes), primaryKey, key, row.pk_hash))
1309
+ ? key
1310
+ : null;
1311
+ }
1312
+ /** Upserts, then deletes, each by key: one order for every writer. */
1313
+ function orderedOperations(ops) {
1314
+ const pkOf = (op) => op.kind === "complete" ? (op.omitted[0]?.pkHash ?? "") : op.pkHash;
1315
+ return [...ops].sort((a, b) => (a.kind === "upsert" ? 0 : 1) - (b.kind === "upsert" ? 0 : 1) ||
1316
+ pkOf(a).localeCompare(pkOf(b)));
1317
+ }
1318
+ /**
1319
+ * The local state a candidate rests on, as one comparable key: the connection,
1320
+ * the log position, delete intents, and per stream its head, its retained
1321
+ * runs, the changes the round acknowledges, and the keys a replacement drops.
1322
+ * New upserts, deletes and runs above the acknowledged watermark are not in
1323
+ * it: they wait for the next round, and a delete above it is an operation of
1324
+ * the next segment, not a state the old one must match.
1325
+ */
1326
+ async function basisOf(deps, connectionId, planned, log) {
1327
+ const [connection] = await deps.db.query("SELECT generation, control_state, control_version FROM connections WHERE connection_id = ?", [connectionId]);
1328
+ const intents = await deps.db.query("SELECT delete_id, intent FROM delete_intents");
1329
+ const streams = [];
1330
+ for (const p of planned) {
1331
+ const [state] = await deps.db.query(`SELECT head_version, head_generation, head_data_hash, last_delete_version, publish_watermark,
1332
+ cursor_unpublished, cursor_seq, cursor_write
1333
+ FROM stream_state WHERE connection_id = ? AND stream = ?`, [connectionId, p.stream]);
1334
+ const runs = await deps.db.query(`SELECT r.run_id, r.state, r.generation, rs.decision, rs.replace
1335
+ FROM runs r JOIN run_streams rs ON rs.run_id = r.run_id
1336
+ WHERE r.connection_id = ? AND rs.stream = ? AND r.state = 'ended'
1337
+ AND rs.decision IN ('publish','noop','deferred','refused','discarded')
1338
+ ORDER BY r.run_id`, [connectionId, p.stream]);
1339
+ const covered = await deps.db.query(`SELECT COUNT(*) AS n, MAX(seq) AS newest FROM record_changes
1340
+ WHERE connection_id = ? AND stream = ? AND seq > ? AND seq <= ?`, [connectionId, p.stream, p.local.publish_watermark, p.ack]);
1341
+ const omitted = p.replace
1342
+ ? await omittedHashes(deps, connectionId, p.stream, p.replace)
1343
+ : p.replacing && p.omitting
1344
+ ? await omittedHashes(deps, connectionId, p.stream, p.replacing, p.omitting)
1345
+ : [];
1346
+ streams.push([p.stream, state, runs, covered, omitted]);
1347
+ }
1348
+ return JSON.stringify([connection, log, intents, streams]);
1349
+ }
1350
+ /** Nothing to write: run evidence for what the log already holds, then compact. */
1351
+ async function commitIdle(deps, connectionId, planned, log) {
1352
+ const statements = [];
1353
+ for (const p of planned) {
1354
+ if (p.plan.deferred || p.rest)
1355
+ continue;
1356
+ if (p.local.head_version > 0 && p.local.head_data_hash !== null)
1357
+ statements.push(...(await runPublicationStatements(deps, connectionId, p.stream, {
1358
+ version: log.position,
1359
+ generation: p.local.head_generation ?? 1,
1360
+ dataHash: p.local.head_data_hash,
1361
+ watermark: p.ack,
1362
+ replaceBelow: undefined,
1363
+ runIds: p.runIds,
1364
+ })));
1365
+ statements.push({
1366
+ sql: "UPDATE stream_state SET publish_watermark = ? WHERE connection_id = ? AND stream = ? AND publish_watermark < ?",
1367
+ params: [p.ack, connectionId, p.stream, p.ack],
1368
+ }, {
1369
+ sql: "UPDATE record_changes SET publish_blocked_reason=NULL WHERE connection_id=? AND stream=? AND seq <= ?",
1370
+ params: [connectionId, p.stream, p.ack],
1371
+ });
1372
+ }
1373
+ statements.push(...(await compaction(deps, connectionId, planned)));
1374
+ if (statements.length > 0)
1375
+ await deps.db.batch(withOrigin("refresh", statements));
1376
+ }
1377
+ async function compaction(deps, connectionId, planned) {
1378
+ const [pending] = await deps.db.query("SELECT COUNT(*) AS n FROM import_ledger WHERE connection_id = ? AND state = 'imported'", [connectionId]);
1379
+ if ((pending?.n ?? 0) > 0)
1380
+ return [];
1381
+ const lowest = Math.min(...planned.map((p) => p.plan.deferred || (p.rest && !p.included)
1382
+ ? p.local.publish_watermark
1383
+ : p.ack));
1384
+ if (!Number.isFinite(lowest))
1385
+ return [];
1386
+ return [
1387
+ {
1388
+ sql: "DELETE FROM record_changes WHERE connection_id = ? AND seq <= ?",
1389
+ params: [connectionId, lowest],
1390
+ },
1391
+ ];
1392
+ }
1393
+ async function commitRound(held, connectionId, entry, clock) {
1394
+ const candidate = entry.candidate;
1395
+ await invalidateExpiredCandidate(held, connectionId, entry);
1396
+ if (entry.state.kind === "invalidated")
1397
+ return { kind: "retry", conflict: false };
1398
+ const [connection] = await held.db.query("SELECT connector, ns, generation, control_state FROM connections WHERE connection_id = ?", [connectionId]);
1399
+ if (!connection || connection.generation !== candidate.generation) {
1400
+ transition(entry, "invalidated");
1401
+ return { kind: "retry", conflict: false };
1402
+ }
1403
+ const log = await readLogState(held, connectionId);
1404
+ if ((await basisOf(held, connectionId, candidate.planned, log)) !==
1405
+ candidate.basis) {
1406
+ transition(entry, "invalidated");
1407
+ return { kind: "retry", conflict: false };
1408
+ }
1409
+ const results = (outcome) => ({
1410
+ kind: "done",
1411
+ more: false,
1412
+ results: candidate.planned.map((p) => ({
1413
+ stream: p.stream,
1414
+ outcome: p.included ? outcome : "deferred",
1415
+ watermark: p.watermark,
1416
+ })),
1417
+ });
1418
+ if (await hasDeleteIntent(held, connection.connector)) {
1419
+ transition(entry, "invalidated");
1420
+ return results("deferred");
1421
+ }
1422
+ const scope = logScope(connection.connector, connection.ns);
1423
+ const control = controlScope(connection.connector, connection.ns);
1424
+ const keyCheck = await deriveKeyCheck(held.keys.namespaceHmac);
1425
+ const hashes = await controlHashes(keccakOf(held.streamCrypto), keyCheck);
1426
+ const metadataHash = await metadataHashFor(scope, new Date(candidate.observedAt).toISOString(), candidate.cipher.length, held.streamCrypto);
1427
+ const signature = await held.signer.signAddData({
1428
+ ownerAddress: held.ownerAddress,
1429
+ scope,
1430
+ dataHash: candidate.dataHash,
1431
+ metadataHash,
1432
+ expectedVersion: BigInt(candidate.position),
1433
+ });
1434
+ const row = {
1435
+ scope,
1436
+ dataHash: candidate.dataHash,
1437
+ metadataHash,
1438
+ expectedVersion: String(candidate.position),
1439
+ signature,
1440
+ // A reset can have no refs while retaining an older registry position.
1441
+ // Only position 1 creates the log row for the first time.
1442
+ ...(candidate.position === 1
1443
+ ? { expectedHeadAbsent: true }
1444
+ : candidate.prevHash !== null
1445
+ ? { expectedHeadDataHash: candidate.prevHash }
1446
+ : {}),
1447
+ };
1448
+ // A first save creates the control row in the same request: one commit.
1449
+ const creation = candidate.createControl
1450
+ ? await controlCreation(held, control, hashes)
1451
+ : null;
1452
+ const request = {
1453
+ ownerAddress: held.ownerAddress,
1454
+ rows: creation ? [creation, row] : [row],
1455
+ requires: [controlCondition(control, connection, hashes)],
1456
+ };
1457
+ // These rows commit together or not at all, so a policy with no room for
1458
+ // them fails the save. A policy not yet known comes with the gateway's
1459
+ // refusal of the request.
1460
+ checkBatchRoom(batchBounds(held.registry), request);
1461
+ let answer;
1462
+ try {
1463
+ answer = await clock.time("registry-commit", () => postBatchOnce(held.registry, request, () => transition(entry, "ambiguous")).catch((error) => {
1464
+ if (error instanceof RegistryRefusedError)
1465
+ checkBatchRoom(batchBounds(held.registry), request);
1466
+ throw error;
1467
+ }));
1468
+ }
1469
+ catch (error) {
1470
+ // Nothing was written: an earlier send that may have landed is settled
1471
+ // first, then the caller refuses the candidate.
1472
+ if (error instanceof RegistryBatchRouteMissingError)
1473
+ await reconcileBeforeRefusal(held, connectionId, entry);
1474
+ throw error;
1475
+ }
1476
+ if (answer.kind === "precondition_failed") {
1477
+ await reconcileBeforeRefusal(held, connectionId, entry);
1478
+ if (entry.state.kind === "uploaded")
1479
+ transition(entry, "refused");
1480
+ return results(await controlFailed(held, connectionId, control, answer.failure));
1481
+ }
1482
+ if (!(await lifetimeHolds(held, connectionId, connection.generation))) {
1483
+ await reconcileBeforeRefusal(held, connectionId, entry);
1484
+ transition(entry, "invalidated");
1485
+ return results("deferred");
1486
+ }
1487
+ if (answer.kind === "refused") {
1488
+ // Nothing was written. The row that lost says why.
1489
+ const [created, logged] = creation
1490
+ ? answer.rows
1491
+ : [undefined, answer.rows[0]];
1492
+ if (created?.kind === "conflict") {
1493
+ // Another device's row holds the control scope: read it.
1494
+ const state = await readControl(held, connectionId, connection, hashes);
1495
+ await reconcileBeforeRefusal(held, connectionId, entry);
1496
+ transition(entry, "invalidated");
1497
+ if (state === "active") {
1498
+ await held.db.batch([markControlActive(connectionId, connection)]);
1499
+ return { kind: "retry", conflict: false };
1500
+ }
1501
+ if (state === "create")
1502
+ return { kind: "retry", conflict: false };
1503
+ return results(state);
1504
+ }
1505
+ const settlement = settleRow(logged, {
1506
+ expectedVersion: row.expectedVersion,
1507
+ dataHash: row.dataHash,
1508
+ });
1509
+ if (settlement === "conflict") {
1510
+ // Another writer holds this position. Take its segments, then plan again.
1511
+ await applyConnection(held, connectionId);
1512
+ transition(entry, "reconciled");
1513
+ transition(entry, "invalidated");
1514
+ return { kind: "retry", conflict: true };
1515
+ }
1516
+ // A copy of this very row landed earlier, with the whole request that
1517
+ // held it: published.
1518
+ if (settlement !== "committed") {
1519
+ await reconcileBeforeRefusal(held, connectionId, entry);
1520
+ transition(entry, "invalidated");
1521
+ return { kind: "retry", conflict: false };
1522
+ }
1523
+ }
1524
+ transition(entry, "committed");
1525
+ if (await hasDeleteIntent(held, connection.connector)) {
1526
+ transition(entry, "invalidated");
1527
+ return results("deferred");
1528
+ }
1529
+ // The registry took the segment: record it, in one batch.
1530
+ const newRef = {
1531
+ position: candidate.position,
1532
+ dataHash: candidate.dataHash,
1533
+ bytes: candidate.clearBytes,
1534
+ removes: candidate.removes,
1535
+ };
1536
+ const statements = candidate.createControl
1537
+ ? [markControlActive(connectionId, connection)]
1538
+ : [];
1539
+ const touched = candidate.planned.filter((p) => p.included);
1540
+ for (const p of touched) {
1541
+ if (p.replace)
1542
+ statements.push(
1543
+ // Remember what the replace drops before it drops it (admit.ts), so a
1544
+ // run still collecting cannot bring those rows back.
1545
+ tombstoneOmissions(connectionId, p.stream, p.replace.o, p.replace.r, held.publishWhileCollecting === true), replaceDelete(connectionId, p.stream, p.replace.o, p.replace.r));
1546
+ else if (p.replacing && p.omitting)
1547
+ statements.push(tombstoneOmissions(connectionId, p.stream, p.replacing.o, p.replacing.r, held.publishWhileCollecting === true, p.omitting), replaceDelete(connectionId, p.stream, p.replacing.o, p.replacing.r, p.omitting));
1548
+ }
1549
+ for (const p of touched) {
1550
+ const meta = p.meta;
1551
+ statements.push({
1552
+ sql: `INSERT OR REPLACE INTO stream_versions (connection_id, stream, version, generation,
1553
+ head_blob, head_format, record_count, observed_at, complete, kind,
1554
+ primary_key, profile_key, profile_version)
1555
+ SELECT ?, ?, MAX(s.head_version, s.last_delete_version) + 1, ?, ?, ?,
1556
+ (SELECT COUNT(*) FROM records r WHERE r.connection_id = ? AND r.stream = ?),
1557
+ ?, ?, 'published', ?, ?, ?
1558
+ FROM stream_state s WHERE s.connection_id = ? AND s.stream = ?`,
1559
+ params: [
1560
+ connectionId,
1561
+ p.stream,
1562
+ candidate.generation,
1563
+ candidate.blobName,
1564
+ 5,
1565
+ connectionId,
1566
+ p.stream,
1567
+ candidate.observedAt,
1568
+ meta.complete ? 1 : 0,
1569
+ JSON.stringify(meta.primaryKey),
1570
+ meta.profile.key,
1571
+ meta.profile.version,
1572
+ connectionId,
1573
+ p.stream,
1574
+ ],
1575
+ }, {
1576
+ sql: `UPDATE stream_state SET primary_key = ?, profile_key = ?, profile_version = ?, complete = ?,
1577
+ head_version = MAX(head_version, last_delete_version) + 1,
1578
+ head_generation = ?, head_data_hash = ?, head_blob = ?,
1579
+ needs_full = CASE WHEN ? = 1 THEN 0 ELSE needs_full END
1580
+ WHERE connection_id = ? AND stream = ?`,
1581
+ params: [
1582
+ JSON.stringify(meta.primaryKey),
1583
+ meta.profile.key,
1584
+ meta.profile.version,
1585
+ meta.complete ? 1 : 0,
1586
+ candidate.generation,
1587
+ candidate.dataHash,
1588
+ candidate.blobName,
1589
+ meta.complete ? 1 : 0,
1590
+ connectionId,
1591
+ p.stream,
1592
+ ],
1593
+ });
1594
+ }
1595
+ statements.push(...(await candidateAcknowledgements(held, connectionId, candidate, "direct")));
1596
+ statements.push(writeLogState(connectionId, {
1597
+ position: candidate.position,
1598
+ base: candidate.base,
1599
+ refs: [...candidate.refs, newRef],
1600
+ snapshot: candidate.snapshot,
1601
+ }), ...(await compaction(held, connectionId, candidate.planned)));
1602
+ await clock.time("local-commit", () => held.db.batch(withOrigin("refresh", statements)));
1603
+ const more = candidate.planned.some((p) => p.rest);
1604
+ return {
1605
+ kind: "done",
1606
+ more,
1607
+ results: publishedResults(connectionId, candidate),
1608
+ };
1609
+ }
1610
+ function publishedResults(connectionId, candidate) {
1611
+ return candidate.planned.map((p) => ({
1612
+ stream: p.stream,
1613
+ outcome: p.included ? "published" : p.plan.deferred ? "deferred" : "noop",
1614
+ watermark: p.ack,
1615
+ ...(p.included && {
1616
+ publication: {
1617
+ connectionId,
1618
+ connector: candidate.connector,
1619
+ ns: candidate.ns,
1620
+ stream: p.stream,
1621
+ head: {
1622
+ version: candidate.position,
1623
+ generation: candidate.generation,
1624
+ dataHash: candidate.dataHash,
1625
+ },
1626
+ watermark: p.ack,
1627
+ runIds: p.runIds,
1628
+ },
1629
+ }),
1630
+ }));
1631
+ }
1632
+ async function candidateAcknowledgements(held, connectionId, candidate, acknowledged) {
1633
+ const statements = [];
1634
+ const touched = candidate.planned.filter((p) => p.included);
1635
+ // A replace still under way read the stream at its basis; the segment this
1636
+ // round committed is this device's own, so the basis moves to it (after the
1637
+ // head columns above have).
1638
+ for (const p of touched)
1639
+ if (p.replacing)
1640
+ statements.push({
1641
+ sql: `UPDATE run_streams SET
1642
+ basis_version = (SELECT head_version FROM stream_state WHERE connection_id = ? AND stream = ?),
1643
+ basis_data_hash = ?, basis_generation = ?
1644
+ WHERE run_id = ? AND stream = ? AND replace = 1
1645
+ AND (SELECT head_data_hash FROM stream_state WHERE connection_id = ? AND stream = ?) = ?`,
1646
+ params: [
1647
+ connectionId,
1648
+ p.stream,
1649
+ candidate.dataHash,
1650
+ candidate.generation,
1651
+ p.replacing.r,
1652
+ p.stream,
1653
+ connectionId,
1654
+ p.stream,
1655
+ candidate.dataHash,
1656
+ ],
1657
+ });
1658
+ for (const p of candidate.planned) {
1659
+ if (p.plan.deferred)
1660
+ continue;
1661
+ if (!p.rest)
1662
+ statements.push(...(await runPublicationStatements(held, connectionId, p.stream, {
1663
+ version: candidate.position,
1664
+ generation: candidate.generation,
1665
+ dataHash: candidate.dataHash,
1666
+ watermark: p.ack,
1667
+ replaceBelow: p.replace ?? undefined,
1668
+ runIds: p.runIds,
1669
+ })));
1670
+ // The cursor this segment carried is published. After a direct commit it
1671
+ // is the log's cursor for the stream: this device's entry takes it, as if
1672
+ // it applied its own segment. After a history apply the staged cursor is
1673
+ // already the log's (this segment's, or a later segment's that wins in log
1674
+ // order), so it stays. A newer one a run end saved since stays, and so
1675
+ // does the entry that run wrote: the match is on the write, since a later
1676
+ // write can store the same cursor (its entry moved away and back).
1677
+ if (p.included && p.cursor !== null)
1678
+ statements.push(...(acknowledged === "direct"
1679
+ ? [
1680
+ {
1681
+ sql: `UPDATE stream_state SET cursor_applied = cursor_unpublished
1682
+ WHERE connection_id = ? AND stream = ? AND cursor_unpublished = ? AND cursor_write = ?`,
1683
+ params: [
1684
+ connectionId,
1685
+ p.stream,
1686
+ p.cursor.saved,
1687
+ p.cursor.write,
1688
+ ],
1689
+ },
1690
+ ]
1691
+ : []), {
1692
+ sql: `UPDATE stream_state SET cursor_unpublished = NULL, cursor_seq = NULL, cursor_children = NULL
1693
+ WHERE connection_id = ? AND stream = ? AND cursor_unpublished = ? AND cursor_write = ?`,
1694
+ params: [connectionId, p.stream, p.cursor.saved, p.cursor.write],
1695
+ });
1696
+ if (p.included || !p.rest)
1697
+ statements.push({
1698
+ sql: "UPDATE stream_state SET publish_watermark = ? WHERE connection_id = ? AND stream = ? AND publish_watermark < ?",
1699
+ params: [p.ack, connectionId, p.stream, p.ack],
1700
+ }, {
1701
+ sql: "UPDATE record_changes SET publish_blocked_reason=NULL WHERE connection_id=? AND stream=? AND seq <= ?",
1702
+ params: [connectionId, p.stream, p.ack],
1703
+ });
1704
+ }
1705
+ return statements;
1706
+ }
1707
+ async function reconcileBeforeRefusal(held, connectionId, entry) {
1708
+ if (!hasAmbiguousCommit(entry))
1709
+ return;
1710
+ await reconcileCandidate(held, connectionId, entry);
1711
+ }
1712
+ async function reconcileCandidate(held, connectionId, entry) {
1713
+ const candidate = entry.candidate;
1714
+ const scope = logScope(candidate.connector, candidate.ns);
1715
+ const read = await held.registry.read(scope);
1716
+ if (isInvalidated(entry)) {
1717
+ transition(entry, "reconciled");
1718
+ return null;
1719
+ }
1720
+ // Apply the registry's history before looking at the local basis. Applying
1721
+ // preserves newer local rows; acknowledgement covers only this candidate's
1722
+ // runs and watermark, never the collector that ended while its reply was lost.
1723
+ await applyConnection(held, connectionId, [{ scope, read }]);
1724
+ await invalidateExpiredCandidate(held, connectionId, entry);
1725
+ if (isInvalidated(entry)) {
1726
+ transition(entry, "reconciled");
1727
+ return null;
1728
+ }
1729
+ const log = await readLogState(held, connectionId);
1730
+ const own = read.found &&
1731
+ read.version >= candidate.position &&
1732
+ log.refs.some((r) => r.position === candidate.position && r.dataHash === candidate.dataHash);
1733
+ if (!own) {
1734
+ transition(entry, "reconciled");
1735
+ transition(entry, "invalidated");
1736
+ return null;
1737
+ }
1738
+ transition(entry, "committed");
1739
+ await held.db.batch(withOrigin("refresh", [
1740
+ ...(await candidateAcknowledgements(held, connectionId, candidate, "history")),
1741
+ ...(await compaction(held, connectionId, candidate.planned)),
1742
+ ]));
1743
+ return publishedResults(connectionId, candidate);
1744
+ }
1745
+ //# sourceMappingURL=log-publish.js.map