@opendatalabs/personal-server-ts-core 0.0.1-canary.052d47e → 0.0.1-canary.05cdd81

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 (1124) hide show
  1. package/dist/additions/budget.d.ts +34 -0
  2. package/dist/additions/budget.d.ts.map +1 -0
  3. package/dist/additions/budget.js +144 -0
  4. package/dist/additions/budget.js.map +1 -0
  5. package/dist/additions/durable.d.ts +94 -0
  6. package/dist/additions/durable.d.ts.map +1 -0
  7. package/dist/additions/durable.js +823 -0
  8. package/dist/additions/durable.js.map +1 -0
  9. package/dist/additions/first-added.d.ts +204 -0
  10. package/dist/additions/first-added.d.ts.map +1 -0
  11. package/dist/additions/first-added.js +598 -0
  12. package/dist/additions/first-added.js.map +1 -0
  13. package/dist/additions/index.d.ts +9 -0
  14. package/dist/additions/index.d.ts.map +1 -0
  15. package/dist/additions/index.js +9 -0
  16. package/dist/additions/index.js.map +1 -0
  17. package/dist/additions/ledger-store.d.ts +69 -0
  18. package/dist/additions/ledger-store.d.ts.map +1 -0
  19. package/dist/additions/ledger-store.js +407 -0
  20. package/dist/additions/ledger-store.js.map +1 -0
  21. package/dist/additions/record-rules.d.ts +54 -0
  22. package/dist/additions/record-rules.d.ts.map +1 -0
  23. package/dist/additions/record-rules.js +198 -0
  24. package/dist/additions/record-rules.js.map +1 -0
  25. package/dist/additions/scope-lock.d.ts +14 -0
  26. package/dist/additions/scope-lock.d.ts.map +1 -0
  27. package/dist/additions/scope-lock.js +32 -0
  28. package/dist/additions/scope-lock.js.map +1 -0
  29. package/dist/additions/summary.d.ts +143 -0
  30. package/dist/additions/summary.d.ts.map +1 -0
  31. package/dist/additions/summary.js +279 -0
  32. package/dist/additions/summary.js.map +1 -0
  33. package/dist/additions/version-inventory.d.ts +86 -0
  34. package/dist/additions/version-inventory.d.ts.map +1 -0
  35. package/dist/additions/version-inventory.js +244 -0
  36. package/dist/additions/version-inventory.js.map +1 -0
  37. package/dist/api/account-storage-mode.d.ts +77 -0
  38. package/dist/api/account-storage-mode.d.ts.map +1 -0
  39. package/dist/api/account-storage-mode.js +72 -0
  40. package/dist/api/account-storage-mode.js.map +1 -0
  41. package/dist/api/index.d.ts +320 -10
  42. package/dist/api/index.d.ts.map +1 -1
  43. package/dist/api/index.js +1758 -181
  44. package/dist/api/index.js.map +1 -1
  45. package/dist/api/legacy-write-gate.d.ts +51 -0
  46. package/dist/api/legacy-write-gate.d.ts.map +1 -0
  47. package/dist/api/legacy-write-gate.js +88 -0
  48. package/dist/api/legacy-write-gate.js.map +1 -0
  49. package/dist/api/oura-collection-requirements.d.ts +16 -0
  50. package/dist/api/oura-collection-requirements.d.ts.map +1 -0
  51. package/dist/api/oura-collection-requirements.js +70 -0
  52. package/dist/api/oura-collection-requirements.js.map +1 -0
  53. package/dist/api/owner-connector-delete.d.ts +79 -0
  54. package/dist/api/owner-connector-delete.d.ts.map +1 -0
  55. package/dist/api/owner-connector-delete.js +109 -0
  56. package/dist/api/owner-connector-delete.js.map +1 -0
  57. package/dist/api/raw-envelope.d.ts +3 -0
  58. package/dist/api/raw-envelope.d.ts.map +1 -0
  59. package/dist/api/raw-envelope.js +215 -0
  60. package/dist/api/raw-envelope.js.map +1 -0
  61. package/dist/api/scope-upload-batches.d.ts +18 -0
  62. package/dist/api/scope-upload-batches.d.ts.map +1 -0
  63. package/dist/api/scope-upload-batches.js +71 -0
  64. package/dist/api/scope-upload-batches.js.map +1 -0
  65. package/dist/api/scope-uploads.d.ts +112 -0
  66. package/dist/api/scope-uploads.d.ts.map +1 -0
  67. package/dist/api/scope-uploads.js +369 -0
  68. package/dist/api/scope-uploads.js.map +1 -0
  69. package/dist/api/switched-delete-refusal.d.ts +16 -0
  70. package/dist/api/switched-delete-refusal.d.ts.map +1 -0
  71. package/dist/api/switched-delete-refusal.js +30 -0
  72. package/dist/api/switched-delete-refusal.js.map +1 -0
  73. package/dist/auth/index.d.ts +3 -1
  74. package/dist/auth/index.d.ts.map +1 -1
  75. package/dist/auth/index.js +3 -1
  76. package/dist/auth/index.js.map +1 -1
  77. package/dist/auth/proof-id.d.ts +8 -0
  78. package/dist/auth/proof-id.d.ts.map +1 -0
  79. package/dist/auth/proof-id.js +29 -0
  80. package/dist/auth/proof-id.js.map +1 -0
  81. package/dist/auth/request.d.ts +24 -0
  82. package/dist/auth/request.d.ts.map +1 -1
  83. package/dist/auth/request.js +99 -4
  84. package/dist/auth/request.js.map +1 -1
  85. package/dist/client.d.ts +78 -0
  86. package/dist/client.d.ts.map +1 -1
  87. package/dist/client.js +1 -0
  88. package/dist/client.js.map +1 -1
  89. package/dist/contracts/auth-device.d.ts +10 -0
  90. package/dist/contracts/auth-device.d.ts.map +1 -1
  91. package/dist/contracts/auth-device.js +2 -0
  92. package/dist/contracts/auth-device.js.map +1 -1
  93. package/dist/contracts/data.d.ts +102 -8
  94. package/dist/contracts/data.d.ts.map +1 -1
  95. package/dist/contracts/data.js +326 -47
  96. package/dist/contracts/data.js.map +1 -1
  97. package/dist/contracts/grants.d.ts.map +1 -1
  98. package/dist/contracts/grants.js +7 -0
  99. package/dist/contracts/grants.js.map +1 -1
  100. package/dist/contracts/index.d.ts +4 -2
  101. package/dist/contracts/index.d.ts.map +1 -1
  102. package/dist/contracts/index.js +3 -1
  103. package/dist/contracts/index.js.map +1 -1
  104. package/dist/contracts/oura-collection-requirements.d.ts +17 -0
  105. package/dist/contracts/oura-collection-requirements.d.ts.map +1 -0
  106. package/dist/contracts/oura-collection-requirements.js +49 -0
  107. package/dist/contracts/oura-collection-requirements.js.map +1 -0
  108. package/dist/contracts/sync.d.ts +9 -1
  109. package/dist/contracts/sync.d.ts.map +1 -1
  110. package/dist/contracts/sync.js +7 -2
  111. package/dist/contracts/sync.js.map +1 -1
  112. package/dist/derivatives/answer-shape.d.ts +83 -0
  113. package/dist/derivatives/answer-shape.d.ts.map +1 -0
  114. package/dist/derivatives/answer-shape.js +320 -0
  115. package/dist/derivatives/answer-shape.js.map +1 -0
  116. package/dist/derivatives/api.d.ts +1 -1
  117. package/dist/derivatives/api.d.ts.map +1 -1
  118. package/dist/derivatives/api.js +8 -0
  119. package/dist/derivatives/api.js.map +1 -1
  120. package/dist/derivatives/compute.d.ts +9 -3
  121. package/dist/derivatives/compute.d.ts.map +1 -1
  122. package/dist/derivatives/compute.js +87 -6
  123. package/dist/derivatives/compute.js.map +1 -1
  124. package/dist/derivatives/index.d.ts +2 -1
  125. package/dist/derivatives/index.d.ts.map +1 -1
  126. package/dist/derivatives/index.js +2 -1
  127. package/dist/derivatives/index.js.map +1 -1
  128. package/dist/derivatives/prompt.d.ts +35 -0
  129. package/dist/derivatives/prompt.d.ts.map +1 -1
  130. package/dist/derivatives/prompt.js +96 -8
  131. package/dist/derivatives/prompt.js.map +1 -1
  132. package/dist/derivatives/registration.d.ts +6 -9
  133. package/dist/derivatives/registration.d.ts.map +1 -1
  134. package/dist/derivatives/registration.js +14 -6
  135. package/dist/derivatives/registration.js.map +1 -1
  136. package/dist/derivatives/scheduler.d.ts +39 -9
  137. package/dist/derivatives/scheduler.d.ts.map +1 -1
  138. package/dist/derivatives/scheduler.js +99 -8
  139. package/dist/derivatives/scheduler.js.map +1 -1
  140. package/dist/derivatives/store.d.ts.map +1 -1
  141. package/dist/derivatives/store.js +2 -0
  142. package/dist/derivatives/store.js.map +1 -1
  143. package/dist/derivatives/types.d.ts +13 -3
  144. package/dist/derivatives/types.d.ts.map +1 -1
  145. package/dist/derivatives/types.js +2 -0
  146. package/dist/derivatives/types.js.map +1 -1
  147. package/dist/errors/pdpp-catalog.d.ts +36 -0
  148. package/dist/errors/pdpp-catalog.d.ts.map +1 -0
  149. package/dist/errors/pdpp-catalog.js +92 -0
  150. package/dist/errors/pdpp-catalog.js.map +1 -0
  151. package/dist/grants/index.d.ts +2 -0
  152. package/dist/grants/index.d.ts.map +1 -1
  153. package/dist/grants/index.js +4 -0
  154. package/dist/grants/index.js.map +1 -1
  155. package/dist/grants/pdpp-binding-store.d.ts +89 -0
  156. package/dist/grants/pdpp-binding-store.d.ts.map +1 -0
  157. package/dist/grants/pdpp-binding-store.js +112 -0
  158. package/dist/grants/pdpp-binding-store.js.map +1 -0
  159. package/dist/grants/pdpp-binding.d.ts +169 -0
  160. package/dist/grants/pdpp-binding.d.ts.map +1 -0
  161. package/dist/grants/pdpp-binding.js +236 -0
  162. package/dist/grants/pdpp-binding.js.map +1 -0
  163. package/dist/keys/index.d.ts +1 -0
  164. package/dist/keys/index.d.ts.map +1 -1
  165. package/dist/keys/index.js +1 -0
  166. package/dist/keys/index.js.map +1 -1
  167. package/dist/keys/owner-master-key.d.ts +37 -0
  168. package/dist/keys/owner-master-key.d.ts.map +1 -0
  169. package/dist/keys/owner-master-key.js +45 -0
  170. package/dist/keys/owner-master-key.js.map +1 -0
  171. package/dist/legacy-projection/bindings.d.ts +31 -0
  172. package/dist/legacy-projection/bindings.d.ts.map +1 -0
  173. package/dist/legacy-projection/bindings.js +4512 -0
  174. package/dist/legacy-projection/bindings.js.map +1 -0
  175. package/dist/legacy-projection/claude-source-record.d.ts +22 -0
  176. package/dist/legacy-projection/claude-source-record.d.ts.map +1 -0
  177. package/dist/legacy-projection/claude-source-record.js +360 -0
  178. package/dist/legacy-projection/claude-source-record.js.map +1 -0
  179. package/dist/legacy-projection/declared-text.d.ts +41 -0
  180. package/dist/legacy-projection/declared-text.d.ts.map +1 -0
  181. package/dist/legacy-projection/declared-text.js +199 -0
  182. package/dist/legacy-projection/declared-text.js.map +1 -0
  183. package/dist/legacy-projection/erase-connector.d.ts +18 -0
  184. package/dist/legacy-projection/erase-connector.d.ts.map +1 -0
  185. package/dist/legacy-projection/erase-connector.js +29 -0
  186. package/dist/legacy-projection/erase-connector.js.map +1 -0
  187. package/dist/legacy-projection/github-browser-bindings.d.ts +3 -0
  188. package/dist/legacy-projection/github-browser-bindings.d.ts.map +1 -0
  189. package/dist/legacy-projection/github-browser-bindings.js +212 -0
  190. package/dist/legacy-projection/github-browser-bindings.js.map +1 -0
  191. package/dist/legacy-projection/github-legacy-fields.d.ts +6 -0
  192. package/dist/legacy-projection/github-legacy-fields.d.ts.map +1 -0
  193. package/dist/legacy-projection/github-legacy-fields.js +202 -0
  194. package/dist/legacy-projection/github-legacy-fields.js.map +1 -0
  195. package/dist/legacy-projection/index.d.ts +48 -0
  196. package/dist/legacy-projection/index.d.ts.map +1 -0
  197. package/dist/legacy-projection/index.js +255 -0
  198. package/dist/legacy-projection/index.js.map +1 -0
  199. package/dist/legacy-projection/meta-040-bindings.d.ts +3 -0
  200. package/dist/legacy-projection/meta-040-bindings.d.ts.map +1 -0
  201. package/dist/legacy-projection/meta-040-bindings.js +112 -0
  202. package/dist/legacy-projection/meta-040-bindings.js.map +1 -0
  203. package/dist/legacy-projection/oura-browser-bindings.d.ts +5 -0
  204. package/dist/legacy-projection/oura-browser-bindings.d.ts.map +1 -0
  205. package/dist/legacy-projection/oura-browser-bindings.js +141 -0
  206. package/dist/legacy-projection/oura-browser-bindings.js.map +1 -0
  207. package/dist/legacy-projection/provenance.d.ts +57 -0
  208. package/dist/legacy-projection/provenance.d.ts.map +1 -0
  209. package/dist/legacy-projection/provenance.js +2 -0
  210. package/dist/legacy-projection/provenance.js.map +1 -0
  211. package/dist/legacy-projection/strava-browser-bindings.d.ts +3 -0
  212. package/dist/legacy-projection/strava-browser-bindings.d.ts.map +1 -0
  213. package/dist/legacy-projection/strava-browser-bindings.js +32 -0
  214. package/dist/legacy-projection/strava-browser-bindings.js.map +1 -0
  215. package/dist/legacy-projection/test-debris.d.ts +2 -0
  216. package/dist/legacy-projection/test-debris.d.ts.map +1 -0
  217. package/dist/legacy-projection/test-debris.js +49 -0
  218. package/dist/legacy-projection/test-debris.js.map +1 -0
  219. package/dist/legacy-projection/types.d.ts +235 -0
  220. package/dist/legacy-projection/types.d.ts.map +1 -0
  221. package/dist/legacy-projection/types.js +2 -0
  222. package/dist/legacy-projection/types.js.map +1 -0
  223. package/dist/lineage/gateway.d.ts +3 -1
  224. package/dist/lineage/gateway.d.ts.map +1 -1
  225. package/dist/lineage/gateway.js +2 -1
  226. package/dist/lineage/gateway.js.map +1 -1
  227. package/dist/localdb/apply.d.ts +13 -0
  228. package/dist/localdb/apply.d.ts.map +1 -0
  229. package/dist/localdb/apply.js +565 -0
  230. package/dist/localdb/apply.js.map +1 -0
  231. package/dist/localdb/batch-commit.d.ts +67 -0
  232. package/dist/localdb/batch-commit.d.ts.map +1 -0
  233. package/dist/localdb/batch-commit.js +121 -0
  234. package/dist/localdb/batch-commit.js.map +1 -0
  235. package/dist/localdb/blobs.d.ts +71 -0
  236. package/dist/localdb/blobs.d.ts.map +1 -0
  237. package/dist/localdb/blobs.js +306 -0
  238. package/dist/localdb/blobs.js.map +1 -0
  239. package/dist/localdb/bootstrap.d.ts +20 -0
  240. package/dist/localdb/bootstrap.d.ts.map +1 -0
  241. package/dist/localdb/bootstrap.js +157 -0
  242. package/dist/localdb/bootstrap.js.map +1 -0
  243. package/dist/localdb/connection-link.d.ts +12 -0
  244. package/dist/localdb/connection-link.d.ts.map +1 -0
  245. package/dist/localdb/connection-link.js +72 -0
  246. package/dist/localdb/connection-link.js.map +1 -0
  247. package/dist/localdb/cycle.d.ts +32 -0
  248. package/dist/localdb/cycle.d.ts.map +1 -0
  249. package/dist/localdb/cycle.js +46 -0
  250. package/dist/localdb/cycle.js.map +1 -0
  251. package/dist/localdb/delete-batch.d.ts +51 -0
  252. package/dist/localdb/delete-batch.d.ts.map +1 -0
  253. package/dist/localdb/delete-batch.js +132 -0
  254. package/dist/localdb/delete-batch.js.map +1 -0
  255. package/dist/localdb/delete.d.ts +81 -0
  256. package/dist/localdb/delete.d.ts.map +1 -0
  257. package/dist/localdb/delete.js +736 -0
  258. package/dist/localdb/delete.js.map +1 -0
  259. package/dist/localdb/deps.d.ts +54 -0
  260. package/dist/localdb/deps.d.ts.map +1 -0
  261. package/dist/localdb/deps.js +10 -0
  262. package/dist/localdb/deps.js.map +1 -0
  263. package/dist/localdb/driver.d.ts +67 -0
  264. package/dist/localdb/driver.d.ts.map +1 -0
  265. package/dist/localdb/driver.js +3 -0
  266. package/dist/localdb/driver.js.map +1 -0
  267. package/dist/localdb/encode.d.ts +217 -0
  268. package/dist/localdb/encode.d.ts.map +1 -0
  269. package/dist/localdb/encode.js +502 -0
  270. package/dist/localdb/encode.js.map +1 -0
  271. package/dist/localdb/fence.d.ts +31 -0
  272. package/dist/localdb/fence.d.ts.map +1 -0
  273. package/dist/localdb/fence.js +69 -0
  274. package/dist/localdb/fence.js.map +1 -0
  275. package/dist/localdb/history.d.ts +74 -0
  276. package/dist/localdb/history.d.ts.map +1 -0
  277. package/dist/localdb/history.js +266 -0
  278. package/dist/localdb/history.js.map +1 -0
  279. package/dist/localdb/import-fingerprint.d.ts +8 -0
  280. package/dist/localdb/import-fingerprint.d.ts.map +1 -0
  281. package/dist/localdb/import-fingerprint.js +35 -0
  282. package/dist/localdb/import-fingerprint.js.map +1 -0
  283. package/dist/localdb/import-ledger.d.ts +27 -0
  284. package/dist/localdb/import-ledger.d.ts.map +1 -0
  285. package/dist/localdb/import-ledger.js +197 -0
  286. package/dist/localdb/import-ledger.js.map +1 -0
  287. package/dist/localdb/import-readback.d.ts +8 -0
  288. package/dist/localdb/import-readback.d.ts.map +1 -0
  289. package/dist/localdb/import-readback.js +69 -0
  290. package/dist/localdb/import-readback.js.map +1 -0
  291. package/dist/localdb/import-snapshot.d.ts +21 -0
  292. package/dist/localdb/import-snapshot.d.ts.map +1 -0
  293. package/dist/localdb/import-snapshot.js +94 -0
  294. package/dist/localdb/import-snapshot.js.map +1 -0
  295. package/dist/localdb/index.d.ts +39 -0
  296. package/dist/localdb/index.d.ts.map +1 -0
  297. package/dist/localdb/index.js +36 -0
  298. package/dist/localdb/index.js.map +1 -0
  299. package/dist/localdb/legacy-import-types.d.ts +110 -0
  300. package/dist/localdb/legacy-import-types.d.ts.map +1 -0
  301. package/dist/localdb/legacy-import-types.js +2 -0
  302. package/dist/localdb/legacy-import-types.js.map +1 -0
  303. package/dist/localdb/legacy-import.d.ts +36 -0
  304. package/dist/localdb/legacy-import.d.ts.map +1 -0
  305. package/dist/localdb/legacy-import.js +288 -0
  306. package/dist/localdb/legacy-import.js.map +1 -0
  307. package/dist/localdb/legacy-retire.d.ts +26 -0
  308. package/dist/localdb/legacy-retire.d.ts.map +1 -0
  309. package/dist/localdb/legacy-retire.js +93 -0
  310. package/dist/localdb/legacy-retire.js.map +1 -0
  311. package/dist/localdb/lifetime-boundary.d.ts +49 -0
  312. package/dist/localdb/lifetime-boundary.d.ts.map +1 -0
  313. package/dist/localdb/lifetime-boundary.js +74 -0
  314. package/dist/localdb/lifetime-boundary.js.map +1 -0
  315. package/dist/localdb/listing.d.ts +51 -0
  316. package/dist/localdb/listing.d.ts.map +1 -0
  317. package/dist/localdb/listing.js +231 -0
  318. package/dist/localdb/listing.js.map +1 -0
  319. package/dist/localdb/merge.d.ts +95 -0
  320. package/dist/localdb/merge.d.ts.map +1 -0
  321. package/dist/localdb/merge.js +282 -0
  322. package/dist/localdb/merge.js.map +1 -0
  323. package/dist/localdb/migrate.d.ts +10 -0
  324. package/dist/localdb/migrate.d.ts.map +1 -0
  325. package/dist/localdb/migrate.js +27 -0
  326. package/dist/localdb/migrate.js.map +1 -0
  327. package/dist/localdb/name.d.ts +3 -0
  328. package/dist/localdb/name.d.ts.map +1 -0
  329. package/dist/localdb/name.js +8 -0
  330. package/dist/localdb/name.js.map +1 -0
  331. package/dist/localdb/older-versions.d.ts +49 -0
  332. package/dist/localdb/older-versions.d.ts.map +1 -0
  333. package/dist/localdb/older-versions.js +172 -0
  334. package/dist/localdb/older-versions.js.map +1 -0
  335. package/dist/localdb/open.d.ts +19 -0
  336. package/dist/localdb/open.d.ts.map +1 -0
  337. package/dist/localdb/open.js +46 -0
  338. package/dist/localdb/open.js.map +1 -0
  339. package/dist/localdb/part-layout.d.ts +74 -0
  340. package/dist/localdb/part-layout.d.ts.map +1 -0
  341. package/dist/localdb/part-layout.js +203 -0
  342. package/dist/localdb/part-layout.js.map +1 -0
  343. package/dist/localdb/publish-meter.d.ts +45 -0
  344. package/dist/localdb/publish-meter.d.ts.map +1 -0
  345. package/dist/localdb/publish-meter.js +62 -0
  346. package/dist/localdb/publish-meter.js.map +1 -0
  347. package/dist/localdb/publish.d.ts +47 -0
  348. package/dist/localdb/publish.d.ts.map +1 -0
  349. package/dist/localdb/publish.js +2100 -0
  350. package/dist/localdb/publish.js.map +1 -0
  351. package/dist/localdb/purge.d.ts +23 -0
  352. package/dist/localdb/purge.d.ts.map +1 -0
  353. package/dist/localdb/purge.js +75 -0
  354. package/dist/localdb/purge.js.map +1 -0
  355. package/dist/localdb/query.d.ts +69 -0
  356. package/dist/localdb/query.d.ts.map +1 -0
  357. package/dist/localdb/query.js +306 -0
  358. package/dist/localdb/query.js.map +1 -0
  359. package/dist/localdb/queue.d.ts +10 -0
  360. package/dist/localdb/queue.d.ts.map +1 -0
  361. package/dist/localdb/queue.js +31 -0
  362. package/dist/localdb/queue.js.map +1 -0
  363. package/dist/localdb/read-selection.d.ts +103 -0
  364. package/dist/localdb/read-selection.d.ts.map +1 -0
  365. package/dist/localdb/read-selection.js +141 -0
  366. package/dist/localdb/read-selection.js.map +1 -0
  367. package/dist/localdb/registry-view.d.ts +65 -0
  368. package/dist/localdb/registry-view.d.ts.map +1 -0
  369. package/dist/localdb/registry-view.js +73 -0
  370. package/dist/localdb/registry-view.js.map +1 -0
  371. package/dist/localdb/replace.d.ts +33 -0
  372. package/dist/localdb/replace.d.ts.map +1 -0
  373. package/dist/localdb/replace.js +22 -0
  374. package/dist/localdb/replace.js.map +1 -0
  375. package/dist/localdb/requirements.d.ts +35 -0
  376. package/dist/localdb/requirements.d.ts.map +1 -0
  377. package/dist/localdb/requirements.js +66 -0
  378. package/dist/localdb/requirements.js.map +1 -0
  379. package/dist/localdb/resolve.d.ts +43 -0
  380. package/dist/localdb/resolve.d.ts.map +1 -0
  381. package/dist/localdb/resolve.js +265 -0
  382. package/dist/localdb/resolve.js.map +1 -0
  383. package/dist/localdb/run-end.d.ts +19 -0
  384. package/dist/localdb/run-end.d.ts.map +1 -0
  385. package/dist/localdb/run-end.js +283 -0
  386. package/dist/localdb/run-end.js.map +1 -0
  387. package/dist/localdb/run-intake.d.ts +16 -0
  388. package/dist/localdb/run-intake.d.ts.map +1 -0
  389. package/dist/localdb/run-intake.js +441 -0
  390. package/dist/localdb/run-intake.js.map +1 -0
  391. package/dist/localdb/run-receipts.d.ts +19 -0
  392. package/dist/localdb/run-receipts.d.ts.map +1 -0
  393. package/dist/localdb/run-receipts.js +151 -0
  394. package/dist/localdb/run-receipts.js.map +1 -0
  395. package/dist/localdb/schema.d.ts +7 -0
  396. package/dist/localdb/schema.d.ts.map +1 -0
  397. package/dist/localdb/schema.js +312 -0
  398. package/dist/localdb/schema.js.map +1 -0
  399. package/dist/localdb/seed.d.ts +39 -0
  400. package/dist/localdb/seed.d.ts.map +1 -0
  401. package/dist/localdb/seed.js +188 -0
  402. package/dist/localdb/seed.js.map +1 -0
  403. package/dist/localdb/slot.d.ts +9 -0
  404. package/dist/localdb/slot.d.ts.map +1 -0
  405. package/dist/localdb/slot.js +15 -0
  406. package/dist/localdb/slot.js.map +1 -0
  407. package/dist/localdb/sync.d.ts +53 -0
  408. package/dist/localdb/sync.d.ts.map +1 -0
  409. package/dist/localdb/sync.js +211 -0
  410. package/dist/localdb/sync.js.map +1 -0
  411. package/dist/localdb/transfer-memory.d.ts +17 -0
  412. package/dist/localdb/transfer-memory.d.ts.map +1 -0
  413. package/dist/localdb/transfer-memory.js +17 -0
  414. package/dist/localdb/transfer-memory.js.map +1 -0
  415. package/dist/localdb/unwrite.d.ts +22 -0
  416. package/dist/localdb/unwrite.d.ts.map +1 -0
  417. package/dist/localdb/unwrite.js +46 -0
  418. package/dist/localdb/unwrite.js.map +1 -0
  419. package/dist/localdb/upload-wave.d.ts +34 -0
  420. package/dist/localdb/upload-wave.d.ts.map +1 -0
  421. package/dist/localdb/upload-wave.js +30 -0
  422. package/dist/localdb/upload-wave.js.map +1 -0
  423. package/dist/localdb/verified-heads.d.ts +13 -0
  424. package/dist/localdb/verified-heads.d.ts.map +1 -0
  425. package/dist/localdb/verified-heads.js +56 -0
  426. package/dist/localdb/verified-heads.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/mcp/approval-url.d.ts +100 -0
  432. package/dist/mcp/approval-url.d.ts.map +1 -0
  433. package/dist/mcp/approval-url.js +171 -0
  434. package/dist/mcp/approval-url.js.map +1 -0
  435. package/dist/mcp/connection-api.d.ts +239 -3
  436. package/dist/mcp/connection-api.d.ts.map +1 -1
  437. package/dist/mcp/connection-api.js +792 -27
  438. package/dist/mcp/connection-api.js.map +1 -1
  439. package/dist/mcp/grant-registration.d.ts +15 -0
  440. package/dist/mcp/grant-registration.d.ts.map +1 -0
  441. package/dist/mcp/grant-registration.js +44 -0
  442. package/dist/mcp/grant-registration.js.map +1 -0
  443. package/dist/mcp/grantee.d.ts +1 -1
  444. package/dist/mcp/grantee.d.ts.map +1 -1
  445. package/dist/mcp/index.d.ts +5 -0
  446. package/dist/mcp/index.d.ts.map +1 -1
  447. package/dist/mcp/index.js +5 -0
  448. package/dist/mcp/index.js.map +1 -1
  449. package/dist/mcp/oauth-redirect.d.ts +14 -0
  450. package/dist/mcp/oauth-redirect.d.ts.map +1 -0
  451. package/dist/mcp/oauth-redirect.js +51 -0
  452. package/dist/mcp/oauth-redirect.js.map +1 -0
  453. package/dist/mcp/read-client.d.ts +27 -3
  454. package/dist/mcp/read-client.d.ts.map +1 -1
  455. package/dist/mcp/read-client.js +325 -19
  456. package/dist/mcp/read-client.js.map +1 -1
  457. package/dist/mcp/resources.d.ts +3 -1
  458. package/dist/mcp/resources.d.ts.map +1 -1
  459. package/dist/mcp/resources.js +14 -2
  460. package/dist/mcp/resources.js.map +1 -1
  461. package/dist/mcp/server.d.ts +47 -0
  462. package/dist/mcp/server.d.ts.map +1 -1
  463. package/dist/mcp/server.js +219 -17
  464. package/dist/mcp/server.js.map +1 -1
  465. package/dist/mcp/session.d.ts +3 -1
  466. package/dist/mcp/session.d.ts.map +1 -1
  467. package/dist/mcp/session.js +58 -11
  468. package/dist/mcp/session.js.map +1 -1
  469. package/dist/mcp/store.d.ts +23 -1
  470. package/dist/mcp/store.d.ts.map +1 -1
  471. package/dist/mcp/store.js +102 -1
  472. package/dist/mcp/store.js.map +1 -1
  473. package/dist/mcp/token-expiry.d.ts +48 -0
  474. package/dist/mcp/token-expiry.d.ts.map +1 -0
  475. package/dist/mcp/token-expiry.js +69 -0
  476. package/dist/mcp/token-expiry.js.map +1 -0
  477. package/dist/mcp/tools.d.ts +154 -3
  478. package/dist/mcp/tools.d.ts.map +1 -1
  479. package/dist/mcp/tools.js +660 -39
  480. package/dist/mcp/tools.js.map +1 -1
  481. package/dist/mcp/types.d.ts +105 -4
  482. package/dist/mcp/types.d.ts.map +1 -1
  483. package/dist/mcp/types.js +13 -1
  484. package/dist/mcp/types.js.map +1 -1
  485. package/dist/mcp/write-client.d.ts +81 -0
  486. package/dist/mcp/write-client.d.ts.map +1 -0
  487. package/dist/mcp/write-client.js +140 -0
  488. package/dist/mcp/write-client.js.map +1 -0
  489. package/dist/oura/history-policy.d.ts +12 -0
  490. package/dist/oura/history-policy.d.ts.map +1 -0
  491. package/dist/oura/history-policy.js +54 -0
  492. package/dist/oura/history-policy.js.map +1 -0
  493. package/dist/oura/index.d.ts +51 -0
  494. package/dist/oura/index.d.ts.map +1 -0
  495. package/dist/oura/index.js +330 -0
  496. package/dist/oura/index.js.map +1 -0
  497. package/dist/payment/own-app.d.ts +8 -0
  498. package/dist/payment/own-app.d.ts.map +1 -0
  499. package/dist/payment/own-app.js +47 -0
  500. package/dist/payment/own-app.js.map +1 -0
  501. package/dist/pdpp/approval.d.ts +271 -0
  502. package/dist/pdpp/approval.d.ts.map +1 -0
  503. package/dist/pdpp/approval.js +486 -0
  504. package/dist/pdpp/approval.js.map +1 -0
  505. package/dist/pdpp/client-identity.d.ts +88 -0
  506. package/dist/pdpp/client-identity.d.ts.map +1 -0
  507. package/dist/pdpp/client-identity.js +196 -0
  508. package/dist/pdpp/client-identity.js.map +1 -0
  509. package/dist/pdpp/client-metadata.d.ts +95 -0
  510. package/dist/pdpp/client-metadata.d.ts.map +1 -0
  511. package/dist/pdpp/client-metadata.js +96 -0
  512. package/dist/pdpp/client-metadata.js.map +1 -0
  513. package/dist/pdpp/commitments.d.ts +75 -0
  514. package/dist/pdpp/commitments.d.ts.map +1 -0
  515. package/dist/pdpp/commitments.js +113 -0
  516. package/dist/pdpp/commitments.js.map +1 -0
  517. package/dist/pdpp/declaration-limits.d.ts +7 -0
  518. package/dist/pdpp/declaration-limits.d.ts.map +1 -0
  519. package/dist/pdpp/declaration-limits.js +7 -0
  520. package/dist/pdpp/declaration-limits.js.map +1 -0
  521. package/dist/pdpp/declaration.d.ts +119 -0
  522. package/dist/pdpp/declaration.d.ts.map +1 -0
  523. package/dist/pdpp/declaration.js +837 -0
  524. package/dist/pdpp/declaration.js.map +1 -0
  525. package/dist/pdpp/index.d.ts +38 -0
  526. package/dist/pdpp/index.d.ts.map +1 -0
  527. package/dist/pdpp/index.js +24 -0
  528. package/dist/pdpp/index.js.map +1 -0
  529. package/dist/pdpp/issuance.d.ts +126 -0
  530. package/dist/pdpp/issuance.d.ts.map +1 -0
  531. package/dist/pdpp/issuance.js +184 -0
  532. package/dist/pdpp/issuance.js.map +1 -0
  533. package/dist/pdpp/pkce.d.ts +53 -0
  534. package/dist/pdpp/pkce.d.ts.map +1 -0
  535. package/dist/pdpp/pkce.js +109 -0
  536. package/dist/pdpp/pkce.js.map +1 -0
  537. package/dist/pdpp/redirect.d.ts +60 -0
  538. package/dist/pdpp/redirect.d.ts.map +1 -0
  539. package/dist/pdpp/redirect.js +125 -0
  540. package/dist/pdpp/redirect.js.map +1 -0
  541. package/dist/pdpp/resolve.d.ts +120 -0
  542. package/dist/pdpp/resolve.d.ts.map +1 -0
  543. package/dist/pdpp/resolve.js +491 -0
  544. package/dist/pdpp/resolve.js.map +1 -0
  545. package/dist/pdpp/review.d.ts +280 -0
  546. package/dist/pdpp/review.d.ts.map +1 -0
  547. package/dist/pdpp/review.js +205 -0
  548. package/dist/pdpp/review.js.map +1 -0
  549. package/dist/pdpp/selection.d.ts +79 -0
  550. package/dist/pdpp/selection.d.ts.map +1 -0
  551. package/dist/pdpp/selection.js +493 -0
  552. package/dist/pdpp/selection.js.map +1 -0
  553. package/dist/pdpp/store.d.ts +228 -0
  554. package/dist/pdpp/store.d.ts.map +1 -0
  555. package/dist/pdpp/store.js +542 -0
  556. package/dist/pdpp/store.js.map +1 -0
  557. package/dist/pdpp/time.d.ts +39 -0
  558. package/dist/pdpp/time.d.ts.map +1 -0
  559. package/dist/pdpp/time.js +173 -0
  560. package/dist/pdpp/time.js.map +1 -0
  561. package/dist/pdpp/tokens.d.ts +181 -0
  562. package/dist/pdpp/tokens.d.ts.map +1 -0
  563. package/dist/pdpp/tokens.js +421 -0
  564. package/dist/pdpp/tokens.js.map +1 -0
  565. package/dist/pdpp/types.d.ts +457 -0
  566. package/dist/pdpp/types.d.ts.map +1 -0
  567. package/dist/pdpp/types.js +68 -0
  568. package/dist/pdpp/types.js.map +1 -0
  569. package/dist/pdpp-version.d.ts +28 -0
  570. package/dist/pdpp-version.d.ts.map +1 -0
  571. package/dist/pdpp-version.js +28 -0
  572. package/dist/pdpp-version.js.map +1 -0
  573. package/dist/policy/data-read.d.ts +52 -1
  574. package/dist/policy/data-read.d.ts.map +1 -1
  575. package/dist/policy/data-read.js +157 -3
  576. package/dist/policy/data-read.js.map +1 -1
  577. package/dist/policy/data-write.d.ts.map +1 -1
  578. package/dist/policy/data-write.js +18 -1
  579. package/dist/policy/data-write.js.map +1 -1
  580. package/dist/policy/index.d.ts +2 -1
  581. package/dist/policy/index.d.ts.map +1 -1
  582. package/dist/policy/index.js +2 -1
  583. package/dist/policy/index.js.map +1 -1
  584. package/dist/policy/reserved-scopes.d.ts +10 -0
  585. package/dist/policy/reserved-scopes.d.ts.map +1 -0
  586. package/dist/policy/reserved-scopes.js +19 -0
  587. package/dist/policy/reserved-scopes.js.map +1 -0
  588. package/dist/ports/index.d.ts +323 -10
  589. package/dist/ports/index.d.ts.map +1 -1
  590. package/dist/ports/index.js.map +1 -1
  591. package/dist/ports/pdpp-auth.d.ts +119 -0
  592. package/dist/ports/pdpp-auth.d.ts.map +1 -0
  593. package/dist/ports/pdpp-auth.js +46 -0
  594. package/dist/ports/pdpp-auth.js.map +1 -0
  595. package/dist/ports/pdpp-auth.test-utils.d.ts +9 -0
  596. package/dist/ports/pdpp-auth.test-utils.d.ts.map +1 -0
  597. package/dist/ports/pdpp-auth.test-utils.js +18 -0
  598. package/dist/ports/pdpp-auth.test-utils.js.map +1 -0
  599. package/dist/publication/publish.d.ts +137 -0
  600. package/dist/publication/publish.d.ts.map +1 -0
  601. package/dist/publication/publish.js +278 -0
  602. package/dist/publication/publish.js.map +1 -0
  603. package/dist/replication/completion.d.ts +20 -0
  604. package/dist/replication/completion.d.ts.map +1 -0
  605. package/dist/replication/completion.js +73 -0
  606. package/dist/replication/completion.js.map +1 -0
  607. package/dist/replication/coordinator-state.d.ts +29 -0
  608. package/dist/replication/coordinator-state.d.ts.map +1 -0
  609. package/dist/replication/coordinator-state.js +88 -0
  610. package/dist/replication/coordinator-state.js.map +1 -0
  611. package/dist/replication/coordinator-state.test-utils.d.ts +32 -0
  612. package/dist/replication/coordinator-state.test-utils.d.ts.map +1 -0
  613. package/dist/replication/coordinator-state.test-utils.js +113 -0
  614. package/dist/replication/coordinator-state.test-utils.js.map +1 -0
  615. package/dist/replication/coordinator.d.ts +264 -0
  616. package/dist/replication/coordinator.d.ts.map +1 -0
  617. package/dist/replication/coordinator.js +499 -0
  618. package/dist/replication/coordinator.js.map +1 -0
  619. package/dist/replication/copies.d.ts +126 -0
  620. package/dist/replication/copies.d.ts.map +1 -0
  621. package/dist/replication/copies.js +437 -0
  622. package/dist/replication/copies.js.map +1 -0
  623. package/dist/replication/copy-promotion.d.ts +132 -0
  624. package/dist/replication/copy-promotion.d.ts.map +1 -0
  625. package/dist/replication/copy-promotion.js +126 -0
  626. package/dist/replication/copy-promotion.js.map +1 -0
  627. package/dist/replication/door.d.ts +33 -0
  628. package/dist/replication/door.d.ts.map +1 -0
  629. package/dist/replication/door.js +10 -0
  630. package/dist/replication/door.js.map +1 -0
  631. package/dist/replication/dpv2.d.ts +141 -0
  632. package/dist/replication/dpv2.d.ts.map +1 -0
  633. package/dist/replication/dpv2.js +320 -0
  634. package/dist/replication/dpv2.js.map +1 -0
  635. package/dist/replication/effects.d.ts +68 -0
  636. package/dist/replication/effects.d.ts.map +1 -0
  637. package/dist/replication/effects.js +89 -0
  638. package/dist/replication/effects.js.map +1 -0
  639. package/dist/replication/engine.d.ts +378 -0
  640. package/dist/replication/engine.d.ts.map +1 -0
  641. package/dist/replication/engine.js +3197 -0
  642. package/dist/replication/engine.js.map +1 -0
  643. package/dist/replication/envelope.d.ts +481 -0
  644. package/dist/replication/envelope.d.ts.map +1 -0
  645. package/dist/replication/envelope.js +192 -0
  646. package/dist/replication/envelope.js.map +1 -0
  647. package/dist/replication/evidence.d.ts +118 -0
  648. package/dist/replication/evidence.d.ts.map +1 -0
  649. package/dist/replication/evidence.js +198 -0
  650. package/dist/replication/evidence.js.map +1 -0
  651. package/dist/replication/finality.d.ts +16 -0
  652. package/dist/replication/finality.d.ts.map +1 -0
  653. package/dist/replication/finality.js +11 -0
  654. package/dist/replication/finality.js.map +1 -0
  655. package/dist/replication/fixtures.d.ts +16 -0
  656. package/dist/replication/fixtures.d.ts.map +1 -0
  657. package/dist/replication/fixtures.js +47 -0
  658. package/dist/replication/fixtures.js.map +1 -0
  659. package/dist/replication/host-config.d.ts +52 -0
  660. package/dist/replication/host-config.d.ts.map +1 -0
  661. package/dist/replication/host-config.js +111 -0
  662. package/dist/replication/host-config.js.map +1 -0
  663. package/dist/replication/host-driver.d.ts +95 -0
  664. package/dist/replication/host-driver.d.ts.map +1 -0
  665. package/dist/replication/host-driver.js +202 -0
  666. package/dist/replication/host-driver.js.map +1 -0
  667. package/dist/replication/host-ports.d.ts +48 -0
  668. package/dist/replication/host-ports.d.ts.map +1 -0
  669. package/dist/replication/host-ports.js +69 -0
  670. package/dist/replication/host-ports.js.map +1 -0
  671. package/dist/replication/identity.d.ts +13 -0
  672. package/dist/replication/identity.d.ts.map +1 -0
  673. package/dist/replication/identity.js +22 -0
  674. package/dist/replication/identity.js.map +1 -0
  675. package/dist/replication/limits.d.ts +124 -0
  676. package/dist/replication/limits.d.ts.map +1 -0
  677. package/dist/replication/limits.js +182 -0
  678. package/dist/replication/limits.js.map +1 -0
  679. package/dist/replication/merge-plan.d.ts +92 -0
  680. package/dist/replication/merge-plan.d.ts.map +1 -0
  681. package/dist/replication/merge-plan.js +229 -0
  682. package/dist/replication/merge-plan.js.map +1 -0
  683. package/dist/replication/namespace.d.ts +4 -0
  684. package/dist/replication/namespace.d.ts.map +1 -0
  685. package/dist/replication/namespace.js +7 -0
  686. package/dist/replication/namespace.js.map +1 -0
  687. package/dist/replication/outcome.d.ts +178 -0
  688. package/dist/replication/outcome.d.ts.map +1 -0
  689. package/dist/replication/outcome.js +83 -0
  690. package/dist/replication/outcome.js.map +1 -0
  691. package/dist/replication/payload.d.ts +39 -0
  692. package/dist/replication/payload.d.ts.map +1 -0
  693. package/dist/replication/payload.js +137 -0
  694. package/dist/replication/payload.js.map +1 -0
  695. package/dist/replication/preparation.d.ts +42 -0
  696. package/dist/replication/preparation.d.ts.map +1 -0
  697. package/dist/replication/preparation.js +118 -0
  698. package/dist/replication/preparation.js.map +1 -0
  699. package/dist/replication/rebaseline.d.ts +33 -0
  700. package/dist/replication/rebaseline.d.ts.map +1 -0
  701. package/dist/replication/rebaseline.js +40 -0
  702. package/dist/replication/rebaseline.js.map +1 -0
  703. package/dist/replication/rebinding.d.ts +43 -0
  704. package/dist/replication/rebinding.d.ts.map +1 -0
  705. package/dist/replication/rebinding.js +52 -0
  706. package/dist/replication/rebinding.js.map +1 -0
  707. package/dist/replication/receive.d.ts +57 -0
  708. package/dist/replication/receive.d.ts.map +1 -0
  709. package/dist/replication/receive.js +114 -0
  710. package/dist/replication/receive.js.map +1 -0
  711. package/dist/replication/record-reducer.d.ts +16 -0
  712. package/dist/replication/record-reducer.d.ts.map +1 -0
  713. package/dist/replication/record-reducer.js +52 -0
  714. package/dist/replication/record-reducer.js.map +1 -0
  715. package/dist/replication/revision.d.ts +24 -0
  716. package/dist/replication/revision.d.ts.map +1 -0
  717. package/dist/replication/revision.js +35 -0
  718. package/dist/replication/revision.js.map +1 -0
  719. package/dist/replication/roster.d.ts +53 -0
  720. package/dist/replication/roster.d.ts.map +1 -0
  721. package/dist/replication/roster.js +115 -0
  722. package/dist/replication/roster.js.map +1 -0
  723. package/dist/replication/schedule.d.ts +73 -0
  724. package/dist/replication/schedule.d.ts.map +1 -0
  725. package/dist/replication/schedule.js +182 -0
  726. package/dist/replication/schedule.js.map +1 -0
  727. package/dist/replication/stream.d.ts +73 -0
  728. package/dist/replication/stream.d.ts.map +1 -0
  729. package/dist/replication/stream.js +542 -0
  730. package/dist/replication/stream.js.map +1 -0
  731. package/dist/replication/transport.d.ts +236 -0
  732. package/dist/replication/transport.d.ts.map +1 -0
  733. package/dist/replication/transport.js +440 -0
  734. package/dist/replication/transport.js.map +1 -0
  735. package/dist/replication/visibility-engine.d.ts +337 -0
  736. package/dist/replication/visibility-engine.d.ts.map +1 -0
  737. package/dist/replication/visibility-engine.js +602 -0
  738. package/dist/replication/visibility-engine.js.map +1 -0
  739. package/dist/replication/visibility-policy.d.ts +26 -0
  740. package/dist/replication/visibility-policy.d.ts.map +1 -0
  741. package/dist/replication/visibility-policy.js +33 -0
  742. package/dist/replication/visibility-policy.js.map +1 -0
  743. package/dist/replication/writer-identity-store.d.ts +100 -0
  744. package/dist/replication/writer-identity-store.d.ts.map +1 -0
  745. package/dist/replication/writer-identity-store.js +218 -0
  746. package/dist/replication/writer-identity-store.js.map +1 -0
  747. package/dist/replication/writer-identity.d.ts +252 -0
  748. package/dist/replication/writer-identity.d.ts.map +1 -0
  749. package/dist/replication/writer-identity.js +281 -0
  750. package/dist/replication/writer-identity.js.map +1 -0
  751. package/dist/replication/writer-identity.test-utils.d.ts +24 -0
  752. package/dist/replication/writer-identity.test-utils.d.ts.map +1 -0
  753. package/dist/replication/writer-identity.test-utils.js +86 -0
  754. package/dist/replication/writer-identity.test-utils.js.map +1 -0
  755. package/dist/schemas/server-config.d.ts +81 -0
  756. package/dist/schemas/server-config.d.ts.map +1 -1
  757. package/dist/schemas/server-config.js +179 -0
  758. package/dist/schemas/server-config.js.map +1 -1
  759. package/dist/signing/request-signer.d.ts +2 -0
  760. package/dist/signing/request-signer.d.ts.map +1 -1
  761. package/dist/signing/request-signer.js +1 -0
  762. package/dist/signing/request-signer.js.map +1 -1
  763. package/dist/storage/adapters/index.d.ts +3 -1
  764. package/dist/storage/adapters/index.d.ts.map +1 -1
  765. package/dist/storage/adapters/index.js +2 -0
  766. package/dist/storage/adapters/index.js.map +1 -1
  767. package/dist/storage/adapters/interface.d.ts +33 -3
  768. package/dist/storage/adapters/interface.d.ts.map +1 -1
  769. package/dist/storage/adapters/interface.js +13 -1
  770. package/dist/storage/adapters/interface.js.map +1 -1
  771. package/dist/storage/adapters/rate-limit-policy.d.ts +66 -0
  772. package/dist/storage/adapters/rate-limit-policy.d.ts.map +1 -0
  773. package/dist/storage/adapters/rate-limit-policy.js +103 -0
  774. package/dist/storage/adapters/rate-limit-policy.js.map +1 -0
  775. package/dist/storage/adapters/sdk.d.ts +9 -1
  776. package/dist/storage/adapters/sdk.d.ts.map +1 -1
  777. package/dist/storage/adapters/sdk.js +32 -8
  778. package/dist/storage/adapters/sdk.js.map +1 -1
  779. package/dist/storage/adapters/throttle.d.ts +30 -0
  780. package/dist/storage/adapters/throttle.d.ts.map +1 -0
  781. package/dist/storage/adapters/throttle.js +94 -0
  782. package/dist/storage/adapters/throttle.js.map +1 -0
  783. package/dist/storage/adapters/vana-audience.d.ts +27 -0
  784. package/dist/storage/adapters/vana-audience.d.ts.map +1 -0
  785. package/dist/storage/adapters/vana-audience.js +99 -0
  786. package/dist/storage/adapters/vana-audience.js.map +1 -0
  787. package/dist/storage/adapters/vana.d.ts +5 -3
  788. package/dist/storage/adapters/vana.d.ts.map +1 -1
  789. package/dist/storage/adapters/vana.js +128 -18
  790. package/dist/storage/adapters/vana.js.map +1 -1
  791. package/dist/storage/blocks/cursor.d.ts +5 -1
  792. package/dist/storage/blocks/cursor.d.ts.map +1 -1
  793. package/dist/storage/blocks/cursor.js +13 -1
  794. package/dist/storage/blocks/cursor.js.map +1 -1
  795. package/dist/storage/blocks/page.d.ts +18 -0
  796. package/dist/storage/blocks/page.d.ts.map +1 -0
  797. package/dist/storage/blocks/page.js +113 -0
  798. package/dist/storage/blocks/page.js.map +1 -0
  799. package/dist/storage/canonical-legacy-projection.d.ts +262 -0
  800. package/dist/storage/canonical-legacy-projection.d.ts.map +1 -0
  801. package/dist/storage/canonical-legacy-projection.js +759 -0
  802. package/dist/storage/canonical-legacy-projection.js.map +1 -0
  803. package/dist/storage/hierarchy/paths.d.ts.map +1 -1
  804. package/dist/storage/hierarchy/paths.js +9 -2
  805. package/dist/storage/hierarchy/paths.js.map +1 -1
  806. package/dist/storage/index/manager.d.ts +46 -5
  807. package/dist/storage/index/manager.d.ts.map +1 -1
  808. package/dist/storage/index/schema.d.ts +1 -1
  809. package/dist/storage/index/schema.js +1 -1
  810. package/dist/storage/index/types.d.ts +7 -1
  811. package/dist/storage/index/types.d.ts.map +1 -1
  812. package/dist/storage/legacy-projection.d.ts +88 -0
  813. package/dist/storage/legacy-projection.d.ts.map +1 -0
  814. package/dist/storage/legacy-projection.js +755 -0
  815. package/dist/storage/legacy-projection.js.map +1 -0
  816. package/dist/storage/legacy-scope-coverage-exceptions.d.ts +13 -0
  817. package/dist/storage/legacy-scope-coverage-exceptions.d.ts.map +1 -0
  818. package/dist/storage/legacy-scope-coverage-exceptions.js +14 -0
  819. package/dist/storage/legacy-scope-coverage-exceptions.js.map +1 -0
  820. package/dist/storage/legacy-scope-coverage.d.ts +53 -0
  821. package/dist/storage/legacy-scope-coverage.d.ts.map +1 -0
  822. package/dist/storage/legacy-scope-coverage.js +416 -0
  823. package/dist/storage/legacy-scope-coverage.js.map +1 -0
  824. package/dist/storage/legacy-scope-entity-keys.d.ts +17 -0
  825. package/dist/storage/legacy-scope-entity-keys.d.ts.map +1 -0
  826. package/dist/storage/legacy-scope-entity-keys.js +109 -0
  827. package/dist/storage/legacy-scope-entity-keys.js.map +1 -0
  828. package/dist/storage/legacy-scope-view.d.ts +201 -0
  829. package/dist/storage/legacy-scope-view.d.ts.map +1 -0
  830. package/dist/storage/legacy-scope-view.js +1044 -0
  831. package/dist/storage/legacy-scope-view.js.map +1 -0
  832. package/dist/storage/legacy-write-seal.d.ts +73 -0
  833. package/dist/storage/legacy-write-seal.d.ts.map +1 -0
  834. package/dist/storage/legacy-write-seal.js +71 -0
  835. package/dist/storage/legacy-write-seal.js.map +1 -0
  836. package/dist/storage/pdpp-records/completion.d.ts +91 -0
  837. package/dist/storage/pdpp-records/completion.d.ts.map +1 -0
  838. package/dist/storage/pdpp-records/completion.js +170 -0
  839. package/dist/storage/pdpp-records/completion.js.map +1 -0
  840. package/dist/storage/pdpp-records/cursor.d.ts +86 -0
  841. package/dist/storage/pdpp-records/cursor.d.ts.map +1 -0
  842. package/dist/storage/pdpp-records/cursor.js +56 -0
  843. package/dist/storage/pdpp-records/cursor.js.map +1 -0
  844. package/dist/storage/pdpp-records/declaration-witness.d.ts +58 -0
  845. package/dist/storage/pdpp-records/declaration-witness.d.ts.map +1 -0
  846. package/dist/storage/pdpp-records/declaration-witness.js +230 -0
  847. package/dist/storage/pdpp-records/declaration-witness.js.map +1 -0
  848. package/dist/storage/pdpp-records/enforcement.d.ts +39 -0
  849. package/dist/storage/pdpp-records/enforcement.d.ts.map +1 -0
  850. package/dist/storage/pdpp-records/enforcement.js +143 -0
  851. package/dist/storage/pdpp-records/enforcement.js.map +1 -0
  852. package/dist/storage/pdpp-records/index.d.ts +7 -0
  853. package/dist/storage/pdpp-records/index.d.ts.map +1 -0
  854. package/dist/storage/pdpp-records/index.js +6 -0
  855. package/dist/storage/pdpp-records/index.js.map +1 -0
  856. package/dist/storage/pdpp-records/ingest-plan.d.ts +39 -0
  857. package/dist/storage/pdpp-records/ingest-plan.d.ts.map +1 -0
  858. package/dist/storage/pdpp-records/ingest-plan.js +103 -0
  859. package/dist/storage/pdpp-records/ingest-plan.js.map +1 -0
  860. package/dist/storage/pdpp-records/interface.d.ts +111 -0
  861. package/dist/storage/pdpp-records/interface.d.ts.map +1 -0
  862. package/dist/storage/pdpp-records/interface.js +2 -0
  863. package/dist/storage/pdpp-records/interface.js.map +1 -0
  864. package/dist/storage/pdpp-records/list-page.d.ts +35 -0
  865. package/dist/storage/pdpp-records/list-page.d.ts.map +1 -0
  866. package/dist/storage/pdpp-records/list-page.js +106 -0
  867. package/dist/storage/pdpp-records/list-page.js.map +1 -0
  868. package/dist/storage/pdpp-records/memory-store.d.ts +9 -0
  869. package/dist/storage/pdpp-records/memory-store.d.ts.map +1 -0
  870. package/dist/storage/pdpp-records/memory-store.js +462 -0
  871. package/dist/storage/pdpp-records/memory-store.js.map +1 -0
  872. package/dist/storage/pdpp-records/portable.d.ts +12 -0
  873. package/dist/storage/pdpp-records/portable.d.ts.map +1 -0
  874. package/dist/storage/pdpp-records/portable.js +11 -0
  875. package/dist/storage/pdpp-records/portable.js.map +1 -0
  876. package/dist/storage/pdpp-records/read-port.d.ts +44 -0
  877. package/dist/storage/pdpp-records/read-port.d.ts.map +1 -0
  878. package/dist/storage/pdpp-records/read-port.js +22 -0
  879. package/dist/storage/pdpp-records/read-port.js.map +1 -0
  880. package/dist/storage/pdpp-records/record-key.d.ts +52 -0
  881. package/dist/storage/pdpp-records/record-key.d.ts.map +1 -0
  882. package/dist/storage/pdpp-records/record-key.js +97 -0
  883. package/dist/storage/pdpp-records/record-key.js.map +1 -0
  884. package/dist/storage/pdpp-records/replication-journal.d.ts +20 -0
  885. package/dist/storage/pdpp-records/replication-journal.d.ts.map +1 -0
  886. package/dist/storage/pdpp-records/replication-journal.js +2 -0
  887. package/dist/storage/pdpp-records/replication-journal.js.map +1 -0
  888. package/dist/storage/pdpp-records/schema.d.ts +41 -0
  889. package/dist/storage/pdpp-records/schema.d.ts.map +1 -0
  890. package/dist/storage/pdpp-records/schema.js +153 -0
  891. package/dist/storage/pdpp-records/schema.js.map +1 -0
  892. package/dist/storage/pdpp-records/stream-declaration.d.ts +86 -0
  893. package/dist/storage/pdpp-records/stream-declaration.d.ts.map +1 -0
  894. package/dist/storage/pdpp-records/stream-declaration.js +48 -0
  895. package/dist/storage/pdpp-records/stream-declaration.js.map +1 -0
  896. package/dist/storage/pdpp-records/sync-selection.d.ts +4 -0
  897. package/dist/storage/pdpp-records/sync-selection.d.ts.map +1 -0
  898. package/dist/storage/pdpp-records/sync-selection.js +37 -0
  899. package/dist/storage/pdpp-records/sync-selection.js.map +1 -0
  900. package/dist/storage/pdpp-records/types.d.ts +204 -0
  901. package/dist/storage/pdpp-records/types.d.ts.map +1 -0
  902. package/dist/storage/pdpp-records/types.js +38 -0
  903. package/dist/storage/pdpp-records/types.js.map +1 -0
  904. package/dist/stream-sync/artifacts.d.ts +38 -0
  905. package/dist/stream-sync/artifacts.d.ts.map +1 -0
  906. package/dist/stream-sync/artifacts.js +141 -0
  907. package/dist/stream-sync/artifacts.js.map +1 -0
  908. package/dist/stream-sync/blobs.d.ts +18 -0
  909. package/dist/stream-sync/blobs.d.ts.map +1 -0
  910. package/dist/stream-sync/blobs.js +83 -0
  911. package/dist/stream-sync/blobs.js.map +1 -0
  912. package/dist/stream-sync/crypto-port.d.ts +20 -0
  913. package/dist/stream-sync/crypto-port.d.ts.map +1 -0
  914. package/dist/stream-sync/crypto-port.js +19 -0
  915. package/dist/stream-sync/crypto-port.js.map +1 -0
  916. package/dist/stream-sync/crypto.d.ts +27 -0
  917. package/dist/stream-sync/crypto.d.ts.map +1 -0
  918. package/dist/stream-sync/crypto.js +67 -0
  919. package/dist/stream-sync/crypto.js.map +1 -0
  920. package/dist/stream-sync/delete-metadata.d.ts +23 -0
  921. package/dist/stream-sync/delete-metadata.d.ts.map +1 -0
  922. package/dist/stream-sync/delete-metadata.js +40 -0
  923. package/dist/stream-sync/delete-metadata.js.map +1 -0
  924. package/dist/stream-sync/index.d.ts +13 -0
  925. package/dist/stream-sync/index.d.ts.map +1 -0
  926. package/dist/stream-sync/index.js +13 -0
  927. package/dist/stream-sync/index.js.map +1 -0
  928. package/dist/stream-sync/intake.d.ts +185 -0
  929. package/dist/stream-sync/intake.d.ts.map +1 -0
  930. package/dist/stream-sync/intake.js +36 -0
  931. package/dist/stream-sync/intake.js.map +1 -0
  932. package/dist/stream-sync/memory-registry.d.ts +58 -0
  933. package/dist/stream-sync/memory-registry.d.ts.map +1 -0
  934. package/dist/stream-sync/memory-registry.js +119 -0
  935. package/dist/stream-sync/memory-registry.js.map +1 -0
  936. package/dist/stream-sync/ports.d.ts +363 -0
  937. package/dist/stream-sync/ports.d.ts.map +1 -0
  938. package/dist/stream-sync/ports.js +68 -0
  939. package/dist/stream-sync/ports.js.map +1 -0
  940. package/dist/stream-sync/publish-plan.d.ts +157 -0
  941. package/dist/stream-sync/publish-plan.d.ts.map +1 -0
  942. package/dist/stream-sync/publish-plan.js +217 -0
  943. package/dist/stream-sync/publish-plan.js.map +1 -0
  944. package/dist/stream-sync/registry.d.ts +24 -0
  945. package/dist/stream-sync/registry.d.ts.map +1 -0
  946. package/dist/stream-sync/registry.js +389 -0
  947. package/dist/stream-sync/registry.js.map +1 -0
  948. package/dist/stream-sync/scope-routing.d.ts +17 -0
  949. package/dist/stream-sync/scope-routing.d.ts.map +1 -0
  950. package/dist/stream-sync/scope-routing.js +24 -0
  951. package/dist/stream-sync/scope-routing.js.map +1 -0
  952. package/dist/stream-sync/seed-staging.d.ts +85 -0
  953. package/dist/stream-sync/seed-staging.d.ts.map +1 -0
  954. package/dist/stream-sync/seed-staging.js +325 -0
  955. package/dist/stream-sync/seed-staging.js.map +1 -0
  956. package/dist/stream-sync/send-gate.d.ts +149 -0
  957. package/dist/stream-sync/send-gate.d.ts.map +1 -0
  958. package/dist/stream-sync/send-gate.js +382 -0
  959. package/dist/stream-sync/send-gate.js.map +1 -0
  960. package/dist/stream-sync/storage-retry.d.ts +210 -0
  961. package/dist/stream-sync/storage-retry.d.ts.map +1 -0
  962. package/dist/stream-sync/storage-retry.js +314 -0
  963. package/dist/stream-sync/storage-retry.js.map +1 -0
  964. package/dist/stream-sync/stream-aead.d.ts +33 -0
  965. package/dist/stream-sync/stream-aead.d.ts.map +1 -0
  966. package/dist/stream-sync/stream-aead.js +183 -0
  967. package/dist/stream-sync/stream-aead.js.map +1 -0
  968. package/dist/stream-sync-read/index.d.ts +4 -0
  969. package/dist/stream-sync-read/index.d.ts.map +1 -0
  970. package/dist/stream-sync-read/index.js +3 -0
  971. package/dist/stream-sync-read/index.js.map +1 -0
  972. package/dist/stream-sync-read/routing.d.ts +27 -0
  973. package/dist/stream-sync-read/routing.d.ts.map +1 -0
  974. package/dist/stream-sync-read/routing.js +49 -0
  975. package/dist/stream-sync-read/routing.js.map +1 -0
  976. package/dist/stream-sync-read/service.d.ts +196 -0
  977. package/dist/stream-sync-read/service.d.ts.map +1 -0
  978. package/dist/stream-sync-read/service.js +17 -0
  979. package/dist/stream-sync-read/service.js.map +1 -0
  980. package/dist/sync/account-mode/authority.d.ts +56 -0
  981. package/dist/sync/account-mode/authority.d.ts.map +1 -0
  982. package/dist/sync/account-mode/authority.js +145 -0
  983. package/dist/sync/account-mode/authority.js.map +1 -0
  984. package/dist/sync/account-mode/evidence-wire.d.ts +23 -0
  985. package/dist/sync/account-mode/evidence-wire.d.ts.map +1 -0
  986. package/dist/sync/account-mode/evidence-wire.js +37 -0
  987. package/dist/sync/account-mode/evidence-wire.js.map +1 -0
  988. package/dist/sync/account-mode/import-waker.d.ts +36 -0
  989. package/dist/sync/account-mode/import-waker.d.ts.map +1 -0
  990. package/dist/sync/account-mode/import-waker.js +55 -0
  991. package/dist/sync/account-mode/import-waker.js.map +1 -0
  992. package/dist/sync/account-mode/index.d.ts +10 -0
  993. package/dist/sync/account-mode/index.d.ts.map +1 -0
  994. package/dist/sync/account-mode/index.js +10 -0
  995. package/dist/sync/account-mode/index.js.map +1 -0
  996. package/dist/sync/account-mode/port.d.ts +11 -0
  997. package/dist/sync/account-mode/port.d.ts.map +1 -0
  998. package/dist/sync/account-mode/port.js +21 -0
  999. package/dist/sync/account-mode/port.js.map +1 -0
  1000. package/dist/sync/account-mode/record.d.ts +52 -0
  1001. package/dist/sync/account-mode/record.d.ts.map +1 -0
  1002. package/dist/sync/account-mode/record.js +60 -0
  1003. package/dist/sync/account-mode/record.js.map +1 -0
  1004. package/dist/sync/account-mode/rw-lock.d.ts +14 -0
  1005. package/dist/sync/account-mode/rw-lock.d.ts.map +1 -0
  1006. package/dist/sync/account-mode/rw-lock.js +59 -0
  1007. package/dist/sync/account-mode/rw-lock.js.map +1 -0
  1008. package/dist/sync/cancellable-gateway.d.ts +25 -0
  1009. package/dist/sync/cancellable-gateway.d.ts.map +1 -0
  1010. package/dist/sync/cancellable-gateway.js +64 -0
  1011. package/dist/sync/cancellable-gateway.js.map +1 -0
  1012. package/dist/sync/data-point-feed.d.ts +3 -0
  1013. package/dist/sync/data-point-feed.d.ts.map +1 -1
  1014. package/dist/sync/data-point-feed.js +20 -1
  1015. package/dist/sync/data-point-feed.js.map +1 -1
  1016. package/dist/sync/delete-data-port.d.ts +19 -0
  1017. package/dist/sync/delete-data-port.d.ts.map +1 -1
  1018. package/dist/sync/delete-data-port.js +42 -9
  1019. package/dist/sync/delete-data-port.js.map +1 -1
  1020. package/dist/sync/engine/change-probe.d.ts +42 -0
  1021. package/dist/sync/engine/change-probe.d.ts.map +1 -0
  1022. package/dist/sync/engine/change-probe.js +79 -0
  1023. package/dist/sync/engine/change-probe.js.map +1 -0
  1024. package/dist/sync/engine/change-push.d.ts +53 -0
  1025. package/dist/sync/engine/change-push.d.ts.map +1 -0
  1026. package/dist/sync/engine/change-push.js +153 -0
  1027. package/dist/sync/engine/change-push.js.map +1 -0
  1028. package/dist/sync/engine/sync-manager.d.ts +181 -2
  1029. package/dist/sync/engine/sync-manager.d.ts.map +1 -1
  1030. package/dist/sync/engine/sync-manager.js +642 -19
  1031. package/dist/sync/engine/sync-manager.js.map +1 -1
  1032. package/dist/sync/index.d.ts +11 -3
  1033. package/dist/sync/index.d.ts.map +1 -1
  1034. package/dist/sync/index.js +11 -1
  1035. package/dist/sync/index.js.map +1 -1
  1036. package/dist/sync/pdpp-import.d.ts +202 -0
  1037. package/dist/sync/pdpp-import.d.ts.map +1 -0
  1038. package/dist/sync/pdpp-import.js +466 -0
  1039. package/dist/sync/pdpp-import.js.map +1 -0
  1040. package/dist/sync/pending-blob-deletions.d.ts +18 -2
  1041. package/dist/sync/pending-blob-deletions.d.ts.map +1 -1
  1042. package/dist/sync/pending-blob-deletions.js +97 -23
  1043. package/dist/sync/pending-blob-deletions.js.map +1 -1
  1044. package/dist/sync/scope-deletions.d.ts +12 -0
  1045. package/dist/sync/scope-deletions.d.ts.map +1 -1
  1046. package/dist/sync/scope-deletions.js +99 -25
  1047. package/dist/sync/scope-deletions.js.map +1 -1
  1048. package/dist/sync/tombstone-finality.d.ts +36 -0
  1049. package/dist/sync/tombstone-finality.d.ts.map +1 -0
  1050. package/dist/sync/tombstone-finality.js +142 -0
  1051. package/dist/sync/tombstone-finality.js.map +1 -0
  1052. package/dist/sync/tombstone-resubmits.d.ts +61 -0
  1053. package/dist/sync/tombstone-resubmits.d.ts.map +1 -0
  1054. package/dist/sync/tombstone-resubmits.js +85 -0
  1055. package/dist/sync/tombstone-resubmits.js.map +1 -0
  1056. package/dist/sync/types.d.ts +26 -0
  1057. package/dist/sync/types.d.ts.map +1 -1
  1058. package/dist/sync/upload-attempts.d.ts +218 -0
  1059. package/dist/sync/upload-attempts.d.ts.map +1 -0
  1060. package/dist/sync/upload-attempts.js +500 -0
  1061. package/dist/sync/upload-attempts.js.map +1 -0
  1062. package/dist/sync/upload-state.d.ts +163 -0
  1063. package/dist/sync/upload-state.d.ts.map +1 -0
  1064. package/dist/sync/upload-state.js +239 -0
  1065. package/dist/sync/upload-state.js.map +1 -0
  1066. package/dist/sync/workers/delete.d.ts +63 -6
  1067. package/dist/sync/workers/delete.d.ts.map +1 -1
  1068. package/dist/sync/workers/delete.js +621 -168
  1069. package/dist/sync/workers/delete.js.map +1 -1
  1070. package/dist/sync/workers/download.d.ts +27 -1
  1071. package/dist/sync/workers/download.d.ts.map +1 -1
  1072. package/dist/sync/workers/download.js +368 -27
  1073. package/dist/sync/workers/download.js.map +1 -1
  1074. package/dist/sync/workers/lost-data-points.d.ts +38 -0
  1075. package/dist/sync/workers/lost-data-points.d.ts.map +1 -0
  1076. package/dist/sync/workers/lost-data-points.js +72 -0
  1077. package/dist/sync/workers/lost-data-points.js.map +1 -0
  1078. package/dist/sync/workers/upload.d.ts +97 -8
  1079. package/dist/sync/workers/upload.d.ts.map +1 -1
  1080. package/dist/sync/workers/upload.js +498 -277
  1081. package/dist/sync/workers/upload.js.map +1 -1
  1082. package/dist/test-support/memory-oracle.calibration.d.ts +16 -0
  1083. package/dist/test-support/memory-oracle.calibration.d.ts.map +1 -0
  1084. package/dist/test-support/memory-oracle.calibration.js +43 -0
  1085. package/dist/test-support/memory-oracle.calibration.js.map +1 -0
  1086. package/dist/test-support/memory-oracle.d.ts +82 -0
  1087. package/dist/test-support/memory-oracle.d.ts.map +1 -0
  1088. package/dist/test-support/memory-oracle.js +104 -0
  1089. package/dist/test-support/memory-oracle.js.map +1 -0
  1090. package/dist/test-utils/account-mode.d.ts +36 -0
  1091. package/dist/test-utils/account-mode.d.ts.map +1 -0
  1092. package/dist/test-utils/account-mode.js +77 -0
  1093. package/dist/test-utils/account-mode.js.map +1 -0
  1094. package/dist/test-utils/index.d.ts +2 -0
  1095. package/dist/test-utils/index.d.ts.map +1 -1
  1096. package/dist/test-utils/index.js +2 -0
  1097. package/dist/test-utils/index.js.map +1 -1
  1098. package/dist/test-utils/legacy-write-seal.d.ts +16 -0
  1099. package/dist/test-utils/legacy-write-seal.d.ts.map +1 -0
  1100. package/dist/test-utils/legacy-write-seal.js +20 -0
  1101. package/dist/test-utils/legacy-write-seal.js.map +1 -0
  1102. package/dist/test-utils/live-grants.d.ts +24 -0
  1103. package/dist/test-utils/live-grants.d.ts.map +1 -0
  1104. package/dist/test-utils/live-grants.js +6 -0
  1105. package/dist/test-utils/live-grants.js.map +1 -0
  1106. package/dist/test-utils/memory-storage.d.ts +18 -2
  1107. package/dist/test-utils/memory-storage.d.ts.map +1 -1
  1108. package/dist/test-utils/memory-storage.js +156 -42
  1109. package/dist/test-utils/memory-storage.js.map +1 -1
  1110. package/dist/write/attribution.d.ts.map +1 -1
  1111. package/dist/write/attribution.js +8 -4
  1112. package/dist/write/attribution.js.map +1 -1
  1113. package/dist/write/route.d.ts.map +1 -1
  1114. package/dist/write/route.js +9 -10
  1115. package/dist/write/route.js.map +1 -1
  1116. package/dist/write/session.d.ts.map +1 -1
  1117. package/dist/write/session.js +13 -0
  1118. package/dist/write/session.js.map +1 -1
  1119. package/dist-test/localdb/conformance.d.ts +13 -0
  1120. package/dist-test/localdb/conformance.d.ts.map +1 -0
  1121. package/dist-test/localdb/conformance.js +292 -0
  1122. package/dist-test/localdb/conformance.js.map +1 -0
  1123. package/dist-test/tsconfig.tsbuildinfo +1 -0
  1124. package/package.json +131 -5
