@diffra-ai/durable 0.0.0-stage → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (411) hide show
  1. package/CHANGELOG.md +442 -0
  2. package/README.md +1153 -2
  3. package/dist/codemode/codemode.d.ts +174 -0
  4. package/dist/codemode/codemode.d.ts.map +1 -0
  5. package/dist/codemode/codemode.js +884 -0
  6. package/dist/codemode/codemode.js.map +1 -0
  7. package/dist/codemode/describe.d.ts +38 -0
  8. package/dist/codemode/describe.d.ts.map +1 -0
  9. package/dist/codemode/describe.js +127 -0
  10. package/dist/codemode/describe.js.map +1 -0
  11. package/dist/codemode/index.d.ts +3 -0
  12. package/dist/codemode/index.d.ts.map +1 -0
  13. package/dist/codemode/index.js +3 -0
  14. package/dist/codemode/index.js.map +1 -0
  15. package/dist/codemode/models.d.ts +29 -0
  16. package/dist/codemode/models.d.ts.map +1 -0
  17. package/dist/codemode/models.js +242 -0
  18. package/dist/codemode/models.js.map +1 -0
  19. package/dist/codemode/output.d.ts +43 -0
  20. package/dist/codemode/output.d.ts.map +1 -0
  21. package/dist/codemode/output.js +168 -0
  22. package/dist/codemode/output.js.map +1 -0
  23. package/dist/documents.d.ts +66 -0
  24. package/dist/documents.d.ts.map +1 -0
  25. package/dist/documents.js +98 -0
  26. package/dist/documents.js.map +1 -0
  27. package/dist/entries.d.ts +31 -0
  28. package/dist/entries.d.ts.map +1 -0
  29. package/dist/entries.js +31 -0
  30. package/dist/entries.js.map +1 -0
  31. package/dist/env/decode.d.ts +16 -0
  32. package/dist/env/decode.d.ts.map +1 -0
  33. package/dist/env/decode.js +28 -0
  34. package/dist/env/decode.js.map +1 -0
  35. package/dist/env/index.d.ts +308 -0
  36. package/dist/env/index.d.ts.map +1 -0
  37. package/dist/env/index.js +49 -0
  38. package/dist/env/index.js.map +1 -0
  39. package/dist/env/line-scan.d.ts +13 -0
  40. package/dist/env/line-scan.d.ts.map +1 -0
  41. package/dist/env/line-scan.js +147 -0
  42. package/dist/env/line-scan.js.map +1 -0
  43. package/dist/env/node-watch.d.ts +29 -0
  44. package/dist/env/node-watch.d.ts.map +1 -0
  45. package/dist/env/node-watch.js +487 -0
  46. package/dist/env/node-watch.js.map +1 -0
  47. package/dist/env/node.d.ts +56 -0
  48. package/dist/env/node.d.ts.map +1 -0
  49. package/dist/env/node.js +1185 -0
  50. package/dist/env/node.js.map +1 -0
  51. package/dist/errors.d.ts +48 -0
  52. package/dist/errors.d.ts.map +1 -0
  53. package/dist/errors.js +76 -0
  54. package/dist/errors.js.map +1 -0
  55. package/dist/harness/agent.d.ts +46 -0
  56. package/dist/harness/agent.d.ts.map +1 -0
  57. package/dist/harness/agent.js +334 -0
  58. package/dist/harness/agent.js.map +1 -0
  59. package/dist/harness/compaction.d.ts +68 -0
  60. package/dist/harness/compaction.d.ts.map +1 -0
  61. package/dist/harness/compaction.js +431 -0
  62. package/dist/harness/compaction.js.map +1 -0
  63. package/dist/harness/context.d.ts +84 -0
  64. package/dist/harness/context.d.ts.map +1 -0
  65. package/dist/harness/context.js +301 -0
  66. package/dist/harness/context.js.map +1 -0
  67. package/dist/harness/define.d.ts +25 -0
  68. package/dist/harness/define.d.ts.map +1 -0
  69. package/dist/harness/define.js +32 -0
  70. package/dist/harness/define.js.map +1 -0
  71. package/dist/harness/generation.d.ts +117 -0
  72. package/dist/harness/generation.d.ts.map +1 -0
  73. package/dist/harness/generation.js +1098 -0
  74. package/dist/harness/generation.js.map +1 -0
  75. package/dist/harness/harness.d.ts +22 -0
  76. package/dist/harness/harness.d.ts.map +1 -0
  77. package/dist/harness/harness.js +438 -0
  78. package/dist/harness/harness.js.map +1 -0
  79. package/dist/harness/inbox.d.ts +84 -0
  80. package/dist/harness/inbox.d.ts.map +1 -0
  81. package/dist/harness/inbox.js +135 -0
  82. package/dist/harness/inbox.js.map +1 -0
  83. package/dist/harness/json.d.ts +26 -0
  84. package/dist/harness/json.d.ts.map +1 -0
  85. package/dist/harness/json.js +51 -0
  86. package/dist/harness/json.js.map +1 -0
  87. package/dist/harness/live.d.ts +285 -0
  88. package/dist/harness/live.d.ts.map +1 -0
  89. package/dist/harness/live.js +257 -0
  90. package/dist/harness/live.js.map +1 -0
  91. package/dist/harness/parks.d.ts +23 -0
  92. package/dist/harness/parks.d.ts.map +1 -0
  93. package/dist/harness/parks.js +52 -0
  94. package/dist/harness/parks.js.map +1 -0
  95. package/dist/harness/partial-changes.d.ts +54 -0
  96. package/dist/harness/partial-changes.d.ts.map +1 -0
  97. package/dist/harness/partial-changes.js +163 -0
  98. package/dist/harness/partial-changes.js.map +1 -0
  99. package/dist/harness/prompt.d.ts +27 -0
  100. package/dist/harness/prompt.d.ts.map +1 -0
  101. package/dist/harness/prompt.js +131 -0
  102. package/dist/harness/prompt.js.map +1 -0
  103. package/dist/harness/provider.d.ts +16 -0
  104. package/dist/harness/provider.d.ts.map +1 -0
  105. package/dist/harness/provider.js +33 -0
  106. package/dist/harness/provider.js.map +1 -0
  107. package/dist/harness/registry-reader.d.ts +11 -0
  108. package/dist/harness/registry-reader.d.ts.map +1 -0
  109. package/dist/harness/registry-reader.js +25 -0
  110. package/dist/harness/registry-reader.js.map +1 -0
  111. package/dist/harness/registry.d.ts +6 -0
  112. package/dist/harness/registry.d.ts.map +1 -0
  113. package/dist/harness/registry.js +101 -0
  114. package/dist/harness/registry.js.map +1 -0
  115. package/dist/harness/scheduler.d.ts +195 -0
  116. package/dist/harness/scheduler.d.ts.map +1 -0
  117. package/dist/harness/scheduler.js +3073 -0
  118. package/dist/harness/scheduler.js.map +1 -0
  119. package/dist/harness/submissions.d.ts +44 -0
  120. package/dist/harness/submissions.d.ts.map +1 -0
  121. package/dist/harness/submissions.js +265 -0
  122. package/dist/harness/submissions.js.map +1 -0
  123. package/dist/harness/task-graph.d.ts +75 -0
  124. package/dist/harness/task-graph.d.ts.map +1 -0
  125. package/dist/harness/task-graph.js +224 -0
  126. package/dist/harness/task-graph.js.map +1 -0
  127. package/dist/harness/telemetry.d.ts +307 -0
  128. package/dist/harness/telemetry.d.ts.map +1 -0
  129. package/dist/harness/telemetry.js +140 -0
  130. package/dist/harness/telemetry.js.map +1 -0
  131. package/dist/harness/tool.d.ts +106 -0
  132. package/dist/harness/tool.d.ts.map +1 -0
  133. package/dist/harness/tool.js +1182 -0
  134. package/dist/harness/tool.js.map +1 -0
  135. package/dist/harness/transcript.d.ts +72 -0
  136. package/dist/harness/transcript.d.ts.map +1 -0
  137. package/dist/harness/transcript.js +264 -0
  138. package/dist/harness/transcript.js.map +1 -0
  139. package/dist/harness/types.d.ts +1146 -0
  140. package/dist/harness/types.d.ts.map +1 -0
  141. package/dist/harness/types.js +2 -0
  142. package/dist/harness/types.js.map +1 -0
  143. package/dist/harness/usage.d.ts +19 -0
  144. package/dist/harness/usage.d.ts.map +1 -0
  145. package/dist/harness/usage.js +57 -0
  146. package/dist/harness/usage.js.map +1 -0
  147. package/dist/harness/util.d.ts +25 -0
  148. package/dist/harness/util.d.ts.map +1 -0
  149. package/dist/harness/util.js +76 -0
  150. package/dist/harness/util.js.map +1 -0
  151. package/dist/harness/view.d.ts +69 -0
  152. package/dist/harness/view.d.ts.map +1 -0
  153. package/dist/harness/view.js +265 -0
  154. package/dist/harness/view.js.map +1 -0
  155. package/dist/ids.d.ts +6 -0
  156. package/dist/ids.d.ts.map +1 -0
  157. package/dist/ids.js +9 -0
  158. package/dist/ids.js.map +1 -0
  159. package/dist/images/cloudflare.d.ts +4 -0
  160. package/dist/images/cloudflare.d.ts.map +1 -0
  161. package/dist/images/cloudflare.js +9 -0
  162. package/dist/images/cloudflare.js.map +1 -0
  163. package/dist/images/exif.d.ts +3 -0
  164. package/dist/images/exif.d.ts.map +1 -0
  165. package/dist/images/exif.js +71 -0
  166. package/dist/images/exif.js.map +1 -0
  167. package/dist/images/fit.d.ts +41 -0
  168. package/dist/images/fit.d.ts.map +1 -0
  169. package/dist/images/fit.js +108 -0
  170. package/dist/images/fit.js.map +1 -0
  171. package/dist/images/index.d.ts +18 -0
  172. package/dist/images/index.d.ts.map +1 -0
  173. package/dist/images/index.js +125 -0
  174. package/dist/images/index.js.map +1 -0
  175. package/dist/images/node-worker.d.ts +19 -0
  176. package/dist/images/node-worker.d.ts.map +1 -0
  177. package/dist/images/node-worker.js +17 -0
  178. package/dist/images/node-worker.js.map +1 -0
  179. package/dist/images/node.d.ts +21 -0
  180. package/dist/images/node.d.ts.map +1 -0
  181. package/dist/images/node.js +121 -0
  182. package/dist/images/node.js.map +1 -0
  183. package/dist/index.d.ts +29 -0
  184. package/dist/index.d.ts.map +1 -0
  185. package/dist/index.js +23 -0
  186. package/dist/index.js.map +1 -0
  187. package/dist/search.d.ts +29 -0
  188. package/dist/search.d.ts.map +1 -0
  189. package/dist/search.js +148 -0
  190. package/dist/search.js.map +1 -0
  191. package/dist/session/cached-storage.d.ts +72 -0
  192. package/dist/session/cached-storage.d.ts.map +1 -0
  193. package/dist/session/cached-storage.js +269 -0
  194. package/dist/session/cached-storage.js.map +1 -0
  195. package/dist/session/conversation-tails.d.ts +33 -0
  196. package/dist/session/conversation-tails.d.ts.map +1 -0
  197. package/dist/session/conversation-tails.js +101 -0
  198. package/dist/session/conversation-tails.js.map +1 -0
  199. package/dist/session/forks.d.ts +10 -0
  200. package/dist/session/forks.d.ts.map +1 -0
  201. package/dist/session/forks.js +42 -0
  202. package/dist/session/forks.js.map +1 -0
  203. package/dist/session/keys.d.ts +69 -0
  204. package/dist/session/keys.d.ts.map +1 -0
  205. package/dist/session/keys.js +161 -0
  206. package/dist/session/keys.js.map +1 -0
  207. package/dist/session/session.d.ts +287 -0
  208. package/dist/session/session.d.ts.map +1 -0
  209. package/dist/session/session.js +1701 -0
  210. package/dist/session/session.js.map +1 -0
  211. package/dist/session/transaction.d.ts +205 -0
  212. package/dist/session/transaction.d.ts.map +1 -0
  213. package/dist/session/transaction.js +1059 -0
  214. package/dist/session/transaction.js.map +1 -0
  215. package/dist/session/writer.d.ts +74 -0
  216. package/dist/session/writer.d.ts.map +1 -0
  217. package/dist/session/writer.js +294 -0
  218. package/dist/session/writer.js.map +1 -0
  219. package/dist/signals.d.ts +180 -0
  220. package/dist/signals.d.ts.map +1 -0
  221. package/dist/signals.js +236 -0
  222. package/dist/signals.js.map +1 -0
  223. package/dist/storage/indexeddb.d.ts +69 -0
  224. package/dist/storage/indexeddb.d.ts.map +1 -0
  225. package/dist/storage/indexeddb.js +883 -0
  226. package/dist/storage/indexeddb.js.map +1 -0
  227. package/dist/storage/jsonl/index.d.ts +2 -0
  228. package/dist/storage/jsonl/index.d.ts.map +1 -0
  229. package/dist/storage/jsonl/index.js +2 -0
  230. package/dist/storage/jsonl/index.js.map +1 -0
  231. package/dist/storage/jsonl/node.d.ts +6 -0
  232. package/dist/storage/jsonl/node.d.ts.map +1 -0
  233. package/dist/storage/jsonl/node.js +8 -0
  234. package/dist/storage/jsonl/node.js.map +1 -0
  235. package/dist/storage/jsonl/storage.d.ts +206 -0
  236. package/dist/storage/jsonl/storage.d.ts.map +1 -0
  237. package/dist/storage/jsonl/storage.js +799 -0
  238. package/dist/storage/jsonl/storage.js.map +1 -0
  239. package/dist/storage/memory.d.ts +68 -0
  240. package/dist/storage/memory.d.ts.map +1 -0
  241. package/dist/storage/memory.js +761 -0
  242. package/dist/storage/memory.js.map +1 -0
  243. package/dist/storage/scan.d.ts +18 -0
  244. package/dist/storage/scan.d.ts.map +1 -0
  245. package/dist/storage/scan.js +29 -0
  246. package/dist/storage/scan.js.map +1 -0
  247. package/dist/storage/sqlite/cloudflare.d.ts +9 -0
  248. package/dist/storage/sqlite/cloudflare.d.ts.map +1 -0
  249. package/dist/storage/sqlite/cloudflare.js +11 -0
  250. package/dist/storage/sqlite/cloudflare.js.map +1 -0
  251. package/dist/storage/sqlite/commit.d.ts +52 -0
  252. package/dist/storage/sqlite/commit.d.ts.map +1 -0
  253. package/dist/storage/sqlite/commit.js +371 -0
  254. package/dist/storage/sqlite/commit.js.map +1 -0
  255. package/dist/storage/sqlite/database.d.ts +2 -0
  256. package/dist/storage/sqlite/database.d.ts.map +1 -0
  257. package/dist/storage/sqlite/database.js +2 -0
  258. package/dist/storage/sqlite/database.js.map +1 -0
  259. package/dist/storage/sqlite/index.d.ts +4 -0
  260. package/dist/storage/sqlite/index.d.ts.map +1 -0
  261. package/dist/storage/sqlite/index.js +3 -0
  262. package/dist/storage/sqlite/index.js.map +1 -0
  263. package/dist/storage/sqlite/migrations.d.ts +12 -0
  264. package/dist/storage/sqlite/migrations.d.ts.map +1 -0
  265. package/dist/storage/sqlite/migrations.js +121 -0
  266. package/dist/storage/sqlite/migrations.js.map +1 -0
  267. package/dist/storage/sqlite/node.d.ts +8 -0
  268. package/dist/storage/sqlite/node.d.ts.map +1 -0
  269. package/dist/storage/sqlite/node.js +12 -0
  270. package/dist/storage/sqlite/node.js.map +1 -0
  271. package/dist/storage/sqlite/rows.d.ts +33 -0
  272. package/dist/storage/sqlite/rows.d.ts.map +1 -0
  273. package/dist/storage/sqlite/rows.js +53 -0
  274. package/dist/storage/sqlite/rows.js.map +1 -0
  275. package/dist/storage/sqlite/schema.d.ts +45 -0
  276. package/dist/storage/sqlite/schema.d.ts.map +1 -0
  277. package/dist/storage/sqlite/schema.js +50 -0
  278. package/dist/storage/sqlite/schema.js.map +1 -0
  279. package/dist/storage/sqlite/statements.d.ts +13 -0
  280. package/dist/storage/sqlite/statements.d.ts.map +1 -0
  281. package/dist/storage/sqlite/statements.js +88 -0
  282. package/dist/storage/sqlite/statements.js.map +1 -0
  283. package/dist/storage/sqlite/storage.d.ts +86 -0
  284. package/dist/storage/sqlite/storage.d.ts.map +1 -0
  285. package/dist/storage/sqlite/storage.js +534 -0
  286. package/dist/storage/sqlite/storage.js.map +1 -0
  287. package/dist/storage/store/commit.d.ts +33 -0
  288. package/dist/storage/store/commit.d.ts.map +1 -0
  289. package/dist/storage/store/commit.js +286 -0
  290. package/dist/storage/store/commit.js.map +1 -0
  291. package/dist/storage/store/documents.d.ts +43 -0
  292. package/dist/storage/store/documents.d.ts.map +1 -0
  293. package/dist/storage/store/documents.js +102 -0
  294. package/dist/storage/store/documents.js.map +1 -0
  295. package/dist/storage/store/index.d.ts +2 -0
  296. package/dist/storage/store/index.d.ts.map +1 -0
  297. package/dist/storage/store/index.js +2 -0
  298. package/dist/storage/store/index.js.map +1 -0
  299. package/dist/storage/store/queries.d.ts +49 -0
  300. package/dist/storage/store/queries.d.ts.map +1 -0
  301. package/dist/storage/store/queries.js +93 -0
  302. package/dist/storage/store/queries.js.map +1 -0
  303. package/dist/storage/store/storage.d.ts +60 -0
  304. package/dist/storage/store/storage.d.ts.map +1 -0
  305. package/dist/storage/store/storage.js +438 -0
  306. package/dist/storage/store/storage.js.map +1 -0
  307. package/dist/storage/store/tables.d.ts +54 -0
  308. package/dist/storage/store/tables.d.ts.map +1 -0
  309. package/dist/storage/store/tables.js +108 -0
  310. package/dist/storage/store/tables.js.map +1 -0
  311. package/dist/tasks.d.ts +6 -0
  312. package/dist/tasks.d.ts.map +1 -0
  313. package/dist/tasks.js +5 -0
  314. package/dist/tasks.js.map +1 -0
  315. package/dist/testing/assertions.d.ts +5 -0
  316. package/dist/testing/assertions.d.ts.map +1 -0
  317. package/dist/testing/assertions.js +25 -0
  318. package/dist/testing/assertions.js.map +1 -0
  319. package/dist/testing/commit-writes.d.ts +5 -0
  320. package/dist/testing/commit-writes.d.ts.map +1 -0
  321. package/dist/testing/commit-writes.js +12 -0
  322. package/dist/testing/commit-writes.js.map +1 -0
  323. package/dist/testing/env-conformance.d.ts +7 -0
  324. package/dist/testing/env-conformance.d.ts.map +1 -0
  325. package/dist/testing/env-conformance.js +531 -0
  326. package/dist/testing/env-conformance.js.map +1 -0
  327. package/dist/testing/index.d.ts +8 -0
  328. package/dist/testing/index.d.ts.map +1 -0
  329. package/dist/testing/index.js +7 -0
  330. package/dist/testing/index.js.map +1 -0
  331. package/dist/testing/runner.d.ts +12 -0
  332. package/dist/testing/runner.d.ts.map +1 -0
  333. package/dist/testing/runner.js +23 -0
  334. package/dist/testing/runner.js.map +1 -0
  335. package/dist/testing/storage-benchmark.d.ts +41 -0
  336. package/dist/testing/storage-benchmark.d.ts.map +1 -0
  337. package/dist/testing/storage-benchmark.js +351 -0
  338. package/dist/testing/storage-benchmark.js.map +1 -0
  339. package/dist/testing/storage-conformance.d.ts +4 -0
  340. package/dist/testing/storage-conformance.d.ts.map +1 -0
  341. package/dist/testing/storage-conformance.js +1554 -0
  342. package/dist/testing/storage-conformance.js.map +1 -0
  343. package/dist/testing/types.d.ts +39 -0
  344. package/dist/testing/types.d.ts.map +1 -0
  345. package/dist/testing/types.js +2 -0
  346. package/dist/testing/types.js.map +1 -0
  347. package/dist/timers.d.ts +21 -0
  348. package/dist/timers.d.ts.map +1 -0
  349. package/dist/timers.js +72 -0
  350. package/dist/timers.js.map +1 -0
  351. package/dist/tool-search/index.d.ts +2 -0
  352. package/dist/tool-search/index.d.ts.map +1 -0
  353. package/dist/tool-search/index.js +2 -0
  354. package/dist/tool-search/index.js.map +1 -0
  355. package/dist/tool-search/tool-search.d.ts +17 -0
  356. package/dist/tool-search/tool-search.d.ts.map +1 -0
  357. package/dist/tool-search/tool-search.js +96 -0
  358. package/dist/tool-search/tool-search.js.map +1 -0
  359. package/dist/tools/bash.d.ts +55 -0
  360. package/dist/tools/bash.d.ts.map +1 -0
  361. package/dist/tools/bash.js +139 -0
  362. package/dist/tools/bash.js.map +1 -0
  363. package/dist/tools/edit-diff.d.ts +89 -0
  364. package/dist/tools/edit-diff.d.ts.map +1 -0
  365. package/dist/tools/edit-diff.js +386 -0
  366. package/dist/tools/edit-diff.js.map +1 -0
  367. package/dist/tools/edit.d.ts +18 -0
  368. package/dist/tools/edit.d.ts.map +1 -0
  369. package/dist/tools/edit.js +117 -0
  370. package/dist/tools/edit.js.map +1 -0
  371. package/dist/tools/env.d.ts +5 -0
  372. package/dist/tools/env.d.ts.map +1 -0
  373. package/dist/tools/env.js +7 -0
  374. package/dist/tools/env.js.map +1 -0
  375. package/dist/tools/file-mutation-queue.d.ts +9 -0
  376. package/dist/tools/file-mutation-queue.d.ts.map +1 -0
  377. package/dist/tools/file-mutation-queue.js +52 -0
  378. package/dist/tools/file-mutation-queue.js.map +1 -0
  379. package/dist/tools/image-processor.d.ts +57 -0
  380. package/dist/tools/image-processor.d.ts.map +1 -0
  381. package/dist/tools/image-processor.js +49 -0
  382. package/dist/tools/image-processor.js.map +1 -0
  383. package/dist/tools/image.d.ts +20 -0
  384. package/dist/tools/image.d.ts.map +1 -0
  385. package/dist/tools/image.js +178 -0
  386. package/dist/tools/image.js.map +1 -0
  387. package/dist/tools/index.d.ts +46 -0
  388. package/dist/tools/index.d.ts.map +1 -0
  389. package/dist/tools/index.js +23 -0
  390. package/dist/tools/index.js.map +1 -0
  391. package/dist/tools/path-utils.d.ts +5 -0
  392. package/dist/tools/path-utils.d.ts.map +1 -0
  393. package/dist/tools/path-utils.js +26 -0
  394. package/dist/tools/path-utils.js.map +1 -0
  395. package/dist/tools/read.d.ts +30 -0
  396. package/dist/tools/read.d.ts.map +1 -0
  397. package/dist/tools/read.js +239 -0
  398. package/dist/tools/read.js.map +1 -0
  399. package/dist/tools/write.d.ts +10 -0
  400. package/dist/tools/write.d.ts.map +1 -0
  401. package/dist/tools/write.js +31 -0
  402. package/dist/tools/write.js.map +1 -0
  403. package/dist/truncate.d.ts +65 -0
  404. package/dist/truncate.d.ts.map +1 -0
  405. package/dist/truncate.js +124 -0
  406. package/dist/truncate.js.map +1 -0
  407. package/dist/types.d.ts +1244 -0
  408. package/dist/types.d.ts.map +1 -0
  409. package/dist/types.js +3 -0
  410. package/dist/types.js.map +1 -0
  411. package/package.json +179 -5
@@ -0,0 +1,1701 @@
1
+ import { awaitWithContext, BACKGROUND_CONTEXT, withoutAbortSignal } from "@diffra-ai/chord/context";
2
+ import { PendingOps, track } from "@diffra-ai/chord/delta";
3
+ import { Watch } from "@diffra-ai/chord/watch";
4
+ import { addressId, checkRecordScope, checkRecordVersion, materializeDocument, resolveAddress, } from "../documents.js";
5
+ import { ReadOnlySession, SessionFailed, StorageRequestError } from "../errors.js";
6
+ import { idFromNumber } from "../ids.js";
7
+ import { hostTimers } from "../timers.js";
8
+ import { CachedStorage, scopeOf } from "./cached-storage.js";
9
+ import { ConversationTails } from "./conversation-tails.js";
10
+ import { ALL_KEYS, appendKey, conversationKey, documentKey, GatedStorage, incarnationKey } from "./keys.js";
11
+ import { storeHeld, Transaction, } from "./transaction.js";
12
+ import { Writer } from "./writer.js";
13
+ const NO_HOLDS = [];
14
+ const NO_OPERATIONS = [];
15
+ const NO_KEYS = [];
16
+ /**
17
+ * Jobs admitted to the line whose outcome is not delivered yet, beyond which the line waits. A count, not bytes: what
18
+ * waits is bounded by what one commit can hold (tool output by its output limits), times the count.
19
+ */
20
+ const MAX_OUTSTANDING = 256;
21
+ const ignore = () => { };
22
+ /**
23
+ * Queues a commit's host dispatch as one microtask through `then`: in the same queue as `queueMicrotask()`, which Node
24
+ * wraps in an async resource that costs about twice the memory and three times the time per stored commit.
25
+ */
26
+ const SETTLED = Promise.resolve();
27
+ /** The default source of a report: a listener, which never fails what ran it. */
28
+ const LISTENER = { kind: "listener_error" };
29
+ /** A telemetry adapter that threw on a commit's event, which must not fail the durable commit. */
30
+ const TELEMETRY = { kind: "host_error", callback: "telemetry" };
31
+ /**
32
+ * Open a Session kernel over one storage backend. `now` is the wall clock for task times; default `Date.now`.
33
+ * `setTimer` arms the timers that evict idle documents; default `setTimeout` (see `HarnessOptions.setTimer`). The first
34
+ * error a Storage method throws fails the Session (`SessionFailed`); see `SessionImpl`.
35
+ */
36
+ export function createSession(storage, options) {
37
+ const retention = options?.documentRetentionMs;
38
+ const within = options?.persistWithinMs;
39
+ return new SessionImpl(storage, options?.now, retention === undefined ? undefined : () => retention, options?.setTimer, false, () => within);
40
+ }
41
+ /** Default document retention: ten minutes, as for kept contexts. */
42
+ let defaultRetention = 600_000;
43
+ /** Internal, for tests: the retention of every Session that keeps the default, as a suite run with eviction at once. */
44
+ export function setDefaultDocumentRetention(ms) {
45
+ defaultRetention = ms;
46
+ }
47
+ /**
48
+ * A retention as given, when it is a number of milliseconds, `0` or more (`Infinity` keeps documents); otherwise the
49
+ * default.
50
+ */
51
+ export function documentRetention(ms) {
52
+ return typeof ms === "number" && ms >= 0 ? ms : defaultRetention;
53
+ }
54
+ /** Default `withinMs` of a deferred commit, `settings.progress.persistWithinMs`. */
55
+ const DEFAULT_PERSIST_WITHIN_MS = 1_000;
56
+ /**
57
+ * A deferred commit's default window as given, when it is a number of milliseconds, `0` or more (`Infinity` waits for a
58
+ * reading or writing commit or close); otherwise the default.
59
+ */
60
+ export function persistWithin(ms) {
61
+ return typeof ms === "number" && ms >= 0 ? ms : DEFAULT_PERSIST_WITHIN_MS;
62
+ }
63
+ /**
64
+ * Session kernel: one mutation line, the loaded document tracker cache, and committed publication.
65
+ *
66
+ * The cache is bounded by use: a document with no watch attached leaves it once it was not read or
67
+ * written for the retention period, and the next access loads it from Storage. Eviction runs as a job on the mutation
68
+ * line, so no transaction ever holds a tracker that leaves.
69
+ *
70
+ * Only committed state is observable. A deferred commit (`CommitPersistence`) is committed in memory first: it is
71
+ * adopted and shown to the Session's own observers, and its changes wait, folded per document and pinned in the cache,
72
+ * for the first commit that reads or writes the document, the document's deadline, a drop of its tracker, or close,
73
+ * which store them.
74
+ *
75
+ * Group commit: the line runs one job at a time, a commit's callback and settlement; a commit with writes then joins
76
+ * the writer's pending batch (logical admission, `Writer`) and the line goes on. The writer stores every commit admitted
77
+ * while no call is in flight in one `commit()` call, off the line, and publishes them one by one, in line order, a
78
+ * macrotask apart: the read caches, adoption, telemetry events, the Session's own observers, and one microtask later
79
+ * `observeCommits()` observers, before every wait the commit resolves and every abort it queues. Host listeners and
80
+ * watch listeners have no order. A deferred commit is published when the commits before it are. A job's every read
81
+ * touches its key (`touch()`); while an unpublished commit writes that key, the job waits for its publication, so no
82
+ * job observes state that is not stored. Outcomes are delivered in line order (`#enqueue()`).
83
+ *
84
+ * Storage failures are final. Every Storage call goes through one guard: the first error a Storage method throws, other
85
+ * than for a cancelled caller, fails the Session, as does a commit it cannot adopt. That call gets the error; every later
86
+ * call and every Storage call still underway gets `SessionFailed`; close listeners run at once with the error, and the
87
+ * Session then closes itself, Storage included, and `closed` settles. Nothing retries: transient errors are the
88
+ * Storage's to retry. Reopening recovers from what was committed.
89
+ */
90
+ export class SessionImpl {
91
+ #storage;
92
+ /** Newest entry and head marker per conversation; none for a read-only Session, whose Storage another process writes. */
93
+ #tails;
94
+ /**
95
+ * The current documents of each live task this Session created, so the commit that ends a task retires them without
96
+ * a scan. An entry starts with its task's creation and goes when the task is terminal: bounded by live tasks.
97
+ */
98
+ #taskDocuments = new Map();
99
+ #documents = new Map();
100
+ /** Cached documents with no observer attached, by address, oldest use first, with the time of that use. */
101
+ #idleDocuments = new Map();
102
+ /** Observers attached per document incarnation (record ID); a cached incarnation with any is never evicted. */
103
+ #attachedDocuments = new Map();
104
+ #clock;
105
+ #documentRetentionMs;
106
+ #persistWithinMs;
107
+ /** Documents with held changes, by incarnation (record ID); each is pinned in the cache until they are stored. */
108
+ #holds = new Map();
109
+ #holdTimer;
110
+ /** Refuse every commit with writes (`HarnessOptions.readOnly`). */
111
+ #readOnly;
112
+ #timers;
113
+ /** The pending eviction: a timer for the oldest idle document, or a line job when the retention is 0. */
114
+ #documentSweep;
115
+ #sweepJobs = 0;
116
+ /** Set once the host declined a background timer: then none is kept, and the end of each commit evicts what expired. */
117
+ #documentTimersUnavailable = false;
118
+ /** Host commit observers (`observeCommits()`), each behind `guardObserver()`. */
119
+ #commitListeners = new Set();
120
+ /** The Session's own listeners, such as its scheduler's: they keep memory in step with storage, so a throw fails it. */
121
+ #internalListeners = new Set();
122
+ #closeListeners = new Set();
123
+ #host;
124
+ /** The record cache under the guard, which the writer applies each batch to at its publication. */
125
+ #cached;
126
+ #writer;
127
+ /** The Storage jobs on the line read through: each read waits while its key has an unpublished writer. */
128
+ #gated;
129
+ /** The end of the last line job: the line runs one job at a time. */
130
+ #tail = Promise.resolve();
131
+ /** Line index of the next job; outcomes are delivered in this order. */
132
+ #nextIndex = 0;
133
+ /** The job on the line, while one runs: its index, and whether it waited at a gate. */
134
+ #current;
135
+ /** Settles once every job so far has its outcome delivered. */
136
+ #fence = Promise.resolve();
137
+ #lastDelivered = -1;
138
+ /** Jobs that started on the line and have no outcome delivered yet (`MAX_OUTSTANDING`). */
139
+ #outstanding = 0;
140
+ #room;
141
+ /** The line index whose outcome the failure is: every later job's outcome is `SessionFailed`, except `#ownOutcomes`. */
142
+ #failAt;
143
+ /** Later jobs whose outcome is their own error all the same: the other parts of a storage call that rejected. */
144
+ #ownOutcomes = new Set();
145
+ #closing;
146
+ #failure;
147
+ /** Set when close reaches the backend: calls that fail from then on fail because it closes. */
148
+ #failed = Promise.withResolvers();
149
+ #closed = Promise.withResolvers();
150
+ get closed() {
151
+ return this.#closed.promise;
152
+ }
153
+ /** Internal: the error that failed the Session, if one did. */
154
+ get failure() {
155
+ return this.#failure;
156
+ }
157
+ /** Internal: rejects with `SessionFailed` the moment the Session fails, before work underway has ended; never resolves. */
158
+ get failed() {
159
+ return this.#failed.promise;
160
+ }
161
+ constructor(storage, now = Date.now, documentRetentionMs = () => undefined, setTimer, readOnly = false, persistWithinMs = () => undefined) {
162
+ // Waits race it; none has to.
163
+ this.#failed.promise.catch(() => { });
164
+ this.#readOnly = readOnly;
165
+ // A read-only Session shows a Storage another process writes, so nothing it reads stays current.
166
+ this.#cached = readOnly ? undefined : new CachedStorage(storage);
167
+ this.#storage = new GuardedStorage(this.#cached ?? storage, this);
168
+ this.#gated = new GatedStorage(this.#storage, (key) => this.touch(key));
169
+ this.#writer = new Writer({
170
+ commit: (batches, receive, context) => this.#storage.commit(batches, receive, context),
171
+ stored: (writes) => {
172
+ this.#cached?.published(writes);
173
+ this.#tails?.apply(writes);
174
+ },
175
+ publishing: (publish, context) => this.#publishing(publish, context),
176
+ failure: () => this.#failure,
177
+ fail: (error, at, own) => this.fail(error, undefined, at, own),
178
+ report: (error, context) => this.report(error, LISTENER, context),
179
+ });
180
+ this.#tails = readOnly ? undefined : new ConversationTails();
181
+ this.#timers = hostTimers(setTimer, (error) => this.report(error, { kind: "host_error", callback: "setTimer" }));
182
+ // Cache bookkeeping must never change the outcome of the operation it follows: a clock or a retention setting
183
+ // that throws counts as now, and as the default.
184
+ this.#clock = () => {
185
+ try {
186
+ return now();
187
+ }
188
+ catch {
189
+ return Date.now();
190
+ }
191
+ };
192
+ this.#documentRetentionMs = () => {
193
+ try {
194
+ return documentRetention(documentRetentionMs());
195
+ }
196
+ catch {
197
+ return documentRetention(undefined);
198
+ }
199
+ };
200
+ this.#persistWithinMs = () => {
201
+ try {
202
+ return persistWithin(persistWithinMs());
203
+ }
204
+ catch {
205
+ return persistWithin(undefined);
206
+ }
207
+ };
208
+ this.#host = {
209
+ storage: this.#gated,
210
+ touch: (key) => this.touch(key),
211
+ now,
212
+ cached: (id) => {
213
+ const cached = this.#documents.get(id);
214
+ if (cached !== undefined)
215
+ this.#touchDocument(id);
216
+ return cached;
217
+ },
218
+ load: (definition, addressId, address, context) => this.#loadDocument(definition, addressId, address, context),
219
+ install: (document) => {
220
+ this.#documents.set(document.addressId, document);
221
+ this.#touchDocument(document.addressId);
222
+ },
223
+ evict: (id, recordId) => {
224
+ if (this.#documents.get(id)?.record.id === recordId)
225
+ this.#dropDocument(id);
226
+ },
227
+ conversationCreated: (tx, record) => this.conversationCreated(tx, record),
228
+ taskDocuments: (taskId) => this.#taskDocuments.get(taskId)?.values(),
229
+ latestEntryId: (conversationId, context) => this.latestEntryId(conversationId, context),
230
+ latestHeadMarker: (conversationId, context) => this.latestHeadMarker(conversationId, undefined, context),
231
+ };
232
+ }
233
+ /** The Storage behind the failure guard; every component reads and writes through it. */
234
+ get storage() {
235
+ return this.#storage;
236
+ }
237
+ /**
238
+ * Internal, on the Session line: the newest entry ID visible from `conversationId`. Known from the Session's own
239
+ * commits when it owns its Storage, so it costs no Storage read after the first.
240
+ */
241
+ latestEntryId(conversationId, context) {
242
+ const gate = this.#touchEntries(conversationId);
243
+ const latest = () => {
244
+ const read = async () => (await this.#storage.scanEntries({ conversationId }, 1, undefined, context)).items[0]?.id;
245
+ return this.#tails === undefined ? read() : this.#tails.latest(conversationId, read);
246
+ };
247
+ return gate === undefined ? latest() : gate.then(latest);
248
+ }
249
+ /**
250
+ * Internal: the newest entry ID of `conversationId` as known from the Session's commits right now, without reading;
251
+ * `undefined` when not known (and always for a read-only Session).
252
+ */
253
+ knownLatestEntryId(conversationId) {
254
+ return this.#tails?.peek(conversationId);
255
+ }
256
+ /**
257
+ * Internal, on the Session line: the newest visible head marker of `conversationId` at or before `atOrBefore`, any
258
+ * when `undefined`; known from the Session's own commits as `latestEntryId()` is.
259
+ */
260
+ latestHeadMarker(conversationId, atOrBefore, context) {
261
+ const gate = this.#touchEntries(conversationId);
262
+ const marker = () => {
263
+ const read = () => this.#storage.findLatestHeadMarker(conversationId, atOrBefore, context);
264
+ return this.#tails === undefined ? read() : this.#tails.marker(conversationId, atOrBefore, read);
265
+ };
266
+ return gate === undefined ? marker() : gate.then(marker);
267
+ }
268
+ /**
269
+ * On the line: wait for what an unpublished commit wrote of a conversation's entries, its appends and its creation,
270
+ * as reading them from Storage fails for a conversation not stored yet.
271
+ */
272
+ #touchEntries(conversationId) {
273
+ const created = this.touch(conversationKey(conversationId));
274
+ const appended = this.touch(appendKey(conversationId));
275
+ if (created === undefined)
276
+ return appended;
277
+ return appended === undefined ? created : Promise.all([created, appended]).then(ignore);
278
+ }
279
+ /**
280
+ * Internal, on the line: wait, while `key` has an unpublished writer (for `ALL_KEYS`, while anything is unpublished),
281
+ * until it is published, then check that the Session is healthy; `undefined` when there is nothing to wait for. A
282
+ * job's every read touches its key first, so it never observes state an earlier job admitted and the writer has not
283
+ * published.
284
+ */
285
+ touch(key) {
286
+ const gate = key === ALL_KEYS ? this.#writer.drained() : this.#writer.gate(key);
287
+ if (gate === undefined)
288
+ return undefined;
289
+ if (this.#current !== undefined)
290
+ this.#current.hit = true;
291
+ return gate.then(() => this.#assertHealthy());
292
+ }
293
+ commit(change, context, options) {
294
+ return this.commitWith(change, context, undefined, options);
295
+ }
296
+ /**
297
+ * Internal: fail the Session with `error`, the first wins, and report it once. Admission ends, and close listeners run
298
+ * now; they read the error from `failure`. The Storage guard calls this; the Harness also calls it for a throw in its
299
+ * scheduler's own commits. `at` is the line index of the job whose outcome the failure is, by default the job on the
300
+ * line: later jobs' outcomes become `SessionFailed`.
301
+ */
302
+ fail(error, context, at, own) {
303
+ if (this.#failure !== undefined)
304
+ return;
305
+ this.#failure = { error };
306
+ // The job that caused it keeps its own outcome; without one, every outcome not delivered yet is `SessionFailed`.
307
+ this.#failAt = at ?? this.#current?.index ?? this.#lastDelivered;
308
+ if (own !== undefined)
309
+ for (const index of own)
310
+ this.#ownOutcomes.add(index);
311
+ this.#failed.reject(new SessionFailed(error));
312
+ // Seal first, so a report handler that calls back finds the Session failed. Closing runs the close listeners
313
+ // synchronously; a failing backend close is the caller's to see, and here nobody waits.
314
+ this.close(BACKGROUND_CONTEXT).catch(() => { });
315
+ this.report(error, { kind: "storage_failed" }, context);
316
+ }
317
+ /**
318
+ * Internal commit exposing the concrete transaction and its internal operations, such as the reserved-ID root
319
+ * bootstrap and task replacement. `scope` sets the default `tx.createTask()` conversation and the task attributed to
320
+ * appended entries.
321
+ */
322
+ commitWith(change, context, scope, options) {
323
+ let withinMs;
324
+ try {
325
+ this.assertUsable();
326
+ withinMs = this.#deferral(options?.persistence);
327
+ }
328
+ catch (error) {
329
+ return Promise.reject(error);
330
+ }
331
+ return this.#enqueue((index) => this.#runCommit(change, context, scope, withinMs, index));
332
+ }
333
+ /**
334
+ * Internal: `commitWith()` for a commit of the scheduler's own whose outcome goes only to scheduler code. When it
335
+ * writes nothing and waited at no gate, it is equivalent to having run before every unpublished commit, so its
336
+ * outcome is delivered at once, ahead of theirs. One that writes is never exempt: its outcome waits for its own
337
+ * publication and every earlier outcome, so no invocation starts on a reservation that is not durable.
338
+ */
339
+ commitInternal(change, context) {
340
+ try {
341
+ this.assertUsable();
342
+ }
343
+ catch (error) {
344
+ return Promise.reject(error);
345
+ }
346
+ return this.#enqueue((index) => this.#runCommit(change, context, undefined, undefined, index), true);
347
+ }
348
+ /**
349
+ * Internal, on the line: call `end` once the outcome of the job on the line settles, its commit published or never to
350
+ * be; at once off the line.
351
+ */
352
+ onJobEnd(end) {
353
+ const job = this.#current;
354
+ if (job === undefined) {
355
+ end();
356
+ return;
357
+ }
358
+ if (job.ends === undefined)
359
+ job.ends = [end];
360
+ else
361
+ job.ends.push(end);
362
+ }
363
+ /** Internal: the Storage jobs on the line read through (`touch()`); off the line, use the plain one. */
364
+ get lineStorage() {
365
+ return this.#gated;
366
+ }
367
+ /** How long a commit may stay in memory before it is stored; `undefined` when it is immediate. */
368
+ #deferral(persistence) {
369
+ if (persistence?.kind !== "deferred")
370
+ return undefined;
371
+ const ms = persistence.withinMs;
372
+ if (ms === undefined)
373
+ return this.#persistWithinMs();
374
+ // Public options: checked here, as the types cannot.
375
+ if (typeof ms !== "number" || !(ms >= 0)) {
376
+ throw new TypeError("CommitPersistence.withinMs must be a number of milliseconds, 0 or more");
377
+ }
378
+ return ms;
379
+ }
380
+ /** Internal: whether `tx` is the transaction of one of this Session's commits. */
381
+ ownsTransaction(tx) {
382
+ return Transaction.ownedBy(tx, this.#host);
383
+ }
384
+ /**
385
+ * Internal: run a read-only job on the mutation line so multi-read derivations observe one committed state. It reads
386
+ * through `storage`, whose reads wait for the publication of what the line admitted before; its outcome comes after
387
+ * theirs.
388
+ */
389
+ readOnLine(job) {
390
+ try {
391
+ this.assertUsable();
392
+ }
393
+ catch (error) {
394
+ return Promise.reject(error);
395
+ }
396
+ return this.#enqueue(async () => {
397
+ this.#assertHealthy();
398
+ return { value: await job(this.#gated) };
399
+ });
400
+ }
401
+ /**
402
+ * Internal: a conversation document's current incarnation and value, for a job already running on the line (see
403
+ * `readOnLine()`). Absent documents are `undefined`.
404
+ */
405
+ async conversationDocumentOnLine(token, conversationId, context) {
406
+ const definition = token.definition;
407
+ const resolved = resolveAddress(definition, [conversationId, context]);
408
+ const loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context);
409
+ if (loaded === undefined)
410
+ return undefined;
411
+ checkRecordScope(definition, loaded.record);
412
+ checkRecordVersion(definition, loaded.record, loaded.storedVersion);
413
+ return { record: loaded.record, version: loaded.valueVersion, value: loaded.tracker.value };
414
+ }
415
+ async snapshot(token, ...args) {
416
+ this.assertUsable();
417
+ const definition = token.definition;
418
+ const resolved = resolveAddress(definition, args);
419
+ const context = args[resolved.nextArgument];
420
+ const cached = this.#documents.get(resolved.id);
421
+ if (cached?.valueVersion === definition.version)
422
+ this.#touchDocument(resolved.id);
423
+ const loaded = cached?.valueVersion === definition.version
424
+ ? cached
425
+ : await this.#enqueue(async () => {
426
+ this.#assertHealthy();
427
+ return { value: await this.#loadDocument(definition, resolved.id, resolved.address, context) };
428
+ });
429
+ if (loaded === undefined)
430
+ return undefined;
431
+ checkRecordScope(definition, loaded.record);
432
+ checkRecordVersion(definition, loaded.record, loaded.storedVersion);
433
+ return loaded.tracker.value;
434
+ }
435
+ watchDoc(token, ...args) {
436
+ // Not async, so an attachment costs one async frame, `#attachDocument`'s; a throw here still rejects.
437
+ try {
438
+ this.assertUsable();
439
+ const definition = token.definition;
440
+ const resolved = resolveAddress(definition, args);
441
+ const context = args[resolved.nextArgument];
442
+ const signal = context.abortSignal;
443
+ return this.#attachDocument(definition, resolved, context, (loaded) => {
444
+ const watch = this.#observeDocument(definition, loaded, createWatch, endWatch);
445
+ if (signal !== undefined)
446
+ watch.observeAbort(signal);
447
+ return watch;
448
+ }, abortWatch);
449
+ }
450
+ catch (error) {
451
+ return Promise.reject(error);
452
+ }
453
+ }
454
+ observeDoc(token, ...args) {
455
+ // Not async, as `watchDoc()`; a throw here still rejects.
456
+ try {
457
+ this.assertUsable();
458
+ const definition = token.definition;
459
+ const resolved = resolveAddress(definition, args);
460
+ const observer = args[resolved.nextArgument];
461
+ const context = args[resolved.nextArgument + 1];
462
+ return this.#attachDocument(definition, resolved, context, (loaded) => {
463
+ const guarded = this.#observeDocument(definition, loaded, (_value, detach, report) => guardObserver(observer, detach, report), endGuarded);
464
+ return observation(loaded.tracker.value, guarded);
465
+ }, detachObservation);
466
+ }
467
+ catch (error) {
468
+ return Promise.reject(error);
469
+ }
470
+ }
471
+ async snapshotAsOf(token, ...args) {
472
+ this.assertUsable();
473
+ const definition = token.definition;
474
+ const resolved = resolveAddress(definition, args);
475
+ if (resolved.address.scope.kind !== "conversation") {
476
+ throw new TypeError("Session.snapshotAsOf() requires a conversation document");
477
+ }
478
+ const conversationId = resolved.address.scope.conversationId;
479
+ const atValue = args[resolved.nextArgument];
480
+ if (typeof atValue !== "number" || !Number.isSafeInteger(atValue)) {
481
+ throw new TypeError("Session.snapshotAsOf() requires an entry ID");
482
+ }
483
+ const at = idFromNumber(atValue);
484
+ const context = args[resolved.nextArgument + 1];
485
+ return this.#enqueue(async () => {
486
+ this.#assertHealthy();
487
+ const storedEntry = await this.#gated.entry(conversationId, at, context);
488
+ if (storedEntry === undefined) {
489
+ throw new Error(`Entry ${at} is not visible from conversation ${conversationId}`);
490
+ }
491
+ const address = {
492
+ ...resolved.address,
493
+ scope: { kind: "conversation", conversationId: storedEntry.entry.conversationId },
494
+ };
495
+ const record = await this.#gated.findDocument(address, storedEntry.commitSeq, context);
496
+ if (record === undefined)
497
+ return { value: undefined };
498
+ const stored = await this.#gated.document(record.id, storedEntry.commitSeq, context);
499
+ if (stored === undefined) {
500
+ throw new Error(`Historical document ${record.id} (${record.kind}) cannot be read`);
501
+ }
502
+ return { value: materializeDocument(definition, stored) };
503
+ });
504
+ }
505
+ close(context) {
506
+ if (this.#closing === undefined) {
507
+ const cleanup = withoutAbortSignal(context);
508
+ // Seal admission before anything else runs, then stop observers; admitted work settles before Storage closes.
509
+ this.#closing = Promise.resolve()
510
+ .then(() => this.beforeClose())
511
+ .then(() => this.#maintain(async () => {
512
+ await this.#drained();
513
+ // Last, after the writes at close (`writeAtClose()`), while the trackers are still here. A failed Session
514
+ // writes nothing; a failing store fails it, and the backend still closes.
515
+ let unstored;
516
+ // Only with something to store: otherwise the backend's close begins in this very job.
517
+ if (this.#failure === undefined && this.#holds.size > 0) {
518
+ await this.#storeHolds(() => [...this.#holds.values()], cleanup).catch((error) => {
519
+ unstored = { error };
520
+ });
521
+ }
522
+ const observers = [...this.#commitListeners];
523
+ this.#commitListeners.clear();
524
+ // After the last publication: the commits admitted before the seal have settled, held changes are stored.
525
+ // Commit observers are synchronous observers, all of them.
526
+ const end = closeEnds(this.#failure).observer;
527
+ for (const observer of observers)
528
+ observer.end(end);
529
+ this.#internalListeners.clear();
530
+ this.#documents.clear();
531
+ this.#idleDocuments.clear();
532
+ this.#attachedDocuments.clear();
533
+ this.#holds.clear();
534
+ this.#taskDocuments.clear();
535
+ try {
536
+ await this.#storage.close(cleanup);
537
+ }
538
+ catch (error) {
539
+ // A Storage that cannot close is a failed one; an earlier failure stays the cause.
540
+ if (this.#failure === undefined) {
541
+ this.#failure = { error };
542
+ this.report(error, { kind: "storage_failed" });
543
+ }
544
+ throw error;
545
+ }
546
+ if (unstored !== undefined)
547
+ throw unstored.error;
548
+ }))
549
+ .finally(() => {
550
+ const failure = this.#failure;
551
+ this.#closed.resolve(failure === undefined ? { kind: "closed" } : { kind: "failed", error: failure.error });
552
+ });
553
+ this.#notifyClose();
554
+ }
555
+ return awaitWithContext(this.#closing, context);
556
+ }
557
+ /** Run the close listeners once, each on its own: one that fails is reported, and the rest still run. */
558
+ #notifyClose() {
559
+ this.#documentSweep?.disarm?.();
560
+ this.#documentSweep = undefined;
561
+ this.#holdTimer?.disarm();
562
+ this.#holdTimer = undefined;
563
+ const listeners = [...this.#closeListeners];
564
+ this.#closeListeners.clear();
565
+ for (const listener of listeners)
566
+ contained(listener, (error) => this.report(error));
567
+ }
568
+ /**
569
+ * Internal: the Session's failure, and errors of listeners, which never fail what ran them; `info` defaults to a
570
+ * listener. A plain Session drops them.
571
+ */
572
+ report(_error, _info = LISTENER, _context) { }
573
+ /**
574
+ * Runs inside every transaction that creates or forks a conversation, after the conversation record is staged. A
575
+ * plain Session stages nothing; a Harness stages its built-in documents.
576
+ */
577
+ conversationCreated(_tx, _record) {
578
+ return Promise.resolve();
579
+ }
580
+ /**
581
+ * Internal, for `beforeClose()`: on the line, after every commit admitted before the seal has settled, write what
582
+ * `writes()` returns then straight to Storage. Nothing is published, since the Session is closing; a failed Session
583
+ * writes nothing.
584
+ */
585
+ writeAtClose(writes) {
586
+ return this.#maintain(async (index) => {
587
+ await this.#drained();
588
+ if (this.#failure !== undefined)
589
+ return;
590
+ const batch = writes();
591
+ if (batch.length === 0)
592
+ return;
593
+ const context = BACKGROUND_CONTEXT;
594
+ await this.#writer.admit({
595
+ index,
596
+ writes: batch,
597
+ keys: [],
598
+ context,
599
+ publish: () => undefined,
600
+ discard: ignore,
601
+ }).outcome;
602
+ });
603
+ }
604
+ /**
605
+ * Keys a commit writes besides its records' (`Transaction.writeKeys()`), at its admission, on the line: a Harness
606
+ * adds the ownership memberships its task changes write. A plain Session adds none.
607
+ */
608
+ membershipKeys(_tx) {
609
+ return NO_KEYS;
610
+ }
611
+ /** Runs after close seals admission and before the line closes Storage; must not reject. */
612
+ beforeClose() {
613
+ return Promise.resolve();
614
+ }
615
+ /**
616
+ * Attach a synchronous observer of every stored commit, with exactly what it stored (`CommitPublication`). Its
617
+ * `advance` runs one microtask after the commit's publication, which follows its storage call, in line order, before
618
+ * every wait the commit resolves and every abort it queues (in no order with watch listeners); it must not block or
619
+ * call Session operations. A throw is reported, detaches it, and ends it `listener_error`; `end` gets the Session's
620
+ * close after its last publication.
621
+ */
622
+ observeCommits(observer) {
623
+ this.assertUsable();
624
+ const guarded = guardObserver(observer, () => this.#commitListeners.delete(guarded), (error, context) => this.report(error, LISTENER, context));
625
+ this.#commitListeners.add(guarded);
626
+ return { detach: () => guarded.detach() };
627
+ }
628
+ /**
629
+ * Internal: follow every commit as memory adopts it (`ObservedCommit`), for the Session's own components, whose state
630
+ * follows memory. A throw leaves that state behind, so it fails the Session instead of being reported. They run at
631
+ * the commit's publication, synchronously, so they call no Storage method, run no task code, and contain every host
632
+ * callback; the waits they resolve and the aborts they queue run after host observers.
633
+ */
634
+ followCommits(listener) {
635
+ this.assertUsable();
636
+ this.#internalListeners.add(listener);
637
+ return () => this.#internalListeners.delete(listener);
638
+ }
639
+ /**
640
+ * Register a listener called synchronously when close begins, also when a failure closes the Session (`failure` is
641
+ * then set). It must not block or call Session operations; a throw is reported.
642
+ */
643
+ subscribeClose(listener) {
644
+ this.assertUsable();
645
+ this.#closeListeners.add(listener);
646
+ return () => this.#closeListeners.delete(listener);
647
+ }
648
+ /** Drop every loaded tracker on the mutation line, held changes stored first; later access cold-loads from Storage. */
649
+ unloadDocuments() {
650
+ return this.#maintain(async () => {
651
+ if (this.#failure === undefined)
652
+ await this.#storeHolds(() => [...this.#holds.values()], BACKGROUND_CONTEXT);
653
+ this.#documents.clear();
654
+ this.#idleDocuments.clear();
655
+ });
656
+ }
657
+ /**
658
+ * Internal, for tests: how many documents the cache holds, how many are idle, how many incarnations are pinned, how
659
+ * many sweep jobs were queued on the line so far, how many documents have held changes, how many live tasks have
660
+ * their documents indexed, and how many conversations have their newest entry kept.
661
+ */
662
+ get documentCacheSizes() {
663
+ return {
664
+ cached: this.#documents.size,
665
+ idle: this.#idleDocuments.size,
666
+ attached: this.#attachedDocuments.size,
667
+ sweeps: this.#sweepJobs,
668
+ held: this.#holds.size,
669
+ taskDocuments: this.#taskDocuments.size,
670
+ tails: this.#tails?.size ?? 0,
671
+ };
672
+ }
673
+ /**
674
+ * Internal, for tests that bound memory: jobs whose outcome is not delivered yet, keys with an unpublished writer,
675
+ * and record reads in flight in the cache. All three are 0 once the line is idle.
676
+ */
677
+ get lineSizes() {
678
+ return {
679
+ outstanding: this.#outstanding,
680
+ unpublished: this.#writer.unpublished,
681
+ reads: this.#cached?.readsInFlight ?? 0,
682
+ };
683
+ }
684
+ /** Note a use of a cached document: an unattached one becomes the newest idle one, and an eviction is scheduled. */
685
+ #touchDocument(addressId) {
686
+ const cached = this.#documents.get(addressId);
687
+ if (cached === undefined || this.#attachedDocuments.has(cached.record.id))
688
+ return;
689
+ const now = this.#clock();
690
+ const since = this.#idleDocuments.get(addressId);
691
+ // A hot document moves to the back at most once per granule, a tenth of the retention up to 1 s: it may then leave
692
+ // up to a granule early, which costs a reload, while a commit-heavy workload skips the reordering.
693
+ if (since !== undefined && now - since < Math.min(1_000, this.#documentRetentionMs() / 10))
694
+ return;
695
+ this.#idleDocuments.delete(addressId);
696
+ this.#idleDocuments.set(addressId, now);
697
+ // A pending sweep for the oldest document comes first unless the retention was shortened since; then it moves up.
698
+ if (this.#documentSweep === undefined || this.#documentSweep.at > now + this.#documentRetentionMs()) {
699
+ this.#scheduleDocumentSweep();
700
+ }
701
+ }
702
+ #dropDocument(addressId) {
703
+ this.#documents.delete(addressId);
704
+ this.#idleDocuments.delete(addressId);
705
+ }
706
+ /**
707
+ * Schedule the eviction of the oldest idle document: on the line at once when the retention is 0, otherwise when it
708
+ * expires, by a background timer (`HarnessOptions.setTimer`), which never keeps the process alive. Where the host
709
+ * declines it, as the default does in Cloudflare Workers, none is kept: the end of each commit evicts what expired.
710
+ */
711
+ #scheduleDocumentSweep() {
712
+ if (this.#closing !== undefined)
713
+ return;
714
+ // Documents with unpublished changes are not swept: their publication touches them again.
715
+ let oldest;
716
+ for (const [addressId, since] of this.#idleDocuments) {
717
+ if (this.#writer.gate(documentKey(addressId)) !== undefined)
718
+ continue;
719
+ oldest = since;
720
+ break;
721
+ }
722
+ if (oldest === undefined)
723
+ return;
724
+ const at = oldest + this.#documentRetentionMs();
725
+ if (this.#documentSweep !== undefined && this.#documentSweep.at <= at)
726
+ return;
727
+ this.#documentSweep?.disarm?.();
728
+ // The pending sweep stays set until its job runs, so touches while the line is busy queue no more.
729
+ const sweep = { at, disarm: undefined };
730
+ const run = () => {
731
+ this.#sweepJobs++;
732
+ this.#maintain(async () => {
733
+ if (this.#documentSweep === sweep)
734
+ this.#documentSweep = undefined;
735
+ if (this.#closing === undefined)
736
+ this.#sweepDocuments();
737
+ }).catch(() => { });
738
+ };
739
+ const delay = at - this.#clock();
740
+ this.#documentSweep = sweep;
741
+ if (delay <= 0) {
742
+ queueMicrotask(run);
743
+ return;
744
+ }
745
+ if (this.#documentTimersUnavailable) {
746
+ this.#documentSweep = undefined;
747
+ return;
748
+ }
749
+ // A timer that fires early sweeps nothing and arms the next one.
750
+ const disarm = this.#timers.background(run, delay);
751
+ if (disarm === undefined) {
752
+ this.#documentTimersUnavailable = true;
753
+ this.#documentSweep = undefined;
754
+ return;
755
+ }
756
+ sweep.disarm = disarm;
757
+ }
758
+ /** On the line: evict the idle documents whose retention passed, oldest first, then schedule the next eviction. */
759
+ #sweepDocuments() {
760
+ const expired = this.#clock() - this.#documentRetentionMs();
761
+ for (const [addressId, since] of this.#idleDocuments) {
762
+ if (since > expired)
763
+ break;
764
+ // A document with an unpublished change stays until its publication touches it.
765
+ if (this.#writer.gate(documentKey(addressId)) !== undefined)
766
+ continue;
767
+ this.#dropDocument(addressId);
768
+ }
769
+ this.#scheduleDocumentSweep();
770
+ }
771
+ /** Pin a cached incarnation for one observer; the returned release unpins it once, idle again after the last. */
772
+ #pinDocument(addressId, recordId) {
773
+ this.#attachedDocuments.set(recordId, (this.#attachedDocuments.get(recordId) ?? 0) + 1);
774
+ this.#idleDocuments.delete(addressId);
775
+ let pinned = true;
776
+ return () => {
777
+ if (!pinned)
778
+ return;
779
+ pinned = false;
780
+ const count = (this.#attachedDocuments.get(recordId) ?? 1) - 1;
781
+ if (count > 0) {
782
+ this.#attachedDocuments.set(recordId, count);
783
+ return;
784
+ }
785
+ this.#attachedDocuments.delete(recordId);
786
+ if (this.#documents.get(addressId)?.record.id === recordId)
787
+ this.#touchDocument(addressId);
788
+ };
789
+ }
790
+ async #runCommit(change, context, scope, withinMs, index) {
791
+ this.#assertHealthy();
792
+ context.abortSignal?.throwIfAborted();
793
+ const tx = new Transaction(this.#host, context, scope);
794
+ let result;
795
+ try {
796
+ result = await change(tx);
797
+ // A callback that caught a failed read must not commit, nor succeed as if it had.
798
+ this.#assertHealthy();
799
+ }
800
+ catch (error) {
801
+ await tx.settleFailure();
802
+ this.#sweepDocuments();
803
+ throw error;
804
+ }
805
+ let writes;
806
+ try {
807
+ writes = await tx.settleSuccess();
808
+ }
809
+ catch (error) {
810
+ // Settlement aborted every change already.
811
+ this.#sweepDocuments();
812
+ throw error;
813
+ }
814
+ if (writes.length === 0) {
815
+ tx.discard();
816
+ this.#sweepDocuments();
817
+ return { value: result };
818
+ }
819
+ if (this.#readOnly) {
820
+ // Refused before Storage: the Session stays healthy, and the caller sees why.
821
+ tx.discard();
822
+ this.#sweepDocuments();
823
+ throw new ReadOnlySession("a commit with writes");
824
+ }
825
+ const discard = () => tx.discard();
826
+ if (withinMs !== undefined) {
827
+ const held = tx.holdable();
828
+ if (held !== undefined) {
829
+ // Adopted in memory when the commits before it are published, as a part of no storage call.
830
+ const part = this.#writer.admit({
831
+ index,
832
+ writes: undefined,
833
+ keys: tx.writeKeys(),
834
+ context,
835
+ publish: () => this.#hold(tx, held, withinMs, context),
836
+ discard,
837
+ });
838
+ this.#sweepDocuments();
839
+ return { value: result, after: part.outcome };
840
+ }
841
+ }
842
+ let membership = this.membershipKeys(tx);
843
+ if (!Array.isArray(membership)) {
844
+ try {
845
+ membership = await membership;
846
+ }
847
+ catch (error) {
848
+ tx.discard();
849
+ this.#sweepDocuments();
850
+ throw error;
851
+ }
852
+ }
853
+ // Logical admission. Held changes leave their queue only here, once nothing but Storage can fail; a commit never
854
+ // stores a hold adopted after it in line order. Taken before the keys, so the documents it stores held changes of
855
+ // are its writes too: a later job that reads one waits for it instead of storing them again.
856
+ const taken = this.#holds.size === 0 ? NO_HOLDS : tx.takeHeld((id) => this.#holds.get(id));
857
+ const keys = tx.writeKeys();
858
+ for (const key of membership)
859
+ keys.push(key);
860
+ const part = this.#writer.admit({
861
+ index,
862
+ writes,
863
+ keys,
864
+ context,
865
+ publish: (seq) => this.#adopt(tx, writes, taken, seq, context),
866
+ discard,
867
+ });
868
+ this.#sweepDocuments();
869
+ return { value: result, after: part.outcome };
870
+ }
871
+ /**
872
+ * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its
873
+ * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it.
874
+ */
875
+ #adopt(tx, writes, taken, seq, context) {
876
+ let documents;
877
+ try {
878
+ documents = tx.adopt(seq);
879
+ }
880
+ catch (error) {
881
+ return { kind: "adoption", error };
882
+ }
883
+ this.#indexTaskDocuments(tx, writes, documents, seq);
884
+ const failure = this.#publish(seq, writes, documents, context);
885
+ if (taken.length > 0)
886
+ this.#release(taken);
887
+ for (const document of documents.stored)
888
+ this.#touchDocument(addressId(document.record));
889
+ return failure === undefined ? undefined : { kind: "listener", error: failure.error };
890
+ }
891
+ /**
892
+ * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents,
893
+ * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index.
894
+ */
895
+ #indexTaskDocuments(tx, writes, documents, seq) {
896
+ for (const id of tx.createdTaskIds())
897
+ this.#taskDocuments.set(id, new Map());
898
+ if (this.#taskDocuments.size === 0)
899
+ return;
900
+ for (const change of documents.stored) {
901
+ if (change.type !== "document" || change.record.scope.kind !== "task")
902
+ continue;
903
+ const known = this.#taskDocuments.get(change.record.scope.taskId);
904
+ if (known === undefined)
905
+ continue;
906
+ if (change.kind === "retire")
907
+ known.delete(change.record.id);
908
+ else if (change.record.createdAt === seq)
909
+ known.set(change.record.id, change.record);
910
+ }
911
+ for (const write of writes) {
912
+ if (write.type === "task" && write.value.state.status === "terminal")
913
+ this.#taskDocuments.delete(write.value.id);
914
+ }
915
+ }
916
+ /**
917
+ * Hold a deferred commit (`Transaction.holdable()`): adopt it in memory, queue its changes per document, pinned, by
918
+ * the earliest deadline of the document's held commits, and show it to the Session's own observers.
919
+ */
920
+ #hold(tx, held, withinMs, context) {
921
+ let documents;
922
+ try {
923
+ documents = tx.adoptHeld();
924
+ }
925
+ catch (error) {
926
+ // As a stored commit's: memory could not adopt it; the writer fails the Session.
927
+ return { kind: "adoption", error };
928
+ }
929
+ const deadline = this.#clock() + withinMs;
930
+ for (const { loaded, ops, base } of held) {
931
+ const id = loaded.record.id;
932
+ let hold = this.#holds.get(id);
933
+ if (hold === undefined) {
934
+ const unpin = this.#pinDocument(loaded.addressId, id);
935
+ hold = { loaded, pending: new PendingOps(), base: false, deadline, unpin };
936
+ this.#holds.set(id, hold);
937
+ }
938
+ hold.pending.push(ops);
939
+ if (base)
940
+ hold.base = true;
941
+ if (deadline < hold.deadline)
942
+ hold.deadline = deadline;
943
+ }
944
+ this.#armHoldTimer();
945
+ const publication = { kind: "memory", changes: documents };
946
+ let failure;
947
+ for (const listener of [...this.#internalListeners]) {
948
+ // Our own observers are synchronous.
949
+ try {
950
+ listener(publication, context);
951
+ }
952
+ catch (error) {
953
+ failure ??= { kind: "listener", error };
954
+ }
955
+ }
956
+ return failure;
957
+ }
958
+ /**
959
+ * Store the held changes `select` returns in one storage transaction, through the writer, from a job on the line. A
960
+ * barrier: they are selected once every commit admitted before is published. Memory already has them, so only
961
+ * `observeCommits()` observers see it, published as the writer publishes it. A failure fails the Session, as every
962
+ * Storage failure does.
963
+ */
964
+ async #storeHolds(select, context) {
965
+ await this.#drained();
966
+ const holds = select();
967
+ if (holds.length === 0)
968
+ return;
969
+ const writes = [];
970
+ const changes = [];
971
+ const keys = [];
972
+ for (const hold of holds) {
973
+ const { record, tracker, valueVersion: version } = hold.loaded;
974
+ const value = tracker.value;
975
+ const stored = storeHeld(hold, NO_OPERATIONS, value, version);
976
+ writes.push({ type: "document.change", id: record.id, content: stored.content });
977
+ keys.push(documentKey(hold.loaded.addressId), incarnationKey(record.id));
978
+ // Held documents are conversation documents.
979
+ const conversationId = record.scope.kind === "conversation" ? record.scope.conversationId : undefined;
980
+ changes.push({ type: "document", kind: "change", record, conversationId, version, value, ops: stored.ops });
981
+ }
982
+ const publish = (seq) => {
983
+ for (const [index, hold] of holds.entries()) {
984
+ if (writes[index].content.kind === "base")
985
+ hold.loaded.deltasSinceBase = 0;
986
+ else
987
+ hold.loaded.deltasSinceBase++;
988
+ }
989
+ if (this.#commitListeners.size > 0)
990
+ this.#notifyHosts({ seq: seq, changes }, context);
991
+ this.#release(holds);
992
+ return undefined;
993
+ };
994
+ // Run from a job on the line, which a failure it causes is the outcome of.
995
+ const index = this.#current.index;
996
+ await this.#writer.admit({ index, writes, keys, context, publish, discard: ignore }).outcome;
997
+ }
998
+ /** After their store: forget `holds`, unpin their documents, and move the timer to the next deadline. */
999
+ #release(holds) {
1000
+ for (const hold of holds) {
1001
+ this.#holds.delete(hold.loaded.record.id);
1002
+ hold.unpin();
1003
+ }
1004
+ this.#armHoldTimer();
1005
+ }
1006
+ /**
1007
+ * Keep a foreground timer (Workers refuse background ones) for the earliest deadline of the held documents. When it
1008
+ * fires, every held document is stored, in one storage transaction: a deadline is the latest time, and the others
1009
+ * cost little more in the same transaction. Once fired, it stays until its job ran.
1010
+ */
1011
+ #armHoldTimer() {
1012
+ if (this.#closing !== undefined)
1013
+ return;
1014
+ let at = Infinity;
1015
+ for (const hold of this.#holds.values())
1016
+ if (hold.deadline < at)
1017
+ at = hold.deadline;
1018
+ const armed = this.#holdTimer;
1019
+ if (armed !== undefined && (armed.fired || armed.at === at))
1020
+ return;
1021
+ armed?.disarm();
1022
+ this.#holdTimer = undefined;
1023
+ if (at === Infinity)
1024
+ return;
1025
+ const timer = { at, disarm: () => { }, fired: false };
1026
+ const run = () => {
1027
+ timer.fired = true;
1028
+ this.#maintain(async () => {
1029
+ if (this.#holdTimer === timer)
1030
+ this.#holdTimer = undefined;
1031
+ // Close stores what is held itself.
1032
+ if (this.#closing !== undefined || this.#failure !== undefined)
1033
+ return;
1034
+ await this.#storeHolds(() => [...this.#holds.values()], BACKGROUND_CONTEXT);
1035
+ }).catch(() => { });
1036
+ };
1037
+ this.#holdTimer = timer;
1038
+ timer.disarm = this.#timers.foreground(run, Math.max(0, at - this.#clock()));
1039
+ }
1040
+ /**
1041
+ * At publication: publish a stored commit. Its telemetry events first, then the dispatch to `observeCommits()`
1042
+ * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws:
1043
+ * returns the first error of an own observer, which fails the Session once its storage call settled.
1044
+ */
1045
+ #publish(seq, writes, documents, context) {
1046
+ const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : undefined;
1047
+ for (const write of writes) {
1048
+ switch (write.type) {
1049
+ case "entry":
1050
+ this.#event("diffra.durable.entry", { "entry.id": write.value.id, "entry.kind": write.value.kind }, context);
1051
+ changes?.push(write);
1052
+ break;
1053
+ case "submission":
1054
+ if (write.value.status === "done" || write.value.status === "unanswered") {
1055
+ this.#event("diffra.durable.submission", {
1056
+ "submission.id": write.value.id,
1057
+ status: write.value.status,
1058
+ "answer.entry_id": write.value.answer,
1059
+ }, context);
1060
+ }
1061
+ changes?.push(write);
1062
+ break;
1063
+ case "conversation":
1064
+ case "task":
1065
+ changes?.push(write);
1066
+ }
1067
+ }
1068
+ if (changes === undefined)
1069
+ return undefined;
1070
+ const tables = changes.length;
1071
+ for (const document of documents.observed)
1072
+ changes.push(document);
1073
+ const observed = { kind: "stored", seq, changes };
1074
+ if (this.#commitListeners.size > 0) {
1075
+ // One publication for both, unless the commit also stored held changes, which only host listeners get.
1076
+ const stored = documents.stored === documents.observed
1077
+ ? observed
1078
+ : { seq, changes: [...changes.slice(0, tables), ...documents.stored] };
1079
+ this.#notifyHosts(stored, context);
1080
+ }
1081
+ // The commit is durable: a failing observer neither fails the commit nor skips the others.
1082
+ let failure;
1083
+ for (const listener of [...this.#internalListeners]) {
1084
+ // Our own observers are synchronous.
1085
+ try {
1086
+ listener(observed, context);
1087
+ }
1088
+ catch (error) {
1089
+ failure ??= { error };
1090
+ }
1091
+ }
1092
+ return failure;
1093
+ }
1094
+ /** At publication: record a commit's telemetry event. A throwing adapter is reported, as publication must not throw. */
1095
+ #event(name, attributes, context) {
1096
+ try {
1097
+ context.telemetry.addEvent(name, attributes);
1098
+ }
1099
+ catch (error) {
1100
+ this.report(error, TELEMETRY, context);
1101
+ }
1102
+ }
1103
+ /**
1104
+ * At publication: call the `observeCommits()` observers with `publication` one microtask from now, and, queued
1105
+ * before the Session's own observers run, before the waits they resolve and the aborts they queue. The observers are
1106
+ * those attached when it runs; their guards report a throw.
1107
+ */
1108
+ #notifyHosts(publication, context) {
1109
+ void SETTLED.then(() => {
1110
+ for (const observer of [...this.#commitListeners])
1111
+ observer.advance(publication, context);
1112
+ });
1113
+ }
1114
+ /**
1115
+ * On the line, as one job: load the document at `resolved` and `attach` to it, so the attachment sees every commit
1116
+ * after the value it starts from; `undefined` when absent. Cancelling `context` meanwhile rejects, after `cancel`
1117
+ * undid an attachment made.
1118
+ */
1119
+ async #attachDocument(definition, resolved, context, attach, cancel) {
1120
+ const signal = context.abortSignal;
1121
+ let cancelled = signal?.aborted ?? false;
1122
+ const markCancelled = () => {
1123
+ cancelled = true;
1124
+ };
1125
+ signal?.addEventListener("abort", markCancelled, { once: true });
1126
+ try {
1127
+ const attached = await this.#enqueue(async () => {
1128
+ this.#assertHealthy();
1129
+ if (cancelled)
1130
+ throw cancellationError(signal);
1131
+ const loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context);
1132
+ if (cancelled)
1133
+ throw cancellationError(signal);
1134
+ return { value: loaded === undefined ? undefined : attach(loaded) };
1135
+ });
1136
+ if (attached === undefined)
1137
+ return undefined;
1138
+ if (cancelled) {
1139
+ cancel(attached);
1140
+ throw cancellationError(signal);
1141
+ }
1142
+ return attached;
1143
+ }
1144
+ finally {
1145
+ signal?.removeEventListener("abort", markCancelled);
1146
+ }
1147
+ }
1148
+ /**
1149
+ * Follow the address of the incarnation `loaded`, after checking the definition, with the observer `create` makes
1150
+ * from its value, the idempotent detach, and the report of a listener error; returns that observer. It gets each
1151
+ * committed change there, a retirement as a `retired` change with the last value it was given and no ops (a change
1152
+ * in the retiring commit is not published), and a later incarnation as a root replacement. When the commit makes the
1153
+ * owner task of a task document terminal, no later commit can change the address: after its changes the commit
1154
+ * subscription and the pin go, and `ownerEnded` tells the observer, which stays subscribed to the Session's close
1155
+ * until it ends (its detach drops that). `end` gets the Session's close. The current incarnation is pinned in the
1156
+ * cache. The detach runs before `end`; once it ran, nothing more of the commit underway reaches the observer or pins
1157
+ * anything for it. `create` and `ownerEnded` are module functions where they can be, so a watch keeps no closure of
1158
+ * its caller.
1159
+ */
1160
+ #observeDocument(definition, loaded, create, ownerEnded) {
1161
+ checkRecordScope(definition, loaded.record);
1162
+ checkRecordVersion(definition, loaded.record, loaded.storedVersion);
1163
+ // The closures below keep only the address, as the cache's ID and first record, which the cache shares while the
1164
+ // document is cached: `loaded` holds its incarnation's tracker, which a retirement frees.
1165
+ const addressId = loaded.addressId;
1166
+ const address = loaded.record;
1167
+ let incarnation = loaded.record.id;
1168
+ // The value of the incarnation followed; none while the address is absent, so the Session keeps no retired value.
1169
+ let value = loaded.tracker.value;
1170
+ // The definition version the observer's value has: a change of another version replaces it whole.
1171
+ let version = loaded.valueVersion;
1172
+ // The incarnation observed stays cached; once it retires or the observer detaches, it is idle again.
1173
+ let unpin = this.#pinDocument(addressId, incarnation);
1174
+ let unsubscribeCommit = () => { };
1175
+ let unsubscribeClose = () => { };
1176
+ let attached = true;
1177
+ const detach = () => {
1178
+ if (!attached)
1179
+ return;
1180
+ attached = false;
1181
+ unsubscribeCommit();
1182
+ unsubscribeClose();
1183
+ unpin();
1184
+ };
1185
+ const observer = create(loaded.tracker.value, detach, (error) => this.report(error));
1186
+ unsubscribeCommit = this.followCommits((publication, context) => {
1187
+ // Listeners run from a copy of the set: another observer's call may have detached this one.
1188
+ if (!attached)
1189
+ return;
1190
+ let ownerEnds = false;
1191
+ for (const change of publication.changes) {
1192
+ if (change.type === "task") {
1193
+ const scope = address.scope;
1194
+ if (scope.kind === "task" &&
1195
+ change.value.id === scope.taskId &&
1196
+ change.value.state.status === "terminal") {
1197
+ ownerEnds = true;
1198
+ }
1199
+ continue;
1200
+ }
1201
+ // The incarnation followed is at the address by definition; only another record needs the address compared.
1202
+ if (change.type !== "document")
1203
+ continue;
1204
+ if (change.record.id !== incarnation && !atAddress(change.record, address))
1205
+ continue;
1206
+ if (change.kind === "retire") {
1207
+ if (change.record.id !== incarnation)
1208
+ continue;
1209
+ // Set with every incarnation.
1210
+ const last = value;
1211
+ incarnation = undefined;
1212
+ value = undefined;
1213
+ unpin();
1214
+ observer.advance({ kind: "value", value: last, ops: NO_OPERATIONS, retired: true }, context);
1215
+ }
1216
+ else if (change.record.id !== incarnation || change.version !== version) {
1217
+ // A new incarnation at the address, or a value of another definition version, whose shape the observer's
1218
+ // value does not have: shown whole.
1219
+ if (change.record.id !== incarnation) {
1220
+ incarnation = change.record.id;
1221
+ unpin();
1222
+ unpin = this.#pinDocument(addressId, incarnation);
1223
+ }
1224
+ version = change.version;
1225
+ value = change.value;
1226
+ observer.advance({ kind: "value", value, ops: [["r", value]], retired: false }, context);
1227
+ }
1228
+ else {
1229
+ // A migration-only base changes nothing for an observer of the new version.
1230
+ if (change.ops.length === 0)
1231
+ continue;
1232
+ value = change.value;
1233
+ observer.advance({ kind: "value", value, ops: change.ops, retired: false }, context);
1234
+ }
1235
+ // The observer may detach in its call, or throw and be detached: the rest of the commit is not its.
1236
+ if (!attached)
1237
+ return;
1238
+ }
1239
+ if (!ownerEnds)
1240
+ return;
1241
+ unsubscribeCommit();
1242
+ unpin();
1243
+ ownerEnded(observer);
1244
+ });
1245
+ unsubscribeClose = this.subscribeClose(() => {
1246
+ detach();
1247
+ observer.end(closeEndOf(observer, closeEnds(this.#failure)));
1248
+ });
1249
+ return observer;
1250
+ }
1251
+ async #loadDocument(definition, addressId, address, context) {
1252
+ // What an unpublished commit wrote at the address is in neither the cache nor what Storage shows yet.
1253
+ const gate = this.touch(documentKey(addressId));
1254
+ if (gate !== undefined)
1255
+ await gate;
1256
+ const cached = this.#documents.get(addressId);
1257
+ // A tracker serves only tokens of the version its value was materialized for; others reload from Storage.
1258
+ if (cached?.valueVersion === definition.version) {
1259
+ this.#touchDocument(addressId);
1260
+ return cached;
1261
+ }
1262
+ if (cached !== undefined) {
1263
+ // The reload must find what memory holds: held changes are stored before their tracker goes, after a barrier.
1264
+ const id = cached.record.id;
1265
+ await this.#storeHolds(() => {
1266
+ const hold = this.#holds.get(id);
1267
+ return hold === undefined ? NO_HOLDS : [hold];
1268
+ }, context);
1269
+ this.#dropDocument(addressId);
1270
+ }
1271
+ const record = await this.#storage.findDocument(address, "current", context);
1272
+ if (record === undefined)
1273
+ return undefined;
1274
+ const stored = await this.#storage.document(record.id, "current", context);
1275
+ if (stored === undefined)
1276
+ throw new Error(`Current document ${record.id} (${record.kind}) cannot be read`);
1277
+ const value = materializeDocument(definition, stored);
1278
+ const loaded = {
1279
+ addressId,
1280
+ record: stored.record,
1281
+ storedVersion: stored.version,
1282
+ valueVersion: definition.version,
1283
+ deltasSinceBase: stored.deltasSinceBase,
1284
+ tracker: track(value),
1285
+ };
1286
+ this.#documents.set(addressId, loaded);
1287
+ this.#touchDocument(addressId);
1288
+ return loaded;
1289
+ }
1290
+ /**
1291
+ * Run `job` on the line, after the jobs before it, and deliver its outcome in line order: once the jobs before it
1292
+ * have theirs, and once its commit, if it admitted one, is published. With `exempt`, a job that admitted no commit and
1293
+ * waited at no gate is delivered as soon as it has its outcome: it is equivalent to having run before every
1294
+ * unpublished commit. A job
1295
+ * whose outcome comes after the one a failure is gets `SessionFailed` instead. At most `MAX_OUTSTANDING` jobs wait
1296
+ * for their delivery; beyond it the line waits.
1297
+ */
1298
+ #enqueue(work, exempt = false) {
1299
+ const job = { index: this.#nextIndex++, hit: false };
1300
+ const ran = this.#tail.then(async () => {
1301
+ while (this.#outstanding >= MAX_OUTSTANDING) {
1302
+ this.#room ??= Promise.withResolvers();
1303
+ await this.#room.promise;
1304
+ }
1305
+ this.#outstanding++;
1306
+ return this.#onLine(job, work);
1307
+ });
1308
+ this.#tail = ran.then(ignore, ignore);
1309
+ const outcome = ran.then((result) => {
1310
+ if (result.after === undefined) {
1311
+ this.#ended(job);
1312
+ return result.value;
1313
+ }
1314
+ return result.after.then(() => {
1315
+ this.#ended(job);
1316
+ return result.value;
1317
+ }, (error) => {
1318
+ this.#ended(job);
1319
+ throw error;
1320
+ });
1321
+ }, (error) => {
1322
+ this.#ended(job);
1323
+ throw error;
1324
+ });
1325
+ // Delivered later, after the outcomes before it: handled now, so an early rejection is not reported unhandled.
1326
+ outcome.catch(ignore);
1327
+ const fence = this.#fence;
1328
+ this.#fence = fence.then(() => outcome).then(ignore, ignore);
1329
+ const index = job.index;
1330
+ const deliver = (fenced) => (fenced ? fence.then(() => outcome) : outcome).then((value) => {
1331
+ this.#delivered(index, fenced);
1332
+ if (this.#poisoned(index))
1333
+ throw new SessionFailed(this.#failure.error);
1334
+ return value;
1335
+ }, (error) => {
1336
+ this.#delivered(index, fenced);
1337
+ throw this.#poisoned(index) ? new SessionFailed(this.#failure.error) : error;
1338
+ });
1339
+ // Only a job without writes is exempt: one with writes waits for its own publication and the outcomes before it.
1340
+ return exempt
1341
+ ? ran.then((result) => deliver(job.hit || result.after !== undefined), () => deliver(job.hit))
1342
+ : deliver(true);
1343
+ }
1344
+ /** Whether job `index` comes after the failure's boundary without an outcome of its own: it gets `SessionFailed`. */
1345
+ #poisoned(index) {
1346
+ return this.#failAt !== undefined && index > this.#failAt && !this.#ownOutcomes.has(index);
1347
+ }
1348
+ /** The job's outcome settled: run what waited for it (`onJobEnd()`). */
1349
+ #ended(job) {
1350
+ const ends = job.ends;
1351
+ if (ends === undefined)
1352
+ return;
1353
+ job.ends = undefined;
1354
+ for (const end of ends)
1355
+ end();
1356
+ }
1357
+ /** Run a job of the Session's own upkeep on the line: no outcome to deliver, so no fence and no `SessionFailed`. */
1358
+ #maintain(work) {
1359
+ const job = { index: this.#nextIndex++, hit: false };
1360
+ const ran = this.#tail.then(() => this.#onLine(job, work));
1361
+ this.#tail = ran.then(ignore, ignore);
1362
+ return ran;
1363
+ }
1364
+ /** Hold the line for job `index` until its line part, through admission, is done. Gates are its touches' own. */
1365
+ async #onLine(job, work) {
1366
+ this.#current = job;
1367
+ try {
1368
+ return await work(job.index);
1369
+ }
1370
+ finally {
1371
+ this.#current = undefined;
1372
+ }
1373
+ }
1374
+ /** A `*` barrier: once every part admitted so far is published, or never will be. */
1375
+ async #drained() {
1376
+ const drained = this.#writer.drained();
1377
+ if (drained !== undefined)
1378
+ await drained;
1379
+ }
1380
+ /**
1381
+ * Run one commit's publication inside the Storage's own scope (`Storage.publishing`), such as a store host's batch;
1382
+ * directly without one. `undefined` when it ran at once, else settles once it ran. A Storage that throws instead of
1383
+ * running it is reported, and the publication runs directly: the commit is stored, so it must be published.
1384
+ */
1385
+ #publishing(publish, context) {
1386
+ const publishing = this.#storage.publishing;
1387
+ if (publishing === undefined) {
1388
+ publish();
1389
+ return undefined;
1390
+ }
1391
+ const done = Promise.withResolvers();
1392
+ let ran = false;
1393
+ const once = () => {
1394
+ if (ran)
1395
+ return;
1396
+ ran = true;
1397
+ try {
1398
+ publish();
1399
+ }
1400
+ finally {
1401
+ done.resolve();
1402
+ }
1403
+ };
1404
+ try {
1405
+ publishing(once, context);
1406
+ }
1407
+ catch (error) {
1408
+ this.report(error, LISTENER, context);
1409
+ once();
1410
+ }
1411
+ return done.promise;
1412
+ }
1413
+ /** Job `index` has its outcome: let the line go on past `MAX_OUTSTANDING`. */
1414
+ #delivered(index, fenced) {
1415
+ if (fenced)
1416
+ this.#lastDelivered = index;
1417
+ this.#outstanding--;
1418
+ const room = this.#room;
1419
+ if (room !== undefined && this.#outstanding < MAX_OUTSTANDING) {
1420
+ this.#room = undefined;
1421
+ room.resolve();
1422
+ }
1423
+ }
1424
+ /** Internal: throw `SessionFailed` when failed, else an error when closing. */
1425
+ assertUsable() {
1426
+ this.#assertHealthy();
1427
+ if (this.#closing !== undefined)
1428
+ throw new Error("Session is closed");
1429
+ }
1430
+ #assertHealthy() {
1431
+ if (this.#failure !== undefined)
1432
+ throw new SessionFailed(this.#failure.error);
1433
+ }
1434
+ }
1435
+ /**
1436
+ * Run a host callback that must not fail its caller: a throw, or a promise it returns that rejects, goes to `onError`,
1437
+ * which is not awaited.
1438
+ */
1439
+ export function contained(callback, onError) {
1440
+ try {
1441
+ const result = callback();
1442
+ // Any thenable, also a promise from another realm; `Promise.resolve` adopts it with handlers of its own.
1443
+ if (typeof result?.then === "function")
1444
+ Promise.resolve(result).catch(onError);
1445
+ }
1446
+ catch (error) {
1447
+ onError(error);
1448
+ }
1449
+ }
1450
+ /**
1451
+ * `observer`, a host's, behind the rule for observers that run at a commit's publication: one that throws, or whose
1452
+ * `advance` returns a promise that rejects, is reported through `report`, detached, and ended `listener_error`, so the
1453
+ * throw never reaches `adopt`; nothing reaches it after its detach or end, and from then on the guard references
1454
+ * neither it nor its source. `detach` is the source's; the returned `detach()` is the observation's.
1455
+ */
1456
+ export function guardObserver(observer, detach, report) {
1457
+ let attached = { observer, detach, report };
1458
+ /** Detach from the source once, and hand back what it was attached with. */
1459
+ const release = () => {
1460
+ const released = attached;
1461
+ attached = undefined;
1462
+ released?.detach();
1463
+ return released;
1464
+ };
1465
+ /** Report a throw of `current`'s `advance`, then detach and end it, unless that happened meanwhile. */
1466
+ const fault = (current, error, context) => {
1467
+ current.report(error, context);
1468
+ if (release() !== undefined) {
1469
+ const end = { kind: "listener_error", error: toError(error) };
1470
+ contained(() => current.observer.end(end), current.report);
1471
+ }
1472
+ };
1473
+ return {
1474
+ advance: (call, context) => {
1475
+ const current = attached;
1476
+ if (current === undefined)
1477
+ return;
1478
+ try {
1479
+ const result = current.observer.advance(call, context);
1480
+ // Any thenable, as `contained()` takes it: a rejection is the observer's throw, after the fact.
1481
+ if (typeof result?.then === "function") {
1482
+ Promise.resolve(result).catch((error) => fault(current, error, context));
1483
+ }
1484
+ }
1485
+ catch (error) {
1486
+ fault(current, error, context);
1487
+ }
1488
+ },
1489
+ end: (end) => {
1490
+ const ending = release();
1491
+ if (ending !== undefined)
1492
+ contained(() => ending.observer.end(end), ending.report);
1493
+ },
1494
+ detach: () => {
1495
+ release();
1496
+ },
1497
+ };
1498
+ }
1499
+ /** A listener's throw as the `Error` a `listener_error` end carries, as Chord's watch makes it. */
1500
+ function toError(error) {
1501
+ if (error instanceof Error)
1502
+ return error;
1503
+ try {
1504
+ return new Error(String(error));
1505
+ }
1506
+ catch {
1507
+ return new Error(Object.prototype.toString.call(error));
1508
+ }
1509
+ }
1510
+ /** The end of an observer whose source closed. */
1511
+ export const ENDED = { kind: "ended" };
1512
+ /**
1513
+ * How a Session's close ends what follows it (decision "Slice 8 S1"), made once per close: an app's watch `ended`; a
1514
+ * synchronous observer (an adapter following the Session, which may open it again) `failed` with "session closed", so
1515
+ * it follows the next Session; `ended` stays for an observed owner that ended (a task document's task). A failed
1516
+ * Session ends both `failed` with its error.
1517
+ */
1518
+ export function closeEnds(failure) {
1519
+ if (failure !== undefined) {
1520
+ const failed = { kind: "failed", error: failure.error };
1521
+ return { watch: failed, observer: failed };
1522
+ }
1523
+ return { watch: ENDED, observer: { kind: "failed", error: new Error("session closed") } };
1524
+ }
1525
+ /** The end `ends` give `follower`: a watch's, or an observer's. */
1526
+ export function closeEndOf(follower, ends) {
1527
+ return follower instanceof Watch ? ends.watch : ends.observer;
1528
+ }
1529
+ /**
1530
+ * The `Observation` of a guarded observer attached at `value`. Built outside the attaching closure, so a detached
1531
+ * observation keeps nothing but `value` and the spent guard alive.
1532
+ */
1533
+ export function observation(value, guarded) {
1534
+ return { value, detach: () => guarded.detach() };
1535
+ }
1536
+ /** A document watch over its source's detach and report. */
1537
+ function createWatch(value, detach, report) {
1538
+ return new Watch(value, detach, report);
1539
+ }
1540
+ /** Undo a watch attached while its acquisition was aborted. */
1541
+ function abortWatch(watch) {
1542
+ watch.abort();
1543
+ }
1544
+ /** Undo an observation attached while its attachment was cancelled. */
1545
+ function detachObservation(attached) {
1546
+ attached.detach();
1547
+ }
1548
+ /** A task document's watch delivers the retirement that ends its task, then ends. */
1549
+ function endWatch(watch) {
1550
+ watch.endAfterDelivery();
1551
+ }
1552
+ /** A task document's observer ends right after the retirement that ends its task. */
1553
+ function endGuarded(guarded) {
1554
+ guarded.end(ENDED);
1555
+ }
1556
+ /** Whether `record` is an incarnation at `address`. */
1557
+ function atAddress(record, address) {
1558
+ if (record.kind !== address.kind || record.key !== address.key)
1559
+ return false;
1560
+ switch (record.scope.kind) {
1561
+ case "session":
1562
+ return address.scope.kind === "session";
1563
+ case "conversation":
1564
+ return address.scope.kind === "conversation" && address.scope.conversationId === record.scope.conversationId;
1565
+ case "task":
1566
+ return address.scope.kind === "task" && address.scope.taskId === record.scope.taskId;
1567
+ }
1568
+ }
1569
+ function cancellationError(signal) {
1570
+ return signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted", "AbortError");
1571
+ }
1572
+ /**
1573
+ * The Session's Storage behind its failure guard; every component of the Session reads and writes through it. Before a
1574
+ * call, a failed Session gets `SessionFailed` without reaching the backend. A call that throws fails the Session and
1575
+ * rethrows the backend's error, unless it is a `StorageRequestError` or a read whose caller's context was aborted:
1576
+ * neither says the Storage is broken.
1577
+ * `close()` always reaches the backend, so a failed Session still closes it.
1578
+ */
1579
+ class GuardedStorage {
1580
+ #storage;
1581
+ #latch;
1582
+ /** Backend calls underway, also those off the Session line, which close waits for before it closes the backend. */
1583
+ #underway = new Set();
1584
+ #closing = false;
1585
+ constructor(storage, latch) {
1586
+ this.#storage = storage;
1587
+ this.#latch = latch;
1588
+ }
1589
+ /** The backend's own scope for a publication (`Storage.publishing`), when it has one; not a call to guard. */
1590
+ get publishing() {
1591
+ return scopeOf(this.#storage);
1592
+ }
1593
+ /**
1594
+ * Guarded like every call, but its outcome is the Session writer's to judge: it publishes the batches received first,
1595
+ * then fails the Session for a refusal or a rejection, and for a Session that failed meanwhile.
1596
+ */
1597
+ async commit(batches, receive, context) {
1598
+ this.#assertHealthy();
1599
+ if (this.#closing)
1600
+ throw new Error("Session is closed");
1601
+ const call = (async () => this.#storage.commit(batches, receive, context))();
1602
+ this.#underway.add(call);
1603
+ try {
1604
+ return await call;
1605
+ }
1606
+ finally {
1607
+ this.#underway.delete(call);
1608
+ }
1609
+ }
1610
+ mintId() {
1611
+ return this.#call(undefined, () => this.#storage.mintId());
1612
+ }
1613
+ conversation(id, context) {
1614
+ return this.#call(context, () => this.#storage.conversation(id, context));
1615
+ }
1616
+ scanConversations(query, limit, cursor, context) {
1617
+ return this.#call(context, () => this.#storage.scanConversations(query, limit, cursor, context));
1618
+ }
1619
+ entry(first, second, third) {
1620
+ if (third === undefined) {
1621
+ const context = second;
1622
+ return this.#call(context, () => this.#storage.entry(first, context));
1623
+ }
1624
+ return this.#call(third, () => this.#storage.entry(first, second, third));
1625
+ }
1626
+ findLatestHeadMarker(conversationId, atOrBeforeEntryId, context) {
1627
+ return this.#call(context, () => this.#storage.findLatestHeadMarker(conversationId, atOrBeforeEntryId, context));
1628
+ }
1629
+ scanEntries(query, limit, cursor, context) {
1630
+ return this.#call(context, () => this.#storage.scanEntries(query, limit, cursor, context));
1631
+ }
1632
+ task(id, context) {
1633
+ return this.#call(context, () => this.#storage.task(id, context));
1634
+ }
1635
+ scanTasks(query, limit, cursor, context) {
1636
+ return this.#call(context, () => this.#storage.scanTasks(query, limit, cursor, context));
1637
+ }
1638
+ submission(id, context) {
1639
+ return this.#call(context, () => this.#storage.submission(id, context));
1640
+ }
1641
+ scanSubmissions(query, limit, cursor, context) {
1642
+ return this.#call(context, () => this.#storage.scanSubmissions(query, limit, cursor, context));
1643
+ }
1644
+ submissionByRequest(conversationId, requestId, context) {
1645
+ return this.#call(context, () => this.#storage.submissionByRequest(conversationId, requestId, context));
1646
+ }
1647
+ findDocument(address, at, context) {
1648
+ return this.#call(context, () => this.#storage.findDocument(address, at, context));
1649
+ }
1650
+ document(id, at, context) {
1651
+ return this.#call(context, () => this.#storage.document(id, at, context));
1652
+ }
1653
+ scanDocuments(query, limit, cursor, context) {
1654
+ return this.#call(context, () => this.#storage.scanDocuments(query, limit, cursor, context));
1655
+ }
1656
+ /**
1657
+ * Close the backend once every call underway has settled, so none outlives it or fails after `closed` settles. New
1658
+ * calls are refused from here on: a paged read must not start its next page while the backend closes.
1659
+ */
1660
+ async close(context) {
1661
+ this.#closing = true;
1662
+ await Promise.allSettled([...this.#underway]);
1663
+ return this.#storage.close(context);
1664
+ }
1665
+ /**
1666
+ * Run one backend call under the guard. `read` is a read's context; `commit()` and `mintId()` pass none, so nothing
1667
+ * exempts their errors: once a batch is admitted, whether it committed is unknown. A call still underway when another
1668
+ * fails the Session ends with `SessionFailed` too, whatever it returns: nothing it read or wrote is used.
1669
+ */
1670
+ async #call(read, run) {
1671
+ this.#assertHealthy();
1672
+ if (this.#closing)
1673
+ throw new Error("Session is closed");
1674
+ let result;
1675
+ // An async wrapper, so a backend that throws synchronously is guarded too.
1676
+ const call = (async () => run())();
1677
+ this.#underway.add(call);
1678
+ try {
1679
+ result = await call;
1680
+ }
1681
+ catch (error) {
1682
+ this.#assertHealthy();
1683
+ // An invalid read, or one its caller cancelled, says nothing about the Storage; it fails that call only.
1684
+ const exempt = read !== undefined && (error instanceof StorageRequestError || read.abortSignal?.aborted === true);
1685
+ if (!exempt)
1686
+ this.#latch.fail(error);
1687
+ throw error;
1688
+ }
1689
+ finally {
1690
+ this.#underway.delete(call);
1691
+ }
1692
+ this.#assertHealthy();
1693
+ return result;
1694
+ }
1695
+ #assertHealthy() {
1696
+ const failure = this.#latch.failure;
1697
+ if (failure !== undefined)
1698
+ throw new SessionFailed(failure.error);
1699
+ }
1700
+ }
1701
+ //# sourceMappingURL=session.js.map