@@ -0,0 +1,2100 @@
1
+ import { holdMemory } from "./transfer-memory.js";
2
+ import { listStreamBlobs, uploadBlobs } from "./blobs.js";
3
+ // PS-2 P09 publish: the publish side of local sync.
4
+ //
5
+ // Per connection, after apply. Per stream with work, in three phases. Only
6
+ // the first and the last hold the connection's queue slot; the middle one
7
+ // holds none, so a run's begin never waits for the upload. The slot is not
8
+ // network-free: the snapshot still reads the registry and prior head blobs,
9
+ // and the commit still reads, signs and posts the CAS under it.
10
+ //
11
+ // SNAPSHOT (slot) 1. Snapshot W = max(seq) in record_changes and the
12
+ // changes with seq > publish_watermark and seq <= W.
13
+ // 2. Registry: a newer registry head is applied (same slot turn) and
14
+ // the stream restarts at step 1; a deleted control row purges the
15
+ // connection and stops.
16
+ // 3. Re-plan the retained ended runs against the registry head. A run
17
+ // accepted at end but now refused is un-written in one batch and
18
+ // apply runs at once; a deferred run defers the stream.
19
+ // Freeze what the next phase needs: the rows of each changed prefix,
20
+ // copied by SQL into the attempt's rows of `publish_spool` (on disk, in
21
+ // the same database; under replace, leaving out rows below the run's
22
+ // stamp), the attachments to upload, and the basis the snapshot rests
23
+ // on (control, stream state, head parts, delete intents, retained runs,
24
+ // W, and what readBasis lists).
25
+ // TRANSFER (no slot) 4. Read the spooled rows page by page, encode,
26
+ // upload every new part and attachment, build the head and upload it.
27
+ // Objects are content addressed and authorize nothing until the registry
28
+ // CAS, so they need no mutual exclusion. The spool is a copy no write to
29
+ // `records` reaches, so continuous collection cannot invalidate a
30
+ // transfer; only the commit's revalidation can. Each page is a plain read
31
+ // (no slot, no transaction across a network await) of at most a few
32
+ // MiB of bodies, so memory is a page and the part in progress. A spool
33
+ // that lost rows discards the candidate before its head exists.
34
+ // Attachment bytes are read by exact id and checked against it. The
35
+ // attempt's spool rows are deleted when the attempt ends, however it
36
+ // ends; `openLocalDb` deletes any a crash left.
37
+ // COMMIT (slot) 5. Re-read the basis and the registry rows. A change in
38
+ // what readBasis compares discards the candidate and re-snapshots (up
39
+ // to MAX_INVALIDATIONS re-snapshots, then the work stays pending for the
40
+ // next cycle); nothing merges. Otherwise head,
41
+ // then registry CAS from head_version: the same data hash skips the CAS;
42
+ // a conflict applies the winner and re-plans, at most 5 tries, then back
43
+ // off. On success one batch: replace deletes (origin refresh), head
44
+ // identity, publish_watermark = the SNAPSHOT's W (never a fresh max, so a
45
+ // run that ended during the transfer stays pending), head_parts,
46
+ // stream_versions, compaction of record_changes at or below the
47
+ // connection's lowest watermark (kept while an import read-back is
48
+ // pending).
49
+ // With a gateway that has a batch route, the streams of one connection
50
+ // that are ready commit in ONE request per slot turn (see commitBatchTurn
51
+ // and batch-commit.ts): group commit, no timer. Each stream that writes
52
+ // sends its row with the registry head's data hash it was planned over;
53
+ // each stream with nothing to write sends a condition on its stream row.
54
+ // The request also names the connection's control row (generation, hash,
55
+ // not deleted). The gateway checks the conditions in the transaction of
56
+ // the writes, so no client read of the control row brackets the write. A
57
+ // failed condition writes nothing: purge (control deleted), defer
58
+ // (another lifetime) or re-plan one stream (its row moved). Otherwise each
59
+ // row answers for itself: 201 publishes that stream (only the frozen
60
+ // watermark is acknowledged); a 409 applies the winner and re-plans that
61
+ // stream, and the others are not affected. A lost reply is answered by
62
+ // sending the same request again. A gateway without the route (404 or
63
+ // 405) is remembered, and every stream commits alone as before
64
+ // (commitCandidate).
65
+ //
66
+ // Seeds (import rows with stamp (0, "seed")) publish only into generation
67
+ // 1; otherwise they are purged and the ledger records excluded(seed_skipped).
68
+ //
69
+ // Every stream of one connection runs together. Each
70
+ // stream's turns take the slot one at a time, so the control row is settled
71
+ // by whichever snapshot runs first and every other stream sees it active; the
72
+ // transfers overlap. Each stream's own state (stream_state row, spool attempt,
73
+ // watermark) is its own; the connection's state (control, apply) is only
74
+ // touched in a slot turn, and a change to it shows in the other streams'
75
+ // readBasis. A purge sets a latch in its turn: streams still running stop at
76
+ // their next turn or upload and report "purged"; no stream starts after it.
77
+ //
78
+ // Queue: this module takes the connection's "publish" slot itself, for the
79
+ // snapshot and the commit. The caller must not hold it. applyConnection and
80
+ // purgeConnection, called inside a turn, run inline in that turn.
81
+ import { keccak_256 } from "@noble/hashes/sha3";
82
+ import { HEAD_FORMAT, classifyControl, classifyStreamRow, controlHashes, controlScope, deriveKeyCheck, digestHead, encodeHead, framesCarryFirstSeen, headBlobName, omissionCutoff, streamScope, toHex, utf8, verifyHead, } from "@opendatalabs/personal-server-ts-stream-sync";
83
+ import { planStreamStep, sameHead, } from "../stream-sync/publish-plan.js";
84
+ import { AmbiguousRegistryReplyError, } from "../stream-sync/ports.js";
85
+ import { applyConnection } from "./apply.js";
86
+ import { createCommitGroup, GATEWAY_MAX_BATCH_REQUIRES, GATEWAY_MAX_BATCH_ROWS, settleRequirementFailure, settleRow, } from "./batch-commit.js";
87
+ import { FrozenRowsChanged, dropSpool, freezePrefixRows, newFrozenFeed, newSpoolAttempt, partTargetOf, startFrozenParts, } from "./encode.js";
88
+ import { planChangedPrefixes, replacedPrefixGroups } from "./part-layout.js";
89
+ import { StorageDeferredError, } from "../stream-sync/storage-retry.js";
90
+ import { meteredBlobs, newPublishMeter, publishTimings, timed, } from "./publish-meter.js";
91
+ import { dropRunRows, replaceDelete, withOrigin } from "./merge.js";
92
+ import { endsEarlierLifetime, hydrateLifetimeBoundary, olderLifetimeFence, } from "./lifetime-boundary.js";
93
+ import { purgeConnection } from "./purge.js";
94
+ import { checkRunFence } from "./fence.js";
95
+ import { replaceMayApply } from "./replace.js";
96
+ import { openRegistryView } from "./registry-view.js";
97
+ import { insideQueue } from "./slot.js";
98
+ import { recallHead, rememberHead, rememberOwnHead } from "./verified-heads.js";
99
+ import { newUploadWave } from "./upload-wave.js";
100
+ import { unwriteRefusedRun } from "./unwrite.js";
101
+ export async function publishConnection(deps, connectionId, options) {
102
+ const opened = await deps.queue.run(connectionId, "publish", async () => {
103
+ const held = insideQueue(deps, connectionId);
104
+ const [connection] = await held.db.query(`SELECT connector, ns, generation FROM connections WHERE connection_id = ?`, [connectionId]);
105
+ if (!connection) {
106
+ throw new Error(`publish: unknown connection ${connectionId}`);
107
+ }
108
+ const keyCheck = await deriveKeyCheck(held.keys.namespaceHmac);
109
+ const hashes = await controlHashes(keccak, keyCheck);
110
+ const streams = await held.db.query(`SELECT stream FROM stream_state WHERE connection_id = ? ORDER BY stream`, [connectionId]);
111
+ if ((await held.db.query("SELECT 1 FROM delete_intents WHERE connector=?", [
112
+ connection.connector,
113
+ ])).length)
114
+ return {
115
+ results: streams.map(({ stream }) => ({
116
+ stream,
117
+ outcome: "deferred",
118
+ watermark: null,
119
+ })),
120
+ };
121
+ if (streams.length === 0) {
122
+ const state = classifyControl(await held.registry.read(controlScope(connection.connector, connection.ns)), hashes);
123
+ if (state.kind === "deleted")
124
+ await purgeConnection(held, connectionId, {
125
+ controlVersion: state.version,
126
+ });
127
+ }
128
+ return { connection, keyCheck, hashes, streams };
129
+ });
130
+ if (opened.results)
131
+ return opened.results;
132
+ const { connection, keyCheck, hashes, streams } = opened;
133
+ const latch = { purged: false };
134
+ const view = openRegistryView(deps, connection, streams.length);
135
+ const sendWindow = deps.blobs.governor.window();
136
+ const commits = connectionCommits(deps, connectionId, latch);
137
+ const published = await publishEach(streams.map(({ stream }) => stream), latch, (stream) => publishStream(deps, connectionId, connection, stream, keyCheck, hashes, latch, view, options, commits)).finally(() => logSendGate(deps, connectionId, sendWindow));
138
+ // A deleted control row purges the whole connection. Every stream that
139
+ // started has a result, "purged" included: with streams running together,
140
+ // a stream after the purged one may already have published, and leaving it
141
+ // out would hide a real publication. A stream missing from the results never
142
+ // started.
143
+ return published;
144
+ }
145
+ /** A stream stopped because another stream's turn purged the connection. */
146
+ class ConnectionPurged extends Error {
147
+ constructor() {
148
+ super("publish: the connection was purged");
149
+ }
150
+ }
151
+ function stopIfPurged(latch) {
152
+ if (latch.purged)
153
+ throw new ConnectionPurged();
154
+ }
155
+ /**
156
+ * Run `publish` for every stream at once. Returns the results of the streams
157
+ * that ran, in stream order whatever order they finished in. Every stream is
158
+ * waited for, so nothing runs on after this returns; a stream that starts
159
+ * after the connection was purged or another stream failed stops at its next
160
+ * turn or upload. The failure of the earliest stream is thrown.
161
+ */
162
+ async function publishEach(streams, latch, publish) {
163
+ const results = streams.map(() => undefined);
164
+ const failures = new Map();
165
+ await Promise.all(streams.map(async (stream, at) => {
166
+ try {
167
+ results[at] = await publish(stream);
168
+ }
169
+ catch (error) {
170
+ failures.set(at, error);
171
+ }
172
+ }));
173
+ if (failures.size > 0)
174
+ throw failures.get(Math.min(...failures.keys()));
175
+ return results.filter((r) => r !== undefined);
176
+ }
177
+ /** One line per publish that sent requests: what the send governor did. */
178
+ function logSendGate(deps, connectionId, window) {
179
+ const stats = window?.end();
180
+ if (!stats || stats.requests === 0)
181
+ return;
182
+ deps.logger.info({
183
+ connectionId,
184
+ gateWindow: stats.window,
185
+ ...(stats.quotaPerSec === undefined
186
+ ? {}
187
+ : {
188
+ quotaPerSec: Object.fromEntries(Object.entries(stats.quotaPerSec).map(([kind, rate]) => [
189
+ kind,
190
+ Math.round(rate * 100) / 100,
191
+ ])),
192
+ }),
193
+ requests: stats.requests,
194
+ throttles: stats.throttles,
195
+ retryAfterWaitMs: Math.round(stats.retryAfterWaitMs),
196
+ peakBytesInFlight: stats.peakBytesInFlight,
197
+ }, "stream sync: publish send gate");
198
+ }
199
+ const keccak = async (data) => keccak_256(data);
200
+ /** metadataHash for a head: keccak over the UTF-8 JSON of the envelope facts. */
201
+ function metadataHashFor(scope, collectedAt, sizeBytes) {
202
+ return `0x${toHex(keccak_256(utf8(JSON.stringify({ scope, collectedAt, sizeBytes }))))}`;
203
+ }
204
+ const MAX_ATTEMPTS = 5;
205
+ /**
206
+ * Re-snapshots allowed after a candidate was discarded (a changed basis, or a
207
+ * spool that lost rows) before the work waits for the next cycle. A cycle
208
+ * builds at most MAX_INVALIDATIONS + 1 candidates for a stream. A write that
209
+ * only re-stamps rows is not a reason to discard: the transfer sends its copy.
210
+ */
211
+ const MAX_INVALIDATIONS = 3;
212
+ async function publishStream(deps, connectionId, connection, stream, keyCheck, hashes, latch, view, options, commits) {
213
+ const run = {
214
+ sawRefusal: false,
215
+ appliedVersion: null,
216
+ attempts: 0,
217
+ invalidations: 0,
218
+ watermark: null,
219
+ spool: null,
220
+ meter: newPublishMeter(),
221
+ };
222
+ const startedAt = deps.now();
223
+ let outcome = "failed";
224
+ try {
225
+ const result = await publishAttempts(deps, run, connectionId, connection, stream, keyCheck, hashes, latch, view, options, commits).catch((error) => {
226
+ if (error instanceof ConnectionPurged)
227
+ return { stream, outcome: "purged", watermark: run.watermark };
228
+ // Storage kept refusing past the retry budget. Nothing is wrong with
229
+ // the data: the stream stays in the durable queue (its watermark is not
230
+ // advanced) and the next cycle sends it again.
231
+ if (error instanceof StorageDeferredError) {
232
+ deps.logger.info({ connectionId, stream, error: error.message }, "stream sync: storage unavailable, publish left in the queue");
233
+ return { stream, outcome: "backoff", watermark: run.watermark };
234
+ }
235
+ throw error;
236
+ });
237
+ outcome = result.outcome;
238
+ return result;
239
+ }
240
+ finally {
241
+ // Commit, discard and failure all end here.
242
+ await endSpool(deps, run);
243
+ logPublishTimings(deps, connectionId, stream, outcome, run.meter, startedAt);
244
+ }
245
+ }
246
+ /**
247
+ * One info line per stream publish that did work, so a journey reads where the
248
+ * time went. A stream with nothing to do (a quiet poll) logs nothing: it would
249
+ * add a line per stream every cycle.
250
+ */
251
+ function logPublishTimings(deps, connectionId, stream, outcome, meter, startedAt) {
252
+ const idle = (outcome === "noop" || outcome === "deferred") &&
253
+ meter.blobGets === 0 &&
254
+ meter.blobPuts === 0;
255
+ if (idle)
256
+ return;
257
+ deps.logger.info({
258
+ connectionId,
259
+ stream,
260
+ outcome,
261
+ ...publishTimings(meter, deps.now() - startedAt),
262
+ }, "stream sync: stream publish timings");
263
+ }
264
+ /**
265
+ * Drop the spool rows of the attempt in `run`, if it spooled any. A failed
266
+ * drop leaves rows that the next start deletes; it must not hide the
267
+ * attempt's result.
268
+ */
269
+ async function endSpool(deps, run) {
270
+ const { spool } = run;
271
+ if (spool === null)
272
+ return;
273
+ run.spool = null;
274
+ await dropSpool(deps, spool.attempt, spool.prefixes).catch((error) => deps.logger.warn({ error: String(error) }, "publish: spool rows not dropped"));
275
+ }
276
+ async function publishAttempts(deps, run, connectionId, connection, stream, keyCheck, hashes, latch, view, options, commits) {
277
+ const context = {
278
+ connectionId,
279
+ connection,
280
+ stream,
281
+ scope: streamScope(connection.connector, connection.ns, stream),
282
+ keyCheck,
283
+ hashes,
284
+ latch,
285
+ view,
286
+ options,
287
+ commits,
288
+ };
289
+ // Another stream may have purged the connection while this one waited for
290
+ // the turn or was transferring: the turn does nothing then.
291
+ const slot = (work) => deps.queue.run(connectionId, "publish", () => {
292
+ stopIfPurged(latch);
293
+ return work(insideQueue(deps, connectionId));
294
+ });
295
+ while (run.attempts < MAX_ATTEMPTS) {
296
+ stopIfPurged(latch);
297
+ if (run.invalidations > MAX_INVALIDATIONS) {
298
+ // Local state kept moving under every candidate. Nothing was published
299
+ // and nothing was acknowledged: the work is still pending next cycle.
300
+ return { stream, outcome: "backoff", watermark: run.watermark };
301
+ }
302
+ // The last attempt's copy is of no use now: it was discarded or ended.
303
+ await endSpool(deps, run);
304
+ // The snapshot starts the transfer itself, as soon as it has planned and
305
+ // before it has copied a row (see `TransferLauncher`).
306
+ const started = {};
307
+ const launch = (plan, feed) => {
308
+ const transfer = timed(deps, (ms) => (run.meter.transferMs += ms), () => transferPlan(deps, context, plan, feed, run.meter));
309
+ // Its outcome is read after the snapshot; until then it is not unhandled.
310
+ transfer.catch(() => undefined);
311
+ started.transfer = transfer;
312
+ };
313
+ let snapshot;
314
+ try {
315
+ snapshot = await timed(deps, (ms) => (run.meter.planMs += ms), () => slot((held) => snapshotStream(held, context, run, launch)));
316
+ }
317
+ catch (error) {
318
+ // The snapshot failed the feed it opened, so the transfer ends; nothing
319
+ // of it runs on after this attempt.
320
+ await started.transfer?.catch(() => undefined);
321
+ throw error;
322
+ }
323
+ if (snapshot.kind === "done")
324
+ return snapshot.result;
325
+ if (snapshot.kind === "retry")
326
+ continue;
327
+ if (snapshot.kind === "idle" || snapshot.kind === "blobs") {
328
+ let idle;
329
+ if (snapshot.kind === "idle") {
330
+ idle = snapshot.idle;
331
+ }
332
+ else {
333
+ await uploadBlobs(deps, snapshot.blobs, run.meter, () => stopIfPurged(latch));
334
+ // The attachments took time outside the slot: the stream row (the
335
+ // planned one, absent included) and the control row are confirmed
336
+ // again before the stream is called done.
337
+ const { evidence, planned, result } = snapshot;
338
+ idle = {
339
+ result,
340
+ evidence,
341
+ hint: planned,
342
+ controlDataHash: snapshot.controlDataHash,
343
+ };
344
+ }
345
+ const ended = await finishIdle(slot, context, run, idle);
346
+ if (ended.kind === "retry") {
347
+ // The stream row moved after the plan read it (while the attachments
348
+ // went up, or after the listing the hint came from): the plan that
349
+ // found nothing to publish is not the registry's any more.
350
+ view.invalidate();
351
+ run.invalidations++;
352
+ continue;
353
+ }
354
+ if (ended.kind === "done")
355
+ return ended.result;
356
+ continue;
357
+ }
358
+ const { candidate } = snapshot;
359
+ stopIfPurged(latch);
360
+ let prepared;
361
+ try {
362
+ // The snapshot's slot turn has ended, so every row is frozen. The
363
+ // transfer returns once every part, attachment and the head is stored.
364
+ prepared = await started.transfer;
365
+ }
366
+ catch (error) {
367
+ if (error instanceof ConnectionPurged)
368
+ throw error;
369
+ // A transfer that lost its input because local state moved (a purge
370
+ // took the spooled rows or an attachment) is a stale candidate, not a
371
+ // failure.
372
+ if (error instanceof FrozenRowsChanged) {
373
+ run.invalidations++;
374
+ continue;
375
+ }
376
+ if ((await readBasis(deps, context, candidate)) === candidate.basis)
377
+ throw error;
378
+ run.invalidations++;
379
+ continue;
380
+ }
381
+ const committed = await commitStream(slot, context, candidate, prepared, run);
382
+ if (committed.kind === "done")
383
+ return committed.result;
384
+ if (committed.kind === "invalidated")
385
+ run.invalidations++;
386
+ }
387
+ return { stream, outcome: "backoff", watermark: run.watermark };
388
+ }
389
+ /**
390
+ * SNAPSHOT, in the slot. Steps 1-3 of the file comment, then everything the
391
+ * transfer needs, read once. Returns a result when the stream ends here.
392
+ */
393
+ async function snapshotStream(deps, context, run, launch) {
394
+ const { connectionId, connection, stream, scope, keyCheck, hashes } = context;
395
+ const control = controlScope(connection.connector, connection.ns);
396
+ const done = (result) => ({ kind: "done", result });
397
+ // An apply changes local state from the registry: a listing taken before it
398
+ // is not a starting point for any stream's first snapshot after it.
399
+ const applyRegistry = async () => {
400
+ context.view.invalidate();
401
+ await applyConnection(deps, connectionId);
402
+ };
403
+ // A deferral writes nothing and retries next cycle. The log line is the only
404
+ // way to tell a stream that waits from one that is stuck for good.
405
+ const deferred = (reason) => {
406
+ deps.logger.warn({ connectionId, stream, reason }, "stream sync: publish deferred");
407
+ return done({ stream, outcome: "deferred", watermark: run.watermark });
408
+ };
409
+ // Step 1: snapshot W and the changes since the last publish.
410
+ let [local] = await deps.db.query(`SELECT primary_key, profile_key, profile_version, complete,
411
+ floor_version, floor_o, floor_r, last_delete_version,
412
+ head_version, head_generation, head_data_hash, publish_watermark
413
+ FROM stream_state WHERE connection_id = ? AND stream = ?`, [connectionId, stream]);
414
+ if (!local) {
415
+ throw new Error(`publish: missing local stream state for ${stream}`);
416
+ }
417
+ const [wRow] = await deps.db.query(`SELECT MAX(seq) AS w FROM record_changes WHERE connection_id = ? AND stream = ?`, [connectionId, stream]);
418
+ const watermark = wRow?.w ?? local.publish_watermark;
419
+ run.watermark = watermark;
420
+ const changes = await deps.db.query(`SELECT pk_hash FROM record_changes
421
+ WHERE connection_id = ? AND stream = ?
422
+ AND seq > ? AND seq <= ?
423
+ AND origin IN ('local', 'import', 'refresh')
424
+ AND NOT EXISTS (SELECT 1 FROM runs r JOIN run_streams rs ON rs.run_id=r.run_id
425
+ WHERE r.connection_id=record_changes.connection_id AND rs.stream=record_changes.stream
426
+ AND r.run_id=record_changes.stamp_r AND r.o=record_changes.stamp_o
427
+ AND rs.decision IN ('refused','discarded'))`, [connectionId, stream, local.publish_watermark, watermark]);
428
+ // Step 2: registry. A deleted control row purges and stops; a foreign
429
+ // control row, or one whose generation moved, defers the stream.
430
+ // The hints of this stream's first snapshot; a snapshot that repeats reads
431
+ // the registry. A control hint is only an active row of this generation:
432
+ // absent would create the row and deleted would purge, so those are read.
433
+ const hints = await context.view.firstSnapshot(scope);
434
+ const hintedState = hints.control && classifyControl(hints.control, hashes);
435
+ const hintedControl = hintedState?.kind === "active" &&
436
+ hintedState.generation === connection.generation;
437
+ let controlRead = hintedControl
438
+ ? hints.control
439
+ : await deps.registry.read(control);
440
+ let controlState = classifyControl(controlRead, hashes);
441
+ if (controlState.kind === "absent") {
442
+ if (connection.generation !== 1)
443
+ return deferred("control_absent_after_first_generation");
444
+ const signature = await deps.signer.signAddData({
445
+ ownerAddress: deps.ownerAddress,
446
+ scope: control,
447
+ dataHash: hashes.activeData,
448
+ metadataHash: hashes.activeMetadata,
449
+ expectedVersion: 1n,
450
+ });
451
+ await deps.registry.post({
452
+ ownerAddress: deps.ownerAddress,
453
+ scope: control,
454
+ dataHash: hashes.activeData,
455
+ metadataHash: hashes.activeMetadata,
456
+ expectedVersion: "1",
457
+ signature,
458
+ });
459
+ controlRead = await deps.registry.read(control);
460
+ controlState = classifyControl(controlRead, hashes);
461
+ }
462
+ if (controlState.kind === "deleted") {
463
+ await purgeConnection(deps, connectionId, {
464
+ controlVersion: controlState.version,
465
+ });
466
+ context.latch.purged = true;
467
+ return done({ stream, outcome: "purged", watermark });
468
+ }
469
+ if (controlState.kind === "foreign" || controlState.kind === "absent") {
470
+ return deferred("control_unavailable");
471
+ }
472
+ if (controlState.generation !== connection.generation) {
473
+ await applyRegistry();
474
+ return deferred("control_generation_moved");
475
+ }
476
+ // A run that began before this control generation never joins it: it is
477
+ // discarded here, before the binding below could give it the generation.
478
+ if (await discardForeignLifetimeRuns(deps, connectionId, controlState.generation)) {
479
+ await applyRegistry();
480
+ return { kind: "retry" };
481
+ }
482
+ await deps.db.batch([
483
+ {
484
+ sql: "UPDATE connections SET control_state='active',control_version=? WHERE connection_id=?",
485
+ params: [controlState.generation, connectionId],
486
+ },
487
+ // C.0: an offline fresh run binds when the registry first answers. Only a
488
+ // run that has ended and passed the lifetime check above: a run still
489
+ // collecting keeps its lifetime (none) until it ends, so a collector that
490
+ // began before another writer moved the lifetime is never handed the new
491
+ // one. End then discards it if the lifetime moved past 1.
492
+ {
493
+ sql: "UPDATE runs SET generation=? WHERE connection_id=? AND generation IS NULL AND state='ended'",
494
+ params: [controlState.generation, connectionId],
495
+ },
496
+ ]);
497
+ // A stream row from the listing is a hint (see `hintedRow` below); a repeat
498
+ // snapshot reads it.
499
+ const hintedRow = hints.stream !== undefined;
500
+ const streamRead = hints.stream ?? (await deps.registry.read(scope));
501
+ const streamRow = classifyStreamRow(streamRead, hashes);
502
+ // Anything a snapshot does besides building a candidate (the commit has its
503
+ // own live checks and a CAS) acts on the registry as it is now, whether or
504
+ // not this turn's reads were hints: the stream row, THEN the control row.
505
+ // That order matters: a stream row outlives the deletion of its connection
506
+ // until cleanup, so a row read alone proves nothing, and the control read
507
+ // made at the top of this turn can predate a deletion the row read then
508
+ // misses (the first stream, a publish of fewer than MIN_STREAMS_FOR_LISTING
509
+ // streams, no listing adapter and a failed listing all read the row live
510
+ // and unhinted). So the control row is always read here, after the row. A
511
+ // row that was a hint is read again and must still be the hinted one;
512
+ // otherwise this turn's own row read already came before the control read.
513
+ // A deleted control row purges; one that moved defers; a hinted row that
514
+ // moved repeats the snapshot, which reads live (a hint serves a first
515
+ // snapshot only).
516
+ const confirmLive = async () => {
517
+ if (hintedRow && !sameRow(await deps.registry.read(scope), streamRead))
518
+ return { kind: "retry" };
519
+ const checked = await checkControl(deps, context);
520
+ return checked ? done({ stream, outcome: checked, watermark }) : null;
521
+ };
522
+ // `registryHead` is the content base: the verified head of THIS lifetime.
523
+ // `registryVersion` and `registryDataHash` are the compare-and-set basis and
524
+ // describe the registry row whatever lifetime its head is from.
525
+ let registryHead = null;
526
+ let registryVersion = 0;
527
+ let registryDataHash = null;
528
+ if (streamRead.found) {
529
+ registryVersion = streamRead.version;
530
+ registryDataHash = streamRead.dataHash;
531
+ }
532
+ if (streamRow === "present" && streamRead.found) {
533
+ const verified = await readRegistryHead(deps, scope, streamRead.dataHash, connection, stream, keyCheck);
534
+ // A head of a later lifetime than this connection knows: it is not ours
535
+ // to replace. Wait for this connection to catch up.
536
+ if (verified.generation > connection.generation)
537
+ return deferred("stream_head_from_later_generation");
538
+ if (verified.generation === connection.generation) {
539
+ registryHead = verified;
540
+ }
541
+ else {
542
+ // No content base. Keep the delete fence of that lifetime: record it
543
+ // locally (see lifetime-boundary.ts) and carry it into the new head.
544
+ const fence = olderLifetimeFence(scope, streamRead, verified, connection.generation);
545
+ const provenEarlier = endsEarlierLifetime(scope, streamRead, connection.generation);
546
+ await hydrateLifetimeBoundary(deps, {
547
+ connectionId,
548
+ stream,
549
+ generation: connection.generation,
550
+ fence,
551
+ provenEarlier,
552
+ primaryKey: verified.primaryKey,
553
+ });
554
+ // No proof this delete ended an earlier lifetime: it may be the delete
555
+ // of this one, awaiting its control tombstone. Do not write over it.
556
+ if (!provenEarlier)
557
+ return deferred("stream_delete_not_proven_earlier");
558
+ local = {
559
+ ...local,
560
+ last_delete_version: Math.max(local.last_delete_version, fence),
561
+ };
562
+ }
563
+ }
564
+ // A registry row newer than the local head is applied (same slot turn)
565
+ // and the stream restarts at step 1. Apply once per version: if the head
566
+ // still lags after apply, proceed with the registry head.
567
+ if (streamRead.found && registryVersion > local.head_version) {
568
+ if (run.appliedVersion !== registryVersion) {
569
+ await applyRegistry();
570
+ run.appliedVersion = registryVersion;
571
+ return { kind: "retry" };
572
+ }
573
+ }
574
+ if (await discardFencedRuns(deps, connectionId, stream)) {
575
+ await applyRegistry();
576
+ return { kind: "retry" };
577
+ }
578
+ if (connection.generation !== 1)
579
+ await excludeSeedsIfAny(deps, connectionId, stream);
580
+ // Step 3: re-plan the retained ended runs against the registry head.
581
+ const plan = await planStream(deps, connectionId, connection, stream, local, registryHead, registryVersion,
582
+ // No content base: a replacing run replaces nothing, as with an absent row.
583
+ registryHead ? registryDataHash : null);
584
+ if (plan.deferred)
585
+ return deferred("run_order_not_settled");
586
+ if (plan.refused) {
587
+ const stale = await confirmLive();
588
+ if (stale)
589
+ return stale;
590
+ run.sawRefusal = true;
591
+ await unwriteRefusedRun(deps, {
592
+ connectionId,
593
+ stream,
594
+ runId: plan.refused.runId,
595
+ reason: plan.refused.reason,
596
+ });
597
+ await applyRegistry();
598
+ return { kind: "retry" };
599
+ }
600
+ const headGeneration = plan.finalHead?.generation ?? connection.generation;
601
+ const blobs = await listStreamBlobs(deps, {
602
+ connectionId,
603
+ stream,
604
+ scope,
605
+ generation: headGeneration,
606
+ });
607
+ // A full refresh drops what the source no longer lists. The replace is
608
+ // work only where some local row was last observed before the replacing
609
+ // run: a row a run saw again, even unchanged, stays as it is and costs no
610
+ // upload. Read as one entry per 16-bit key prefix, so memory does not grow
611
+ // with the number of rows dropped, and as a seek on the observation index,
612
+ // so a refresh that dropped nothing does not read the stream.
613
+ const replaced = registryHead && plan.replaceBelow
614
+ ? await replacedPrefixGroups(deps.db, connectionId, stream, plan.replaceBelow)
615
+ : [];
616
+ // Heads of an older frame generation are rewritten whole. A head that only
617
+ // lacks a newer field keeps its parts: its next publish writes the field.
618
+ const framesStale = Boolean(registryHead &&
619
+ framesCarryFirstSeen(registryHead.format) !==
620
+ framesCarryFirstSeen(HEAD_FORMAT));
621
+ const hasWork = registryHead
622
+ ? changes.length > 0 ||
623
+ replaced.length > 0 ||
624
+ framesStale ||
625
+ (plan.steps.some((step) => step.decision.kind === "publish") &&
626
+ !(plan.finalHead &&
627
+ sameHead(plan.finalHead, {
628
+ generation: registryHead.generation,
629
+ primaryKey: registryHead.primaryKey,
630
+ profile: registryHead.profile,
631
+ complete: registryHead.complete,
632
+ })))
633
+ : plan.replaceBelow !== undefined ||
634
+ changes.length > 0 ||
635
+ plan.steps.some((step) => step.decision.kind === "publish");
636
+ if (!hasWork) {
637
+ // On the batch path a snapshot that rests on hints and has nothing to
638
+ // upload confirms them as conditions of its commit request (the gateway
639
+ // judges its stream row and the control row in the request's
640
+ // transaction), not as two live reads. A stream row that was not found
641
+ // cannot be a condition: it reads live.
642
+ const asCondition = (hintedRow || hintedControl) &&
643
+ blobs.length === 0 &&
644
+ !context.commits.unsupported &&
645
+ (!hintedRow || streamRead.found);
646
+ if (!asCondition) {
647
+ const stale = await confirmLive();
648
+ if (stale)
649
+ return stale;
650
+ }
651
+ const controlDataHash = (controlRead.found ? controlRead.dataHash : hashes.activeData);
652
+ const result = {
653
+ stream,
654
+ outcome: run.sawRefusal ? "refused" : "noop",
655
+ watermark,
656
+ };
657
+ // No change to publish: the registry head, read in this slot turn, already
658
+ // holds what the plan produces, so a pending run it covers is saved by it.
659
+ const evidence = registryHead && registryDataHash !== null
660
+ ? {
661
+ version: registryVersion,
662
+ generation: registryHead.generation,
663
+ dataHash: registryDataHash,
664
+ watermark: local.publish_watermark,
665
+ replaceBelow: undefined,
666
+ runIds: plan.steps.map((step) => step.runId),
667
+ }
668
+ : null;
669
+ if (blobs.length > 0) {
670
+ return {
671
+ kind: "blobs",
672
+ blobs,
673
+ result,
674
+ evidence,
675
+ planned: streamRead,
676
+ controlDataHash,
677
+ };
678
+ }
679
+ if (asCondition) {
680
+ return {
681
+ kind: "idle",
682
+ idle: {
683
+ result,
684
+ evidence,
685
+ hint: hintedRow ? streamRead : null,
686
+ controlDataHash,
687
+ },
688
+ };
689
+ }
690
+ if (evidence)
691
+ await saveRunEvidence(deps, connectionId, stream, evidence);
692
+ return done(result);
693
+ }
694
+ // Seeds publish only into generation 1; otherwise they are purged
695
+ // and the ledger records excluded(seed_skipped).
696
+ if (headGeneration !== 1) {
697
+ await excludeSeedsIfAny(deps, connectionId, stream);
698
+ }
699
+ // Step 4 input: the changed prefixes, planned by the spec's bucket planner
700
+ // so parts are sized by the byte target (see part-layout.ts).
701
+ const rewriteAll = framesStale;
702
+ // A host with a frozen read view needs no copy: the rows are read from
703
+ // `records` in a view opened now, in this slot turn, so it holds exactly the
704
+ // state this turn has read. The transfer releases it.
705
+ let snapshot;
706
+ let changedPrefixes;
707
+ try {
708
+ // A driver that cannot give a view now (not WAL) keeps the copy.
709
+ const view = await deps.db.snapshot?.().catch((error) => {
710
+ deps.logger.warn({ connectionId, stream, error: String(error) }, "publish_snapshot_unavailable");
711
+ return undefined;
712
+ });
713
+ if (view) {
714
+ snapshot = {
715
+ frozen: {
716
+ view,
717
+ connectionId,
718
+ stream,
719
+ replaceBelow: plan.replaceBelow,
720
+ },
721
+ // Once only: the transfer and the plan's `finally` both release it.
722
+ release: (() => {
723
+ let released;
724
+ return () => (released ??= view.release());
725
+ })(),
726
+ };
727
+ // Records change only inside a slot turn, and this one has the slot, so
728
+ // the view holds what step 1 read. Check it: a view that disagrees with
729
+ // the snapshot's W must not be published.
730
+ const [seen] = await view.query(`SELECT MAX(seq) AS w FROM record_changes WHERE connection_id = ? AND stream = ?`, [connectionId, stream]);
731
+ if ((seen?.w ?? local.publish_watermark) !== watermark) {
732
+ await snapshot.release();
733
+ return { kind: "retry" };
734
+ }
735
+ changedPrefixes = await planChangedPrefixes(view, {
736
+ connectionId,
737
+ stream,
738
+ changedKeys: changes.map((change) => change.pk_hash),
739
+ replaced,
740
+ baseParts: registryHead?.parts ?? [],
741
+ targetBytes: partTargetOf(deps),
742
+ rewriteAll,
743
+ });
744
+ }
745
+ else {
746
+ changedPrefixes = await planChangedPrefixes(deps.db, {
747
+ connectionId,
748
+ stream,
749
+ changedKeys: changes.map((change) => change.pk_hash),
750
+ replaced,
751
+ baseParts: registryHead?.parts ?? [],
752
+ targetBytes: partTargetOf(deps),
753
+ rewriteAll,
754
+ });
755
+ }
756
+ // Read the caller's head extras and the clock now: the transfer reads
757
+ // neither again.
758
+ await context.options?.headExtras?.(stream);
759
+ }
760
+ catch (error) {
761
+ await snapshot?.release().catch(() => undefined);
762
+ throw error;
763
+ }
764
+ const attempt = newSpoolAttempt();
765
+ // Recorded before the freeze, so a freeze that fails part-way is still dropped.
766
+ if (changedPrefixes.length > 0 && !snapshot)
767
+ run.spool = { attempt, prefixes: changedPrefixes };
768
+ const observedAt = plan.newestRunObservedAt ?? registryHead?.observedAt ?? deps.now();
769
+ const head = {
770
+ complete: plan.finalHead?.complete ?? registryHead?.complete ?? false,
771
+ connector: connection.connector,
772
+ format: HEAD_FORMAT,
773
+ generation: headGeneration,
774
+ keyCheck,
775
+ lastDeleteVersion: Math.max(
776
+ // Includes an earlier lifetime's fence, hydrated above.
777
+ local.last_delete_version, streamRow === "tombstoned" ? registryVersion : 0),
778
+ ns: connection.ns,
779
+ observedAt,
780
+ primaryKey: plan.finalHead?.primaryKey ??
781
+ registryHead?.primaryKey ??
782
+ JSON.parse(local.primary_key),
783
+ profile: plan.finalHead?.profile ??
784
+ registryHead?.profile ?? {
785
+ key: local.profile_key ?? connection.connector,
786
+ version: local.profile_version ?? local.floor_version ?? "0",
787
+ },
788
+ // When the source last dropped what it no longer lists: the replacing
789
+ // run's time, else the registry head's, so a later partial run in this
790
+ // head does not widen it (see omissionCutoff). A known cutoff is never
791
+ // lowered: a device whose clock is behind the registry head's publishes
792
+ // an earlier observedAt, and the omission is no earlier for that. The two
793
+ // times are independent; observedAt stays the time of the newest run.
794
+ replacedAt: Math.max(plan.replaceBelow?.o ?? 0, registryHead ? omissionCutoff(registryHead) : 0),
795
+ stream,
796
+ };
797
+ // The transfer starts here. Everything it needs but the rows is known.
798
+ const feed = newFrozenFeed();
799
+ const plannedTransfer = {
800
+ registryVersion,
801
+ registryDataHash,
802
+ baseParts: registryHead?.parts ?? [],
803
+ changedPrefixes,
804
+ attempt,
805
+ snapshot,
806
+ blobs,
807
+ headGeneration,
808
+ head,
809
+ };
810
+ const runIds = plan.steps.map((step) => step.runId);
811
+ const readThisBasis = () => readBasis(deps, context, {
812
+ watermark,
813
+ localWatermark: local.publish_watermark,
814
+ runIds,
815
+ });
816
+ let basis;
817
+ if (snapshot) {
818
+ // Nothing to copy, so nothing to overlap: the turn ends after the basis,
819
+ // and the transfer reads the frozen view from then on. A view that is
820
+ // not handed over is released here.
821
+ try {
822
+ basis = await readThisBasis();
823
+ }
824
+ catch (error) {
825
+ await snapshot.release().catch(() => undefined);
826
+ throw error;
827
+ }
828
+ launch(plannedTransfer, feed);
829
+ for (const prefix of changedPrefixes)
830
+ feed.push({ prefix, rows: null });
831
+ feed.end();
832
+ }
833
+ else {
834
+ // The rows reach the transfer prefix by prefix as they are copied, still
835
+ // inside this slot turn (see `freezePrefixRows` for why that is one
836
+ // consistent state).
837
+ launch(plannedTransfer, feed);
838
+ try {
839
+ await freezePrefixRows(deps, {
840
+ connectionId,
841
+ stream,
842
+ attempt,
843
+ changedPrefixes,
844
+ replaceBelow: plan.replaceBelow,
845
+ onFrozen: (frozen) => feed.push(frozen),
846
+ stopped: () => feed.abandoned(),
847
+ });
848
+ basis = await readThisBasis();
849
+ feed.end();
850
+ }
851
+ catch (error) {
852
+ feed.fail(error);
853
+ throw error;
854
+ }
855
+ }
856
+ return {
857
+ kind: "candidate",
858
+ candidate: {
859
+ basis,
860
+ watermark,
861
+ localWatermark: local.publish_watermark,
862
+ registryVersion,
863
+ registryDataHash,
864
+ controlDataHash: (controlRead.found
865
+ ? controlRead.dataHash
866
+ : hashes.activeData),
867
+ baseParts: registryHead?.parts ?? [],
868
+ changedPrefixes,
869
+ attempt,
870
+ blobs,
871
+ headGeneration,
872
+ head,
873
+ replaceBelow: plan.replaceBelow,
874
+ runIds,
875
+ sawRefusal: run.sawRefusal,
876
+ },
877
+ };
878
+ }
879
+ /**
880
+ * TRANSFER, outside the slot. Attachments, parts and the head, each a
881
+ * content-addressed object. It reads the attempt's spooled rows (page by page)
882
+ * and attachment bytes by exact id, so it cannot encode rows the snapshot did
883
+ * not freeze, and no write to `records` can invalidate it. A spool that lost
884
+ * rows throws FrozenRowsChanged.
885
+ *
886
+ * It starts while the snapshot is still copying rows: `feed` announces each
887
+ * prefix once it is copied, and the transfer encodes and uploads it then. It
888
+ * returns only after the feed has ended (every prefix copied and the snapshot's
889
+ * basis read) and every upload is stored, so the commit (the registry write)
890
+ * never runs before the stream's last file is in storage, nor before the
891
+ * snapshot is whole.
892
+ *
893
+ * The uploads are not ordered among themselves: nothing points at any of them
894
+ * until the registry CAS, and the head names its parts by hash, which are
895
+ * known once they are encoded. Each upload starts when it is ready. The
896
+ * storage client's limits decide how many go on the wire at once.
897
+ */
898
+ async function transferPlan(deps, context, plan, feed, meter) {
899
+ const wave = newUploadWave();
900
+ try {
901
+ const prepared = await transferOnWave(deps, context, plan, feed, meter, wave);
902
+ await wave.drain();
903
+ return prepared;
904
+ }
905
+ catch (error) {
906
+ // Nothing of this transfer runs on after it returns, nor reports unseen.
907
+ await wave.settle();
908
+ throw error;
909
+ }
910
+ finally {
911
+ // A snapshot still copying has no reader left: it stops.
912
+ feed.abandon();
913
+ // The frozen view ends here on every way out (it ends earlier on success).
914
+ await plan.snapshot?.release().catch(() => undefined);
915
+ }
916
+ }
917
+ async function transferOnWave(deps, context, plan, feed, meter, wave) {
918
+ const { scope, latch } = context;
919
+ // A stream with no registry row has nothing in storage to find: a probe
920
+ // could only answer "no". An upload of a stored name keeps or replaces the
921
+ // object with another encryption of the same clear bytes, so skipping a
922
+ // probe can repeat an upload and never drop one. Where a row exists (a
923
+ // resume, a refresh) files may well be stored, and a probe saves the upload.
924
+ // The rule is "no registry row", never "this device uploaded it before":
925
+ // storage can delete or overwrite objects.
926
+ const probe = plan.registryVersion > 0;
927
+ if (plan.blobs.length > 0) {
928
+ wave.start(() => uploadBlobs(deps, plan.blobs, meter, () => stopIfPurged(latch), probe));
929
+ }
930
+ const encoded = await startFrozenParts(deps, {
931
+ attempt: plan.attempt,
932
+ view: plan.snapshot?.frozen,
933
+ scope,
934
+ generation: plan.headGeneration,
935
+ frozen: feed,
936
+ wave,
937
+ probe,
938
+ meter,
939
+ // A purge by another stream ends this transfer before its next upload.
940
+ beforeUpload: () => stopIfPurged(latch),
941
+ });
942
+ // Every row is read: the view's read transaction ends now, not when the
943
+ // uploads end, so it holds the log back no longer than the reads need it.
944
+ await plan.snapshot?.release();
945
+ const parts = mergedParts(plan.baseParts, encoded, plan.changedPrefixes);
946
+ const recordCount = parts.reduce((sum, part) => sum + part.count, 0);
947
+ const blobs = meteredBlobs(deps, meter);
948
+ // The head is built, verified and encrypted in memory and stays there until
949
+ // its upload settles. It is held as one part's worth, like a part, from
950
+ // before it is built, so heads of many streams cannot pile up under a slow
951
+ // store. The upload task owns the reservation once it starts.
952
+ const release = await holdMemory(blobs, partTargetOf(deps));
953
+ let handedOver = false;
954
+ try {
955
+ const headBytes = encodeHead({ ...plan.head, parts, recordCount });
956
+ const { dataHash, blobName } = await digestHead(keccak, headBytes);
957
+ // The same data hash as the registry head: nothing to upload or post.
958
+ if (plan.registryDataHash !== null &&
959
+ dataHash.toLowerCase() === plan.registryDataHash.toLowerCase()) {
960
+ return {
961
+ parts,
962
+ recordCount,
963
+ dataHash,
964
+ blobName,
965
+ encryptedLength: null,
966
+ verifiedHead: null,
967
+ };
968
+ }
969
+ // The reader's own check, on the bytes about to be uploaded: a head that
970
+ // would not verify is never uploaded, posted or remembered.
971
+ const verified = await verifyHead(keccak, headBytes, {
972
+ dataHash,
973
+ connector: context.connection.connector,
974
+ ns: context.connection.ns,
975
+ stream: context.stream,
976
+ keyCheck: context.keyCheck,
977
+ });
978
+ if (verified.kind !== "ok") {
979
+ throw new Error(`publish: the head built for ${context.stream} failed verification: ${verified.kind}`);
980
+ }
981
+ const encrypted = await deps.keys.encrypt(scope, headBytes);
982
+ stopIfPurged(latch);
983
+ // Started with the parts still going: the head names them by hash.
984
+ wave.start(async () => {
985
+ try {
986
+ if (!probe || !(await blobs.exists(`${scope}/${blobName}`))) {
987
+ // A sibling may have purged the connection while the probe was out.
988
+ stopIfPurged(latch);
989
+ await blobs.put(`${scope}/${blobName}`, encrypted, () => stopIfPurged(latch));
990
+ }
991
+ }
992
+ finally {
993
+ release();
994
+ }
995
+ });
996
+ handedOver = true;
997
+ return {
998
+ parts,
999
+ recordCount,
1000
+ dataHash,
1001
+ blobName,
1002
+ encryptedLength: encrypted.length,
1003
+ verifiedHead: verified.head,
1004
+ };
1005
+ }
1006
+ finally {
1007
+ if (!handedOver)
1008
+ release();
1009
+ }
1010
+ }
1011
+ /** Write run evidence on its own: the no-work path has no head to commit. */
1012
+ async function saveRunEvidence(deps, connectionId, stream, evidence) {
1013
+ const statements = await runPublicationStatements(deps, connectionId, stream, evidence);
1014
+ if (statements.length > 0)
1015
+ await deps.db.batch(statements);
1016
+ }
1017
+ /** Whether two reads of a stream's row are the same row version and content. */
1018
+ function sameRow(a, b) {
1019
+ if (!a.found || !b.found)
1020
+ return a.found === b.found;
1021
+ return (a.version === b.version &&
1022
+ a.dataHash.toLowerCase() === b.dataHash.toLowerCase());
1023
+ }
1024
+ /**
1025
+ * COMMIT, in the slot. The candidate stands only if what readBasis compares
1026
+ * is unchanged and the registry row is the one it was built over; the
1027
+ * registry CAS stays the remote fence.
1028
+ */
1029
+ async function commitCandidate(deps, context, candidate, prepared, run) {
1030
+ const { connectionId, stream, scope } = context;
1031
+ const { watermark } = candidate;
1032
+ const done = (result) => ({ kind: "done", result });
1033
+ // Local state: what readBasis compares (control, stream state, head parts,
1034
+ // delete intents, selected runs, the covered change log, removals and
1035
+ // foreign writes above W) is the snapshot's. Later begins change none.
1036
+ if ((await readBasis(deps, context, candidate)) !== candidate.basis) {
1037
+ return { kind: "invalidated" };
1038
+ }
1039
+ // The registry row is not re-read here. A CAS follows (below) and is the
1040
+ // fence: a stale expectedVersion answers 409, the winner is applied, the
1041
+ // stream re-plans and is never marked published. The no-op path sends no
1042
+ // CAS and re-reads the row itself.
1043
+ const { dataHash: headHash } = prepared;
1044
+ // Step 5: if the new head's data hash equals the registry head's, skip the
1045
+ // CAS and record the local state (watermark advances, the head is already
1046
+ // published).
1047
+ if (prepared.encryptedLength === null) {
1048
+ // No CAS follows, so this read is the only fence: the registry row is
1049
+ // still the one the candidate was built over.
1050
+ const read = await deps.registry.read(scope);
1051
+ const version = read.found ? read.version : 0;
1052
+ const dataHash = read.found ? read.dataHash.toLowerCase() : null;
1053
+ if (version !== candidate.registryVersion ||
1054
+ dataHash !== (candidate.registryDataHash?.toLowerCase() ?? null)) {
1055
+ return { kind: "invalidated" };
1056
+ }
1057
+ const checked = await checkControl(deps, context);
1058
+ if (checked)
1059
+ return done({ stream, outcome: checked, watermark });
1060
+ return finishNoop(deps, context, candidate, prepared);
1061
+ }
1062
+ const addRegisterMs = (ms) => (run.meter.headRegisterMs += ms);
1063
+ const { newVersion, metadataHash, signature } = await timed(deps, addRegisterMs, () => signHead(deps, context, candidate, prepared.encryptedLength, prepared));
1064
+ const beforePost = await checkControl(deps, context);
1065
+ if (beforePost)
1066
+ return done({ stream, outcome: beforePost, watermark });
1067
+ run.attempts++;
1068
+ const posted = await timed(deps, addRegisterMs, () => deps.registry.post({
1069
+ ownerAddress: deps.ownerAddress,
1070
+ scope,
1071
+ dataHash: headHash,
1072
+ metadataHash,
1073
+ expectedVersion: String(newVersion),
1074
+ signature,
1075
+ }));
1076
+ if (posted.kind === "conflict") {
1077
+ // Another writer moved this row, so a listing read before that is no
1078
+ // starting point for any stream not yet started, including after the
1079
+ // last try, which ends this stream without a retry.
1080
+ context.view.invalidate();
1081
+ // Apply the winner and re-plan. On the last try, back off without
1082
+ // applying again: the winner will be applied on the next cycle.
1083
+ if (run.attempts === MAX_ATTEMPTS) {
1084
+ return done({ stream, outcome: "backoff", watermark });
1085
+ }
1086
+ await applyConnection(deps, connectionId);
1087
+ return { kind: "retry" };
1088
+ }
1089
+ const afterPost = await checkControl(deps, context);
1090
+ if (afterPost)
1091
+ return done({ stream, outcome: afterPost, watermark });
1092
+ return finishPosted(deps, context, candidate, prepared, newVersion);
1093
+ }
1094
+ /**
1095
+ * The head equals the registry's: nothing was posted. Record the local state
1096
+ * (the watermark advances; the head is already published) and report it.
1097
+ */
1098
+ async function finishNoop(deps, context, candidate, prepared) {
1099
+ const { connectionId, connection, stream } = context;
1100
+ const { watermark } = candidate;
1101
+ await commitLocal(deps, context, candidate, prepared, candidate.registryVersion, false);
1102
+ return {
1103
+ kind: "done",
1104
+ result: {
1105
+ stream,
1106
+ outcome: candidate.sawRefusal ? "refused" : "noop",
1107
+ watermark,
1108
+ ...(watermark > candidate.localWatermark && {
1109
+ publication: {
1110
+ connectionId,
1111
+ connector: connection.connector,
1112
+ ns: connection.ns,
1113
+ stream,
1114
+ head: {
1115
+ version: candidate.registryVersion,
1116
+ generation: candidate.headGeneration,
1117
+ dataHash: prepared.dataHash,
1118
+ },
1119
+ watermark,
1120
+ runIds: candidate.runIds,
1121
+ },
1122
+ }),
1123
+ },
1124
+ };
1125
+ }
1126
+ /** Sign the head's registry row: version `registryVersion + 1`. */
1127
+ async function signHead(deps, context, candidate, encryptedLength, prepared) {
1128
+ const newVersion = candidate.registryVersion + 1;
1129
+ const metadataHash = metadataHashFor(context.scope, new Date(candidate.head.observedAt).toISOString(), encryptedLength);
1130
+ const signature = await deps.signer.signAddData({
1131
+ ownerAddress: deps.ownerAddress,
1132
+ scope: context.scope,
1133
+ dataHash: prepared.dataHash,
1134
+ metadataHash,
1135
+ expectedVersion: BigInt(newVersion),
1136
+ });
1137
+ return { newVersion, metadataHash, signature };
1138
+ }
1139
+ /** The local write of a stream's head: stream state, parts, evidence, compaction. */
1140
+ function commitLocal(deps, context, candidate, prepared, version, isNewVersion) {
1141
+ return commitBatch(deps, context.connectionId, context.stream, {
1142
+ version,
1143
+ generation: candidate.headGeneration,
1144
+ dataHash: prepared.dataHash,
1145
+ blobName: prepared.blobName,
1146
+ recordCount: prepared.recordCount,
1147
+ observedAt: candidate.head.observedAt,
1148
+ complete: candidate.head.complete,
1149
+ parts: prepared.parts,
1150
+ watermark: candidate.watermark,
1151
+ lastDeleteVersion: candidate.head.lastDeleteVersion ?? 0,
1152
+ replaceBelow: candidate.replaceBelow,
1153
+ primaryKey: candidate.head.primaryKey,
1154
+ profile: candidate.head.profile,
1155
+ isNewVersion,
1156
+ runIds: candidate.runIds,
1157
+ });
1158
+ }
1159
+ /** The registry took the row: record it locally and report the publication. */
1160
+ async function finishPosted(deps, context, candidate, prepared, newVersion) {
1161
+ const { connectionId, connection, stream, scope } = context;
1162
+ await commitLocal(deps, context, candidate, prepared, newVersion, true);
1163
+ // The next snapshot of this stream meets this head at the registry. This
1164
+ // device built, verified and committed it, so it need not download it.
1165
+ if (prepared.verifiedHead) {
1166
+ rememberOwnHead(deps, scope, prepared.dataHash, context.keyCheck, prepared.verifiedHead);
1167
+ }
1168
+ return {
1169
+ kind: "done",
1170
+ result: {
1171
+ stream,
1172
+ outcome: "published",
1173
+ watermark: candidate.watermark,
1174
+ publication: {
1175
+ connectionId,
1176
+ connector: connection.connector,
1177
+ ns: connection.ns,
1178
+ stream,
1179
+ head: {
1180
+ version: newVersion,
1181
+ generation: candidate.headGeneration,
1182
+ dataHash: prepared.dataHash,
1183
+ },
1184
+ watermark: candidate.watermark,
1185
+ runIds: candidate.runIds,
1186
+ },
1187
+ },
1188
+ };
1189
+ }
1190
+ /** A stream whose head differs from the registry's writes a row. */
1191
+ const writesHead = (entry) => entry.kind === "head" && entry.prepared.encryptedLength !== null;
1192
+ /**
1193
+ * The stream row a stream that writes nothing holds fixed: the row it planned
1194
+ * over. `null` if it has none to hold.
1195
+ */
1196
+ const fenceOf = (entry) => entry.kind === "idle"
1197
+ ? entry.idle.hint?.found
1198
+ ? {
1199
+ version: entry.idle.hint.version,
1200
+ dataHash: entry.idle.hint.dataHash,
1201
+ }
1202
+ : null
1203
+ : {
1204
+ version: entry.candidate.registryVersion,
1205
+ dataHash: entry.candidate.registryDataHash,
1206
+ };
1207
+ const controlHashOf = (entry) => entry.kind === "idle"
1208
+ ? entry.idle.controlDataHash
1209
+ : entry.candidate.controlDataHash;
1210
+ const watermarkOf = (entry) => entry.kind === "idle"
1211
+ ? entry.idle.result.watermark
1212
+ : entry.candidate.watermark;
1213
+ function connectionCommits(deps, connectionId, latch) {
1214
+ const commits = {
1215
+ unsupported: deps.registry.postBatch === undefined,
1216
+ group: createCommitGroup({
1217
+ runInSlot: (work) => deps.queue.run(connectionId, "publish", () => {
1218
+ stopIfPurged(latch);
1219
+ return work(insideQueue(deps, connectionId));
1220
+ }),
1221
+ flush: (held, entries) => commitBatchTurn(held, entries, commits),
1222
+ // A turn is bounded by what the gateway accepts: rows are the streams
1223
+ // that write, and each stream that does not write is one more condition
1224
+ // beside the control row's.
1225
+ canJoin: (taken, next) => {
1226
+ const writes = (list) => list.filter(writesHead).length;
1227
+ return writesHead(next)
1228
+ ? writes(taken) < GATEWAY_MAX_BATCH_ROWS
1229
+ : taken.length - writes(taken) < GATEWAY_MAX_BATCH_REQUIRES - 1;
1230
+ },
1231
+ }),
1232
+ };
1233
+ return commits;
1234
+ }
1235
+ /**
1236
+ * COMMIT of one stream. It joins the connection's commit group. A head that
1237
+ * equals the registry's writes no row; it joins as a condition on its stream
1238
+ * row instead. A stream commits alone, in its own slot turn with fresh reads
1239
+ * of its stream row and the control row, when the registry has no batch route.
1240
+ */
1241
+ async function commitStream(slot, context, candidate, prepared, run) {
1242
+ const alone = () => slot((held) => commitCandidate(held, context, candidate, prepared, run));
1243
+ if (context.commits.unsupported)
1244
+ return alone();
1245
+ const turn = await context.commits.group.submit({
1246
+ kind: "head",
1247
+ context,
1248
+ candidate,
1249
+ prepared,
1250
+ run,
1251
+ });
1252
+ return turn.kind === "unbatched" ? alone() : turn;
1253
+ }
1254
+ /**
1255
+ * The end of a stream that has no candidate. On the batch path its hints are
1256
+ * confirmed by the conditions of a commit request. Without the batch route,
1257
+ * when the request finds the route absent, or when the stream row to confirm
1258
+ * is absent (a request cannot hold an absent row fixed), they are confirmed by
1259
+ * live reads in its own slot turn.
1260
+ */
1261
+ async function finishIdle(slot, context, run, idle) {
1262
+ const conditional = !context.commits.unsupported && idle.hint?.found !== false;
1263
+ if (conditional) {
1264
+ const turn = await context.commits.group.submit({
1265
+ kind: "idle",
1266
+ context,
1267
+ idle,
1268
+ run,
1269
+ });
1270
+ if (turn.kind !== "unbatched")
1271
+ return turn;
1272
+ }
1273
+ return slot((held) => confirmIdle(held, context, idle));
1274
+ }
1275
+ /**
1276
+ * Confirm an idle stream with live reads, in the slot: the stream row first,
1277
+ * then the control row (see `confirmLive`). The row is read whenever the
1278
+ * stream holds one to compare (`hint`: a listing's row, or the planned row
1279
+ * after an attachment upload, absent included); a row that is no longer that
1280
+ * one means the plan is stale: "retry", which re-snapshots live. A connection
1281
+ * deleted meanwhile purges and one that moved defers, never "noop". Evidence is
1282
+ * written only after both reads agree with the plan; with none to save the
1283
+ * reads still run, because a "noop" is a claim about the registry too.
1284
+ */
1285
+ async function confirmIdle(held, context, idle) {
1286
+ const { stream } = context;
1287
+ const end = (outcome) => ({
1288
+ kind: "done",
1289
+ result: outcome
1290
+ ? { stream, outcome, watermark: idle.result.watermark }
1291
+ : idle.result,
1292
+ });
1293
+ if (idle.hint && !sameRow(await held.registry.read(context.scope), idle.hint))
1294
+ return { kind: "retry" };
1295
+ const checked = await checkControl(held, context);
1296
+ if (checked)
1297
+ return end(checked);
1298
+ if (idle.evidence) {
1299
+ await saveRunEvidence(held, context.connectionId, stream, idle.evidence);
1300
+ }
1301
+ return end(null);
1302
+ }
1303
+ /** The identical request twice at most: a lost reply is resent once. */
1304
+ async function postBatchOnce(registry, request) {
1305
+ try {
1306
+ return await registry.postBatch(request);
1307
+ }
1308
+ catch (error) {
1309
+ if (!(error instanceof AmbiguousRegistryReplyError))
1310
+ throw error;
1311
+ }
1312
+ // The first send may have landed. The gateway answers a row it already holds
1313
+ // with its own hash, which settleRow reads as published. A second lost
1314
+ // reply is an unknown outcome and throws, as a lost single write does.
1315
+ return registry.postBatch(request);
1316
+ }
1317
+ /**
1318
+ * COMMIT of the streams that wait at one slot turn, in the slot: one request.
1319
+ *
1320
+ * Each stream's local basis is still the snapshot's. A stream whose head
1321
+ * differs from the registry's gets a signed row; its `expectedHeadDataHash` is
1322
+ * the registry head the snapshot saw, so a same-version refresh by another
1323
+ * writer is refused, not overwritten. A stream whose head equals the
1324
+ * registry's writes nothing; the request carries a condition on its stream row
1325
+ * (version and data hash) instead, and the stream is recorded when the
1326
+ * request succeeds. So is a stream with no candidate whose snapshot rests on a
1327
+ * listing hint (`idle`): its stream-row condition replaces the live reads of
1328
+ * `confirmLive`, and its run evidence is saved on the request's success. The
1329
+ * control row is a condition too: this connection's
1330
+ * generation, its hash, not deleted. The gateway checks every condition in the
1331
+ * transaction of the writes, so no client read brackets the request. The local
1332
+ * delete-intent check below stops a send that is already wrong; it is not what
1333
+ * keeps a write from landing after a delete. The conditions are.
1334
+ *
1335
+ * Conditions are the batch's: one that fails writes nothing for anyone.
1336
+ * control row deleted -> purge the connection
1337
+ * control row otherwise -> defer every stream (another lifetime)
1338
+ * a stream row moved -> that stream re-plans. The others go again in
1339
+ * the next request, sent at once from this same
1340
+ * slot turn, without it. They do not return to
1341
+ * the pool: the stream that re-plans would
1342
+ * rejoin before the flush, and if it kept moving
1343
+ * its siblings would never commit.
1344
+ * Otherwise each row answers for itself, and its siblings are not affected:
1345
+ * 201, or a 409 whose winner is this row's own content (a copy of it landed)
1346
+ * -> local commit, published; the watermark
1347
+ * acknowledged is the snapshot's
1348
+ * any other 409 -> apply the winner once and re-plan that stream
1349
+ * (the attempt count bounds it)
1350
+ * A reply is settled only if the local lifetime is still the one the request
1351
+ * carried (the control row's generation); otherwise it is discarded and every
1352
+ * stream is deferred. A request with no row to write (every stream unchanged)
1353
+ * is sent as conditions only. No batch route: every stream commits alone. A
1354
+ * lost reply is answered by the same request sent once more: the gateway
1355
+ * returns the original 201 for a row it already holds and judges the
1356
+ * conditions again, so a resend after a delete purges.
1357
+ *
1358
+ * A delete that lands after the request commits is not seen here (the old
1359
+ * check after the write could see it); the next snapshot reads the tombstone
1360
+ * and purges.
1361
+ */
1362
+ async function commitBatchTurn(held, entries, commits) {
1363
+ const { connectionId, connection } = entries[0].context;
1364
+ const control = controlScope(connection.connector, connection.ns);
1365
+ const outcomes = new Map();
1366
+ const ok = (at, value) => outcomes.set(at, { status: "fulfilled", value });
1367
+ const fail = (at, reason) => outcomes.set(at, { status: "rejected", reason });
1368
+ const done = (at, outcome) => ok(at, {
1369
+ kind: "done",
1370
+ result: {
1371
+ stream: entries[at].context.stream,
1372
+ outcome,
1373
+ watermark: watermarkOf(entries[at]),
1374
+ },
1375
+ });
1376
+ const headAt = (at) => {
1377
+ const entry = entries[at];
1378
+ if (entry.kind !== "head")
1379
+ throw new Error("publish: an idle stream has no head to write");
1380
+ return entry;
1381
+ };
1382
+ const settle = () => entries.map((_, at) => outcomes.get(at) ?? {
1383
+ status: "rejected",
1384
+ reason: new Error("publish: a commit turn left a stream unsettled"),
1385
+ });
1386
+ const signed = [];
1387
+ /** Streams with nothing to write: a condition on their row, recorded on success. */
1388
+ const fenced = [];
1389
+ for (const [at, entry] of entries.entries()) {
1390
+ try {
1391
+ if (entry.kind === "idle") {
1392
+ // No local basis to compare: it holds its hints, and the request
1393
+ // confirms them.
1394
+ fenced.push(at);
1395
+ continue;
1396
+ }
1397
+ const { context, candidate, prepared, run } = entry;
1398
+ if ((await readBasis(held, context, candidate)) !== candidate.basis) {
1399
+ ok(at, { kind: "invalidated" });
1400
+ continue;
1401
+ }
1402
+ if (!writesHead(entry)) {
1403
+ fenced.push(at);
1404
+ continue;
1405
+ }
1406
+ const head = await timed(held, (ms) => (run.meter.headRegisterMs += ms), () => signHead(held, context, candidate, prepared.encryptedLength, prepared));
1407
+ signed.push({
1408
+ at,
1409
+ newVersion: head.newVersion,
1410
+ row: {
1411
+ scope: context.scope,
1412
+ dataHash: prepared.dataHash,
1413
+ metadataHash: head.metadataHash,
1414
+ expectedVersion: String(head.newVersion),
1415
+ signature: head.signature,
1416
+ ...(candidate.registryDataHash !== null && {
1417
+ expectedHeadDataHash: candidate.registryDataHash,
1418
+ }),
1419
+ },
1420
+ });
1421
+ }
1422
+ catch (error) {
1423
+ fail(at, error);
1424
+ }
1425
+ }
1426
+ /** The streams still in the request: one that moved leaves it. */
1427
+ let live = fenced;
1428
+ let rows;
1429
+ for (;;) {
1430
+ if (signed.length === 0 && live.length === 0)
1431
+ return settle();
1432
+ // The local veto, under the slot, right before the request: a delete
1433
+ // intent can appear after the snapshot recorded it in its basis, which
1434
+ // then still compares equal.
1435
+ if (await hasDeleteIntent(held, connection.connector)) {
1436
+ for (const { at } of signed)
1437
+ done(at, "deferred");
1438
+ for (const at of live)
1439
+ done(at, "deferred");
1440
+ return settle();
1441
+ }
1442
+ const first = entries[signed[0]?.at ?? live[0]];
1443
+ const request = {
1444
+ ownerAddress: held.ownerAddress,
1445
+ rows: signed.map(({ row }) => row),
1446
+ requires: [
1447
+ {
1448
+ scope: control,
1449
+ expectedVersion: String(connection.generation),
1450
+ notDeleted: true,
1451
+ expectedDataHash: controlHashOf(first),
1452
+ },
1453
+ ...live.flatMap((at) => {
1454
+ const fence = fenceOf(entries[at]);
1455
+ return fence
1456
+ ? [
1457
+ {
1458
+ scope: entries[at].context.scope,
1459
+ expectedVersion: String(fence.version),
1460
+ notDeleted: true,
1461
+ expectedDataHash: fence.dataHash,
1462
+ },
1463
+ ]
1464
+ : [];
1465
+ }),
1466
+ ],
1467
+ };
1468
+ const answer = await timed(held, (ms) => {
1469
+ for (const { at } of signed)
1470
+ headAt(at).run.meter.headRegisterMs += ms;
1471
+ }, () => postBatchOnce(held.registry, request));
1472
+ if (answer.kind === "unsupported") {
1473
+ commits.unsupported = true;
1474
+ for (const { at } of signed)
1475
+ ok(at, { kind: "unbatched" });
1476
+ for (const at of live)
1477
+ ok(at, { kind: "unbatched" });
1478
+ return settle();
1479
+ }
1480
+ if (answer.kind === "rows") {
1481
+ rows = answer.rows;
1482
+ break;
1483
+ }
1484
+ // Nothing was written. Without the gateway's detail, read the control row.
1485
+ const verdict = answer.failure
1486
+ ? settleRequirementFailure(answer.failure, control)
1487
+ : null;
1488
+ if (verdict?.kind === "stream_moved") {
1489
+ const moved = live.find((at) => entries[at].context.scope === verdict.scope);
1490
+ if (moved !== undefined) {
1491
+ // One stream's row is not the one it was planned over. It re-plans.
1492
+ // The rest decided nothing: loop and send them now, without it. The
1493
+ // listing it came from is older than the row that moved. A stream
1494
+ // with no candidate (`idle`) is counted as an invalidation by its
1495
+ // caller; one with a candidate is counted here.
1496
+ entries[moved].context.view.invalidate();
1497
+ if (entries[moved].kind === "head")
1498
+ entries[moved].run.invalidations++;
1499
+ entries[moved].run.attempts++;
1500
+ if (entries[moved].run.attempts >= MAX_ATTEMPTS)
1501
+ done(moved, "backoff");
1502
+ else
1503
+ ok(moved, { kind: "retry" });
1504
+ live = live.filter((at) => at !== moved);
1505
+ continue;
1506
+ }
1507
+ }
1508
+ let outcome;
1509
+ if (verdict?.kind === "purge") {
1510
+ await purgeConnection(held, connectionId, {
1511
+ controlVersion: verdict.controlVersion,
1512
+ });
1513
+ for (const { context } of entries)
1514
+ context.latch.purged = true;
1515
+ outcome = "purged";
1516
+ }
1517
+ else if (verdict === null) {
1518
+ outcome = (await checkControl(held, first.context)) ?? "deferred";
1519
+ }
1520
+ else {
1521
+ outcome = "deferred";
1522
+ }
1523
+ for (const { at } of signed)
1524
+ done(at, outcome);
1525
+ for (const at of live)
1526
+ done(at, outcome);
1527
+ return settle();
1528
+ }
1529
+ // A reply, stored or fresh, is for the lifetime the request carried. If the
1530
+ // local one moved meanwhile (a purge and a reconnect), settling would record
1531
+ // this lifetime's rows under another: discard the reply.
1532
+ if (!(await lifetimeHolds(held, connectionId, connection.generation))) {
1533
+ for (const { at } of signed)
1534
+ done(at, "deferred");
1535
+ for (const at of live)
1536
+ done(at, "deferred");
1537
+ return settle();
1538
+ }
1539
+ for (const { at } of signed)
1540
+ headAt(at).run.attempts++;
1541
+ const answerRows = rows;
1542
+ const conflicted = [];
1543
+ for (const [i, { at, newVersion, row }] of signed.entries()) {
1544
+ const settlement = settleRow(answerRows[i], {
1545
+ expectedVersion: row.expectedVersion,
1546
+ dataHash: row.dataHash,
1547
+ });
1548
+ if (settlement === "conflict") {
1549
+ conflicted.push(at);
1550
+ continue;
1551
+ }
1552
+ const { context, candidate, prepared } = headAt(at);
1553
+ try {
1554
+ if (await hasDeleteIntent(held, connection.connector)) {
1555
+ done(at, "deferred");
1556
+ }
1557
+ else {
1558
+ ok(at, await finishPosted(held, context, candidate, prepared, newVersion));
1559
+ }
1560
+ }
1561
+ catch (error) {
1562
+ fail(at, error);
1563
+ }
1564
+ }
1565
+ // The conditions held, in the transaction of the writes: the streams with
1566
+ // nothing to write hold the registry's row as they planned it.
1567
+ for (const at of live) {
1568
+ const entry = entries[at];
1569
+ try {
1570
+ if (await hasDeleteIntent(held, connection.connector)) {
1571
+ done(at, "deferred");
1572
+ }
1573
+ else if (entry.kind === "idle") {
1574
+ // The hints held: the evidence the plan matched is recorded.
1575
+ if (entry.idle.evidence) {
1576
+ await saveRunEvidence(held, entry.context.connectionId, entry.context.stream, entry.idle.evidence);
1577
+ }
1578
+ ok(at, { kind: "done", result: entry.idle.result });
1579
+ }
1580
+ else {
1581
+ ok(at, await finishNoop(held, entry.context, entry.candidate, entry.prepared));
1582
+ }
1583
+ }
1584
+ catch (error) {
1585
+ fail(at, error);
1586
+ }
1587
+ }
1588
+ if (conflicted.length > 0) {
1589
+ // Another writer moved those rows, so a listing read before that is no
1590
+ // starting point for any stream not yet started, including after the last
1591
+ // try, which ends a stream without a retry (as in `commitCandidate`).
1592
+ entries[conflicted[0]].context.view.invalidate();
1593
+ try {
1594
+ // Apply the winners once, after the rows that committed are recorded.
1595
+ if (conflicted.some((at) => entries[at].run.attempts < MAX_ATTEMPTS)) {
1596
+ await applyConnection(held, connectionId);
1597
+ }
1598
+ for (const at of conflicted) {
1599
+ if (entries[at].run.attempts === MAX_ATTEMPTS)
1600
+ done(at, "backoff");
1601
+ else
1602
+ ok(at, { kind: "retry" });
1603
+ }
1604
+ }
1605
+ catch (error) {
1606
+ for (const at of conflicted)
1607
+ fail(at, error);
1608
+ }
1609
+ }
1610
+ return settle();
1611
+ }
1612
+ /** Whether the connection's local lifetime is still generation `generation`. */
1613
+ async function lifetimeHolds(deps, connectionId, generation) {
1614
+ const [row] = await deps.db.query(`SELECT generation FROM connections WHERE connection_id = ?`, [connectionId]);
1615
+ return row !== undefined && Number(row.generation) === generation;
1616
+ }
1617
+ /**
1618
+ * The local state a candidate rests on, as one comparable key. It compares the
1619
+ * connection's control, the stream's head fields and parts, the connection's
1620
+ * delete intents, the selected runs, the changes at or below W, and what
1621
+ * happened above W that could make the frozen rows wrong (below). It is not
1622
+ * every input: stream floor and profile fields, and runs that ended after the
1623
+ * snapshot, are left out on purpose.
1624
+ *
1625
+ * A candidate survives a run that begins or ends after the snapshot and the
1626
+ * rows it upserts (origin `local` or `import`, sequence above W): they stay
1627
+ * queued above W, compaction never passes W, and a later publish carries them.
1628
+ * A removal above W is different: a remote head that still shows the row
1629
+ * would outlive the local delete. So every removal above W (a PDPP record
1630
+ * delete is origin `local`, `explicit_delete`) and every write of another
1631
+ * origin (a purge, a refresh) is in the key. Reads only; no transaction is
1632
+ * held.
1633
+ */
1634
+ async function readBasis(deps, context, snapshot) {
1635
+ const { connectionId, connection, stream } = context;
1636
+ const [connectionRow] = await deps.db.query(`SELECT generation, control_state, control_version FROM connections WHERE connection_id = ?`, [connectionId]);
1637
+ const [streamRow] = await deps.db.query(`SELECT head_version, head_generation, head_data_hash, head_blob,
1638
+ last_delete_version, publish_watermark
1639
+ FROM stream_state WHERE connection_id = ? AND stream = ?`, [connectionId, stream]);
1640
+ const headParts = await deps.db.query(`SELECT prefix, seq, part_hash, bytes, count FROM head_parts
1641
+ WHERE connection_id = ? AND stream = ? ORDER BY prefix, seq`, [connectionId, stream]);
1642
+ const intents = await deps.db.query(`SELECT delete_id, intent FROM delete_intents WHERE connector = ?`, [connection.connector]);
1643
+ const runs = [];
1644
+ for (const runId of snapshot.runIds) {
1645
+ runs.push(await deps.db.query(`SELECT r.run_id, r.state, r.generation, rs.decision, rs.replace,
1646
+ (SELECT COUNT(*) FROM run_rows rr
1647
+ WHERE rr.run_id = r.run_id AND rr.stream = rs.stream) AS row_count
1648
+ FROM runs r JOIN run_streams rs ON rs.run_id = r.run_id
1649
+ WHERE r.run_id = ? AND rs.stream = ?`, [runId, stream]));
1650
+ }
1651
+ const covered = await deps.db.query(`SELECT COUNT(*) AS n, MAX(seq) AS newest FROM record_changes
1652
+ WHERE connection_id = ? AND stream = ? AND seq > ? AND seq <= ?`, [connectionId, stream, snapshot.localWatermark, snapshot.watermark]);
1653
+ const foreign = await deps.db.query(`SELECT COUNT(*) AS n FROM record_changes
1654
+ WHERE connection_id = ? AND stream = ? AND seq > ?
1655
+ AND (origin NOT IN ('local', 'import')
1656
+ OR op = 'remove' OR explicit_delete = 1)`, [connectionId, stream, snapshot.watermark]);
1657
+ return JSON.stringify([
1658
+ connectionRow ?? null,
1659
+ streamRow ?? null,
1660
+ headParts,
1661
+ intents,
1662
+ runs,
1663
+ covered,
1664
+ foreign,
1665
+ ]);
1666
+ }
1667
+ /** A local delete of the connector is under way: nothing is published. */
1668
+ async function hasDeleteIntent(deps, connector) {
1669
+ const rows = await deps.db.query("SELECT 1 FROM delete_intents WHERE connector=?", [connector]);
1670
+ return rows.length > 0;
1671
+ }
1672
+ async function checkControl(deps, context) {
1673
+ const { connectionId: id, connection, hashes } = context;
1674
+ if (await hasDeleteIntent(deps, connection.connector))
1675
+ return "deferred";
1676
+ const state = classifyControl(await deps.registry.read(controlScope(connection.connector, connection.ns)), hashes);
1677
+ if (state.kind === "deleted") {
1678
+ await purgeConnection(deps, id, { controlVersion: state.version });
1679
+ context.latch.purged = true;
1680
+ return "purged";
1681
+ }
1682
+ if (state.kind !== "active" || state.generation !== connection.generation)
1683
+ return "deferred";
1684
+ return null;
1685
+ }
1686
+ /** The ended runs whose decision still awaits publication, oldest first. */
1687
+ async function retainedRuns(deps, connectionId, stream) {
1688
+ return deps.db.query(`SELECT r.run_id, r.o, r.generation, r.artifact_version,
1689
+ rs.primary_key, rs.profile_key, rs.profile_version,
1690
+ rs.full_read, rs.foreign_checkpoint, rs.seed, rs.decision,
1691
+ rs.replace, rs.basis_version, rs.basis_generation, rs.basis_data_hash,
1692
+ (SELECT COUNT(*) FROM run_rows rr
1693
+ WHERE rr.run_id = r.run_id AND rr.stream = rs.stream) AS row_count
1694
+ FROM runs r JOIN run_streams rs ON rs.run_id = r.run_id
1695
+ WHERE r.connection_id = ? AND rs.stream = ? AND r.state = 'ended'
1696
+ AND rs.decision IN ('publish', 'noop', 'deferred')
1697
+ ORDER BY r.o, r.run_id`, [connectionId, stream]);
1698
+ }
1699
+ /**
1700
+ * A run belongs to the connection lifetime it began in. A run that began
1701
+ * before the current control generation (it has no generation of its own, or
1702
+ * its begin basis is another control version) must never publish into the
1703
+ * current one: its rows may be rows another writer deleted. Such runs are
1704
+ * discarded with `lifetime_changed` and the connection recollects.
1705
+ *
1706
+ * Without this the "bind unbound runs" step of the snapshot hands a run that
1707
+ * ended before a delete+reconnect the NEW generation, and the next cycle
1708
+ * publishes the deleted rows back.
1709
+ */
1710
+ export async function discardForeignLifetimeRuns(deps, connectionId, currentGeneration) {
1711
+ const runs = await deps.db.query(`SELECT r.run_id, r.o, rs.stream, r.generation, r.begin_control_version
1712
+ FROM runs r JOIN run_streams rs ON rs.run_id = r.run_id
1713
+ WHERE r.connection_id = ? AND r.state = 'ended'
1714
+ AND rs.decision IN ('publish', 'noop', 'deferred')`, [connectionId]);
1715
+ const foreign = runs.filter((run) => (run.generation === null && currentGeneration > 1) ||
1716
+ (run.begin_control_version !== null &&
1717
+ run.begin_control_version > 0 &&
1718
+ run.begin_control_version !== currentGeneration));
1719
+ if (foreign.length === 0)
1720
+ return false;
1721
+ const statements = [];
1722
+ for (const run of foreign) {
1723
+ statements.push(...dropRunRows(connectionId, run.stream, run.o, run.run_id), {
1724
+ sql: "UPDATE run_streams SET decision='discarded',reason='lifetime_changed',replace=0,publication_state='superseded',publication_reason='lifetime_changed' WHERE run_id=? AND stream=?",
1725
+ params: [run.run_id, run.stream],
1726
+ }, {
1727
+ sql: "DELETE FROM run_rows WHERE run_id=? AND stream=?",
1728
+ params: [run.run_id, run.stream],
1729
+ });
1730
+ }
1731
+ for (const stream of new Set(foreign.map((run) => run.stream))) {
1732
+ statements.push({
1733
+ sql: "DELETE FROM head_parts WHERE connection_id=? AND stream=?",
1734
+ params: [connectionId, stream],
1735
+ });
1736
+ }
1737
+ // The discarded rows were collected against a lifetime that ended: the next
1738
+ // run collects in full instead of resuming from their checkpoint.
1739
+ statements.push({
1740
+ sql: "UPDATE connections SET checkpoint = NULL WHERE connection_id = ?",
1741
+ params: [connectionId],
1742
+ });
1743
+ await deps.db.batch(withOrigin("purge", statements));
1744
+ return true;
1745
+ }
1746
+ async function discardFencedRuns(deps, id, stream) {
1747
+ const runs = await deps.db.query(`SELECT r.run_id,r.o FROM runs r JOIN run_streams rs ON rs.run_id=r.run_id
1748
+ WHERE r.connection_id=? AND rs.stream=? AND r.state='ended' AND rs.decision IN ('publish','noop','deferred')`, [id, stream]);
1749
+ const statements = [];
1750
+ for (const run of runs) {
1751
+ const trip = (await checkRunFence(deps, run.run_id, "publish")).find((t) => t.stream === stream);
1752
+ if (!trip)
1753
+ continue;
1754
+ statements.push(...dropRunRows(id, stream, run.o, run.run_id), {
1755
+ sql: "UPDATE run_streams SET decision='discarded',reason=?,replace=0,publication_state='superseded',publication_reason=? WHERE run_id=? AND stream=?",
1756
+ params: [trip.trip, trip.trip, run.run_id, stream],
1757
+ }, {
1758
+ sql: "DELETE FROM run_rows WHERE run_id=? AND stream=?",
1759
+ params: [run.run_id, stream],
1760
+ });
1761
+ }
1762
+ if (statements.length === 0)
1763
+ return false;
1764
+ statements.push({
1765
+ sql: "DELETE FROM head_parts WHERE connection_id=? AND stream=?",
1766
+ params: [id, stream],
1767
+ });
1768
+ await deps.db.batch(withOrigin("purge", statements));
1769
+ return true;
1770
+ }
1771
+ async function readRegistryHead(deps, scope, dataHash, connection, stream, keyCheck) {
1772
+ const remembered = recallHead(deps, scope, dataHash, keyCheck);
1773
+ if (remembered)
1774
+ return remembered;
1775
+ const blobName = headBlobName(dataHash);
1776
+ const cipher = await deps.blobs.get(`${scope}/${blobName}`);
1777
+ if (cipher === null) {
1778
+ throw new Error(`publish: registry head blob ${blobName} is missing for ${stream}`);
1779
+ }
1780
+ const clear = await deps.keys.decrypt(scope, cipher);
1781
+ const verified = await verifyHead(keccak, clear, {
1782
+ dataHash,
1783
+ connector: connection.connector,
1784
+ ns: connection.ns,
1785
+ stream,
1786
+ keyCheck,
1787
+ });
1788
+ if (verified.kind !== "ok") {
1789
+ throw new Error(`publish: registry head for ${stream} failed verification: ${verified.kind}`);
1790
+ }
1791
+ rememberHead(deps, scope, dataHash, keyCheck, verified.head);
1792
+ return verified.head;
1793
+ }
1794
+ async function planStream(deps, connectionId, connection, stream, local, registryHead, registryVersion, registryDataHash) {
1795
+ const runs = await retainedRuns(deps, connectionId, stream);
1796
+ const newest = runs.length > 0 ? runs[runs.length - 1] : undefined;
1797
+ const baseHead = registryHead
1798
+ ? {
1799
+ generation: registryHead.generation,
1800
+ primaryKey: registryHead.primaryKey,
1801
+ profile: registryHead.profile,
1802
+ complete: registryHead.complete,
1803
+ }
1804
+ : local.head_version > 0 || local.floor_o !== null
1805
+ ? {
1806
+ generation: local.head_generation ??
1807
+ newest?.generation ??
1808
+ connection.generation,
1809
+ primaryKey: JSON.parse(local.primary_key),
1810
+ profile: {
1811
+ key: local.profile_key ?? connection.connector,
1812
+ version: local.profile_version ??
1813
+ local.floor_version ??
1814
+ newest?.artifact_version ??
1815
+ "0",
1816
+ },
1817
+ complete: local.complete === 1,
1818
+ }
1819
+ : null;
1820
+ // The floor at publish carries the version floor but no committed stamp:
1821
+ // commit order was enforced at end (a late run was refused there and
1822
+ // never entered the retained set), so the retained runs are already
1823
+ // accepted and ordered.
1824
+ let state = {
1825
+ head: baseHead,
1826
+ floor: { version: local.floor_version, committed: null },
1827
+ };
1828
+ const steps = [];
1829
+ let replaceBelow;
1830
+ for (const run of runs) {
1831
+ const planRun = {
1832
+ runId: run.run_id,
1833
+ observedAt: run.o,
1834
+ generation: run.generation,
1835
+ primaryKey: JSON.parse(run.primary_key ?? local.primary_key),
1836
+ profile: {
1837
+ key: run.profile_key ?? connection.connector,
1838
+ version: run.profile_version ?? run.artifact_version,
1839
+ },
1840
+ full: run.full_read === 1,
1841
+ foreignCheckpoint: run.foreign_checkpoint === 1,
1842
+ empty: run.row_count === 0,
1843
+ seed: run.seed,
1844
+ };
1845
+ const decision = planStreamStep(state, planRun);
1846
+ if (decision.kind === "refused") {
1847
+ return {
1848
+ steps,
1849
+ finalHead: state.head,
1850
+ deferred: false,
1851
+ refused: { runId: run.run_id, reason: decision.reason },
1852
+ replaceBelow: undefined,
1853
+ newestRunObservedAt: newest?.o ?? null,
1854
+ };
1855
+ }
1856
+ if (decision.kind === "deferred") {
1857
+ return {
1858
+ steps,
1859
+ finalHead: state.head,
1860
+ deferred: true,
1861
+ refused: null,
1862
+ replaceBelow: undefined,
1863
+ newestRunObservedAt: newest?.o ?? null,
1864
+ };
1865
+ }
1866
+ steps.push({ runId: run.run_id, decision });
1867
+ if (decision.kind === "publish" && decision.replacesBase)
1868
+ replaceBelow = { o: run.o, r: run.run_id };
1869
+ state = {
1870
+ head: decision.head,
1871
+ floor: { version: decision.floor, committed: null },
1872
+ };
1873
+ }
1874
+ // Replace (H): the newest retained replacing run whose basis matches the
1875
+ // registry head's identity. The basis was recorded at begin and is never
1876
+ // refreshed; a predicted head has no identity, so replace defers.
1877
+ for (let i = runs.length - 1; i >= 0; i--) {
1878
+ const run = runs[i];
1879
+ if (run.replace !== 1)
1880
+ continue;
1881
+ const applies = replaceMayApply({
1882
+ basisVersion: run.basis_version,
1883
+ basisDataHash: run.basis_data_hash,
1884
+ basisKnown: run.basis_generation !== null,
1885
+ }, registryDataHash === null
1886
+ ? null
1887
+ : { version: registryVersion, dataHash: registryDataHash });
1888
+ if (applies &&
1889
+ (!replaceBelow ||
1890
+ run.o > replaceBelow.o ||
1891
+ (run.o === replaceBelow.o && run.run_id > replaceBelow.r))) {
1892
+ replaceBelow = { o: run.o, r: run.run_id };
1893
+ break;
1894
+ }
1895
+ }
1896
+ return {
1897
+ steps,
1898
+ finalHead: state.head,
1899
+ deferred: false,
1900
+ refused: null,
1901
+ replaceBelow,
1902
+ newestRunObservedAt: newest?.o ?? null,
1903
+ };
1904
+ }
1905
+ /** Purge seed rows for a stream whose head generation is not 1. */
1906
+ async function excludeSeedsIfAny(deps, connectionId, stream) {
1907
+ const [row] = await deps.db.query(`SELECT COUNT(*) AS n FROM records
1908
+ WHERE connection_id = ? AND stream = ? AND stamp_o = 0 AND stamp_r = 'seed'`, [connectionId, stream]);
1909
+ if ((row?.n ?? 0) === 0)
1910
+ return;
1911
+ await deps.db.batch(withOrigin("purge", [
1912
+ {
1913
+ sql: `DELETE FROM records
1914
+ WHERE connection_id = ? AND stream = ? AND stamp_o = 0 AND stamp_r = 'seed'`,
1915
+ params: [connectionId, stream],
1916
+ },
1917
+ {
1918
+ sql: `UPDATE run_streams SET seed='none' WHERE stream=? AND seed='merged'
1919
+ AND run_id IN (SELECT run_id FROM runs WHERE connection_id=?)`,
1920
+ params: [stream, connectionId],
1921
+ },
1922
+ {
1923
+ sql: `UPDATE import_ledger SET state = 'excluded', reason = 'seed_skipped', at = ?
1924
+ WHERE connection_id = ? AND stream = ? AND state = 'imported'`,
1925
+ params: [deps.now(), connectionId, stream],
1926
+ },
1927
+ ]));
1928
+ }
1929
+ /**
1930
+ * The new head's parts: the base head's parts for prefixes not re-encoded,
1931
+ * the freshly encoded parts for the changed prefixes, grouped by prefix
1932
+ * and ordered by prefix.
1933
+ */
1934
+ function mergedParts(baseParts, encoded, changedPrefixes) {
1935
+ const changed = [...changedPrefixes];
1936
+ const groups = new Map();
1937
+ const push = (prefix, part) => {
1938
+ const group = groups.get(prefix);
1939
+ if (group)
1940
+ group.push(part);
1941
+ else
1942
+ groups.set(prefix, [part]);
1943
+ };
1944
+ for (const part of baseParts) {
1945
+ // A base part goes when it overlaps a changed prefix (see
1946
+ // `selectChangedBuckets`: then every prefix it overlaps is changed).
1947
+ if (!changed.some((prefix) => prefix.startsWith(part.prefix) || part.prefix.startsWith(prefix))) {
1948
+ push(part.prefix, part);
1949
+ }
1950
+ }
1951
+ for (const part of encoded) {
1952
+ push(part.prefix, {
1953
+ prefix: part.prefix,
1954
+ bytes: part.bytes,
1955
+ count: part.count,
1956
+ hash: part.partHash,
1957
+ });
1958
+ }
1959
+ return [...groups.keys()].sort().flatMap((prefix) => groups.get(prefix));
1960
+ }
1961
+ const RUN_ID_CHUNK = 400;
1962
+ /**
1963
+ * Durable run-to-publication evidence, written in the same batch as the head.
1964
+ * Only runs still `pending` move to `published`, so a later publication never
1965
+ * rewrites older evidence and runs from before this column stay `unknown`.
1966
+ * The ids are the plan's: a run that ended after planning is not covered.
1967
+ * The watermark is stored as evidence only; it is a local change sequence and
1968
+ * is never compared with a run's `o`.
1969
+ */
1970
+ async function runPublicationStatements(deps, connectionId, stream, input) {
1971
+ const planned = new Set(input.runIds);
1972
+ const pending = (await deps.db.query(`SELECT rs.run_id FROM run_streams rs JOIN runs r ON r.run_id = rs.run_id
1973
+ WHERE r.connection_id = ? AND rs.stream = ? AND rs.publication_state = 'pending'`, [connectionId, stream]))
1974
+ .map((row) => row.run_id)
1975
+ .filter((runId) => planned.has(runId));
1976
+ const statements = [];
1977
+ for (let i = 0; i < pending.length; i += RUN_ID_CHUNK) {
1978
+ const chunk = pending.slice(i, i + RUN_ID_CHUNK);
1979
+ statements.push({
1980
+ sql: `UPDATE run_streams SET publication_state = 'published',
1981
+ published_generation = ?, published_version = ?, published_data_hash = ?,
1982
+ published_watermark = ?, publication_reason = NULL
1983
+ WHERE stream = ? AND publication_state = 'pending'
1984
+ AND run_id IN (${chunk.map(() => "?").join(",")})`,
1985
+ params: [
1986
+ input.generation,
1987
+ input.version,
1988
+ input.dataHash,
1989
+ input.watermark ?? 0,
1990
+ stream,
1991
+ ...chunk,
1992
+ ],
1993
+ });
1994
+ }
1995
+ if (input.replaceBelow) {
1996
+ // The replacement dropped older rows: older runs were saved, then replaced.
1997
+ const { o, r } = input.replaceBelow;
1998
+ statements.push({
1999
+ sql: `UPDATE run_streams SET publication_state = 'superseded', publication_reason = ?
2000
+ WHERE stream = ? AND publication_state = 'published'
2001
+ AND run_id IN (SELECT run_id FROM runs
2002
+ WHERE connection_id = ? AND (o < ? OR (o = ? AND run_id < ?)))`,
2003
+ params: [`replaced_by:${r}`, stream, connectionId, o, o, r],
2004
+ });
2005
+ }
2006
+ return statements;
2007
+ }
2008
+ /**
2009
+ * The one batch after a successful CAS (or a skipped CAS): replace deletes
2010
+ * (origin refresh), head identity, publish_watermark = W, head_parts, a
2011
+ * stream_versions row for a new version, and compaction of record_changes
2012
+ * at or below the connection's lowest watermark — skipped entirely while
2013
+ * an import read-back is pending (an imported ledger row for the
2014
+ * connection).
2015
+ */
2016
+ async function commitBatch(deps, connectionId, stream, input) {
2017
+ const statements = [];
2018
+ if (input.replaceBelow) {
2019
+ statements.push(replaceDelete(connectionId, stream, input.replaceBelow.o, input.replaceBelow.r));
2020
+ }
2021
+ statements.push({
2022
+ sql: `UPDATE stream_state SET head_version = ?, head_generation = ?,
2023
+ head_data_hash = ?, head_blob = ?, publish_watermark = ?,
2024
+ last_delete_version = ?, primary_key = ?, profile_key = ?, profile_version = ?, complete = ?,
2025
+ needs_full = CASE WHEN ? = 1 THEN 0 WHEN ? > 0 THEN 1 ELSE needs_full END
2026
+ WHERE connection_id = ? AND stream = ?`,
2027
+ params: [
2028
+ input.version,
2029
+ input.generation,
2030
+ input.dataHash,
2031
+ input.blobName,
2032
+ input.watermark ?? 0,
2033
+ input.lastDeleteVersion,
2034
+ JSON.stringify(input.primaryKey),
2035
+ input.profile.key,
2036
+ input.profile.version,
2037
+ input.complete ? 1 : 0,
2038
+ input.complete ? 1 : 0,
2039
+ input.lastDeleteVersion,
2040
+ connectionId,
2041
+ stream,
2042
+ ],
2043
+ });
2044
+ statements.push(...(await runPublicationStatements(deps, connectionId, stream, input)));
2045
+ statements.push({
2046
+ sql: `DELETE FROM head_parts WHERE connection_id = ? AND stream = ?`,
2047
+ params: [connectionId, stream],
2048
+ });
2049
+ const seqByPrefix = new Map();
2050
+ for (const part of input.parts) {
2051
+ const seq = seqByPrefix.get(part.prefix) ?? 0;
2052
+ seqByPrefix.set(part.prefix, seq + 1);
2053
+ statements.push({
2054
+ sql: `INSERT INTO head_parts (connection_id, stream, prefix, seq, part_hash, bytes, count)
2055
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
2056
+ params: [
2057
+ connectionId,
2058
+ stream,
2059
+ part.prefix,
2060
+ seq,
2061
+ part.hash,
2062
+ part.bytes,
2063
+ part.count,
2064
+ ],
2065
+ });
2066
+ }
2067
+ if (input.isNewVersion) {
2068
+ statements.push({
2069
+ sql: `INSERT INTO stream_versions (connection_id, stream, version, generation,
2070
+ head_blob, head_format, record_count, observed_at, complete, kind)
2071
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'published')`,
2072
+ params: [
2073
+ connectionId,
2074
+ stream,
2075
+ input.version,
2076
+ input.generation,
2077
+ input.blobName,
2078
+ HEAD_FORMAT,
2079
+ input.recordCount,
2080
+ input.observedAt,
2081
+ input.complete ? 1 : 0,
2082
+ ],
2083
+ });
2084
+ }
2085
+ const [pendingImport] = await deps.db.query(`SELECT COUNT(*) AS n FROM import_ledger
2086
+ WHERE connection_id = ? AND state = 'imported'`, [connectionId]);
2087
+ if ((pendingImport?.n ?? 0) === 0) {
2088
+ // The connection's lowest watermark after this stream's update: the
2089
+ // new watermark for this stream, the current watermark of the others.
2090
+ const [others] = await deps.db.query(`SELECT MIN(publish_watermark) AS m FROM stream_state
2091
+ WHERE connection_id = ? AND stream != ?`, [connectionId, stream]);
2092
+ const lowest = Math.min(input.watermark ?? 0, others?.m ?? Number.POSITIVE_INFINITY);
2093
+ statements.push({
2094
+ sql: `DELETE FROM record_changes WHERE connection_id = ? AND seq <= ?`,
2095
+ params: [connectionId, lowest],
2096
+ });
2097
+ }
2098
+ await deps.db.batch(withOrigin("refresh", statements));
2099
+ }
2100
+ //# sourceMappingURL=publish.js.map