@agentshouse/mdruntime 0.1.0-c450c0a30a409 → 0.1.0-c4566b4b35aaa

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 (428) hide show
  1. package/README.md +24 -19
  2. package/dist/acceptance.d.ts +3 -0
  3. package/dist/acceptance.d.ts.map +1 -0
  4. package/dist/acceptance.js +299 -0
  5. package/dist/act-lanes.d.ts +30 -0
  6. package/dist/act-lanes.d.ts.map +1 -0
  7. package/dist/act-lanes.js +225 -0
  8. package/dist/actions.d.ts +26 -0
  9. package/dist/actions.d.ts.map +1 -0
  10. package/dist/actions.js +313 -0
  11. package/dist/adapter.d.ts +212 -117
  12. package/dist/adapter.d.ts.map +1 -1
  13. package/dist/attached-model.d.ts +6 -10
  14. package/dist/attached-model.d.ts.map +1 -1
  15. package/dist/attached-model.js +35 -41
  16. package/dist/authored.d.ts +88 -0
  17. package/dist/authored.d.ts.map +1 -0
  18. package/dist/authored.js +345 -0
  19. package/dist/binary.d.ts +0 -5
  20. package/dist/binary.d.ts.map +1 -1
  21. package/dist/binary.js +1 -1
  22. package/dist/bootstrap.d.ts +30 -11
  23. package/dist/bootstrap.d.ts.map +1 -1
  24. package/dist/bootstrap.js +305 -140
  25. package/dist/cell.d.ts +6 -0
  26. package/dist/cell.d.ts.map +1 -0
  27. package/dist/cell.js +9 -0
  28. package/dist/chain.d.ts +12 -0
  29. package/dist/chain.d.ts.map +1 -0
  30. package/dist/chain.js +64 -0
  31. package/dist/change-set.d.ts +10 -16
  32. package/dist/change-set.d.ts.map +1 -1
  33. package/dist/change-set.js +17 -90
  34. package/dist/change.d.ts +5 -1
  35. package/dist/change.d.ts.map +1 -1
  36. package/dist/change.js +8 -3
  37. package/dist/chat-types.d.ts +3 -0
  38. package/dist/chat-types.d.ts.map +1 -0
  39. package/dist/chat-types.js +11 -0
  40. package/dist/client.d.ts +42 -26
  41. package/dist/client.d.ts.map +1 -1
  42. package/dist/client.js +88 -26
  43. package/dist/collection.d.ts +32 -21
  44. package/dist/collection.d.ts.map +1 -1
  45. package/dist/collection.js +53 -368
  46. package/dist/column.d.ts +5 -0
  47. package/dist/column.d.ts.map +1 -0
  48. package/dist/column.js +9 -0
  49. package/dist/compile.d.ts +18 -0
  50. package/dist/compile.d.ts.map +1 -0
  51. package/dist/compile.js +723 -0
  52. package/dist/connection.d.ts +7 -139
  53. package/dist/connection.d.ts.map +1 -1
  54. package/dist/connection.js +112 -4163
  55. package/dist/context.d.ts +2 -0
  56. package/dist/context.d.ts.map +1 -0
  57. package/dist/{chat/context.js → context.js} +2 -5
  58. package/dist/conversation-live.d.ts +150 -0
  59. package/dist/conversation-live.d.ts.map +1 -0
  60. package/dist/conversation-live.js +259 -0
  61. package/dist/conversation-row.d.ts +40 -0
  62. package/dist/conversation-row.d.ts.map +1 -0
  63. package/dist/conversation-row.js +66 -0
  64. package/dist/conversation.d.ts +73 -50
  65. package/dist/conversation.d.ts.map +1 -1
  66. package/dist/conversation.js +1029 -838
  67. package/dist/declaration.d.ts +10 -0
  68. package/dist/declaration.d.ts.map +1 -0
  69. package/dist/declaration.js +24 -0
  70. package/dist/digest.d.ts +7 -0
  71. package/dist/digest.d.ts.map +1 -0
  72. package/dist/digest.js +113 -0
  73. package/dist/discovery.d.ts +12 -0
  74. package/dist/discovery.d.ts.map +1 -0
  75. package/dist/discovery.js +162 -0
  76. package/dist/download.d.ts +6 -0
  77. package/dist/download.d.ts.map +1 -0
  78. package/dist/download.js +42 -0
  79. package/dist/durability.d.ts +21 -4
  80. package/dist/durability.d.ts.map +1 -1
  81. package/dist/durability.js +12 -0
  82. package/dist/entry.d.ts +10 -2
  83. package/dist/entry.d.ts.map +1 -1
  84. package/dist/entry.js +47 -32
  85. package/dist/expectation.d.ts +26 -13
  86. package/dist/expectation.d.ts.map +1 -1
  87. package/dist/expectation.js +72 -19
  88. package/dist/failure.d.ts +3 -0
  89. package/dist/failure.d.ts.map +1 -1
  90. package/dist/failure.js +8 -0
  91. package/dist/figures.d.ts +49 -0
  92. package/dist/figures.d.ts.map +1 -0
  93. package/dist/figures.js +199 -0
  94. package/dist/file.d.ts +2 -19
  95. package/dist/file.d.ts.map +1 -1
  96. package/dist/file.js +8 -122
  97. package/dist/holdings.d.ts +29 -0
  98. package/dist/holdings.d.ts.map +1 -0
  99. package/dist/holdings.js +95 -0
  100. package/dist/host.d.ts +22 -8
  101. package/dist/host.d.ts.map +1 -1
  102. package/dist/host.js +125 -51
  103. package/dist/house-query.d.ts +21 -0
  104. package/dist/house-query.d.ts.map +1 -0
  105. package/dist/house-query.js +41 -0
  106. package/dist/identity.d.ts +0 -2
  107. package/dist/identity.d.ts.map +1 -1
  108. package/dist/identity.js +0 -6
  109. package/dist/index.d.ts +44 -17
  110. package/dist/index.d.ts.map +1 -1
  111. package/dist/index.js +22 -6
  112. package/dist/install.d.ts +60 -0
  113. package/dist/install.d.ts.map +1 -0
  114. package/dist/install.js +537 -0
  115. package/dist/lifecycle.d.ts +7 -0
  116. package/dist/lifecycle.d.ts.map +1 -0
  117. package/dist/lifecycle.js +287 -0
  118. package/dist/listing.d.ts +60 -0
  119. package/dist/listing.d.ts.map +1 -0
  120. package/dist/listing.js +168 -0
  121. package/dist/live.d.ts +25 -0
  122. package/dist/live.d.ts.map +1 -0
  123. package/dist/live.js +206 -0
  124. package/dist/loaded.d.ts +5 -0
  125. package/dist/loaded.d.ts.map +1 -0
  126. package/dist/loaded.js +40 -0
  127. package/dist/locks.d.ts +7 -0
  128. package/dist/locks.d.ts.map +1 -0
  129. package/dist/locks.js +32 -0
  130. package/dist/lost.d.ts +5 -0
  131. package/dist/lost.d.ts.map +1 -0
  132. package/dist/lost.js +49 -0
  133. package/dist/media.d.ts +25 -0
  134. package/dist/media.d.ts.map +1 -0
  135. package/dist/media.js +296 -0
  136. package/dist/memory.d.ts +21 -7
  137. package/dist/memory.d.ts.map +1 -1
  138. package/dist/memory.js +305 -117
  139. package/dist/messages.d.ts +58 -0
  140. package/dist/messages.d.ts.map +1 -0
  141. package/dist/messages.js +164 -0
  142. package/dist/modal.d.ts +2 -0
  143. package/dist/modal.d.ts.map +1 -0
  144. package/dist/modal.js +11 -0
  145. package/dist/model.d.ts +12 -13
  146. package/dist/model.d.ts.map +1 -1
  147. package/dist/model.js +11 -22
  148. package/dist/models.d.ts +10 -0
  149. package/dist/models.d.ts.map +1 -0
  150. package/dist/models.js +153 -0
  151. package/dist/name.d.ts +4 -0
  152. package/dist/name.d.ts.map +1 -0
  153. package/dist/name.js +122 -0
  154. package/dist/observation.d.ts +40 -10
  155. package/dist/observation.d.ts.map +1 -1
  156. package/dist/observation.js +265 -44
  157. package/dist/online.d.ts +7 -0
  158. package/dist/online.d.ts.map +1 -0
  159. package/dist/online.js +29 -0
  160. package/dist/opened.d.ts +22 -0
  161. package/dist/opened.d.ts.map +1 -0
  162. package/dist/opened.js +107 -0
  163. package/dist/opening.d.ts +4 -0
  164. package/dist/opening.d.ts.map +1 -0
  165. package/dist/opening.js +53 -0
  166. package/dist/outcome.d.ts +38 -10
  167. package/dist/outcome.d.ts.map +1 -1
  168. package/dist/outcome.js +49 -2
  169. package/dist/overlay.d.ts +7 -5
  170. package/dist/overlay.d.ts.map +1 -1
  171. package/dist/overlay.js +50 -176
  172. package/dist/page-metadata.d.ts +8 -0
  173. package/dist/page-metadata.d.ts.map +1 -0
  174. package/dist/page-metadata.js +19 -0
  175. package/dist/parts.d.ts +6 -0
  176. package/dist/parts.d.ts.map +1 -0
  177. package/dist/parts.js +36 -0
  178. package/dist/paths.d.ts +2 -0
  179. package/dist/paths.d.ts.map +1 -1
  180. package/dist/paths.js +26 -0
  181. package/dist/preparation.d.ts +41 -0
  182. package/dist/preparation.d.ts.map +1 -0
  183. package/dist/preparation.js +314 -0
  184. package/dist/presence.d.ts +58 -0
  185. package/dist/presence.d.ts.map +1 -0
  186. package/dist/presence.js +231 -0
  187. package/dist/queries.d.ts +16 -0
  188. package/dist/queries.d.ts.map +1 -0
  189. package/dist/queries.js +285 -0
  190. package/dist/query.d.ts +20 -207
  191. package/dist/query.d.ts.map +1 -1
  192. package/dist/query.js +3 -494
  193. package/dist/{chat/questions.d.ts → questions.d.ts} +6 -7
  194. package/dist/questions.d.ts.map +1 -0
  195. package/dist/{chat/questions.js → questions.js} +12 -7
  196. package/dist/queue.d.ts +40 -0
  197. package/dist/queue.d.ts.map +1 -0
  198. package/dist/queue.js +480 -0
  199. package/dist/reach.d.ts +28 -15
  200. package/dist/reach.d.ts.map +1 -1
  201. package/dist/reach.js +360 -166
  202. package/dist/react.d.ts +21 -3
  203. package/dist/react.d.ts.map +1 -1
  204. package/dist/react.js +33 -1
  205. package/dist/{chat/read.d.ts → read.d.ts} +2 -0
  206. package/dist/read.d.ts.map +1 -0
  207. package/dist/{chat/read.js → read.js} +4 -0
  208. package/dist/readiness.d.ts +22 -20
  209. package/dist/readiness.d.ts.map +1 -1
  210. package/dist/readiness.js +5 -13
  211. package/dist/reads.d.ts +38 -10
  212. package/dist/reads.d.ts.map +1 -1
  213. package/dist/reads.js +163 -83
  214. package/dist/recovery.d.ts +4 -0
  215. package/dist/recovery.d.ts.map +1 -1
  216. package/dist/recovery.js +59 -2
  217. package/dist/refresh.d.ts +18 -15
  218. package/dist/refresh.d.ts.map +1 -1
  219. package/dist/refresh.js +145 -79
  220. package/dist/refusal.d.ts +5 -0
  221. package/dist/refusal.d.ts.map +1 -0
  222. package/dist/refusal.js +55 -0
  223. package/dist/replica.d.ts +50 -38
  224. package/dist/replica.d.ts.map +1 -1
  225. package/dist/replica.js +319 -229
  226. package/dist/retried.d.ts +30 -0
  227. package/dist/retried.d.ts.map +1 -0
  228. package/dist/retried.js +72 -0
  229. package/dist/room-draft.d.ts +53 -13
  230. package/dist/room-draft.d.ts.map +1 -1
  231. package/dist/room-draft.js +402 -116
  232. package/dist/room-drafts.d.ts +24 -0
  233. package/dist/room-drafts.d.ts.map +1 -0
  234. package/dist/room-drafts.js +220 -0
  235. package/dist/room-list.d.ts +10 -0
  236. package/dist/room-list.d.ts.map +1 -0
  237. package/dist/room-list.js +45 -0
  238. package/dist/rows.d.ts +32 -31
  239. package/dist/rows.d.ts.map +1 -1
  240. package/dist/rows.js +59 -124
  241. package/dist/running.d.ts +5 -0
  242. package/dist/running.d.ts.map +1 -0
  243. package/dist/running.js +10 -0
  244. package/dist/runtime.d.ts +35 -0
  245. package/dist/runtime.d.ts.map +1 -0
  246. package/dist/runtime.js +1 -0
  247. package/dist/save.d.ts +44 -87
  248. package/dist/save.d.ts.map +1 -1
  249. package/dist/save.js +391 -279
  250. package/dist/saves.d.ts +34 -0
  251. package/dist/saves.d.ts.map +1 -0
  252. package/dist/saves.js +437 -0
  253. package/dist/search.d.ts +12 -95
  254. package/dist/search.d.ts.map +1 -1
  255. package/dist/search.js +10 -317
  256. package/dist/seed.d.ts +11 -2
  257. package/dist/seed.d.ts.map +1 -1
  258. package/dist/seed.js +71 -1
  259. package/dist/shared.d.ts +1 -10
  260. package/dist/shared.d.ts.map +1 -1
  261. package/dist/shared.js +13 -135
  262. package/dist/shown.d.ts +35 -0
  263. package/dist/shown.d.ts.map +1 -0
  264. package/dist/shown.js +313 -0
  265. package/dist/socket/admission.d.ts +7 -0
  266. package/dist/socket/admission.d.ts.map +1 -0
  267. package/dist/socket/admission.js +39 -0
  268. package/dist/socket/answers.d.ts +6 -0
  269. package/dist/socket/answers.d.ts.map +1 -0
  270. package/dist/socket/answers.js +20 -0
  271. package/dist/socket/lanes.d.ts +28 -0
  272. package/dist/socket/lanes.d.ts.map +1 -0
  273. package/dist/socket/lanes.js +103 -0
  274. package/dist/socket/reads.d.ts +10 -0
  275. package/dist/socket/reads.d.ts.map +1 -0
  276. package/dist/socket/reads.js +31 -0
  277. package/dist/socket/session.d.ts +39 -0
  278. package/dist/socket/session.d.ts.map +1 -0
  279. package/dist/socket/session.js +24 -0
  280. package/dist/socket.d.ts +68 -0
  281. package/dist/socket.d.ts.map +1 -0
  282. package/dist/socket.js +165 -0
  283. package/dist/source.d.ts +59 -0
  284. package/dist/source.d.ts.map +1 -0
  285. package/dist/source.js +93 -0
  286. package/dist/status.d.ts +4 -5
  287. package/dist/status.d.ts.map +1 -1
  288. package/dist/status.js +3 -7
  289. package/dist/store/installs.d.ts +30 -0
  290. package/dist/store/installs.d.ts.map +1 -0
  291. package/dist/store/installs.js +40 -0
  292. package/dist/store/readiness.d.ts +11 -0
  293. package/dist/store/readiness.d.ts.map +1 -0
  294. package/dist/store/readiness.js +68 -0
  295. package/dist/store/records.d.ts +226 -0
  296. package/dist/store/records.d.ts.map +1 -0
  297. package/dist/store/records.js +468 -0
  298. package/dist/store/room-held.d.ts +8 -0
  299. package/dist/store/room-held.d.ts.map +1 -0
  300. package/dist/store/room-held.js +17 -0
  301. package/dist/store/rooms-shown.d.ts +8 -0
  302. package/dist/store/rooms-shown.d.ts.map +1 -0
  303. package/dist/store/rooms-shown.js +13 -0
  304. package/dist/store/space.d.ts +11 -0
  305. package/dist/store/space.d.ts.map +1 -0
  306. package/dist/store/space.js +41 -0
  307. package/dist/store/watchers.d.ts +17 -0
  308. package/dist/store/watchers.d.ts.map +1 -0
  309. package/dist/store/watchers.js +56 -0
  310. package/dist/store/writes.d.ts +24 -0
  311. package/dist/store/writes.d.ts.map +1 -0
  312. package/dist/store/writes.js +125 -0
  313. package/dist/store.d.ts +114 -165
  314. package/dist/store.d.ts.map +1 -1
  315. package/dist/store.js +162 -804
  316. package/dist/stored.d.ts +167 -0
  317. package/dist/stored.d.ts.map +1 -0
  318. package/dist/stored.js +700 -0
  319. package/dist/surface.d.ts +94 -0
  320. package/dist/surface.d.ts.map +1 -0
  321. package/dist/surface.js +255 -0
  322. package/dist/sync.d.ts +20 -0
  323. package/dist/sync.d.ts.map +1 -0
  324. package/dist/sync.js +549 -0
  325. package/dist/tables.d.ts +376 -0
  326. package/dist/tables.d.ts.map +1 -0
  327. package/dist/tables.js +499 -0
  328. package/dist/tallies.d.ts +18 -0
  329. package/dist/tallies.d.ts.map +1 -0
  330. package/dist/tallies.js +128 -0
  331. package/dist/transfer.d.ts +0 -5
  332. package/dist/transfer.d.ts.map +1 -1
  333. package/dist/turn.d.ts +1 -1
  334. package/dist/turn.d.ts.map +1 -1
  335. package/dist/turn.js +28 -20
  336. package/dist/validation.d.ts +29 -0
  337. package/dist/validation.d.ts.map +1 -0
  338. package/dist/validation.js +98 -0
  339. package/dist/windows.d.ts +1 -11
  340. package/dist/windows.d.ts.map +1 -1
  341. package/dist/windows.js +2 -70
  342. package/dist/wire.d.ts +88 -9
  343. package/dist/wire.d.ts.map +1 -1
  344. package/dist/wire.js +31 -6
  345. package/package.json +19 -19
  346. package/AGENTS.md +0 -304
  347. package/dist/attempt.d.ts +0 -16
  348. package/dist/attempt.d.ts.map +0 -1
  349. package/dist/attempt.js +0 -70
  350. package/dist/chat/acts.d.ts +0 -33
  351. package/dist/chat/acts.d.ts.map +0 -1
  352. package/dist/chat/acts.js +0 -36
  353. package/dist/chat/context.d.ts +0 -3
  354. package/dist/chat/context.d.ts.map +0 -1
  355. package/dist/chat/earlier.d.ts +0 -10
  356. package/dist/chat/earlier.d.ts.map +0 -1
  357. package/dist/chat/earlier.js +0 -54
  358. package/dist/chat/house.d.ts +0 -25
  359. package/dist/chat/house.d.ts.map +0 -1
  360. package/dist/chat/house.js +0 -38
  361. package/dist/chat/input.d.ts +0 -11
  362. package/dist/chat/input.d.ts.map +0 -1
  363. package/dist/chat/input.js +0 -99
  364. package/dist/chat/kit.d.ts +0 -61
  365. package/dist/chat/kit.d.ts.map +0 -1
  366. package/dist/chat/kit.js +0 -123
  367. package/dist/chat/lasting.d.ts +0 -6
  368. package/dist/chat/lasting.d.ts.map +0 -1
  369. package/dist/chat/lasting.js +0 -19
  370. package/dist/chat/list.d.ts +0 -28
  371. package/dist/chat/list.d.ts.map +0 -1
  372. package/dist/chat/list.js +0 -103
  373. package/dist/chat/markdown.d.ts +0 -21
  374. package/dist/chat/markdown.d.ts.map +0 -1
  375. package/dist/chat/markdown.js +0 -246
  376. package/dist/chat/message.d.ts +0 -7
  377. package/dist/chat/message.d.ts.map +0 -1
  378. package/dist/chat/message.js +0 -221
  379. package/dist/chat/messages.d.ts +0 -30
  380. package/dist/chat/messages.d.ts.map +0 -1
  381. package/dist/chat/messages.js +0 -198
  382. package/dist/chat/name.d.ts +0 -7
  383. package/dist/chat/name.d.ts.map +0 -1
  384. package/dist/chat/name.js +0 -37
  385. package/dist/chat/opened.d.ts +0 -12
  386. package/dist/chat/opened.d.ts.map +0 -1
  387. package/dist/chat/opened.js +0 -19
  388. package/dist/chat/overlay.d.ts +0 -32
  389. package/dist/chat/overlay.d.ts.map +0 -1
  390. package/dist/chat/overlay.js +0 -107
  391. package/dist/chat/parts.d.ts +0 -57
  392. package/dist/chat/parts.d.ts.map +0 -1
  393. package/dist/chat/parts.js +0 -119
  394. package/dist/chat/pieces.d.ts +0 -62
  395. package/dist/chat/pieces.d.ts.map +0 -1
  396. package/dist/chat/pieces.js +0 -1110
  397. package/dist/chat/process.d.ts +0 -20
  398. package/dist/chat/process.d.ts.map +0 -1
  399. package/dist/chat/process.js +0 -32
  400. package/dist/chat/provider.d.ts +0 -66
  401. package/dist/chat/provider.d.ts.map +0 -1
  402. package/dist/chat/provider.js +0 -643
  403. package/dist/chat/question.d.ts +0 -9
  404. package/dist/chat/question.d.ts.map +0 -1
  405. package/dist/chat/question.js +0 -69
  406. package/dist/chat/questions.d.ts.map +0 -1
  407. package/dist/chat/read.d.ts.map +0 -1
  408. package/dist/chat/ready.d.ts +0 -36
  409. package/dist/chat/ready.d.ts.map +0 -1
  410. package/dist/chat/ready.js +0 -93
  411. package/dist/chat/steady.d.ts +0 -3
  412. package/dist/chat/steady.d.ts.map +0 -1
  413. package/dist/chat/steady.js +0 -26
  414. package/dist/chat/style.d.ts +0 -4
  415. package/dist/chat/style.d.ts.map +0 -1
  416. package/dist/chat/style.js +0 -305
  417. package/dist/chat.d.ts +0 -15
  418. package/dist/chat.d.ts.map +0 -1
  419. package/dist/chat.js +0 -8
  420. package/dist/fence.d.ts +0 -6
  421. package/dist/fence.d.ts.map +0 -1
  422. package/dist/fence.js +0 -10
  423. package/dist/log.d.ts +0 -5
  424. package/dist/log.d.ts.map +0 -1
  425. package/dist/log.js +0 -14
  426. package/dist/read-side.d.ts +0 -27
  427. package/dist/read-side.d.ts.map +0 -1
  428. package/dist/read-side.js +0 -1179
@@ -1,4176 +1,125 @@
1
- import { roomTarget, target } from '@agentshouse/mdmodel';
2
- import { attachedModel } from './attached-model.js';
3
- import { cached, modelTypes, NO_MODEL, sameModel, } from './model.js';
4
- import { observing, whole } from './observation.js';
5
- import { filterOf, identityOf, planOf, plain, queryKey, } from './query.js';
6
- import { createReadSide } from './read-side.js';
7
- import { seededResult } from './seed.js';
8
- import { documentKey, markdownPath, roomOfKey } from './rows.js';
9
- import { createSearchIndex, searchPlanOf, } from './search.js';
10
- import { capped, MAXIMUM_WINDOW } from './windows.js';
11
- import { bootstrapRoom } from './bootstrap.js';
12
- import { changeSet, changing, entering, mergeChangeSets } from './change-set.js';
13
- import { createConversationStore, } from './conversation.js';
14
- import { leaving as leavingIn, partnerOf, queuedFile, } from './change.js';
15
- import { indexReferrers, referencesIndexed, validRoot, } from './collection.js';
16
- import { runtimeError } from './failure.js';
17
- import { createLog } from './log.js';
18
- import { binaryRecord } from './binary.js';
19
- import { ABSENT_TARGET, absentBinary, binaryAnswer, binaryLinkAnswer, calledResult, failure, historyAnswer, LOCKED_UNREADABLE, lockedRoom, undeclared, UNCERTAIN, UNREADABLE, } from './outcome.js';
1
+ import { notReadyWaitMs } from '@agentshouse/mdmodel';
2
+ import { submitLater } from './acceptance.js';
3
+ import { invokeAction, called, readConversationHistory, resendLater } from './actions.js';
4
+ import { builtInModel, NO_ROOM_TYPES } from './attached-model.js';
5
+ import { createLiveConversations } from './conversation-live.js';
6
+ import { writeRule } from './declaration.js';
7
+ import { refusedForSpace } from './durability.js';
8
+ import { uncaught } from './failure.js';
9
+ import { createFigures } from './figures.js';
10
+ import { scheduleCurrency, spaceFreed, start } from './lifecycle.js';
11
+ import { createLiveQueries } from './live.js';
12
+ import { open } from './opening.js';
13
+ import { deliverOwedReadiness, filled, prepare } from './preparation.js';
14
+ import { createPresence } from './presence.js';
15
+ import { answeredPlan, figuresCover, roomTallies } from './queries.js';
16
+ import { readAnswers } from './reads.js';
20
17
  import { createRecovery } from './recovery.js';
21
- import { doorReads } from './reads.js';
22
- import { refreshRoom } from './refresh.js';
23
- import { buildBatch, buildMove, joined, limiting, queuedDocuments, requeuing, } from './save.js';
24
- import { applyReturned, compositionOf, confirmedOf, landed, readReclassified, replicating, sameMembership, standing, } from './replica.js';
25
- import { binaryBase, changedParts, changesOf, held, heldFile, joinedDraft, moveTarget, readParts, returnedBy, returnedInto, staleWrite, underneath, withdrawnDrafts, } from './room-draft.js';
26
- import { same, saving, STARTING, transferring, } from './status.js';
27
- import { detectStorageLoss, nextGeneration } from './durability.js';
28
- import { readinessOf, SETTLED_ROOMS, } from './readiness.js';
29
- import { FencedMap } from './fence.js';
30
- import { keysIn, tallying } from './shared.js';
31
- import { finished, inChunks, ROW_WEIGHT, stepped, yielded } from './turn.js';
32
- import { identityTime, roomDraftRevision } from './identity.js';
33
- import { beneath, normalize } from './paths.js';
34
- import { openRuntimeStore, } from './store.js';
35
- import { unconfirmed } from './transfer.js';
36
- import { governs, holds, narrowed, planReach, } from './reach.js';
37
- function roomsAlone(plan) {
38
- return (plan.reach === null &&
39
- plan.root.types === null &&
40
- plan.root.where === null &&
41
- plan.root.pathPrefix === null &&
42
- plan.paths === null &&
43
- plan.hop === null &&
44
- plan.backlinks === null);
45
- }
46
- function within(root, path) {
47
- return root === '' || beneath(root, path);
48
- }
49
- function declaredSelection(room) {
50
- const selection = room.typedSelection;
51
- if (selection === undefined)
52
- return true;
53
- if (!Array.isArray(selection.roots) || selection.roots.length === 0)
54
- return false;
55
- return selection.roots.every((root, index) => validRoot(root) &&
56
- root !== '' &&
57
- selection.roots.every((other, at) => at === index || !within(other, root)));
58
- }
59
- const OPENING_LANE = 'opening';
60
- const CONVERSATION_LANE = 'conversations';
61
- const ROOM_READS = 256;
18
+ import { createRetries } from './retried.js';
19
+ import { publishChangeSet, show } from './shown.js';
20
+ import { createSocket } from './socket.js';
21
+ import { createStore } from './store.js';
22
+ import { composedRuntime } from './surface.js';
23
+ import { discover } from './sync.js';
62
24
  const ROOM_ATTEMPTS = 16;
63
- // A Room that locks offline stays readable this long after the connection drops, so a laptop waking or changing network keeps working while a disconnected device locks soon after.
64
- const LOCK_GRACE_MS = 120_000;
65
- function operationOf(input) {
66
- const operation = input?.operation_id;
67
- return typeof operation === 'string' ? operation : null;
68
- }
69
- const outside = new Map();
70
- function outsideOf(roots) {
71
- const key = JSON.stringify(roots);
72
- const held = outside.get(key);
73
- if (held !== undefined)
74
- return held;
75
- const counted = (path) => (roots.some((root) => beneath(root, path)) ? 0 : 1);
76
- const made = {
77
- documents: (path) => (markdownPath(path) ? counted(path) : 0),
78
- binaries: counted,
79
- };
80
- outside.set(key, made);
81
- return made;
82
- }
83
- function abandonedOn(signal) {
84
- return new Promise((resolve) => {
85
- if (signal.aborted)
86
- resolve(null);
87
- else
88
- signal.addEventListener('abort', () => resolve(null), { once: true });
89
- });
90
- }
91
- function roomLane(locator) {
92
- return `room ${locator}`;
93
- }
94
- function pendingKey(locator, id) {
95
- return `${locator}\u0000${id}`;
96
- }
97
25
  export function composeRuntime(options) {
98
- const localSaves = options.adapter.localSaves === true;
99
- let authorization = options.authorization;
100
- let opening;
101
- let store;
102
- const fences = new Map();
103
- const isFenced = (locator) => fences.has(locator);
104
- let fencings = 0;
105
- const lastFenced = new Map();
106
- const fencedSince = (locator, since) => fences.has(locator) || (lastFenced.get(locator) ?? 0) > since;
107
- let discoveries = 0;
108
- const replicas = new FencedMap(isFenced);
109
- const queuesWithoutReplica = new FencedMap(isFenced);
110
- const pendings = new Map();
111
- const seeds = new Map();
112
- const seedWatchers = new Map();
113
- const roomDrafts = new FencedMap(isFenced);
114
- const presentations = new Map();
115
- let limits = [];
116
- let capabilities = [];
117
- const rooms = new FencedMap(isFenced);
118
- const counted = new Map();
119
- const unreadable = new Set();
120
- const isModelFenced = (key) => isFenced(key.slice(key.indexOf(' ') + 1));
121
- const models = new FencedMap(isModelFenced);
122
- const liveModels = new FencedMap(isModelFenced);
123
- const invalidModels = new Set();
124
- const discovered = new Map();
125
- const reads = doorReads(options.adapter, (locator) => discovered.get(locator), () => generation);
126
- let roomsListed = false;
127
- const scopedRefusals = new Map();
128
- const sourceRefusals = new Map();
129
- const declarationRefusals = new Set();
130
- function modelKey(locator, attached) {
131
- return `${attached} ${locator}`;
132
- }
133
- function modelOf(locator, attached = 'collection') {
134
- return models.get(modelKey(locator, attached)) ?? NO_MODEL;
135
- }
136
- function savedModel(locator, attached) {
137
- return invalidModels.has(modelKey(locator, attached))
138
- ? { status: 'unavailable', reason: 'revoked' }
139
- : modelOf(locator, attached);
140
- }
141
- function compositionFor(record) {
142
- return compositionOf({
143
- ...record,
144
- model: savedModel(record.locator, 'collection'),
145
- selectionModel: savedModel(record.locator, 'typed-selection'),
146
- });
147
- }
148
- let refusal = null;
149
- let storageLoss = null;
150
- let status = STARTING;
151
- let shown = STARTING;
152
- let discoveryPaused = false;
153
- let closed = false;
154
- let stopping = false;
155
- let withdrawStream;
156
- const announced = new Map();
157
- let underway = null;
158
- let streamed = null;
159
- let handed = false;
160
- const recovery = (options.recovery ?? createRecovery()).scope(ROOM_ATTEMPTS);
161
- const repairing = new Set();
162
- const calling = new Set();
163
- const repairable = new Map();
164
- let outcomeRetention = null;
165
- const answering = new Map();
166
- let complete = false;
167
- let recorded = false;
168
- const stale = new Set();
169
- let generation = 0;
170
- let discovering = null;
171
- let opened = null;
172
- const owed = new Set();
173
- const reloadsDue = new Map();
174
- const lanes = new Map();
175
- let roomReads = { generation, free: ROOM_READS, waiting: [] };
176
- const working = new Set();
177
- let mutations = Promise.resolve();
178
- const roomListeners = new Set();
179
- const refusalListeners = new Set();
180
- const storageLossListeners = new Set();
181
- const statusListeners = new Set();
182
- const queueSubscriptions = new Set();
183
- const roomDraftListeners = new Set();
184
- const presentationListeners = new Set();
185
- const readSide = createReadSide();
186
- let withdrawConversations;
187
- let currencyQueued = null;
188
- let socketOpen = false;
189
- const confirmed = new Set();
190
- let lockGrace = null;
191
- const lockListeners = new Set();
192
- let serviceMode = 'open';
193
- let haltedRefusal = false;
194
- let openSignals = 0;
195
- const serviceModeListeners = new Set();
196
- let member = null;
197
- const memberListeners = new Set();
198
- const prepared = new Set();
199
- const projecting = new Set();
200
- const unpreparedDemand = new Set();
201
- const unindexable = new Set();
202
- let preparing = false;
203
- let targets = {};
204
- let persistence = options.shell.persistence;
205
- let capacity = null;
206
- const paused = new Set();
207
- let rechecking = null;
208
- const readinessWatches = new Set();
209
- let readinessQueued = false;
210
- const catching = new Set();
211
- const transfers = new FencedMap(isFenced);
212
- const conversations = createConversationStore({
213
- agents: declaredAgents,
214
- documents: ({ locator }) => rowsQuery(planOf({ rooms: [locator], select: { fields: 'all' } }, roomFacts())),
215
- call: (name, input) => invokeAction(name, input),
216
- durably,
217
- stream: () => options.adapter.conversations,
218
- publish: publishChangeSet,
219
- online: () => connectionOf() !== 'unreachable' && refusal === null,
220
- closed: () => closed,
221
- unanswered: resendLater,
222
- expired: (operation) => pastHorizon(operation),
223
- });
224
- const searchIndex = createSearchIndex({
225
- room: (room) => readSide.room(room),
226
- document: (room, path) => readSide.document(room, path),
227
- });
228
- const roomsToIndex = new Set();
229
- const conversationsToIndex = new Set();
230
- let indexing = false;
231
- const journal = createLog();
232
- let notifyReady = () => { };
233
- const ready = new Promise((resolve) => {
234
- notifyReady = resolve;
235
- });
236
- function rememberRoomDraft(record) {
237
- const room = roomDrafts.get(record.locator) ?? new Map();
238
- room.set(record.path, record);
239
- roomDrafts.set(record.locator, room);
240
- }
241
- function forgetRoomDraft(locator, path) {
242
- const room = roomDrafts.get(locator);
243
- if (room === undefined)
244
- return;
245
- room.delete(path);
246
- if (room.size === 0)
247
- roomDrafts.delete(locator);
248
- }
249
- function roomDraftOf(record) {
250
- return structuredClone({
251
- room: record.locator,
252
- path: record.path,
253
- revision: record.revision,
254
- parts: record.parts,
255
- changedUnderneath: underneath(record.parts, record.path, replicas.get(record.locator)?.visible),
256
- returned: record.returned,
257
- });
258
- }
259
- function snapshotRoomDrafts() {
260
- const records = [...roomDrafts.values()].flatMap((room) => [...room.values()]);
261
- records.sort((left, right) => {
262
- if (left.locator !== right.locator)
263
- return left.locator < right.locator ? -1 : 1;
264
- if (left.path !== right.path)
265
- return left.path < right.path ? -1 : 1;
266
- return 0;
267
- });
268
- return records.map(roomDraftOf);
269
- }
270
- function publishRoomDrafts(waitingOnly) {
271
- if (closed)
272
- return;
273
- const value = snapshotRoomDrafts();
274
- for (const listener of roomDraftListeners) {
275
- if (waitingOnly && listener.ready)
276
- continue;
277
- listener.ready = true;
278
- listener.notify(value);
279
- }
280
- }
281
- function presentationOf(app) {
282
- const value = presentations.get(app);
283
- return value === undefined ? null : structuredClone(value);
284
- }
285
- function keepPresentation(app, next) {
286
- return exclusive(async () => {
287
- const local = await openLocal();
288
- const stored = next(presentations.get(app));
289
- await local.present({ app, value: stored });
290
- presentations.set(app, stored);
291
- publishChangeSet(changeSet('', null, null, { presentation: app }));
292
- });
293
- }
294
- function emitPresentation(app) {
295
- if (closed)
296
- return;
297
- for (const listener of presentationListeners) {
298
- if (listener.app === app && listener.ready)
299
- listener.notify(presentationOf(app));
300
- }
301
- }
302
- function pending() {
303
- return (!localSaves &&
304
- (queuesWithoutReplica.size > 0 ||
305
- [...replicas.values()].some((replica) => replica.queue.length > 0)));
306
- }
307
- function attention() {
308
- const attentionRequired = [];
309
- for (const record of [...roomDrafts.values()].flatMap((room) => [...room.values()])) {
310
- if (record.returned === null)
311
- continue;
312
- attentionRequired.push({
313
- room: record.locator,
314
- path: record.path,
315
- returned: structuredClone(record.returned),
316
- });
317
- }
318
- for (const [room, refusal] of sourceRefusals)
319
- attentionRequired.push({ room, refusal: structuredClone(refusal) });
320
- attentionRequired.sort((left, right) => {
321
- if (left.room !== right.room)
322
- return left.room < right.room ? -1 : 1;
323
- if ('refusal' in left || 'refusal' in right) {
324
- if ('refusal' in left && 'refusal' in right)
325
- return 0;
326
- return 'refusal' in left ? -1 : 1;
327
- }
328
- if (left.path !== right.path)
329
- return left.path < right.path ? -1 : 1;
330
- return 0;
331
- });
332
- let reset = null;
333
- for (const { submission } of pendings.values()) {
334
- if (submission.state !== 'reset')
335
- continue;
336
- if (reset === null || submission.reset < reset)
337
- reset = submission.reset;
338
- }
339
- return { attentionRequired, reset };
340
- }
341
- function documentsIn(locator) {
342
- const replica = replicas.get(locator);
343
- return replica === undefined ? 0 : finished(counting(replica));
344
- }
345
- function* counting(replica) {
346
- const weighed = outsideOf(replica.confirmed.record.typedSelection?.roots ?? []);
347
- return ((yield* tallying(replica.visible.documents, weighed.documents)) +
348
- (yield* tallying(replica.visible.binaries, weighed.binaries)));
349
- }
350
- function listed() {
351
- return structuredClone([...rooms.values()].map((room) => {
352
- const documents = documentsIn(room.locator);
353
- counted.set(room.locator, documents);
354
- return locked(room.locator)
355
- ? {
356
- ...room,
357
- model: modelTypes(NO_MODEL),
358
- typedSelection: null,
359
- documents: 0,
360
- locked: true,
361
- }
362
- : { ...room, documents, locked: false };
363
- }));
364
- }
365
- function locked(locator) {
366
- return rooms.get(locator)?.replica.offline === 'locked' && !confirmed.has(locator);
367
- }
368
- function lockedRooms() {
369
- return [...rooms.keys()].filter(locked).sort();
370
- }
371
- function relocked(before) {
372
- const after = lockedRooms();
373
- if (JSON.stringify(after) === JSON.stringify(before))
374
- return;
375
- journal.record(`locked ${after.length}`);
376
- emitRooms();
377
- for (const notify of [...lockListeners])
378
- notify();
379
- }
380
- function confirmLocks(listed) {
381
- if (!socketOpen)
382
- return;
383
- for (const room of listed) {
384
- if (room.replica.admission === 'admitted')
385
- confirmed.add(room.locator);
386
- }
387
- }
388
- function connectionLost() {
389
- if (lockGrace !== null || closed)
390
- return;
391
- lockGrace = setTimeout(() => {
392
- lockGrace = null;
393
- if (socketOpen || closed)
394
- return;
395
- const before = lockedRooms();
396
- confirmed.clear();
397
- relocked(before);
398
- }, LOCK_GRACE_MS);
399
- }
400
- function connectionLive() {
401
- if (lockGrace !== null)
402
- clearTimeout(lockGrace);
403
- lockGrace = null;
404
- }
405
- function watchLocks(notify) {
406
- lockListeners.add(notify);
407
- return () => {
408
- lockListeners.delete(notify);
409
- };
410
- }
411
- function roomFacts(reach = null) {
412
- const held = [...rooms.values()]
413
- .filter((room) => holds(reach, room.locator))
414
- .map((room) => {
415
- const governed = governs(reach, room);
416
- const attached = [
417
- ...(governed.collection ? [modelOf(room.locator)] : []),
418
- ...(governed.selection ? [modelOf(room.locator, 'typed-selection')] : []),
419
- ];
420
- return {
421
- locator: room.locator,
422
- available: attached.every((model) => model.status !== 'unavailable'),
423
- types: attached.flatMap((model) => model.status === 'unavailable' ? [] : Object.values(model.types)),
424
- };
425
- });
426
- return { listed: roomsListed, rooms: held };
427
- }
428
- function emitRooms() {
429
- readSide.recover();
430
- queueReadiness();
431
- const value = listed();
432
- for (const listener of roomListeners)
433
- listener(value);
434
- }
435
- function emitRefusal() {
436
- queueReadiness();
437
- for (const listener of refusalListeners)
438
- listener(refusal);
439
- }
440
- function emitStorageLoss() {
441
- queueReadiness();
442
- for (const listener of storageLossListeners)
443
- listener(storageLoss);
444
- }
445
- function emitMember() {
446
- for (const listener of memberListeners)
447
- listener(member);
448
- }
449
- function moveTo(next) {
450
- if (closed)
451
- return;
452
- status = next;
453
- show();
454
- }
455
- function show() {
456
- if (closed)
457
- return;
458
- queueReadiness();
459
- const next = status.state === 'synced' && !conversations.current()
460
- ? { ...status, state: 'syncing' }
461
- : status;
462
- if (same(shown, next))
463
- return;
464
- shown = next;
465
- for (const listener of statusListeners)
466
- listener(shown);
467
- }
468
- function entryOf(locator, batch) {
469
- if (localSaves)
470
- return Object.freeze({ batch, state: 'local' });
471
- const state = pendings.get(pendingKey(locator, batch.id));
472
- if (state?.accepted !== undefined) {
473
- return Object.freeze({ batch, state: 'accepted', roomVersion: state.accepted });
474
- }
475
- return Object.freeze({ batch, ...(state?.submission ?? { state: 'waiting' }) });
476
- }
477
- function entriesOf(locator) {
478
- return (replicas.get(locator)?.queue ?? queuesWithoutReplica.get(locator) ?? []).map((batch) => entryOf(locator, batch));
479
- }
480
- function emitQueue(locator) {
481
- const entries = entriesOf(locator);
482
- for (const subscription of queueSubscriptions) {
483
- if (subscription.locator === locator)
484
- subscription.notify(entries);
485
- }
486
- }
487
- function applyChangeSet(set) {
488
- const held = {
489
- ...set,
490
- documents: set.documents.filter(({ locator }) => prepared.has(locator) || projecting.has(locator)),
491
- };
492
- const applied = readSide.apply(held, () => searchIndex.changed(held));
493
- if (applied instanceof Promise)
494
- void applied.catch(unpublished);
495
- }
496
- function unpublished(error) {
497
- journal.record(`publication failed ${error instanceof Error ? error.name : 'unknown'}`);
498
- }
499
- async function referenced(locator) {
500
- for (;;) {
501
- const record = replicas.get(locator)?.confirmed.record;
502
- if (record === undefined || closed)
503
- return;
504
- const held = { text: record.documents, binaries: record.binaries };
505
- const composition = compositionOf(record);
506
- if (referencesIndexed(held, composition))
507
- return;
508
- await indexReferrers(held, composition);
509
- }
510
- }
511
- async function prepareReplica(locator) {
512
- await referenced(locator);
513
- const replica = replicas.get(locator);
514
- if (replica === undefined || closed || prepared.has(locator))
515
- return;
516
- const visible = replica.visible;
517
- const entered = [];
518
- projecting.add(locator);
519
- try {
520
- await inChunks(await stepped(keysIn(visible.documents, visible.binaries)), (path) => ROW_WEIGHT + (visible.documents[path]?.length ?? 0), (chunk) => {
521
- const current = replicas.get(locator);
522
- if (current === undefined || closed)
523
- return;
524
- const set = entering(locator, current, chunk);
525
- entered.push(set);
526
- return readSide.apply(set);
527
- });
528
- if (!replicas.has(locator) || closed)
529
- return;
530
- prepared.add(locator);
531
- }
532
- finally {
533
- projecting.delete(locator);
534
- }
535
- conversations.changed(mergeChangeSets(entered));
536
- readSide.recover();
537
- queueReadiness();
538
- }
539
- function unprepared() {
540
- return [...unpreparedDemand, ...replicas.keys()].find((locator) => !prepared.has(locator) && !unindexable.has(locator));
541
- }
542
- function unbuilt(locator, error) {
543
- unindexable.add(locator);
544
- journal.record(`index failed ${locator} ${error instanceof Error ? error.name : 'unknown'}`);
545
- queueReadiness();
546
- }
547
- function prepare(locators = []) {
548
- for (const locator of locators)
549
- unpreparedDemand.add(locator);
550
- if (preparing)
551
- return;
552
- preparing = true;
553
- void (async () => {
554
- try {
555
- for (let waiting = unprepared(); waiting !== undefined; waiting = unprepared()) {
556
- await yielded();
557
- if (closed)
558
- return;
559
- unpreparedDemand.delete(waiting);
560
- await prepareReplica(waiting).catch((error) => unbuilt(waiting, error));
561
- }
562
- }
563
- finally {
564
- preparing = false;
565
- }
566
- })();
567
- }
568
- function roomsOfReach(reach) {
569
- return new Set([...reach.rooms, ...reach.documents.map(roomOfKey)]);
570
- }
571
- function reachedRooms(plan) {
572
- const reached = plan.reach === null ? null : roomsOfReach(plan.reach);
573
- const named = plan.rooms ??
574
- (reached === null
575
- ? [...new Set([...rooms.keys(), ...replicas.keys(), ...queuesWithoutReplica.keys()])]
576
- : [...reached]);
577
- return [...new Set(named)]
578
- .filter((locator) => (reached === null || reached.has(locator)) && !plan.locked.includes(locator))
579
- .sort();
580
- }
581
- function awaited(locator) {
582
- return (!roomsListed ||
583
- (rooms.has(locator) && discovered.get(locator)?.replica.admission === 'admitted'));
584
- }
585
- function covered(plan) {
586
- const locators = reachedRooms(plan);
587
- if (locators.length === 0 && plan.rooms === null && plan.reach === null && !roomsListed) {
588
- return { pending: [] };
589
- }
590
- const pending = [];
591
- const coverage = [];
592
- const overlay = [];
593
- for (const locator of locators) {
594
- const replica = replicas.get(locator);
595
- if (replica === undefined) {
596
- if (awaited(locator))
597
- pending.push({ room: locator, awaits: 'acquisition' });
598
- continue;
599
- }
600
- if (!prepared.has(locator)) {
601
- pending.push({ room: locator, awaits: 'preparation' });
602
- continue;
603
- }
604
- coverage.push({
605
- room: locator,
606
- generation: replica.confirmed.record.transfer,
607
- current: !(catching.has(locator) || owed.has(locator) || transfers.has(locator)),
608
- });
609
- for (const batch of replica.queue)
610
- overlay.push(batch.id);
611
- }
612
- if (pending.length > 0)
613
- return { pending };
614
- return { coverage: { rooms: coverage, indexes: [], overlay } };
615
- }
616
- function awaitPreparation(cover) {
617
- if (!('pending' in cover))
618
- return;
619
- const waiting = cover.pending.filter(({ awaits }) => awaits === 'preparation');
620
- if (waiting.length > 0)
621
- prepare(waiting.map(({ room }) => room));
622
- }
623
- function requiredRooms(given) {
624
- const reach = planReach(given);
625
- if (reach === null)
626
- return { listed: roomsListed, rooms: [...rooms.keys()].sort() };
627
- const named = [...roomsOfReach(reach)].sort();
628
- if (roomsListed)
629
- return { listed: true, rooms: named.filter((room) => rooms.has(room)) };
630
- return { listed: named.every((room) => replicas.has(room)), rooms: named };
631
- }
632
- function roomState(locator, search) {
633
- if (sourceRefusals.has(locator))
634
- return 'refused';
635
- const listedRoom = discovered.get(locator);
636
- if (roomsListed &&
637
- (listedRoom === undefined ||
638
- listedRoom.replica.admission !== 'admitted' ||
639
- unreadable.has(locator)))
640
- return 'unadmitted';
641
- if (!replicas.has(locator))
642
- return 'acquiring';
643
- if (!prepared.has(locator))
644
- return 'preparing';
645
- if (search && !searchIndex.rooms().has(locator))
646
- return 'indexing';
647
- return 'complete';
648
- }
649
- function conversationCoverage(reach, search) {
650
- const declared = reach === null || reach.conversations;
651
- if (!declared || options.adapter.conversations === undefined || declaredAgents() === undefined)
652
- return 'undeclared';
653
- if (!conversations.known() || !conversations.current())
654
- return 'acquiring';
655
- if (!search)
656
- return 'complete';
657
- const unindexed = conversations
658
- .searchable()
659
- .filter((one) => conversations.acquired(one) && !searchIndex.conversations().has(one));
660
- if (unindexed.length === 0)
661
- return 'complete';
662
- index([], unindexed);
663
- return 'indexing';
664
- }
665
- function connectionOf() {
666
- if (socketOpen)
667
- return 'connected';
668
- if (status.providerUnreachable)
669
- return 'unreachable';
670
- return options.adapter.roomStream === undefined && status.lastCompleted !== null
671
- ? 'connected'
672
- : 'connecting';
673
- }
674
- function refusedIn(locators) {
675
- return locators.flatMap((room) => {
676
- const held = sourceRefusals.get(room);
677
- if (held === undefined)
678
- return [];
679
- const { file, location } = held.fields;
680
- return [
681
- {
682
- room,
683
- file: typeof file === 'string' ? file : '',
684
- rule: held.code,
685
- location: typeof location === 'string' ? location : null,
686
- },
687
- ];
688
- });
689
- }
690
- function readinessFor(port, reach) {
691
- const required = requiredRooms(reach);
692
- const search = port.search === 'required';
693
- const coverage = required.rooms.map((room) => ({ room, state: roomState(room, search) }));
694
- const building = (state) => coverage
695
- .filter((room) => room.state === state && !unindexable.has(room.room))
696
- .map(({ room }) => room);
697
- const preparing = building('preparing');
698
- if (preparing.length > 0)
699
- prepare(preparing);
700
- const indexing = building('indexing');
701
- if (indexing.length > 0)
702
- index(indexing, []);
703
- return readinessOf({
704
- code: port.code,
705
- coverage: {
706
- listed: required.listed,
707
- rooms: coverage,
708
- conversations: conversationCoverage(reach, search),
709
- search: search ? 'required' : 'unused',
710
- },
711
- persistence,
712
- connection: connectionOf(),
713
- house: refusal !== null ? 'refused' : writesHeld() ? 'write-halted' : 'open',
714
- capacity: capacity !== null &&
715
- coverage.some(({ room, state }) => paused.has(room) || !SETTLED_ROOMS.has(state))
716
- ? capacity
717
- : port.capacity,
718
- refused: refusedIn(required.rooms),
719
- lost: storageLoss !== null,
720
- established: targets[port.target]?.established === true,
721
- });
722
- }
723
- function establish(name) {
724
- targets = { ...targets, [name]: { established: true } };
725
- queueReadiness();
726
- void durably((local) => local.keepTargets(targets)).catch(() => {
727
- journal.record(`target record failed ${name}`);
728
- });
729
- }
730
- function deliverReadiness(watch) {
731
- if (!readinessWatches.has(watch))
732
- return;
733
- const readiness = readinessFor(watch.port, watch.reach);
734
- if (readiness.ready && targets[watch.port.target]?.established !== true) {
735
- establish(watch.port.target);
736
- }
737
- const shown = JSON.stringify(readiness);
738
- if (shown === watch.last)
739
- return;
740
- watch.last = shown;
741
- watch.deliver(structuredClone(readiness));
742
- }
743
- function queueReadiness() {
744
- if (readinessQueued || closed || readinessWatches.size === 0)
745
- return;
746
- readinessQueued = true;
747
- queueMicrotask(() => {
748
- readinessQueued = false;
749
- if (closed)
750
- return;
751
- for (const watch of [...readinessWatches])
752
- deliverReadiness(watch);
753
- });
754
- }
755
- function watchReadiness(port, reach, deliver) {
756
- const watch = { port, reach, deliver, last: null };
757
- readinessWatches.add(watch);
758
- void openLocal().then(() => deliverReadiness(watch), () => deliverReadiness(watch));
759
- return () => {
760
- readinessWatches.delete(watch);
761
- };
762
- }
763
- function layerBytes(layer) {
764
- let bytes = 0;
765
- for (const [path, text] of Object.entries(layer.documents))
766
- bytes += (path.length + text.length) * 2;
767
- return bytes;
768
- }
769
- function grownBy(next, previous) {
770
- if (previous === undefined)
771
- return layerBytes(next);
772
- const documents = Object.fromEntries(Object.entries(next.documents).filter(([path, text]) => previous.documents[path] !== text));
773
- return layerBytes({ ...next, documents });
774
- }
775
- function exceeded(error) {
776
- return (typeof error === 'object' &&
777
- error !== null &&
778
- error.name === 'QuotaExceededError');
779
- }
780
- async function estimated() {
781
- const estimate = options.shell.estimate === undefined ? null : await options.shell.estimate();
782
- return estimate === null ? null : Math.max(0, estimate.total - estimate.usage);
783
- }
784
- function pause(locator, cause) {
785
- paused.add(locator);
786
- capacity = cause;
787
- journal.record(`capacity ${cause.cause} ${locator} ${cause.needed} ${cause.available ?? '-'}`);
788
- queueReadiness();
789
- if (rechecking !== null)
790
- return;
791
- // A paused preparation measures the browser's space again each minute, so space freed elsewhere resumes it without a retry.
792
- rechecking = setInterval(() => {
793
- void recheck();
794
- }, 60_000);
795
- }
796
- async function recheck() {
797
- const held = capacity;
798
- if (held === null || closed)
799
- return;
800
- const available = await estimated().catch(() => null);
801
- if (available === null || available < (held.needed ?? 0))
802
- return;
803
- if (held.cause === 'storage-exceeded' &&
804
- (held.available === null || available <= held.available))
805
- return;
806
- resume();
807
- }
808
- function resume() {
809
- if (rechecking !== null)
810
- clearInterval(rechecking);
811
- rechecking = null;
812
- if (paused.size === 0 && capacity === null)
813
- return;
814
- paused.clear();
815
- capacity = null;
816
- journal.record('capacity resumed');
817
- queueReadiness();
818
- if (!closed && authorization !== undefined)
819
- void sync('unstreamed');
820
- }
821
- async function reclaimed(local) {
822
- const unreferenced = [...transfers.keys()].filter((locator) => !discovered.has(locator));
823
- for (const locator of unreferenced) {
824
- await local.abandon(locator);
825
- transfers.delete(locator);
826
- }
827
- if (unreferenced.length > 0)
828
- journal.record(`capacity reclaimed ${unreferenced.length}`);
829
- return unreferenced.length > 0;
830
- }
831
- async function admitted(local, locator, needed) {
832
- if (paused.has(locator))
833
- return false;
834
- let available = await estimated().catch(() => null);
835
- if (available === null || available >= needed)
836
- return true;
837
- if (await reclaimed(local))
838
- available = await estimated().catch(() => null);
839
- if (available === null || available >= needed)
840
- return true;
841
- pause(locator, { cause: 'insufficient-space', needed, available });
842
- return false;
843
- }
844
- async function exceededOn(locator, bytes) {
845
- const available = await estimated().catch(() => null);
846
- pause(locator, { cause: 'storage-exceeded', needed: bytes, available });
847
- }
848
- function seedRoomHeld(room, version) {
849
- return prepared.has(room) && reachedBy(room, version);
850
- }
851
- function seedHeld(at) {
852
- return Object.entries(at).every(([room, version]) => (roomsListed && !rooms.has(room)) || seedRoomHeld(room, version));
853
- }
854
- function seedApplies(plan) {
855
- const seed = seeds.get(plan.key);
856
- if (seed === undefined)
857
- return null;
858
- if (!seedHeld(seed.at))
859
- return seed;
860
- seeds.delete(plan.key);
861
- return null;
862
- }
863
- function seedBehind(plan, cover) {
864
- const seed = seedApplies(plan);
865
- if (seed === null || 'pending' in cover)
866
- return cover;
867
- return {
868
- pending: Object.entries(seed.at)
869
- .filter(([room, version]) => !seedRoomHeld(room, version))
870
- .map(([room]) => ({ room, awaits: 'acquisition' })),
871
- };
872
- }
873
- function seed(entry) {
874
- if (seedHeld(entry.at))
875
- return;
876
- for (const { query, rows } of entry.queries) {
877
- const key = queryKey(query);
878
- seeds.set(key, { rows, at: entry.at });
879
- for (const shown of seedWatchers.get(key) ?? [])
880
- shown();
881
- }
882
- }
883
- async function rowsQuery(plan) {
884
- const before = covered(plan);
885
- awaitPreparation(before);
886
- const seeded = seedApplies(plan);
887
- if (seeded !== null)
888
- return seededResult(seeded).result;
889
- if ('pending' in before)
890
- return before;
891
- const { rows, at: cover } = await readSide.query(plan, () => covered(plan));
892
- awaitPreparation(cover);
893
- if ('pending' in cover)
894
- return cover;
895
- return { ...rows, coverage: cover.coverage };
896
- }
897
- async function indexConversation(conversation) {
898
- searchIndex.indexMessages(conversation, [], false);
899
- let after = null;
900
- for (;;) {
901
- const batch = await durably((local) => local.messagesAfter(conversation, after));
902
- if (closed)
903
- return;
904
- searchIndex.indexMessages(conversation, batch.map(({ identity, text }) => ({ conversation, identity, text })), batch.length === 0);
905
- if (batch.length === 0)
906
- return;
907
- after = batch[batch.length - 1].identity;
908
- }
909
- }
910
- function indexNext() {
911
- const room = [...roomsToIndex].find((locator) => !searchIndex.rooms().has(locator) && !unindexable.has(locator));
912
- if (room !== undefined) {
913
- roomsToIndex.delete(room);
914
- return () => prepared.has(room)
915
- ? searchIndex.indexRoom(room).catch((error) => unbuilt(room, error))
916
- : undefined;
917
- }
918
- const conversation = [...conversationsToIndex].find((one) => !searchIndex.conversations().has(one));
919
- if (conversation === undefined)
920
- return null;
921
- conversationsToIndex.delete(conversation);
922
- return () => indexConversation(conversation);
923
- }
924
- function index(rooms, named) {
925
- for (const room of rooms)
926
- roomsToIndex.add(room);
927
- for (const conversation of named)
928
- conversationsToIndex.add(conversation);
929
- if (indexing)
930
- return;
931
- indexing = true;
932
- void (async () => {
933
- try {
934
- for (let unit = indexNext(); unit !== null && !closed; unit = indexNext()) {
935
- await yielded();
936
- await unit();
937
- queueReadiness();
938
- }
939
- }
940
- finally {
941
- indexing = false;
942
- }
943
- })().catch(() => { });
944
- }
945
- function publishChangeSet(set) {
946
- applyChangeSet(set);
947
- if (set.rooms.length > 0 ||
948
- [...new Set(set.documents.map(({ locator }) => locator))].some((locator) => rooms.has(locator) && counted.get(locator) !== documentsIn(locator)))
949
- emitRooms();
950
- for (const locator of set.queues)
951
- emitQueue(locator);
952
- if (set.drafts.length > 0 ||
953
- set.documents.some((change) => roomDrafts.get(change.locator)?.has(change.path) === true)) {
954
- publishRoomDrafts(false);
955
- }
956
- for (const app of set.presentations)
957
- emitPresentation(app);
958
- conversations.changed(set);
959
- }
960
- async function refuse(reason, provider = null) {
961
- discoveryPaused = true;
962
- try {
963
- if (reason === 'revoked-authorization') {
964
- await exclusive(async () => {
965
- const revoked = { status: 'unavailable', reason: 'revoked' };
966
- try {
967
- const local = await openLocal();
968
- await local.revokeModels([...replicas.values()].map((replica) => replica.confirmed.record));
969
- }
970
- catch {
971
- journal.record('model revocation persistence failed');
972
- }
973
- const keys = new Set(models.keys());
974
- for (const locator of rooms.keys()) {
975
- keys.add(modelKey(locator, 'collection'));
976
- keys.add(modelKey(locator, 'typed-selection'));
977
- }
978
- for (const key of keys) {
979
- invalidModels.add(key);
980
- models.set(key, revoked);
981
- liveModels.delete(key);
982
- }
983
- const revocations = [];
984
- for (const locator of [...rooms.keys()]) {
985
- const before = replicas.get(locator) ?? null;
986
- const after = before === null
987
- ? null
988
- : await stepped(replicating(await confirmedOf({ ...before.confirmed.record, model: revoked, selectionModel: revoked }, before.confirmed), before.queue, before));
989
- const set = await stepped(changing(locator, before, after, { room: true }));
990
- revocations.push([locator, before, after, set]);
991
- }
992
- const changed = [];
993
- for (const [locator, before, after, set] of revocations) {
994
- const room = rooms.get(locator);
995
- if (room === undefined || (replicas.get(locator) ?? null) !== before)
996
- continue;
997
- if (after !== null)
998
- replicas.set(locator, after);
999
- rooms.set(locator, {
1000
- ...room,
1001
- model: modelTypes(revoked),
1002
- typedSelection: room.typedSelection === null
1003
- ? null
1004
- : { ...room.typedSelection, model: modelTypes(revoked) },
1005
- });
1006
- changed.push(set);
1007
- }
1008
- publishChangeSet(mergeChangeSets(changed));
1009
- });
1010
- }
1011
- }
1012
- finally {
1013
- refusal = {
1014
- code: reason,
1015
- retryable: false,
1016
- reauthorizationOffered: reason === 'revoked-authorization',
1017
- refusal: provider,
1018
- };
1019
- journal.record(`connection refused ${reason}`);
1020
- emitRefusal();
1021
- }
1022
- }
1023
- function list(room, synchronizationAvailable) {
1024
- const selection = room.typedSelection ?? null;
1025
- rooms.set(room.locator, {
1026
- name: room.name,
1027
- locator: room.locator,
1028
- handle: room.handle,
1029
- operations: room.operations,
1030
- replica: room.replica,
1031
- model: modelTypes(modelOf(room.locator)),
1032
- typedSelection: selection === null
1033
- ? null
1034
- : {
1035
- roots: selection.roots,
1036
- model: modelTypes(modelOf(room.locator, 'typed-selection')),
1037
- },
1038
- providerOwnedPaths: room.providerOwnedPaths,
1039
- roomVersion: replicas.get(room.locator)?.confirmed.record.roomVersion ?? null,
1040
- synchronizationAvailable,
1041
- refusal: scopedRefusals.get(room.locator) ?? sourceRefusals.get(room.locator) ?? null,
1042
- });
1043
- }
1044
- async function applyDiscovery(found, started, covered) {
1045
- const lockedBefore = lockedRooms();
1046
- for (const room of found) {
1047
- const fence = fences.get(room.locator);
1048
- if (fence !== undefined && fence.erased && fence.at < started)
1049
- fences.delete(room.locator);
1050
- }
1051
- await loseRooms(found
1052
- .filter((room) => room.replica.admission !== 'admitted' && heldLocally(room.locator))
1053
- .map((room) => room.locator));
1054
- const listed = found.filter((room) => !fences.has(room.locator));
1055
- const listedLocators = new Set(listed.map((room) => room.locator));
1056
- for (const locator of listedLocators)
1057
- scopedRefusals.delete(locator);
1058
- if (covered === undefined)
1059
- discovered.clear();
1060
- else
1061
- for (const locator of covered)
1062
- discovered.delete(locator);
1063
- for (const room of listed)
1064
- discovered.set(room.locator, room);
1065
- const unlisted = unlistedHeld(new Set(found.map((room) => room.locator))).filter((locator) => covered === undefined || covered.includes(locator));
1066
- if (options.adapter.exhaustiveDiscovery === true)
1067
- await loseRooms(unlisted);
1068
- else
1069
- unlistedKept(unlisted);
1070
- for (const room of listed) {
1071
- const held = replicas.get(room.locator)?.confirmed.record;
1072
- if (held !== undefined && held.replica.selection !== room.replica.selection) {
1073
- list(held, false);
1074
- continue;
1075
- }
1076
- list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));
1077
- }
1078
- confirmLocks(listed);
1079
- roomsListed = true;
1080
- emitRooms();
1081
- relocked(lockedBefore);
1082
- return listed;
1083
- }
1084
- function heldLocally(locator) {
1085
- return (replicas.has(locator) ||
1086
- roomDrafts.has(locator) ||
1087
- transfers.has(locator) ||
1088
- queuesWithoutReplica.has(locator));
1089
- }
1090
- function unlistedHeld(listed) {
1091
- return [
1092
- ...new Set([
1093
- ...rooms.keys(),
1094
- ...roomDrafts.keys(),
1095
- ...transfers.keys(),
1096
- ...queuesWithoutReplica.keys(),
1097
- ]),
1098
- ].filter((locator) => !listed.has(locator));
1099
- }
1100
- function unlistedKept(unlisted) {
1101
- for (const locator of unlisted) {
1102
- const held = replicas.get(locator)?.confirmed.record;
1103
- if (held !== undefined)
1104
- list(held, false);
1105
- else
1106
- rooms.delete(locator);
1107
- }
1108
- }
1109
- function fence(locators) {
1110
- const fresh = [...new Set(locators)].filter((locator) => !fences.has(locator));
1111
- const removed = fresh.map((locator) => ({
1112
- locator,
1113
- shown: prepared.has(locator) || projecting.has(locator) ? (replicas.get(locator) ?? null) : null,
1114
- drafts: [...(roomDrafts.get(locator)?.keys() ?? [])],
1115
- }));
1116
- for (const locator of fresh) {
1117
- fences.set(locator, { at: discoveries, erased: false });
1118
- lastFenced.set(locator, ++fencings);
1119
- confirmed.delete(locator);
1120
- for (const batch of replicas.get(locator)?.queue ?? queuesWithoutReplica.get(locator) ?? [])
1121
- pendings.delete(pendingKey(locator, batch.id));
1122
- replicas.delete(locator);
1123
- queuesWithoutReplica.delete(locator);
1124
- rooms.delete(locator);
1125
- roomDrafts.delete(locator);
1126
- transfers.delete(locator);
1127
- catching.delete(locator);
1128
- discovered.delete(locator);
1129
- announced.delete(locator);
1130
- unreadable.delete(locator);
1131
- stale.delete(locator);
1132
- repairable.delete(locator);
1133
- unindexable.delete(locator);
1134
- paused.delete(locator);
1135
- prepared.delete(locator);
1136
- scopedRefusals.delete(locator);
1137
- sourceRefusals.delete(locator);
1138
- declarationRefusals.delete(locator);
1139
- for (const attached of ['collection', 'typed-selection']) {
1140
- const key = modelKey(locator, attached);
1141
- models.delete(key);
1142
- liveModels.delete(key);
1143
- invalidModels.delete(key);
1144
- }
1145
- journal.record(`room lost ${locator}`);
1146
- }
1147
- if (fresh.length === 0)
1148
- return fresh;
1149
- searchIndex.forget(fresh);
1150
- const withdrawn = readSide.apply(stepped(withdrawing(removed)), (set) => conversations.changed(set));
1151
- if (withdrawn instanceof Promise)
1152
- void withdrawn.catch(unpublished);
1153
- publishChangeSet(mergeChangeSets(removed.map(({ locator, drafts }) => changeSet(locator, null, null, { room: true, queue: true, drafts }))));
1154
- readSide.recover();
1155
- moveTo({ ...status, ...attention() });
1156
- return fresh;
1157
- }
1158
- function* withdrawing(removed) {
1159
- const sets = [];
1160
- for (const { locator, shown } of removed)
1161
- sets.push(yield* changing(locator, shown, null));
1162
- return mergeChangeSets(sets);
1163
- }
1164
- async function erased(local, locators) {
1165
- await local.erase(locators);
1166
- for (const locator of locators) {
1167
- const held = fences.get(locator);
1168
- if (held !== undefined)
1169
- held.erased = true;
1170
- }
1171
- }
1172
- async function loseRooms(locators) {
1173
- const fresh = fence(locators);
1174
- if (fresh.length === 0)
1175
- return;
1176
- await durably(async (local) => {
1177
- await erased(local, fresh);
1178
- await unpair(local);
1179
- });
1180
- }
1181
- function restored(key, persisted) {
1182
- const prior = models.get(key);
1183
- if (prior !== undefined &&
1184
- prior.status !== 'unavailable' &&
1185
- (persisted.status === 'unavailable' || !sameModel(prior.snapshot, persisted.snapshot))) {
1186
- invalidModels.add(key);
1187
- }
1188
- const model = persisted.status === 'unavailable' ||
1189
- liveModels.get(key) === JSON.stringify(persisted.snapshot)
1190
- ? persisted
1191
- : cached(persisted);
1192
- models.set(key, model);
1193
- if (model.status === 'unavailable') {
1194
- liveModels.delete(key);
1195
- invalidModels.delete(key);
1196
- }
1197
- return model;
1198
- }
1199
- async function hydrate(opened) {
1200
- const [records, queues, kept, presented, held, chatDrafts, lastCompleted, declared, named, known, staged, heldTargets,] = await Promise.all([
1201
- opened.all(),
1202
- opened.queues(),
1203
- opened.roomDrafts(),
1204
- opened.presentation(),
1205
- opened.conversations(),
1206
- opened.chatDrafts(),
1207
- opened.lastCompleted(),
1208
- opened.providerLimits(),
1209
- opened.capabilities(),
1210
- opened.member(),
1211
- opened.transfers(),
1212
- opened.targets(),
1213
- ]);
1214
- const queuedBatches = new Map(queues.map((queue) => [queue.locator, queue.pending.map(({ batch }) => batch)]));
1215
- const previousReplicas = new Map(replicas);
1216
- const read = new Map();
1217
- for (const record of records) {
1218
- const model = restored(modelKey(record.locator, 'collection'), record.model);
1219
- const selectionModel = restored(modelKey(record.locator, 'typed-selection'), record.selectionModel);
1220
- const prior = previousReplicas.get(record.locator);
1221
- const confirmed = await confirmedOf({ ...record, model, selectionModel }, prior?.confirmed);
1222
- const replica = await stepped(replicating(confirmed, queuedBatches.get(record.locator) ?? [], prior));
1223
- await stepped(counting(replica));
1224
- read.set(record.locator, replica);
1225
- }
1226
- const sets = new Map();
1227
- for (const locator of new Set([...previousReplicas.keys(), ...read.keys()])) {
1228
- sets.set(locator, await stepped(changing(locator, previousReplicas.get(locator) ?? null, read.get(locator) ?? null)));
1229
- }
1230
- targets = heldTargets;
1231
- transfers.clear();
1232
- for (const record of staged)
1233
- transfers.set(record.locator, record);
1234
- limits = declared;
1235
- capabilities = named;
1236
- member = known;
1237
- roomDrafts.clear();
1238
- for (const record of kept)
1239
- rememberRoomDraft(record);
1240
- presentations.clear();
1241
- for (const record of presented)
1242
- presentations.set(record.app, record.value);
1243
- conversations.hydrate(held, chatDrafts);
1244
- pendings.clear();
1245
- for (const queue of queues) {
1246
- for (const { batch, state } of queue.pending) {
1247
- pendings.set(pendingKey(queue.locator, batch.id), state);
1248
- }
1249
- }
1250
- replicas.clear();
1251
- queuesWithoutReplica.clear();
1252
- for (const [locator, queue] of queuedBatches) {
1253
- if (!read.has(locator))
1254
- queuesWithoutReplica.set(locator, queue);
1255
- }
1256
- for (const record of records) {
1257
- if (fences.has(record.locator))
1258
- continue;
1259
- const replica = read.get(record.locator);
1260
- const { model, selectionModel } = replica.confirmed.record;
1261
- replicas.set(record.locator, replica);
1262
- const existing = rooms.get(record.locator);
1263
- if (existing === undefined)
1264
- list(record, false);
1265
- else {
1266
- rooms.set(record.locator, {
1267
- ...existing,
1268
- roomVersion: record.roomVersion,
1269
- operations: record.operations,
1270
- replica: record.replica,
1271
- model: modelTypes(model),
1272
- typedSelection: record.typedSelection === null
1273
- ? null
1274
- : {
1275
- roots: record.typedSelection.roots,
1276
- model: modelTypes(selectionModel),
1277
- },
1278
- });
1279
- }
1280
- }
1281
- return {
1282
- lastCompleted,
1283
- locators: new Set([...queuedBatches.keys(), ...replicas.keys()]),
1284
- read: mergeChangeSets([...sets].flatMap(([locator, set]) => (fences.has(locator) ? [] : [set]))),
1285
- };
1286
- }
1287
- async function readState(opened) {
1288
- const { lastCompleted, locators, read } = await hydrate(opened);
1289
- applyChangeSet(read);
1290
- prepare();
1291
- if (replicas.size > 0)
1292
- emitRooms();
1293
- if (member !== null)
1294
- emitMember();
1295
- for (const locator of locators)
1296
- emitQueue(locator);
1297
- publishRoomDrafts(false);
1298
- return lastCompleted;
1299
- }
1300
- async function open() {
1301
- if (closed)
1302
- throw new Error('runtime closed');
1303
- const opened = await openRuntimeStore(isFenced);
1304
- store = opened;
1305
- const interrupted = await opened.fences();
1306
- for (const locator of interrupted) {
1307
- fences.set(locator, { at: discoveries, erased: false });
1308
- lastFenced.set(locator, ++fencings);
1309
- }
1310
- const kept = options.shell.generation;
1311
- const storedGeneration = await opened.generation();
1312
- const loss = detectStorageLoss(storedGeneration, kept);
1313
- const generation = nextGeneration(storedGeneration, kept);
1314
- if (generation !== storedGeneration)
1315
- await opened.rememberGeneration(generation);
1316
- if (generation !== kept)
1317
- await options.shell.keepGeneration(generation);
1318
- if (loss !== null) {
1319
- storageLoss = loss;
1320
- emitStorageLoss();
1321
- }
1322
- const lastCompleted = await readState(opened);
1323
- if (interrupted.length > 0)
1324
- await erased(opened, interrupted);
1325
- moveTo({ ...status, lastCompleted, ...attention() });
1326
- void exclusive(() => unpair(opened)).catch(() => {
1327
- journal.record('unpair failed');
1328
- });
1329
- return opened;
1330
- }
1331
- function durably(work) {
1332
- return exclusive(async () => {
1333
- const local = await openLocal();
1334
- return work(local);
1335
- });
1336
- }
1337
- function openLocal() {
1338
- opening ??= open().catch((error) => {
1339
- opening = undefined;
1340
- throw error;
1341
- });
1342
- return opening;
1343
- }
1344
- function exclusive(work) {
1345
- const next = mutations.then(work, work);
1346
- mutations = next.then(() => undefined, () => undefined);
1347
- return next;
1348
- }
1349
- function withdrawable(locator) {
1350
- return (batch) => {
1351
- const state = pendings.get(pendingKey(locator, batch.id));
1352
- return state !== undefined && state.submission.state !== 'submitted' && !state.lost;
1353
- };
1354
- }
1355
- function landedWhole(locator, batch, confirmed, current) {
1356
- if (!landed(batch, confirmed, current))
1357
- return false;
1358
- const partner = partnerOf(batch, locator);
1359
- if (partner === null)
1360
- return true;
1361
- const other = replicas.get(partner);
1362
- const half = other?.queue.find((one) => one.id === batch.id);
1363
- return other !== undefined && half !== undefined && landed(half, other.confirmed);
1364
- }
1365
- function carriedBack(locator, unlanded, written) {
1366
- const back = new Map();
1367
- const taken = [];
1368
- for (const batch of unlanded) {
1369
- const between = batch.between;
1370
- if (between === undefined)
1371
- continue;
1372
- const source = between.source.room;
1373
- const destination = between.destination.room;
1374
- for (const { path: to } of pendings.get(pendingKey(destination, batch.id))?.drafts ?? []) {
1375
- const record = roomDrafts.get(destination)?.get(to);
1376
- const path = between.moves.find((move) => move.to === to)?.path;
1377
- if (record === undefined || path === undefined)
1378
- continue;
1379
- const [into, key] = source === locator ? [written, path] : [back, documentKey(source, path)];
1380
- const existing = into.get(key) ?? roomDrafts.get(source)?.get(path);
1381
- taken.push({ locator: destination, path: to });
1382
- into.set(key, {
1383
- locator: source,
1384
- path,
1385
- revision: roomDraftRevision(),
1386
- parts: returnedInto(existing?.parts, record.parts),
1387
- returned: existing?.returned ?? null,
1388
- });
1389
- }
1390
- }
1391
- const records = [...back.values()];
1392
- const elsewhere = taken.filter((one) => one.locator !== locator);
1393
- const rooms = new Set([...records, ...elsewhere].map((one) => one.locator));
1394
- return {
1395
- taken: taken.filter((one) => one.locator === locator).map(({ path }) => path),
1396
- writes: [...rooms].map((room) => ({
1397
- locator: room,
1398
- roomDrafts: records.filter((record) => record.locator === room),
1399
- consumedRoomDrafts: elsewhere.filter((one) => one.locator === room).map(({ path }) => path),
1400
- })),
1401
- changes: [...rooms].map((room) => changeSet(room, null, null, {
1402
- drafts: [...records, ...elsewhere]
1403
- .filter((one) => one.locator === room)
1404
- .map(({ path }) => path),
1405
- })),
1406
- remember() {
1407
- for (const one of taken)
1408
- forgetRoomDraft(one.locator, one.path);
1409
- for (const record of records)
1410
- rememberRoomDraft(record);
1411
- },
1412
- };
1413
- }
1414
- async function settle(local, locator, before, confirmed, queue, settling = {}) {
1415
- const previousQueue = before?.queue ?? queuesWithoutReplica.get(locator) ?? [];
1416
- const { withdrawn, kept } = await stepped(standing(confirmed, queue, withdrawable(locator), localSaves));
1417
- const founded = kept.filter((batch) => !queue.includes(batch));
1418
- const queueChanged = kept.length !== previousQueue.length || founded.length > 0;
1419
- const unqueued = withdrawn.map((batch) => ({
1420
- batch,
1421
- landed: landedWhole(locator, batch, confirmed),
1422
- }));
1423
- const returning = [
1424
- ...[...unqueued].reverse().map(({ batch, landed }) => ({
1425
- batch,
1426
- returned: localSaves || landed ? null : returnedBy('withdrawn'),
1427
- })),
1428
- ...(settling.leaving === undefined ? [] : [settling.leaving]),
1429
- ];
1430
- const written = new Map();
1431
- for (const { batch, returned } of returning) {
1432
- if (returned === null || batch.between?.destination.room === locator)
1433
- continue;
1434
- for (const saved of pendings.get(pendingKey(locator, batch.id))?.drafts ?? []) {
1435
- const existing = written.get(saved.path) ?? roomDrafts.get(locator)?.get(saved.path);
1436
- written.set(saved.path, {
1437
- locator,
1438
- path: saved.path,
1439
- revision: roomDraftRevision(),
1440
- parts: returnedInto(existing?.parts, saved.parts),
1441
- returned,
1442
- });
1443
- }
1444
- }
1445
- const carried = carriedBack(locator, [
1446
- ...[...unqueued].reverse().flatMap(({ batch, landed }) => (landed ? [] : [batch])),
1447
- ...(settling.leaving === undefined || settling.leaving.returned === null
1448
- ? []
1449
- : [settling.leaving.batch]),
1450
- ], written);
1451
- await local.keepAuthored({
1452
- locator,
1453
- queue: kept,
1454
- founded,
1455
- roomDrafts: [...written.values()],
1456
- consumedRoomDrafts: carried.taken,
1457
- }, ...carried.writes);
1458
- const staying = new Set(kept.map((batch) => batch.id));
1459
- for (const batch of previousQueue) {
1460
- if (!staying.has(batch.id))
1461
- pendings.delete(pendingKey(locator, batch.id));
1462
- }
1463
- for (const record of written.values())
1464
- rememberRoomDraft(record);
1465
- carried.remember();
1466
- const drafts = [...written.keys(), ...carried.taken];
1467
- try {
1468
- await local.write({
1469
- next: confirmed.record,
1470
- previous: before?.confirmed.record ?? null,
1471
- ...(settling.stored === undefined ? {} : { stored: settling.stored }),
1472
- });
1473
- }
1474
- catch (error) {
1475
- const held = before === undefined ? null : await stepped(replicating(before.confirmed, kept, before));
1476
- const set = await stepped(changing(locator, before ?? null, held, { queue: queueChanged, drafts }));
1477
- if (held !== null)
1478
- replicas.set(locator, held);
1479
- else if (kept.length > 0)
1480
- queuesWithoutReplica.set(locator, kept);
1481
- else
1482
- queuesWithoutReplica.delete(locator);
1483
- publishChangeSet(mergeChangeSets([set, ...carried.changes]));
1484
- moveTo({ ...status, ...attention() });
1485
- throw error;
1486
- }
1487
- const changed = { room: settling.room, queue: queueChanged, drafts };
1488
- const next = await stepped(replicating(confirmed, kept, before));
1489
- await stepped(counting(next));
1490
- const set = await stepped(changing(locator, before ?? null, next, changed));
1491
- return () => {
1492
- queuesWithoutReplica.delete(locator);
1493
- for (const { batch, landed } of unqueued) {
1494
- const outcome = localSaves ? 'dropped' : landed ? 'landed' : 'withdrawn';
1495
- journal.record(`outcome ${locator} ${batch.id} ${outcome}`);
1496
- }
1497
- replicas.set(locator, next);
1498
- return mergeChangeSets([
1499
- heldChange(locator, before ?? null, next, set, changed),
1500
- ...carried.changes,
1501
- ]);
1502
- };
1503
- }
1504
- function heldChange(locator, before, next, set, changed) {
1505
- const held = replicas.get(locator) ?? null;
1506
- return held === next ? set : changeSet(locator, before, held, changed);
1507
- }
1508
- function adoptModels(locator, record) {
1509
- for (const [attached, model] of [
1510
- ['collection', record.model],
1511
- ['typed-selection', record.selectionModel],
1512
- ]) {
1513
- const key = modelKey(locator, attached);
1514
- models.set(key, model);
1515
- invalidModels.delete(key);
1516
- if (model.status === 'current')
1517
- liveModels.set(key, JSON.stringify(model.snapshot));
1518
- else if (model.status === 'unavailable')
1519
- liveModels.delete(key);
1520
- }
1521
- }
1522
- function remodel(locator, answers, held) {
1523
- const taken = (answer, previous, attached) => {
1524
- if (answer === undefined)
1525
- return previous;
1526
- const { state, refused } = attachedModel(answer, previous);
1527
- if (refused !== null) {
1528
- const where = refused.location === undefined ? '' : ` ${refused.location}`;
1529
- journal.record(`model invalid ${locator} ${attached} ${refused.identity} ${refused.rule}${where}`);
1530
- }
1531
- models.set(modelKey(locator, attached), state);
1532
- return state;
1533
- };
1534
- return {
1535
- collection: taken(answers?.collection, held.collection, 'collection'),
1536
- selection: taken(answers?.selection, held.selection, 'typed-selection'),
1537
- };
1538
- }
1539
- function publish(local, room, confirmed, landing, live) {
1540
- const { base, stored } = landing;
1541
- return exclusive(async () => {
1542
- if (stored !== undefined) {
1543
- await indexReferrers({ text: confirmed.record.documents, binaries: confirmed.record.binaries }, compositionOf(confirmed.record));
1544
- }
1545
- if (!live()) {
1546
- caughtUpTo(room.locator);
1547
- return true;
1548
- }
1549
- const prior = replicas.get(room.locator);
1550
- if (base !== undefined &&
1551
- (prior?.confirmed.record.roomVersion !== base.record.roomVersion ||
1552
- prior.confirmed.record.revisions !== base.record.revisions)) {
1553
- return false;
1554
- }
1555
- adoptModels(room.locator, confirmed.record);
1556
- const queue = prior?.queue ?? queuesWithoutReplica.get(room.locator) ?? [];
1557
- const roomVersion = confirmed.record.roomVersion;
1558
- const accepted = queue.filter((batch) => {
1559
- const accepted = pendings.get(pendingKey(room.locator, batch.id))?.accepted;
1560
- return (accepted !== undefined && options.adapter.reached(room.locator, roomVersion, accepted));
1561
- });
1562
- let settled;
1563
- try {
1564
- settled = await settle(local, room.locator, prior, confirmed, queue.filter((batch) => !accepted.includes(batch)), { room: true, ...(stored === undefined ? {} : { stored }) });
1565
- }
1566
- catch (error) {
1567
- if (!exceeded(error))
1568
- throw error;
1569
- await exceededOn(room.locator, grownBy(confirmed.record, prior?.confirmed.record));
1570
- caughtUpTo(room.locator);
1571
- return true;
1572
- }
1573
- const set = settled();
1574
- if (stored !== undefined) {
1575
- transfers.delete(room.locator);
1576
- catching.delete(room.locator);
1577
- }
1578
- for (const batch of accepted)
1579
- pendings.delete(pendingKey(room.locator, batch.id));
1580
- stale.delete(room.locator);
1581
- unindexable.delete(room.locator);
1582
- if (unreadable.delete(room.locator))
1583
- scopedRefusals.delete(room.locator);
1584
- sourceRefusals.delete(room.locator);
1585
- declarationRefusals.delete(room.locator);
1586
- list(room, true);
1587
- if (prior === undefined)
1588
- prepared.add(room.locator);
1589
- publishChangeSet(set);
1590
- await unpair(local);
1591
- moveTo({ ...status, ...attention() });
1592
- options.adapter.roomStream?.published(room.locator, roomVersion);
1593
- if (accepted.length > 0 && (replicas.get(room.locator)?.queue.length ?? 0) > 0) {
1594
- submitLater(room.locator);
1595
- }
1596
- return true;
1597
- });
1598
- }
1599
- async function savedRoom(locator) {
1600
- const local = await openLocal();
1601
- await referenced(locator);
1602
- const replica = replicas.get(locator);
1603
- const room = rooms.get(locator);
1604
- if (replica === undefined || room === undefined) {
1605
- throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
1606
- }
1607
- return { local, replica, room };
1608
- }
1609
- async function saveRoomDrafts(locator, named, writtenBy) {
1610
- const target = await savedRoom(locator);
1611
- const saved = [];
1612
- for (const { path, revision } of named) {
1613
- const record = roomDrafts.get(locator)?.get(path);
1614
- if (record === undefined || record.revision !== revision) {
1615
- return { outcome: 'refused', code: 'stale', retryable: false, file: path };
1616
- }
1617
- if (!saved.some((draft) => draft.path === path))
1618
- saved.push({ path, parts: record.parts });
1619
- }
1620
- return committed(locator, target, saved, new Set(saved.map(({ path }) => path)), writtenBy);
1621
- }
1622
- async function saveParts(locator, named, writtenBy) {
1623
- const read = named.map(({ path, parts }) => ({ path, parts: readParts(parts) }));
1624
- if (read.some(({ path }, at) => path === '' ||
1625
- normalize(path) !== path ||
1626
- read.findIndex((one) => one.path === path) !== at)) {
1627
- throw runtimeError('room-draft-malformed');
1628
- }
1629
- const target = await savedRoom(locator);
1630
- const saved = [];
1631
- for (const { path, parts } of read) {
1632
- const file = parts.file === undefined
1633
- ? undefined
1634
- : await heldFile(parts.file.blob, binaryBase(target.replica.visible, path));
1635
- saved.push({ path, parts: held(undefined, parts, file) });
1636
- }
1637
- return committed(locator, target, saved, new Set(), writtenBy);
1638
- }
1639
- function carriedDrafts(locator, saved, consumed) {
1640
- const holding = roomDrafts.get(locator);
1641
- return new Map(saved.flatMap(({ path, parts }) => {
1642
- const record = holding?.get(path);
1643
- if (parts.move === undefined || record === undefined || consumed.has(path))
1644
- return [];
1645
- const to = moveTarget(parts.move);
1646
- if (to === path || holding?.has(to) === true)
1647
- return [];
1648
- return [[path, { ...record, path: to, revision: roomDraftRevision() }]];
1649
- }));
1650
- }
1651
- function sideOf(locator, replica, room) {
1652
- const record = replica.confirmed.record;
1653
- return {
1654
- room: locator,
1655
- handle: room.handle,
1656
- baseRoomVersion: record.roomVersion,
1657
- composition: compositionFor(record),
1658
- operations: room.operations,
1659
- providerOwnedPaths: room.providerOwnedPaths,
1660
- visible: replica.visible,
1661
- queued: queuedDocuments(replica.queue),
1662
- clean: {
1663
- text: record.documents,
1664
- binaries: record.binaries,
1665
- composition: compositionOf(record),
1666
- },
1667
- };
1668
- }
1669
- function movedInto(locator, saved) {
1670
- const into = saved.find(({ parts }) => parts.move?.room !== undefined && parts.move.room !== locator);
1671
- return into?.parts.move?.room ?? null;
1672
- }
1673
- async function committedMove(locator, destination, { local, replica, room }, saved, consumed, writtenBy) {
1674
- const mixed = saved.find(({ parts }) => Object.keys(parts).length !== 1 || parts.move?.room !== destination);
1675
- if (mixed !== undefined) {
1676
- return { outcome: 'refused', code: 'mixed-room-move', retryable: false, file: mixed.path };
1677
- }
1678
- const changed = saved.flatMap(({ path, parts }) => changedParts(path, underneath(parts, path, replica.visible)));
1679
- if (changed.length > 0)
1680
- return { outcome: 'refused', code: 'changed-underneath', retryable: false, parts: changed };
1681
- await referenced(destination);
1682
- const target = replicas.get(destination);
1683
- const listedRoom = rooms.get(destination);
1684
- if (target === undefined || listedRoom === undefined) {
1685
- throw runtimeError('room-not-held', `No Local Replica for ${destination}`);
1686
- }
1687
- const built = await buildMove({
1688
- source: sideOf(locator, replica, room),
1689
- destination: sideOf(destination, target, listedRoom),
1690
- moves: saved.map(({ path, parts }) => ({ path, to: moveTarget(parts.move) })),
1691
- providerLimits: limits,
1692
- local: localSaves,
1693
- ...(writtenBy === undefined ? {} : { writtenBy }),
1694
- });
1695
- if (built.kind === 'refused')
1696
- return { outcome: 'refused', ...built.refusal };
1697
- const id = built.leaving.id;
1698
- const carrying = saved.flatMap(({ path, parts }) => {
1699
- const record = roomDrafts.get(locator)?.get(path);
1700
- const to = moveTarget(parts.move);
1701
- if (record === undefined || consumed.has(path) || roomDrafts.get(destination)?.has(to)) {
1702
- return [];
1703
- }
1704
- const moved = {
1705
- ...record,
1706
- locator: destination,
1707
- path: to,
1708
- revision: roomDraftRevision(),
1709
- };
1710
- return [{ from: path, record: moved }];
1711
- });
1712
- const carried = carrying.map(({ record }) => record);
1713
- const marked = carried.map(({ path }) => ({ path, parts: {} }));
1714
- const left = [...consumed, ...carrying.map(({ from }) => from)];
1715
- const leavingQueue = [...replica.queue, built.leaving];
1716
- const arrivingQueue = [...target.queue, built.arriving];
1717
- try {
1718
- await local.keepAuthored({
1719
- locator,
1720
- queue: leavingQueue,
1721
- saved: new Map([[id, saved]]),
1722
- consumedRoomDrafts: left,
1723
- }, {
1724
- locator: destination,
1725
- queue: arrivingQueue,
1726
- saved: new Map([[id, marked]]),
1727
- roomDrafts: carried,
1728
- });
1729
- }
1730
- catch {
1731
- return { outcome: 'refused', code: 'durable-write', retryable: true };
1732
- }
1733
- const nextSource = await stepped(replicating(replica.confirmed, leavingQueue, replica));
1734
- const nextDestination = await stepped(replicating(target.confirmed, arrivingQueue, target));
1735
- const sets = [
1736
- await stepped(changing(locator, replica, nextSource, { queue: true, drafts: left })),
1737
- await stepped(changing(destination, target, nextDestination, {
1738
- queue: true,
1739
- drafts: carried.map(({ path }) => path),
1740
- })),
1741
- ];
1742
- if (fences.has(locator) || fences.has(destination)) {
1743
- throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
1744
- }
1745
- pendings.set(pendingKey(locator, id), {
1746
- drafts: saved,
1747
- submission: { state: 'waiting' },
1748
- lost: false,
1749
- });
1750
- pendings.set(pendingKey(destination, id), {
1751
- drafts: marked,
1752
- submission: { state: 'waiting' },
1753
- lost: false,
1754
- });
1755
- for (const path of left)
1756
- forgetRoomDraft(locator, path);
1757
- for (const record of carried)
1758
- rememberRoomDraft(record);
1759
- replicas.set(locator, nextSource);
1760
- replicas.set(destination, nextDestination);
1761
- publishChangeSet(mergeChangeSets(sets));
1762
- queuedSave(locator);
1763
- return { outcome: 'saved', identifier: id };
1764
- }
1765
- function queuedSave(locator) {
1766
- if (!localSaves)
1767
- recorded = false;
1768
- moveTo({ ...(localSaves ? status : saving(status)), ...attention() });
1769
- submitLater(locator);
1770
- }
1771
- async function committed(locator, target, saved, consumed, writtenBy) {
1772
- const into = movedInto(locator, saved);
1773
- if (into !== null)
1774
- return committedMove(locator, into, target, saved, consumed, writtenBy);
1775
- const { local, replica, room } = target;
1776
- const changed = saved.flatMap(({ path, parts }) => changedParts(path, underneath(parts, path, replica.visible)));
1777
- if (changed.length > 0)
1778
- return { outcome: 'refused', code: 'changed-underneath', retryable: false, parts: changed };
1779
- const parts = saved.map(({ path, parts }) => changesOf(path, parts));
1780
- const changes = parts.flatMap(({ changes }) => changes);
1781
- const visibleOver = function* (queue) {
1782
- return (yield* replicating(replica.confirmed, queue, replica)).visible;
1783
- };
1784
- const requeue = await stepped(requeuing(replica.queue, changes, replica.visible, withdrawable(locator), visibleOver));
1785
- if (requeue.kind === 'refused')
1786
- return { outcome: 'refused', ...requeue.refusal };
1787
- const foreign = [...requeue.withdrawn.keys()].some((origin) => {
1788
- const writer = replica.queue.find((batch) => batch.id === origin)?.writtenBy;
1789
- return writer?.app !== writtenBy?.app || writer?.release !== writtenBy?.release;
1790
- });
1791
- if (foreign) {
1792
- return {
1793
- outcome: 'refused',
1794
- code: 'unknown-revision',
1795
- retryable: false,
1796
- file: [...requeue.queued].at(-1),
1797
- };
1798
- }
1799
- const withdrawing = requeue.withdrawn.size > 0;
1800
- const input = {
1801
- local: localSaves,
1802
- baseRoomVersion: replica.confirmed.record.roomVersion,
1803
- composition: compositionFor(replica.confirmed.record),
1804
- operations: room.operations,
1805
- providerOwnedPaths: room.providerOwnedPaths,
1806
- providerLimits: limits,
1807
- handle: room.handle,
1808
- visible: replica.visible,
1809
- changes,
1810
- bases: parts.flatMap(({ bases }) => bases),
1811
- queued: queuedDocuments(replica.queue),
1812
- writtenBy,
1813
- clean: {
1814
- text: replica.confirmed.record.documents,
1815
- binaries: replica.confirmed.record.binaries,
1816
- composition: compositionOf(replica.confirmed.record),
1817
- },
1818
- };
1819
- const checked = withdrawing
1820
- ? await buildBatch({ ...input, queued: new Set([...input.queued, ...requeue.queued]) })
1821
- : null;
1822
- if (checked?.kind === 'refused')
1823
- return { outcome: 'refused', ...checked.refusal };
1824
- const owners = [...requeue.owners].flatMap((origin) => {
1825
- const batch = requeue.withdrawn.get(origin);
1826
- return batch === undefined || batch === null ? [] : [{ origin, batch }];
1827
- });
1828
- if (owners.length > 1) {
1829
- return {
1830
- outcome: 'refused',
1831
- code: 'unknown-revision',
1832
- retryable: false,
1833
- file: [...requeue.queued].at(-1),
1834
- };
1835
- }
1836
- const built = !withdrawing
1837
- ? await buildBatch(input)
1838
- : requeue.changes.length === 0
1839
- ? null
1840
- : await buildBatch({
1841
- ...input,
1842
- visible: (await stepped(replicating(replica.confirmed, requeue.queue, replica)))
1843
- .visible,
1844
- changes: requeue.changes,
1845
- queued: queuedDocuments(requeue.queue),
1846
- });
1847
- if (built?.kind === 'refused')
1848
- return { outcome: 'refused', ...built.refusal };
1849
- const [owner] = owners;
1850
- const join = built === null || owner === undefined
1851
- ? null
1852
- : joined(requeue.queue, owner.batch, built.batch);
1853
- if (join?.kind === 'refused')
1854
- return { outcome: 'refused', ...join.refusal };
1855
- const withdrawn = new Map(requeue.withdrawn);
1856
- if (join !== null && owner !== undefined)
1857
- withdrawn.set(owner.origin, join.batch);
1858
- const drafted = new Map();
1859
- for (const [origin, replaced] of withdrawn) {
1860
- if (replaced === null)
1861
- continue;
1862
- const carried = withdrawnDrafts(pendings.get(pendingKey(locator, origin))?.drafts ?? [], changes);
1863
- drafted.set(replaced.id, replaced === join?.batch
1864
- ? [
1865
- ...carried.map((held) => joinedDraft(held, saved)),
1866
- ...saved.filter((draft) => !carried.some((held) => held.path === draft.path)),
1867
- ]
1868
- : carried);
1869
- }
1870
- if (built !== null && join === null)
1871
- drafted.set(built.batch.id, saved);
1872
- const batches = join !== null ? join.queue : built === null ? requeue.queue : [...requeue.queue, built.batch];
1873
- for (const replaced of withdrawn.values()) {
1874
- if (replaced === null || !batches.includes(replaced))
1875
- continue;
1876
- const limited = await stepped(limiting(batches, replaced, limits, visibleOver));
1877
- if (limited !== null)
1878
- return { outcome: 'refused', ...limited };
1879
- }
1880
- const carried = carriedDrafts(locator, saved, consumed);
1881
- const left = [...consumed, ...carried.keys()];
1882
- const arrived = [...carried.values()];
1883
- try {
1884
- await local.keepAuthored({
1885
- locator,
1886
- queue: batches,
1887
- saved: drafted,
1888
- consumedRoomDrafts: left,
1889
- roomDrafts: arrived,
1890
- });
1891
- }
1892
- catch {
1893
- return { outcome: 'refused', code: 'durable-write', retryable: true };
1894
- }
1895
- const next = await stepped(replicating(replica.confirmed, batches, replica));
1896
- const set = await stepped(changing(locator, replica, next, {
1897
- queue: true,
1898
- drafts: [...left, ...arrived.map(({ path }) => path)],
1899
- }));
1900
- if (fences.has(locator))
1901
- throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
1902
- for (const origin of withdrawn.keys())
1903
- pendings.delete(pendingKey(locator, origin));
1904
- for (const [id, drafts] of drafted) {
1905
- pendings.set(pendingKey(locator, id), {
1906
- drafts,
1907
- submission: { state: 'waiting' },
1908
- lost: false,
1909
- });
1910
- }
1911
- for (const path of left)
1912
- forgetRoomDraft(locator, path);
1913
- for (const record of arrived)
1914
- rememberRoomDraft(record);
1915
- replicas.set(locator, next);
1916
- publishChangeSet(set);
1917
- queuedSave(locator);
1918
- const identifier = join?.batch.id ??
1919
- built?.batch.id ??
1920
- [...requeue.withdrawn].map(([origin, replaced]) => replaced?.id ?? origin).at(-1);
1921
- return { outcome: 'saved', identifier };
1922
- }
1923
- async function mark(local, locator, batch, submission, lost) {
1924
- const partner = partnerOf(batch, locator);
1925
- for (const held of partner === null ? [locator] : [locator, partner]) {
1926
- const state = pendings.get(pendingKey(held, batch.id));
1927
- if (!continuing() ||
1928
- state === undefined ||
1929
- (JSON.stringify(state.submission) === JSON.stringify(submission) && state.lost === lost)) {
1930
- continue;
1931
- }
1932
- await local.submit(held, batch.id, submission, lost);
1933
- if (fences.has(held))
1934
- continue;
1935
- pendings.set(pendingKey(held, batch.id), { ...state, submission, lost });
1936
- const replica = replicas.get(held);
1937
- if (replica !== undefined)
1938
- publishChangeSet(changeSet(held, replica, replica, { queue: true }));
1939
- }
1940
- moveTo({ ...status, ...attention() });
1941
- }
1942
- async function keepUpload(local, locator, identifier, upload) {
1943
- if (!continuing())
1944
- throw new Error('connection refused');
1945
- await local.keepUpload(locator, identifier, upload);
1946
- if (fences.has(locator))
1947
- throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
1948
- const key = pendingKey(locator, identifier);
1949
- pendings.set(key, { ...pendings.get(key), upload });
1950
- if (!continuing())
1951
- throw new Error('connection refused');
1952
- }
1953
- async function readHistory(locator, path, query = {}) {
1954
- if (closed || refusal !== null)
1955
- return UNCERTAIN;
1956
- try {
1957
- await ensureAuthorization();
1958
- }
1959
- catch {
1960
- return UNCERTAIN;
1961
- }
1962
- if (closed || authorization === undefined || refusal !== null)
1963
- return UNCERTAIN;
1964
- const since = fencings;
1965
- const transfer = ['transfer', 'history', locator, path];
1966
- if (query.revision !== undefined)
1967
- transfer.push(query.revision);
1968
- if (query.pageToken !== undefined)
1969
- transfer.push(query.pageToken);
1970
- journal.record(transfer.join(' '));
1971
- try {
1972
- const result = await options.adapter.history(authorization, {
1973
- locator,
1974
- path,
1975
- ...(query.revision === undefined ? {} : { revision: query.revision }),
1976
- ...(query.pageToken === undefined ? {} : { pageToken: query.pageToken }),
1977
- });
1978
- journal.record(`outcome history ${result.kind}`);
1979
- if (fencedSince(locator, since))
1980
- return failure({ kind: 'room-not-readable', locator });
1981
- if (result.kind === 'scoped-refusal') {
1982
- const room = replicas.get(result.locator)?.confirmed.record;
1983
- if (room !== undefined)
1984
- await scoped(result, room, await openLocal());
1985
- }
1986
- if (result.kind === 'revoked-authorization')
1987
- await refuse('revoked-authorization');
1988
- return historyAnswer(result);
1989
- }
1990
- catch {
1991
- journal.record('outcome history transport-uncertainty');
1992
- return UNCERTAIN;
1993
- }
1994
- }
1995
- function located(room, path, destination) {
1996
- const crossing = roomTarget(destination);
1997
- if (crossing === null) {
1998
- const named = target(path, destination);
1999
- return named === null || !rooms.has(room) ? null : { room, path: named };
2000
- }
2001
- const held = [...rooms.values()].find((listed) => listed.handle === crossing.handle);
2002
- return held === undefined ? null : { room: held.locator, path: crossing.path };
2003
- }
2004
- async function resolveReference(room, path, destination) {
2005
- if (roomTarget(destination) === null && target(path, destination) === null) {
2006
- return ABSENT_TARGET;
2007
- }
2008
- const at = located(room, path, destination);
2009
- if (at === null)
2010
- return UNREADABLE;
2011
- if (locked(at.room))
2012
- return LOCKED_UNREADABLE;
2013
- const visible = replicas.get(at.room)?.visible;
2014
- if (visible?.documents[at.path] !== undefined || visible?.binaries[at.path] !== undefined) {
2015
- return { kind: 'document', ...at };
2016
- }
2017
- const history = await readHistory(at.room, at.path);
2018
- if (history.kind === 'no-history' || history.kind === 'revision')
2019
- return ABSENT_TARGET;
2020
- if (history.kind !== 'history')
2021
- return history;
2022
- const [last] = history.revisions;
2023
- if (last === undefined)
2024
- return ABSENT_TARGET;
2025
- return history.deleted === true
2026
- ? { kind: 'deleted', ...at, revision: last }
2027
- : { kind: 'document', ...at };
2028
- }
2029
- function queuedBlob(locator, path, localId) {
2030
- for (const batch of replicas.get(locator)?.queue ?? []) {
2031
- const change = batch.changes[queuedFile(batch, path, localId)];
2032
- if (change?.kind === 'binary')
2033
- return change.blob;
2034
- }
2035
- return null;
2036
- }
2037
- function binaryRoom(request) {
2038
- if (request.kind === 'path')
2039
- return request.locator;
2040
- const scope = options.adapter.referrerScope(request.referrer);
2041
- return scope?.kind === 'room' ? scope.locator : null;
2042
- }
2043
- async function transferBinary(request, transfer, answer) {
2044
- if (closed || refusal !== null)
2045
- return UNCERTAIN;
2046
- try {
2047
- await ensureAuthorization();
2048
- }
2049
- catch {
2050
- return UNCERTAIN;
2051
- }
2052
- if (closed || authorization === undefined || refusal !== null)
2053
- return UNCERTAIN;
2054
- const since = fencings;
2055
- journal.record(request.kind === 'path'
2056
- ? `transfer binary ${request.locator} ${request.path}`
2057
- : `transfer binary ${request.fileRef}`);
2058
- try {
2059
- const result = await transfer(authorization);
2060
- const settled = result;
2061
- journal.record(`outcome binary ${settled.kind}`);
2062
- const locator = binaryRoom(request);
2063
- if (locator !== null && fencedSince(locator, since))
2064
- return failure({ kind: 'room-not-readable', locator });
2065
- if (settled.kind === 'scoped-refusal') {
2066
- const room = replicas.get(settled.locator)?.confirmed.record;
2067
- if (room !== undefined)
2068
- await scoped(settled, room, await openLocal());
2069
- }
2070
- if (settled.kind === 'revoked-authorization')
2071
- await refuse('revoked-authorization');
2072
- return answer(result);
2073
- }
2074
- catch {
2075
- journal.record('outcome binary transport-uncertainty');
2076
- return UNCERTAIN;
2077
- }
2078
- }
2079
- function readBinary(request) {
2080
- return transferBinary(request, (held) => options.adapter.binary(held, request), binaryAnswer);
2081
- }
2082
- function binaryPath(locator, path, revision) {
2083
- if (revision !== undefined)
2084
- return { kind: 'path', locator, path, revision };
2085
- const visible = replicas.get(locator)?.visible;
2086
- const held = visible?.binaries[path];
2087
- if (visible === undefined || held === undefined)
2088
- return null;
2089
- if (held.state === 'pending')
2090
- return { kind: 'pending', localId: held.localId };
2091
- const record = binaryRecord(path, held, visible.revisions[path]);
2092
- if (record.state !== 'accepted')
2093
- return null;
2094
- const replica = replicas.get(locator);
2095
- const queued = (replica?.queue ?? []).flatMap((batch) => batch.changes);
2096
- const holds = (at) => {
2097
- const kept = replica?.confirmed.record.binaries[at];
2098
- return (kept?.state === 'accepted' &&
2099
- kept.fileRef === record.fileRef &&
2100
- replica?.confirmed.record.revisions[at] === record.revision);
2101
- };
2102
- let confirmed = path;
2103
- for (let index = queued.length - 1; index >= 0 && !holds(confirmed); index -= 1) {
2104
- const change = queued[index];
2105
- if (change.kind === 'move' && change.to === confirmed)
2106
- confirmed = change.path;
2107
- }
2108
- return {
2109
- kind: 'path',
2110
- locator,
2111
- path: confirmed,
2112
- revision: record.revision,
2113
- fileRef: record.fileRef,
2114
- };
2115
- }
2116
- async function readBinaryPath(locator, path, revision) {
2117
- await ready;
2118
- const asked = binaryPath(locator, path, revision);
2119
- if (asked === null)
2120
- return absentBinary(path);
2121
- if (asked.kind === 'pending') {
2122
- const blob = queuedBlob(locator, path, asked.localId);
2123
- return blob === null ? absentBinary(path) : { kind: 'binary', blob };
2124
- }
2125
- return readBinary(asked);
2126
- }
2127
- async function linkBinaryPath(locator, path, revision) {
2128
- await ready;
2129
- const asked = binaryPath(locator, path, revision);
2130
- if (asked === null || asked.kind === 'pending')
2131
- return absentBinary(path);
2132
- return transferBinary(asked, (held) => options.adapter.link(held, asked), binaryLinkAnswer);
2133
- }
2134
- async function readBinaryReference(reference) {
2135
- await ready;
2136
- return readBinary({
2137
- kind: 'reference',
2138
- fileRef: reference.fileRef,
2139
- referrer: reference.referrer,
2140
- });
2141
- }
2142
- function declaredAgents() {
2143
- for (const capability of capabilities) {
2144
- if (capability.conversationAgents !== undefined)
2145
- return capability.conversationAgents;
2146
- }
2147
- return undefined;
2148
- }
2149
- function declaredAction(name) {
2150
- for (const capability of capabilities) {
2151
- for (const action of capability.actions ?? []) {
2152
- if (action.name === name)
2153
- return action;
2154
- }
2155
- }
2156
- return undefined;
2157
- }
2158
- function calledRooms(name, input) {
2159
- const member = declaredAction(name)?.room;
2160
- if (member === undefined || input === null || typeof input !== 'object')
2161
- return [];
2162
- const named = input[member];
2163
- return (Array.isArray(named) ? named : [named]).filter((room) => typeof room === 'string');
2164
- }
2165
- async function invokeAction(name, input, dispatching) {
2166
- await ready;
2167
- if (closed || refusal !== null)
2168
- return UNCERTAIN;
2169
- if (declaredAction(name) === undefined)
2170
- return undeclared(name);
2171
- try {
2172
- await ensureAuthorization();
2173
- }
2174
- catch {
2175
- return UNCERTAIN;
2176
- }
2177
- if (closed || authorization === undefined || refusal !== null)
2178
- return UNCERTAIN;
2179
- await dispatching?.();
2180
- journal.record(`transfer action ${name}`);
2181
- try {
2182
- const result = await options.adapter.action(authorization, { name, input });
2183
- if (result.kind === 'scoped-refusal') {
2184
- const room = replicas.get(result.locator)?.confirmed.record;
2185
- if (room !== undefined)
2186
- await scoped(result, room, await openLocal());
2187
- }
2188
- if (result.kind === 'revoked-authorization')
2189
- await refuse('revoked-authorization');
2190
- journal.record(`outcome action ${result.kind}`);
2191
- if (result.kind === 'rejected')
2192
- journal.record(`refusal rejected ${result.code}`);
2193
- return calledResult(result);
2194
- }
2195
- catch {
2196
- journal.record('outcome action transport-uncertainty');
2197
- return UNCERTAIN;
2198
- }
2199
- }
2200
- function unsettled(result) {
2201
- return result.kind !== 'action' && result.retryable;
2202
- }
2203
- async function recoveredAction(name, input) {
2204
- const operation = operationOf(input);
2205
- if (operation === null)
2206
- return invokeAction(name, input);
2207
- const kept = async () => (await openLocal()).keepCall({ operation, name, input });
2208
- calling.add(operation);
2209
- try {
2210
- let result = await invokeAction(name, input, kept);
2211
- if (unsettled(result)) {
2212
- await recovery.attempt(`action ${operation}`, async () => {
2213
- if (closed || refusal !== null)
2214
- return 'done';
2215
- if (!socketOpen)
2216
- return 'again';
2217
- result = await invokeAction(name, input, kept);
2218
- return unsettled(result) ? 'again' : 'done';
2219
- }, { again: true });
2220
- }
2221
- if (!unsettled(result))
2222
- await (await openLocal()).dropCall(operation);
2223
- return result;
2224
- }
2225
- finally {
2226
- calling.delete(operation);
2227
- }
2228
- }
2229
- async function resendCalls(signal) {
2230
- if (!socketOpen || closed || stopping)
2231
- return 'done';
2232
- const local = await openLocal();
2233
- for (const held of await local.calls()) {
2234
- if (calling.has(held.operation))
2235
- continue;
2236
- if (closed || signal.aborted)
2237
- return 'done';
2238
- if (pastHorizon(held.operation)) {
2239
- await local.dropCall(held.operation);
2240
- continue;
2241
- }
2242
- calling.add(held.operation);
2243
- try {
2244
- if (unsettled(await invokeAction(held.name, held.input)))
2245
- return 'again';
2246
- await local.dropCall(held.operation);
2247
- }
2248
- finally {
2249
- calling.delete(held.operation);
2250
- }
2251
- }
2252
- return 'done';
2253
- }
2254
- function continuing() {
2255
- return !closed && !discoveryPaused;
2256
- }
2257
- function reachedBy(locator, roomVersion) {
2258
- const held = replicas.get(locator);
2259
- return (held !== undefined &&
2260
- options.adapter.reached(locator, held.confirmed.record.roomVersion, roomVersion));
2261
- }
2262
- function writtenAfter(locator, roomVersion, path) {
2263
- const written = replicas.get(locator)?.confirmed.record.written[path];
2264
- return (written !== undefined &&
2265
- options.adapter.reached(locator, written, roomVersion) &&
2266
- !options.adapter.reached(locator, roomVersion, written));
2267
- }
2268
- async function pullRefresh(authorized, confirmed, live) {
2269
- if (!live())
2270
- return unconfirmed;
2271
- const turn = generation;
2272
- try {
2273
- const result = await refreshRoom(reads, authorized, confirmed, (models, held) => (live() ? remodel(confirmed.record.locator, models, held) : held), live);
2274
- const detail = result.kind === 'advanced' ? result.confirmed.record.roomVersion : result.kind;
2275
- journal.record(`transfer refresh ${confirmed.record.locator} ${detail}`);
2276
- return result;
2277
- }
2278
- catch (error) {
2279
- journal.record(`transfer refresh ${confirmed.record.locator} transport-uncertainty`);
2280
- throw error;
2281
- }
2282
- finally {
2283
- reads.finished(confirmed.record.locator, turn);
2284
- }
2285
- }
2286
- function staging(local, live) {
2287
- return {
2288
- held: (locator) => transfers.get(locator) ?? null,
2289
- staged: (record) => local.staged(record),
2290
- stage: (record, page) => exclusive(async () => {
2291
- if (!live())
2292
- return false;
2293
- const bytes = layerBytes(page);
2294
- if (!(await admitted(local, record.locator, bytes)))
2295
- return false;
26
+ const { adapter, shell } = options;
27
+ const roomTypes = adapter.roomTypes ?? NO_ROOM_TYPES;
28
+ const builtIn = builtInModel(roomTypes);
29
+ const typedPaths = adapter.typedPaths ?? [];
30
+ const retries = createRetries(shell);
31
+ const socket = createSocket(adapter, retries, options.authorization);
32
+ const presence = createPresence(notReadyWaitMs);
33
+ const store = createStore({
34
+ retries,
35
+ database: {
36
+ async ask(request) {
2296
37
  try {
2297
- await local.stage(record, page);
38
+ return await options.database.ask(request);
2298
39
  }
2299
40
  catch (error) {
2300
- if (!exceeded(error))
2301
- throw error;
2302
- await exceededOn(record.locator, bytes);
2303
- return false;
2304
- }
2305
- transfers.set(record.locator, record);
2306
- readSide.recover();
2307
- return true;
2308
- }),
2309
- abandon: (locator) => exclusive(async () => {
2310
- if (!live())
2311
- return;
2312
- await local.abandon(locator);
2313
- transfers.delete(locator);
2314
- readSide.recover();
2315
- }),
2316
- };
2317
- }
2318
- function reusable(room) {
2319
- const record = replicas.get(room.locator)?.confirmed.record;
2320
- if (record === undefined || record.replica.selection !== room.replica.selection)
2321
- return null;
2322
- return { documents: record.documents, revisions: record.revisions };
2323
- }
2324
- async function pullBootstrap(authorized, room, local, live) {
2325
- if (!live())
2326
- return unconfirmed;
2327
- const turn = generation;
2328
- if (replicas.has(room.locator)) {
2329
- catching.add(room.locator);
2330
- readSide.recover();
2331
- }
2332
- try {
2333
- const result = await bootstrapRoom(reads, authorized, room, {
2334
- collection: modelOf(room.locator),
2335
- selection: modelOf(room.locator, 'typed-selection'),
2336
- }, (models, held) => (live() ? remodel(room.locator, models, held) : held), live, staging(local, live), reusable(room));
2337
- const detail = result.kind === 'staged' ? result.confirmed.record.roomVersion : result.kind;
2338
- journal.record(`transfer bootstrap ${room.locator} ${detail}`);
2339
- if (result.kind !== 'staged')
2340
- caughtUpTo(room.locator);
2341
- return result;
2342
- }
2343
- catch (error) {
2344
- journal.record(`transfer bootstrap ${room.locator} transport-uncertainty`);
2345
- caughtUpTo(room.locator);
2346
- throw error;
2347
- }
2348
- finally {
2349
- reads.finished(room.locator, turn);
2350
- }
2351
- }
2352
- function caughtUpTo(locator) {
2353
- if (catching.delete(locator))
2354
- readSide.recover();
2355
- }
2356
- function behind(room) {
2357
- const held = replicas.get(room.locator)?.confirmed.record.roomVersion;
2358
- return (held !== undefined &&
2359
- [announced.get(room.locator), room.roomVersion].some((later) => later !== undefined && !options.adapter.reached(room.locator, held, later)));
2360
- }
2361
- async function advance(room, local, authorized, live) {
2362
- const carried = reads.carried(room.locator);
2363
- const withheld = await advanceOnce(room, local, authorized, live);
2364
- if (withheld !== null || reads.carried(room.locator) === carried || !behind(room)) {
2365
- return withheld;
2366
- }
2367
- return advanceOnce(room, local, authorized, live);
2368
- }
2369
- async function advanceOnce(room, local, authorized, live) {
2370
- await referenced(room.locator);
2371
- if (!live() || paused.has(room.locator))
2372
- return unconfirmed;
2373
- const held = replicas.get(room.locator);
2374
- if (held !== undefined) {
2375
- const refreshed = await pullRefresh(authorized, held.confirmed, live);
2376
- if (!live())
2377
- return unconfirmed;
2378
- if (refreshed.kind === 'still-current') {
2379
- stale.delete(room.locator);
2380
- if (sourceRefusals.has(room.locator))
2381
- return null;
2382
- if (unreadable.delete(room.locator)) {
2383
- scopedRefusals.delete(room.locator);
2384
- list(room, true);
2385
- emitRooms();
2386
- }
2387
- return null;
2388
- }
2389
- if (refreshed.kind === 'advanced') {
2390
- if (!(await publish(local, room, refreshed.confirmed, { base: held.confirmed }, live))) {
2391
- const now = replicas.get(room.locator)?.confirmed.record.roomVersion;
2392
- const reached = now !== undefined &&
2393
- options.adapter.reached(room.locator, now, refreshed.confirmed.record.roomVersion);
2394
- return reached ? null : advance(room, local, authorized, live);
2395
- }
2396
- await retainModel(local, room, 'collection', modelOf(room.locator));
2397
- return null;
2398
- }
2399
- if (refreshed.kind !== 'beyond-horizon')
2400
- return refreshed;
2401
- if (opened !== null) {
2402
- owed.add(room.locator);
2403
- readSide.recover();
2404
- return unconfirmed;
2405
- }
2406
- if (reloadsDue.get(room.locator) === generation)
2407
- return unconfirmed;
2408
- }
2409
- const bootstrapped = await pullBootstrap(authorized, room, local, live);
2410
- if (!live())
2411
- return unconfirmed;
2412
- if (bootstrapped.kind !== 'staged')
2413
- return bootstrapped;
2414
- await publish(local, room, bootstrapped.confirmed, { stored: bootstrapped.stored }, live);
2415
- return null;
2416
- }
2417
- async function withhold(withheld, room, local, progress) {
2418
- if (withheld.kind === 'unconfirmed')
2419
- return;
2420
- if (withheld.kind === 'refused')
2421
- stale.delete(room.locator);
2422
- else
2423
- stale.add(room.locator);
2424
- if (withheld.kind === 'transport-uncertainty' || withheld.kind === 'retryable-refusal') {
2425
- const reset = withheld.kind === 'retryable-refusal' ? withheld.reset : undefined;
2426
- repairable.set(room.locator, reset);
2427
- repairLater(room.locator, reset === undefined ? { again: true } : { at: Date.parse(reset) });
2428
- }
2429
- else
2430
- repairable.delete(room.locator);
2431
- if (withheld.kind === 'scoped-refusal') {
2432
- await scoped(withheld, room, local);
2433
- }
2434
- else if (withheld.kind === 'transport-uncertainty') {
2435
- progress.reachable = false;
2436
- }
2437
- else if (withheld.kind === 'retryable-refusal') {
2438
- journal.record(`refusal ${withheld.kind} ${withheld.code}`);
2439
- }
2440
- else if (withheld.kind === 'room-not-readable') {
2441
- unreadable.add(room.locator);
2442
- list(room, false);
2443
- emitRooms();
2444
- }
2445
- else if (withheld.kind === 'refused') {
2446
- refusedSource(room, withheld);
2447
- }
2448
- else if (withheld.kind === 'revoked-authorization') {
2449
- await refuse('revoked-authorization');
2450
- }
2451
- }
2452
- function refusedSource(room, { refusal }) {
2453
- sourceRefusals.set(room.locator, {
2454
- code: refusal.rule,
2455
- retryable: false,
2456
- fields: {
2457
- file: refusal.file,
2458
- ...(refusal.location === undefined ? {} : { location: refusal.location }),
2459
- ...(refusal.referrers === undefined ? {} : { referrers: refusal.referrers }),
2460
- },
2461
- });
2462
- declarationRefusals.delete(room.locator);
2463
- unreadable.add(room.locator);
2464
- list(room, false);
2465
- emitRooms();
2466
- moveTo({ ...status, ...attention() });
2467
- journal.record(`source refused ${room.locator} ${refusal.rule} ${refusal.file}`);
2468
- }
2469
- function leaving(batch, result) {
2470
- if (result.kind === 'expired')
2471
- return { batch, returned: returnedBy('expired') };
2472
- return {
2473
- batch,
2474
- returned: {
2475
- kind: result.kind,
2476
- code: result.code,
2477
- fields: result.fields,
2478
- retryable: result.retryable,
2479
- },
2480
- };
2481
- }
2482
- function logAccepted(locator, submitted, accepted) {
2483
- journal.record(`outcome ${locator} ${submitted.id} accepted ${accepted.roomVersion}` +
2484
- (accepted.author === undefined ? '' : ` author ${accepted.author}`) +
2485
- (accepted.time === undefined ? '' : ` time ${accepted.time}`));
2486
- }
2487
- async function adoptAccepted(room, local, submitted, accepted) {
2488
- await referenced(room.locator);
2489
- if (!continuing())
2490
- return unconfirmed;
2491
- const current = replicas.get(room.locator);
2492
- if (current === undefined || !current.queue.some((batch) => batch.id === submitted.id)) {
2493
- return null;
2494
- }
2495
- const held = current.confirmed.record.roomVersion;
2496
- logAccepted(room.locator, submitted, accepted);
2497
- const applied = options.adapter.reached(room.locator, held, accepted.roomVersion)
2498
- ? { kind: 'staged', confirmed: current.confirmed }
2499
- : await applyReturned(current.confirmed, submitted, accepted, options.adapter.follows(room.locator, held, accepted.roomVersion)
2500
- ? accepted.roomVersion
2501
- : held, accepted.roomVersion);
2502
- if (applied.kind !== 'staged') {
2503
- const key = pendingKey(room.locator, submitted.id);
2504
- const state = pendings.get(key);
2505
- await local.accept(room.locator, submitted.id, accepted.roomVersion);
2506
- if (state !== undefined && !fences.has(room.locator))
2507
- pendings.set(key, { ...state, accepted: accepted.roomVersion });
2508
- emitQueue(room.locator);
2509
- return applied;
2510
- }
2511
- const settled = await settle(local, room.locator, current, applied.confirmed, current.queue.filter((batch) => batch.id !== submitted.id), { room: true });
2512
- pendings.delete(pendingKey(room.locator, submitted.id));
2513
- unreadable.delete(room.locator);
2514
- sourceRefusals.delete(room.locator);
2515
- declarationRefusals.delete(room.locator);
2516
- const set = settled();
2517
- list(room, true);
2518
- publishChangeSet(set);
2519
- moveTo({ ...status, ...attention() });
2520
- return null;
2521
- }
2522
- async function adopted(room, local, submitted, accepted) {
2523
- const failed = await exclusive(async () => {
2524
- const adopting = await adoptAccepted(room, local, submitted, accepted);
2525
- await unpair(local);
2526
- return adopting;
2527
- });
2528
- if (failed === null)
2529
- return true;
2530
- if (failed.kind === 'refused' && continuing())
2531
- refusedSource(room, failed);
2532
- return false;
2533
- }
2534
- async function adoptedMove(room, partner, local, submitted, accepted) {
2535
- const other = discovered.get(partner);
2536
- const failed = await exclusive(async () => {
2537
- const left = await adoptAccepted(room, local, submitted, accepted);
2538
- const arriving = replicas.get(partner)?.queue.find((batch) => batch.id === submitted.id);
2539
- const arrived = other === undefined || arriving === undefined || accepted.destination === undefined
2540
- ? null
2541
- : await adoptAccepted(other, local, arriving, {
2542
- kind: 'accepted',
2543
- ...accepted.destination,
2544
- });
2545
- if (other !== undefined && arrived?.kind === 'refused' && continuing()) {
2546
- refusedSource(other, arrived);
2547
- }
2548
- await unpair(local);
2549
- return left;
2550
- });
2551
- submitLater(partner);
2552
- if (failed === null)
2553
- return true;
2554
- if (failed.kind === 'refused' && continuing())
2555
- refusedSource(room, failed);
2556
- return false;
2557
- }
2558
- function queueIn(locator) {
2559
- return replicas.get(locator)?.queue ?? queuesWithoutReplica.get(locator) ?? [];
2560
- }
2561
- function behindIn(locator, batch) {
2562
- const held = replicas.get(locator)?.queue;
2563
- if (held === undefined)
2564
- return queuesWithoutReplica.get(locator) !== undefined;
2565
- return held.findIndex((one) => one.id === batch.id) > 0;
2566
- }
2567
- function unpaired(skipped) {
2568
- for (const locator of [...replicas.keys(), ...queuesWithoutReplica.keys()]) {
2569
- for (const batch of queueIn(locator)) {
2570
- const partner = partnerOf(batch, locator);
2571
- if (partner === null || skipped.has(pendingKey(locator, batch.id)))
2572
- continue;
2573
- if (queueIn(partner).some((held) => held.id === batch.id))
2574
- continue;
2575
- if (pendings.get(pendingKey(locator, batch.id))?.accepted !== undefined)
2576
- continue;
2577
- if (leavingIn(batch, locator) && !withdrawable(locator)(batch))
2578
- continue;
2579
- return { locator, batch };
2580
- }
2581
- }
2582
- return null;
2583
- }
2584
- async function unpair(local) {
2585
- const handled = new Set();
2586
- for (let held = unpaired(handled); held !== null && continuing(); held = unpaired(handled)) {
2587
- const { locator, batch } = held;
2588
- handled.add(pendingKey(locator, batch.id));
2589
- journal.record(`outcome ${locator} ${batch.id} ${localSaves ? 'dropped' : 'unpaired'}`);
2590
- const leaving = {
2591
- batch,
2592
- returned: !localSaves && leavingIn(batch, locator) ? returnedBy('withdrawn') : null,
2593
- };
2594
- const current = replicas.get(locator);
2595
- if (current !== undefined) {
2596
- const settled = await settle(local, locator, current, current.confirmed, current.queue.filter((one) => one.id !== batch.id), { leaving });
2597
- publishChangeSet(settled());
2598
- continue;
2599
- }
2600
- const queue = queueIn(locator).filter((one) => one.id !== batch.id);
2601
- const written = new Map((leaving.returned === null
2602
- ? []
2603
- : (pendings.get(pendingKey(locator, batch.id))?.drafts ?? [])).map((saved) => [
2604
- saved.path,
2605
- {
2606
- locator,
2607
- path: saved.path,
2608
- revision: roomDraftRevision(),
2609
- parts: returnedInto(roomDrafts.get(locator)?.get(saved.path)?.parts, saved.parts),
2610
- returned: leaving.returned,
2611
- },
2612
- ]));
2613
- const carried = carriedBack(locator, leaving.returned === null ? [] : [batch], written);
2614
- await local.keepAuthored({
2615
- locator,
2616
- queue,
2617
- roomDrafts: [...written.values()],
2618
- consumedRoomDrafts: carried.taken,
2619
- }, ...carried.writes);
2620
- pendings.delete(pendingKey(locator, batch.id));
2621
- if (queue.length > 0)
2622
- queuesWithoutReplica.set(locator, queue);
2623
- else
2624
- queuesWithoutReplica.delete(locator);
2625
- for (const record of written.values())
2626
- rememberRoomDraft(record);
2627
- carried.remember();
2628
- publishChangeSet(mergeChangeSets([
2629
- changeSet(locator, null, null, {
2630
- queue: true,
2631
- drafts: [...written.keys(), ...carried.taken],
2632
- }),
2633
- ...carried.changes,
2634
- ]));
2635
- }
2636
- if (handled.size === 0)
2637
- return;
2638
- moveTo({ ...status, ...attention() });
2639
- for (const key of handled)
2640
- submitLater(key.slice(0, key.indexOf('\u0000')));
2641
- }
2642
- async function discardHeld(head, room, local, signal) {
2643
- const partner = partnerOf(head, room.locator);
2644
- const other = partner === null ? undefined : discovered.get(partner);
2645
- await discardPending(room, local, signal);
2646
- if (other !== undefined && !signal.aborted)
2647
- await discardPending(other, local, signal);
2648
- }
2649
- async function submitRoom(room, local, authorized, progress, signal) {
2650
- while (continuing() && authorization !== undefined && !signal.aborted) {
2651
- const replica = replicas.get(room.locator);
2652
- const head = replica?.queue[0];
2653
- if (replica === undefined || head === undefined)
2654
- return 'done';
2655
- const state = pendings.get(pendingKey(room.locator, head.id));
2656
- if (state?.accepted !== undefined)
2657
- return 'done';
2658
- const partner = partnerOf(head, room.locator);
2659
- if (partner !== null && !leavingIn(head, room.locator)) {
2660
- submitLater(partner);
2661
- return 'done';
2662
- }
2663
- if (partner !== null && behindIn(partner, head)) {
2664
- progress.complete = false;
2665
- return 'done';
2666
- }
2667
- const { submission, lost: earlier } = state ?? {
2668
- submission: { state: 'waiting' },
2669
- lost: false,
2670
- };
2671
- if (submission.state === 'reset' && Date.now() < Date.parse(submission.reset)) {
2672
- progress.complete = false;
2673
- return { at: Date.parse(submission.reset) };
2674
- }
2675
- if (writesHeld()) {
2676
- progress.complete = false;
2677
- journal.record(`submission ${room.locator} ${head.id} held`);
2678
- return 'done';
2679
- }
2680
- const lost = earlier || submission.state === 'submitted';
2681
- if (lost && pastHorizon(head.id)) {
2682
- await discardHeld(head, room, local, signal);
2683
- return 'done';
2684
- }
2685
- let result;
2686
- journal.record(`submission ${room.locator} ${head.id}`);
2687
- await exclusive(() => mark(local, room.locator, head, { state: 'submitted' }, lost));
2688
- if (discoveryPaused || fences.has(room.locator))
2689
- return 'done';
2690
- if (signal.aborted || writesHeld()) {
2691
- await exclusive(() => mark(local, room.locator, head, submission, earlier));
2692
- if (signal.aborted)
2693
- return 'done';
2694
- progress.complete = false;
2695
- journal.record(`submission ${room.locator} ${head.id} held`);
2696
- return 'done';
2697
- }
2698
- const opensBefore = openSignals;
2699
- const answeredHere = awaitingAnswer(room.locator);
2700
- const answeredThere = partner === null ? () => { } : awaitingAnswer(partner);
2701
- const answered = () => {
2702
- answeredHere();
2703
- answeredThere();
2704
- };
2705
- try {
2706
- result = await options.adapter.mutate(authorized, {
2707
- locator: room.locator,
2708
- changeBatch: head,
2709
- ...(state?.upload === undefined ? {} : { upload: state.upload }),
2710
- }, (upload) => exclusive(() => keepUpload(local, room.locator, head.id, upload)));
2711
- }
2712
- catch {
2713
- answered();
2714
- progress.complete = false;
2715
- if (continuing())
2716
- progress.reachable = false;
2717
- return 'again';
2718
- }
2719
- if (signal.aborted) {
2720
- answered();
2721
- return 'done';
2722
- }
2723
- if (result.kind !== 'accepted' || !continuing())
2724
- answered();
2725
- if (!continuing())
2726
- return 'done';
2727
- if (result.kind === 'transport-uncertainty') {
2728
- progress.complete = false;
2729
- progress.reachable = false;
2730
- return 'again';
2731
- }
2732
- if (result.kind === 'room-not-readable') {
2733
- const unread = discovered.get(result.locator) ?? room;
2734
- progress.complete = false;
2735
- unreadable.add(unread.locator);
2736
- list(unread, false);
2737
- emitRooms();
2738
- return 'done';
2739
- }
2740
- if (result.kind === 'revoked-authorization') {
2741
- await refuse('revoked-authorization');
2742
- return 'done';
2743
- }
2744
- if (result.kind === 'scoped-refusal') {
2745
- await scoped(result, room, local);
2746
- progress.complete = false;
2747
- return 'done';
2748
- }
2749
- if (result.kind === 'write-halted') {
2750
- journal.record(`outcome ${room.locator} ${head.id} write-halted`);
2751
- await exclusive(() => mark(local, room.locator, head, { state: 'waiting' }, lost));
2752
- if (serviceMode === 'open' && openSignals !== opensBefore)
2753
- continue;
2754
- haltedRefusal = true;
2755
- progress.complete = false;
2756
- return 'done';
2757
- }
2758
- const other = partner === null ? undefined : discovered.get(partner);
2759
- if (result.kind === 'conflicted' ||
2760
- result.kind === 'rejected' ||
2761
- result.kind === 'expired' ||
2762
- result.kind === 'retryable-refusal') {
2763
- if (result.kind === 'expired' && lost && result.restored !== true) {
2764
- journal.record(`outcome ${room.locator} ${head.id} expired`);
2765
- await discardHeld(head, room, local, signal);
2766
- return 'done';
2767
- }
2768
- if (result.kind === 'expired') {
2769
- await exclusive(() => mark(local, room.locator, head, { state: 'waiting' }, partner !== null && lost));
2770
- const there = other === undefined ? null : await advance(other, local, authorized, continuing);
2771
- if (other !== undefined && there !== null) {
2772
- await withhold(there, other, local, progress);
2773
- return 'done';
2774
- }
2775
- const withheld = await advance(room, local, authorized, continuing);
2776
- if (withheld !== null) {
2777
- await withhold(withheld, room, local, progress);
2778
- return 'done';
2779
- }
2780
- }
2781
- journal.record(`outcome ${room.locator} ${head.id} ${result.kind}` +
2782
- (result.kind === 'conflicted' && result.roomVersion !== undefined
2783
- ? ` ${result.roomVersion}`
2784
- : ''));
2785
- if (result.kind !== 'expired')
2786
- journal.record(`refusal ${result.kind} ${result.code}`);
2787
- }
2788
- if (result.kind === 'retryable-refusal') {
2789
- const reset = result.reset;
2790
- progress.complete = false;
2791
- await exclusive(() => mark(local, room.locator, head, reset === undefined ? { state: 'waiting' } : { state: 'reset', reset }, lost));
2792
- return reset === undefined ? 'again' : { at: Date.parse(reset) };
2793
- }
2794
- if (result.kind === 'conflicted' || result.kind === 'rejected' || result.kind === 'expired') {
2795
- const left = leaving(head, result);
2796
- const refreshed = async () => ({
2797
- there: other === undefined ? null : await advance(other, local, authorized, continuing),
2798
- here: await advance(room, local, authorized, continuing),
2799
- });
2800
- const judged = result.kind === 'conflicted' && other !== undefined ? await refreshed() : null;
2801
- if (judged !== null && (judged.there !== null || judged.here !== null)) {
2802
- await exclusive(() => mark(local, room.locator, head, { state: 'waiting' }, lost));
2803
- if (other !== undefined && judged.there !== null) {
2804
- await withhold(judged.there, other, local, progress);
2805
- }
2806
- if (judged.here !== null)
2807
- await withhold(judged.here, room, local, progress);
2808
- return 'done';
2809
- }
2810
- await exclusive(async () => {
2811
- if (!continuing())
2812
- return;
2813
- const current = replicas.get(room.locator);
2814
- if (current === undefined || !current.queue.some((batch) => batch.id === head.id)) {
2815
- return;
2816
- }
2817
- const settled = await settle(local, room.locator, current, current.confirmed, current.queue.filter((batch) => batch.id !== head.id), {
2818
- leaving: (result.kind === 'expired' && landedWhole(room.locator, head, current.confirmed)) ||
2819
- (result.kind === 'conflicted' &&
2820
- landedWhole(room.locator, head, current.confirmed, result.affected))
2821
- ? { ...left, returned: null }
2822
- : left,
2823
- });
2824
- publishChangeSet(settled());
2825
- await unpair(local);
2826
- moveTo({ ...status, ...attention() });
2827
- });
2828
- if (result.kind === 'expired')
2829
- continue;
2830
- const { there, here } = judged ?? (await refreshed());
2831
- if (other !== undefined && there !== null)
2832
- await withhold(there, other, local, progress);
2833
- if (here !== null) {
2834
- await withhold(here, room, local, progress);
2835
- return 'done';
2836
- }
2837
- continue;
2838
- }
2839
- const kept = await (partner === null
2840
- ? adopted(room, local, head, result)
2841
- : adoptedMove(room, partner, local, head, result)).finally(answered);
2842
- if (!kept) {
2843
- progress.complete = false;
2844
- return 'done';
2845
- }
2846
- }
2847
- return 'done';
2848
- }
2849
- function pastHorizon(identity) {
2850
- return (outcomeRetention !== null && identityTime(identity) + outcomeRetention * 1000 <= Date.now());
2851
- }
2852
- async function discardPending(room, local, signal) {
2853
- const { locator } = room;
2854
- const discarded = await exclusive(async () => {
2855
- if (fences.has(locator))
2856
- return false;
2857
- const before = replicas.get(locator);
2858
- const queue = before?.queue ?? queuesWithoutReplica.get(locator) ?? [];
2859
- fences.set(locator, { at: discoveries, erased: false });
2860
- lastFenced.set(locator, ++fencings);
2861
- try {
2862
- await local.discard(locator);
2863
- }
2864
- finally {
2865
- fences.delete(locator);
2866
- }
2867
- for (const batch of queue)
2868
- pendings.delete(pendingKey(locator, batch.id));
2869
- queuesWithoutReplica.delete(locator);
2870
- const after = before === undefined ? null : await stepped(replicating(before.confirmed, [], before));
2871
- if (after !== null)
2872
- replicas.set(locator, after);
2873
- journal.record(`room discarded ${locator}`);
2874
- publishChangeSet(changeSet(locator, before ?? null, after, { queue: true }));
2875
- moveTo({ ...status, ...attention() });
2876
- return true;
2877
- });
2878
- if (!discarded)
2879
- return;
2880
- const progress = { complete: true, reachable: true };
2881
- await roomTask(locator, async (live) => {
2882
- await Promise.race([
2883
- reload(room, local, progress, () => live() && !signal.aborted),
2884
- abandonedOn(signal),
2885
- ]);
2886
- });
2887
- if (signal.aborted)
2888
- return;
2889
- await rest(progress);
2890
- }
2891
- function awaitingAnswer(locator) {
2892
- let release = () => { };
2893
- const awaited = new Promise((resolve) => {
2894
- release = resolve;
2895
- });
2896
- answering.set(locator, { generation, answered: awaited });
2897
- return () => {
2898
- if (answering.get(locator)?.answered === awaited)
2899
- answering.delete(locator);
2900
- release();
2901
- };
2902
- }
2903
- async function retainModel(local, room, attached, next) {
2904
- const key = modelKey(room.locator, attached);
2905
- const previous = modelOf(room.locator, attached);
2906
- const heldBefore = replicas.get(room.locator)?.confirmed.record;
2907
- if (JSON.stringify(previous) === JSON.stringify(next) &&
2908
- (heldBefore === undefined ||
2909
- (JSON.stringify(heldBefore.operations) === JSON.stringify(room.operations) &&
2910
- JSON.stringify(heldBefore.replica) === JSON.stringify(room.replica) &&
2911
- JSON.stringify(heldBefore.typedSelection) ===
2912
- JSON.stringify(room.typedSelection ?? null))))
2913
- return;
2914
- if (next.status === 'unavailable') {
2915
- invalidModels.add(key);
2916
- liveModels.delete(key);
2917
- }
2918
- await exclusive(async () => {
2919
- if (!continuing())
2920
- return;
2921
- const held = replicas.get(room.locator);
2922
- let changed = null;
2923
- if (held !== undefined) {
2924
- const declared = {
2925
- ...held.confirmed.record,
2926
- operations: room.operations,
2927
- replica: room.replica,
2928
- typedSelection: room.typedSelection ?? null,
2929
- ...(attached === 'collection' ? { model: next } : { selectionModel: next }),
2930
- };
2931
- const reclassified = sameMembership(declared, held.confirmed.record)
2932
- ? { kind: 'staged', confirmed: await confirmedOf(declared, held.confirmed) }
2933
- : await readReclassified(declared, held.confirmed);
2934
- const record = reclassified.kind === 'staged'
2935
- ? declared
2936
- : {
2937
- ...declared,
2938
- typedSelection: held.confirmed.record.typedSelection,
2939
- };
2940
- const read = reclassified.kind === 'deferred'
2941
- ? { kind: 'staged', confirmed: await confirmedOf(record, held.confirmed) }
2942
- : reclassified;
2943
- await local.write({ next: record, previous: held.confirmed.record });
2944
- const replica = read.kind === 'staged'
2945
- ? await stepped(replicating(read.confirmed, held.queue, held))
2946
- : { ...held, confirmed: { ...held.confirmed, record } };
2947
- await stepped(counting(replica));
2948
- const set = await stepped(changing(room.locator, held, replica, { room: true }));
2949
- replicas.set(room.locator, replica);
2950
- changed = heldChange(room.locator, held, replica, set, { room: true });
2951
- if (read.kind === 'staged') {
2952
- if (declarationRefusals.delete(room.locator)) {
2953
- sourceRefusals.delete(room.locator);
2954
- unreadable.delete(room.locator);
2955
- }
2956
- }
2957
- else {
2958
- refusedSource(room, read);
2959
- declarationRefusals.add(room.locator);
2960
- }
2961
- }
2962
- models.set(key, next);
2963
- if (next.status === 'current') {
2964
- liveModels.set(key, JSON.stringify(next.snapshot));
2965
- invalidModels.delete(key);
2966
- }
2967
- list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));
2968
- if (changed === null)
2969
- emitRooms();
2970
- else
2971
- publishChangeSet(changed);
2972
- });
2973
- }
2974
- async function scoped(result, room, local) {
2975
- if (result.scope === 'content' && !result.retryable) {
2976
- journal.record(`scoped refusal ${room.locator} ${result.scope} ${result.code}`);
2977
- await loseRooms([room.locator]);
2978
- return;
2979
- }
2980
- scopedRefusals.set(room.locator, {
2981
- code: result.code,
2982
- fields: result.fields,
2983
- retryable: result.retryable,
2984
- });
2985
- let scopedAway = room;
2986
- if (result.scope === 'model')
2987
- await retainModel(local, room, 'collection', {
2988
- status: 'unavailable',
2989
- reason: 'not-readable',
2990
- });
2991
- else if (result.scope !== 'operation') {
2992
- unreadable.add(room.locator);
2993
- scopedAway = { ...room, replica: { ...room.replica, admission: 'unavailable' } };
2994
- await retainModel(local, scopedAway, 'collection', modelOf(room.locator));
2995
- }
2996
- if (!continuing())
2997
- return;
2998
- list(scopedAway, scopedAway.replica.admission === 'admitted' && !unreadable.has(room.locator));
2999
- emitRooms();
3000
- journal.record(`scoped refusal ${room.locator} ${result.scope} ${result.code}`);
3001
- }
3002
- function heldRooms(listed) {
3003
- return listed.flatMap((room) => {
3004
- const record = replicas.get(room.locator)?.confirmed.record;
3005
- if (record === undefined || record.replica.selection !== room.replica.selection)
3006
- return [];
3007
- return [
3008
- {
3009
- locator: room.locator,
3010
- roomVersion: record.roomVersion,
3011
- documents: record.documents,
3012
- revisions: record.revisions,
3013
- },
3014
- ];
3015
- });
3016
- }
3017
- async function synchronize(listed, local, progress, attempt, live) {
3018
- const prepared = await Promise.allSettled(listed.map((room) => prepareRoom(room, local, progress)));
3019
- if (!live())
3020
- return;
3021
- const ready = listed.filter((_, index) => {
3022
- const outcome = prepared[index];
3023
- return outcome?.status === 'fulfilled' && outcome.value;
3024
- });
3025
- if (attempt === 'opened') {
3026
- options.adapter.roomStream?.hold(heldRooms(ready));
3027
- handed = true;
3028
- }
3029
- discovering?.release();
3030
- const loaded = await Promise.allSettled(ready
3031
- .filter((room) => attempt === 'unstreamed' || !replicas.has(room.locator))
3032
- .map((room) => roomTask(room.locator, (held) => loadRoom(room, local, progress, held))));
3033
- const failed = [...prepared, ...loaded].find((room) => room.status === 'rejected');
3034
- if (failed !== undefined)
3035
- throw failed.reason;
3036
- }
3037
- async function prepareRoom(room, local, progress) {
3038
- if (closed || authorization === undefined) {
3039
- progress.complete = false;
3040
- return false;
3041
- }
3042
- const prior = replicas.get(room.locator)?.confirmed.record;
3043
- if (prior !== undefined && prior.replica.selection !== room.replica.selection) {
3044
- list(prior, false);
3045
- emitRooms();
3046
- journal.record(`selection changed ${room.locator}`);
3047
- progress.complete = false;
3048
- return false;
3049
- }
3050
- if (prior !== undefined)
3051
- await retainModel(local, room, 'collection', modelOf(room.locator));
3052
- if (discoveryPaused || authorization === undefined)
3053
- return false;
3054
- return room.replica.admission === 'admitted';
3055
- }
3056
- async function caughtUp(room, local, progress, live) {
3057
- if (authorization === undefined || !live() || !behind(room))
3058
- return;
3059
- const withheld = await advance(room, local, authorization, live);
3060
- if (withheld !== null)
3061
- await withhold(withheld, room, local, progress);
3062
- }
3063
- function revoked(locator) {
3064
- return ['collection', 'typed-selection'].some((attached) => {
3065
- const model = modelOf(locator, attached);
3066
- return model.status === 'unavailable' && model.reason === 'revoked';
3067
- });
3068
- }
3069
- async function loadRoom(room, local, progress, live) {
3070
- if (!live() || authorization === undefined)
3071
- return;
3072
- if (replicas.has(room.locator) && revoked(room.locator)) {
3073
- await reload(room, local, progress, live);
3074
- return;
3075
- }
3076
- const withheld = await advance(room, local, authorization, live);
3077
- if (withheld !== null) {
3078
- await withhold(withheld, room, local, progress);
3079
- return;
3080
- }
3081
- await caughtUp(room, local, progress, live);
3082
- }
3083
- async function reload(room, local, progress, live) {
3084
- try {
3085
- if (live())
3086
- reloadsDue.delete(room.locator);
3087
- if (!live() || authorization === undefined)
3088
- return;
3089
- const bootstrapped = await pullBootstrap(authorization, room, local, live);
3090
- if (!live())
3091
- return;
3092
- if (bootstrapped.kind !== 'staged') {
3093
- await withhold(bootstrapped, room, local, progress);
3094
- return;
3095
- }
3096
- await publish(local, room, bootstrapped.confirmed, { stored: bootstrapped.stored }, live);
3097
- await caughtUp(room, local, progress, live);
3098
- }
3099
- finally {
3100
- caughtUpTo(room.locator);
3101
- }
3102
- }
3103
- async function discoverRooms(local, progress, attempt, live, scope) {
3104
- if (closed || authorization === undefined) {
3105
- notifyReady();
3106
- return;
3107
- }
3108
- moveTo(transferring(status));
3109
- discoveries += 1;
3110
- const started = discoveries;
3111
- let result;
3112
- try {
3113
- result = await options.adapter.discover(authorization, scope);
3114
- }
3115
- catch {
3116
- result = { kind: 'transport-uncertainty' };
3117
- }
3118
- if (!live()) {
3119
- progress.complete = false;
3120
- notifyReady();
3121
- return;
3122
- }
3123
- journal.record(`connection discover ${result.kind}`);
3124
- if (result.kind === 'transport-uncertainty') {
3125
- for (const room of rooms.values()) {
3126
- await retainModel(local, room, 'collection', cached(modelOf(room.locator)));
3127
- if (room.typedSelection !== null) {
3128
- await retainModel(local, room, 'typed-selection', cached(modelOf(room.locator, 'typed-selection')));
3129
- }
3130
- }
3131
- progress.reachable = false;
3132
- progress.complete = false;
3133
- notifyReady();
3134
- return;
3135
- }
3136
- if (result.kind === 'contract-unavailable') {
3137
- journal.record(`connection contract unavailable ${result.code}`);
3138
- await refuse('missing-required-guarantee', {
3139
- code: result.code,
3140
- fields: result.fields,
3141
- retryable: result.retryable,
3142
- });
3143
- notifyReady();
3144
- return;
3145
- }
3146
- if (result.kind === 'revoked-authorization') {
3147
- await refuse('revoked-authorization');
3148
- notifyReady();
3149
- return;
3150
- }
3151
- for (const room of result.rooms) {
3152
- if (room.operations === undefined ||
3153
- !['write', 'delete'].every((operation) => Array.isArray(room.operations[operation]) &&
3154
- room.operations[operation].every((scope) => typeof scope === 'string')) ||
3155
- room.replica === undefined ||
3156
- typeof room.replica.selection !== 'string' ||
3157
- room.replica.selection.length === 0 ||
3158
- !['admitted', 'unavailable'].includes(room.replica.admission) ||
3159
- !['locked', 'open'].includes(room.replica.offline)) {
3160
- journal.record(`invalid model or replica declaration ${room.locator}`);
3161
- await refuse('missing-required-guarantee');
3162
- notifyReady();
3163
- return;
3164
- }
3165
- if (!declaredSelection(room)) {
3166
- journal.record(`invalid typed selection declaration ${room.locator}`);
3167
- await refuse('missing-required-guarantee');
3168
- notifyReady();
3169
- return;
3170
- }
3171
- }
3172
- if (refusal !== null) {
3173
- refusal = null;
3174
- emitRefusal();
3175
- }
3176
- const previousCapabilities = capabilities;
3177
- capabilities = result.capabilities;
3178
- outcomeRetention = result.retention.outcome;
3179
- notifyReady();
3180
- if (JSON.stringify(result.providerLimits) !== JSON.stringify(limits) ||
3181
- JSON.stringify(result.capabilities) !== JSON.stringify(previousCapabilities)) {
3182
- limits = result.providerLimits;
3183
- await local.declare(limits, capabilities);
3184
- }
3185
- const signedIn = result.member ?? null;
3186
- if (JSON.stringify(signedIn) !== JSON.stringify(member)) {
3187
- await local.keepMember(signedIn);
3188
- member = signedIn;
3189
- emitMember();
3190
- }
3191
- await synchronize(await applyDiscovery(result.rooms, started, result.covered), local, progress, attempt, live);
3192
- }
3193
- async function ensureAuthorization() {
3194
- if (authorization !== undefined)
3195
- return;
3196
- try {
3197
- authorization = await options.adapter.authorize();
3198
- journal.record('connection authorize');
3199
- }
3200
- catch (error) {
3201
- journal.record('connection authorize transport-uncertainty');
3202
- throw error;
3203
- }
3204
- }
3205
- async function admittedRead(work) {
3206
- if (roomReads.generation !== generation) {
3207
- roomReads = { generation, free: ROOM_READS, waiting: [] };
3208
- }
3209
- const reads = roomReads;
3210
- while (reads.free === 0)
3211
- await new Promise((admit) => reads.waiting.push(admit));
3212
- reads.free -= 1;
3213
- try {
3214
- await work();
3215
- }
3216
- finally {
3217
- reads.free += 1;
3218
- reads.waiting.shift()?.();
3219
- }
3220
- }
3221
- function roomTask(locator, work) {
3222
- return task(roomLane(locator), (live) => admittedRead(() => work(live)));
3223
- }
3224
- function task(lane, work) {
3225
- if (stopping)
3226
- return Promise.resolve();
3227
- const held = lanes.get(lane);
3228
- const current = held?.generation === generation ? held : { generation, chain: Promise.resolve() };
3229
- const turn = current.generation;
3230
- const live = () => turn === generation && continuing();
3231
- const run = current.chain.then(() => work(live)).catch(() => undefined);
3232
- current.chain = run;
3233
- lanes.set(lane, current);
3234
- working.add(run);
3235
- void run.finally(() => working.delete(run));
3236
- return run;
3237
- }
3238
- function sync(attempt) {
3239
- return task(OPENING_LANE, async (live) => {
3240
- if (!live()) {
3241
- notifyReady();
3242
- return;
3243
- }
3244
- const progress = { complete: true, reachable: true };
3245
- const gate = discover();
3246
- if (attempt === 'opened')
3247
- opened = generation;
3248
- underway = attempt === 'opened' ? { generation, progress } : null;
3249
- if (attempt === 'opened')
3250
- streamed = progress;
3251
- complete = false;
3252
- recorded = false;
3253
- moveTo(transferring(status));
3254
- handed = false;
3255
- try {
3256
- const local = await openLocal();
3257
- if (!live())
3258
- return;
3259
- await ensureAuthorization();
3260
- if (!live())
3261
- return;
3262
- await discoverRooms(local, progress, attempt, live);
3263
- }
3264
- catch {
3265
- progress.complete = false;
3266
- if (attempt === 'opened' && !handed)
3267
- progress.reachable = false;
3268
- }
3269
- finally {
3270
- gate.release();
3271
- notifyReady();
3272
- }
3273
- if (!live())
3274
- return;
3275
- if (attempt !== 'opened') {
3276
- await finishOpening(progress, live);
3277
- return;
3278
- }
3279
- if (handed || closed || progress.reachable)
3280
- return;
3281
- underway = null;
3282
- opened = null;
3283
- journal.record('connection reopen');
3284
- await rest(progress, live);
3285
- options.adapter.roomStream?.reopen();
3286
- });
3287
- }
3288
- function rediscover(scope) {
3289
- return task(OPENING_LANE, async (live) => {
3290
- if (!live() || !socketOpen)
3291
- return;
3292
- const progress = { complete: true, reachable: true };
3293
- const gate = discover();
3294
- moveTo(transferring(status));
3295
- try {
3296
- const local = await openLocal();
3297
- if (!live())
3298
- return;
3299
- await ensureAuthorization();
3300
- if (!live())
3301
- return;
3302
- await discoverRooms(local, progress, 'authorized', live, scope);
3303
- }
3304
- catch {
3305
- progress.complete = false;
3306
- }
3307
- finally {
3308
- gate.release();
3309
- notifyReady();
3310
- }
3311
- if (!live())
3312
- return;
3313
- if (!progress.complete)
3314
- complete = false;
3315
- await rest(progress, live);
3316
- });
3317
- }
3318
- function closedSocket(revoked, lost) {
3319
- const opened = socketOpen;
3320
- socketOpen = false;
3321
- connectionLost();
3322
- if (lost) {
3323
- reads.lost();
3324
- conversations.lost();
3325
- }
3326
- if (revoked) {
3327
- void refuse('revoked-authorization');
3328
- return;
3329
- }
3330
- complete = false;
3331
- if (streamed !== null)
3332
- streamed.complete = false;
3333
- moveTo({
3334
- ...status,
3335
- state: status.state === 'synced' ? 'syncing' : status.state,
3336
- providerUnreachable: status.providerUnreachable || !opened,
3337
- });
3338
- }
3339
- function applyOpening(expired) {
3340
- const progress = underway?.generation === generation ? underway.progress : null;
3341
- const cycle = progress ?? { complete: true, reachable: true };
3342
- if (opened === generation)
3343
- opened = null;
3344
- const reloading = progress === null ? [] : owedReloads(expired);
3345
- const replacing = reloadNow((room) => expired.includes(room.locator) || reloading.includes(room.locator), cycle);
3346
- return task(OPENING_LANE, async (live) => {
3347
- underway = null;
3348
- if (!live())
3349
- return;
3350
- if (progress === null) {
3351
- await replacing;
3352
- await rest(cycle, live);
3353
- return;
3354
- }
3355
- await roomsCarried([...expired, ...reloading]);
3356
- if (!live())
3357
- return;
3358
- try {
3359
- const local = await openLocal();
3360
- const reloaded = await replacing;
3361
- if (progress.reachable) {
3362
- for (const room of discovered.values()) {
3363
- if (replicas.has(room.locator) &&
3364
- !expired.includes(room.locator) &&
3365
- !reloading.includes(room.locator)) {
3366
- await confirmModels(room, local);
3367
- }
3368
- }
41
+ if (refusedForSpace(error))
42
+ filled(runtime);
43
+ throw error;
3369
44
  }
3370
- const failed = reloaded.find((outcome) => outcome.status === 'rejected');
3371
- if (failed !== undefined)
3372
- throw failed.reason;
3373
- }
3374
- catch {
3375
- progress.complete = false;
3376
- progress.reachable = false;
3377
- }
3378
- if (live())
3379
- await finishOpening(progress, live);
3380
- });
3381
- }
3382
- function owedReloads(expired) {
3383
- const reloading = [...discovered.values()]
3384
- .filter((room) => replicas.has(room.locator) &&
3385
- !expired.includes(room.locator) &&
3386
- (owed.has(room.locator) || revoked(room.locator)))
3387
- .map((room) => room.locator);
3388
- owed.clear();
3389
- for (const locator of reloading)
3390
- catching.add(locator);
3391
- readSide.recover();
3392
- return reloading;
3393
- }
3394
- async function reloadNow(replaced, progress) {
3395
- const reloaded = [...discovered.values()].filter((room) => replicas.has(room.locator) && replaced(room));
3396
- for (const room of reloaded)
3397
- reloadsDue.set(room.locator, generation);
3398
- try {
3399
- const local = await openLocal();
3400
- return await Promise.allSettled(reloaded.map((room) => roomTask(room.locator, (live) => reload(room, local, progress, live))));
3401
- }
3402
- catch {
3403
- for (const room of reloaded)
3404
- reloadsDue.delete(room.locator);
3405
- progress.reachable = false;
3406
- return [];
3407
- }
3408
- }
3409
- async function confirmModels(room, local) {
3410
- for (const attached of ['collection', 'typed-selection']) {
3411
- const model = modelOf(room.locator, attached);
3412
- if (model.status === 'cached') {
3413
- await retainModel(local, room, attached, { ...model, status: 'current' });
3414
- }
3415
- }
3416
- }
3417
- function submitLater(locator) {
3418
- if (localSaves)
3419
- return;
3420
- void recovery.attempt(`submit ${locator}`, (signal) => submitPass(locator, signal));
3421
- }
3422
- async function submitPass(locator, signal) {
3423
- const room = discovered.get(locator);
3424
- if (closed || stopping || discoveryPaused || room === undefined)
3425
- return 'done';
3426
- const progress = { complete: true, reachable: true };
3427
- let next;
3428
- try {
3429
- await ensureAuthorization();
3430
- if (authorization === undefined)
3431
- return 'done';
3432
- next = await submitRoom(room, await openLocal(), authorization, progress, signal);
3433
- }
3434
- catch {
3435
- progress.reachable = false;
3436
- next = 'again';
3437
- }
3438
- if (signal.aborted)
3439
- return 'done';
3440
- await rest(progress);
3441
- return next === 'again' && !socketOpen ? 'done' : next;
3442
- }
3443
- function repairLater(locator, when) {
3444
- if (!socketOpen || repairing.has(locator))
3445
- return;
3446
- void recovery.attempt(`repair ${locator}`, (signal) => repairPass(locator, signal), when);
3447
- }
3448
- async function repairPass(locator, signal) {
3449
- const room = discovered.get(locator);
3450
- if (!socketOpen || closed || stopping || discoveryPaused || !stale.has(locator))
3451
- return 'done';
3452
- if (room === undefined || room.replica.admission !== 'admitted')
3453
- return 'done';
3454
- const progress = { complete: true, reachable: true };
3455
- repairing.add(locator);
3456
- try {
3457
- const local = await openLocal();
3458
- await roomTask(locator, async (live) => {
3459
- const current = () => live() && !signal.aborted;
3460
- if (!current() || authorization === undefined)
3461
- return;
3462
- const withheld = await Promise.race([
3463
- advance(room, local, authorization, current),
3464
- abandonedOn(signal),
3465
- ]);
3466
- if (withheld !== null && current())
3467
- await withhold(withheld, room, local, progress);
3468
- });
3469
- }
3470
- catch {
3471
- stale.add(locator);
3472
- progress.reachable = false;
3473
- }
3474
- finally {
3475
- repairing.delete(locator);
3476
- }
3477
- if (signal.aborted)
3478
- return 'done';
3479
- await rest(progress);
3480
- if (!stale.has(locator)) {
3481
- if ((replicas.get(locator)?.queue.length ?? 0) > 0)
3482
- submitLater(locator);
3483
- return 'done';
3484
- }
3485
- if (!repairable.has(locator))
3486
- return 'done';
3487
- const reset = repairable.get(locator);
3488
- return reset === undefined ? 'again' : { at: Date.parse(reset) };
3489
- }
3490
- function resendLater() {
3491
- if (!socketOpen)
3492
- return;
3493
- void recovery.attempt('resend', resendPass, { again: true });
3494
- }
3495
- async function resendPass(signal) {
3496
- if (!socketOpen || closed || stopping || discoveryPaused)
3497
- return 'done';
3498
- const reading = { complete: true, reachable: true };
3499
- try {
3500
- await conversations.resend(reading);
3501
- }
3502
- catch {
3503
- reading.reachable = false;
3504
- }
3505
- if (signal.aborted)
3506
- return 'done';
3507
- return reading.reachable && reading.complete ? 'done' : 'again';
3508
- }
3509
- function submitAll() {
3510
- for (const [locator, replica] of replicas) {
3511
- if (replica.queue.length > 0)
3512
- submitLater(locator);
3513
- }
3514
- }
3515
- async function finishOpening(progress, live) {
3516
- try {
3517
- if (!live()) {
3518
- progress.complete = false;
3519
- return;
3520
- }
3521
- reads.applied();
3522
- submitAll();
3523
- for (const locator of stale)
3524
- if (repairable.has(locator))
3525
- repairLater(locator, {});
3526
- await conversations.reconcile();
3527
- if (status.providerUnreachable)
3528
- conversations.reconnected();
3529
- const reading = { complete: true, reachable: true };
3530
- await conversations.catchUp(reading);
3531
- if (progress.reachable && reading.reachable)
3532
- await conversations.resend(reading);
3533
- if (progress.reachable)
3534
- void recovery.attempt('calls', resendCalls);
3535
- if (!reading.reachable) {
3536
- progress.reachable = false;
3537
- resendLater();
3538
- }
3539
- }
3540
- catch {
3541
- progress.complete = false;
3542
- }
3543
- finally {
3544
- if (live()) {
3545
- complete = progress.complete;
3546
- await rest(progress, live);
3547
- }
3548
- }
3549
- }
3550
- async function rest(progress, live = () => !closed) {
3551
- if (!live())
3552
- return;
3553
- let lastCompleted = status.lastCompleted;
3554
- let synced = complete && stale.size === 0 && !pending();
3555
- if (synced && !recorded) {
3556
- const completedAt = new Date().toISOString();
3557
- try {
3558
- await (await openLocal()).complete(completedAt);
3559
- if (!live())
3560
- return;
3561
- recorded = true;
3562
- lastCompleted = completedAt;
3563
- }
3564
- catch {
3565
- synced = false;
3566
- }
3567
- }
3568
- moveTo({
3569
- state: pending() ? 'pending' : synced && complete ? 'synced' : 'syncing',
3570
- lastCompleted,
3571
- providerUnreachable: !progress.reachable,
3572
- ...attention(),
3573
- });
3574
- }
3575
- function discover() {
3576
- let release = () => { };
3577
- const done = new Promise((resolve) => {
3578
- release = resolve;
3579
- });
3580
- discovering = { generation, done, release };
3581
- return discovering;
3582
- }
3583
- function applyRoom(locator, roomVersion) {
3584
- announced.set(locator, roomVersion);
3585
- return task(roomLane(locator), async (live) => {
3586
- if (discovering?.generation === generation)
3587
- await discovering.done;
3588
- const saving = answering.get(locator);
3589
- if (saving?.generation === generation)
3590
- await saving.answered;
3591
- if (!live() || authorization === undefined)
3592
- return;
3593
- const room = discovered.get(locator);
3594
- const held = replicas.get(locator);
3595
- if (room === undefined || room.replica.admission !== 'admitted')
3596
- return;
3597
- if (held !== undefined &&
3598
- (held.confirmed.record.replica.selection !== room.replica.selection ||
3599
- options.adapter.reached(locator, held.confirmed.record.roomVersion, roomVersion))) {
3600
- return;
3601
- }
3602
- const during = underway?.generation === generation ? underway.progress : null;
3603
- const progress = during ?? { complete: true, reachable: true };
3604
- if (during === null)
3605
- moveTo(transferring(status));
3606
- try {
3607
- const local = await openLocal();
3608
- await admittedRead(async () => {
3609
- if (!live() || authorization === undefined)
3610
- return;
3611
- const withheld = await advance(room, local, authorization, live);
3612
- if (withheld !== null)
3613
- await withhold(withheld, room, local, progress);
3614
- });
3615
- }
3616
- catch {
3617
- stale.add(locator);
3618
- }
3619
- finally {
3620
- if (during === null)
3621
- await rest(progress, live);
3622
- }
3623
- });
3624
- }
3625
- function roomsCarried(replacing) {
3626
- const replaced = new Set(replacing.map(roomLane));
3627
- return Promise.all([...lanes]
3628
- .filter(([lane, held]) => lane !== OPENING_LANE && !replaced.has(lane) && held.generation === generation)
3629
- .map(([, held]) => held.chain));
3630
- }
3631
- const receipts = {
3632
- heads: async () => (await openLocal()).receivedHeads(),
3633
- parts: async (key, count) => (await openLocal()).receivedParts(key, count),
3634
- keep: async (key, head, part) => (await openLocal()).keepReceived(key, head, part),
3635
- drop: async (keys) => (await openLocal()).dropReceived(keys),
3636
- };
3637
- function observeStream() {
3638
- const stream = options.adapter.roomStream;
3639
- if (stream === undefined || withdrawStream !== undefined)
3640
- return;
3641
- withdrawStream = stream.observe((event) => {
3642
- if (closed || stopping)
3643
- return;
3644
- if (event.kind === 'opened') {
3645
- socketOpen = true;
3646
- connectionLive();
3647
- generation += 1;
3648
- reads.opened();
3649
- conversations.reopened();
3650
- recovery.resume();
3651
- void sync('opened');
3652
- }
3653
- else if (event.kind === 'closed')
3654
- closedSocket(event.revoked, event.lost);
3655
- else if (event.kind === 'opening')
3656
- void applyOpening(event.expired);
3657
- else if (event.kind === 'authority-changed')
3658
- void rediscover(event.scope);
3659
- else
3660
- void applyRoom(event.locator, event.roomVersion);
3661
- }, receipts);
3662
- }
3663
- function writesHeld() {
3664
- return serviceMode === 'write-halted' || haltedRefusal;
3665
- }
3666
- function signalled(mode) {
3667
- if (closed)
3668
- return;
3669
- if (mode === 'open')
3670
- openSignals += 1;
3671
- const releasing = mode === 'open' && (haltedRefusal || serviceMode === 'write-halted');
3672
- if (mode === 'open')
3673
- haltedRefusal = false;
3674
- if (mode !== serviceMode) {
3675
- serviceMode = mode;
3676
- queueReadiness();
3677
- journal.record(`service mode ${mode}`);
3678
- for (const listener of serviceModeListeners)
3679
- listener(mode);
3680
- }
3681
- if (releasing)
3682
- submitAll();
3683
- }
3684
- function observeConversations() {
3685
- const stream = options.adapter.conversations;
3686
- if (stream === undefined || withdrawConversations !== undefined)
3687
- return;
3688
- withdrawConversations = stream.observe((event) => {
3689
- if (event.kind === 'list' || event.kind === 'listed' || event.kind === 'unlisted')
3690
- queueReadiness();
3691
- if (conversations.receive(event)) {
3692
- void ready.then(scheduleCurrency);
3693
- return;
3694
- }
3695
- if (event.kind !== 'gap' || conversations.current())
3696
- return;
3697
- show();
3698
- scheduleCurrency();
3699
- });
3700
- }
3701
- function scheduleCurrency() {
3702
- if (currencyQueued === generation || closed || stopping)
3703
- return;
3704
- currencyQueued = generation;
3705
- void task(CONVERSATION_LANE, runCurrency);
3706
- }
3707
- async function runCurrency(live) {
3708
- if (currencyQueued === generation)
3709
- currencyQueued = null;
3710
- if (!live())
3711
- return;
3712
- await conversations.reconcile();
3713
- if (conversations.current()) {
3714
- show();
3715
- return;
3716
- }
3717
- const progress = { complete: false, reachable: !status.providerUnreachable };
3718
- moveTo(transferring(status));
3719
- try {
3720
- await conversations.catchUp(progress);
3721
- }
3722
- catch {
3723
- progress.reachable = false;
3724
- }
3725
- await rest(progress, live);
3726
- }
3727
- function close() {
3728
- if (closed)
3729
- return;
3730
- closed = true;
3731
- if (rechecking !== null)
3732
- clearInterval(rechecking);
3733
- connectionLive();
3734
- lockListeners.clear();
3735
- readinessWatches.clear();
3736
- withdrawStream?.();
3737
- withdrawStream = undefined;
3738
- withdrawConversations?.();
3739
- withdrawConversations = undefined;
3740
- withdrawServiceMode?.();
3741
- conversations.close();
3742
- void recovery.retire();
3743
- store?.close();
3744
- void opening?.then((opened) => {
3745
- opened.close();
3746
- }, () => { });
3747
- roomListeners.clear();
3748
- refusalListeners.clear();
3749
- storageLossListeners.clear();
3750
- statusListeners.clear();
3751
- serviceModeListeners.clear();
3752
- memberListeners.clear();
3753
- readSide.close();
3754
- queueSubscriptions.clear();
3755
- roomDraftListeners.clear();
3756
- presentationListeners.clear();
3757
- }
3758
- async function stop() {
3759
- stopping = true;
3760
- await recovery.retire();
3761
- await Promise.all(working);
3762
- await mutations;
3763
- close();
3764
- }
3765
- const withdrawServiceMode = options.adapter.serviceMode?.observe(signalled);
3766
- observeConversations();
3767
- options.signal?.addEventListener('abort', close, { once: true });
3768
- if (options.signal?.aborted)
3769
- close();
3770
- observeStream();
3771
- void openLocal().then(() => {
3772
- if (capabilities.length > 0)
3773
- notifyReady();
3774
- }, () => {
3775
- notifyReady();
3776
- });
3777
- if (options.adapter.roomStream === undefined)
3778
- void sync('unstreamed');
3779
- function planned(input, reach) {
3780
- const plan = planOf(input, roomFacts(reach), planReach(reach));
3781
- const named = plan.paths !== null &&
3782
- plan.rooms !== null &&
3783
- plan.paths.length * plan.rooms.length <= MAXIMUM_WINDOW;
3784
- return plan.limit === null && named ? plan : { ...plan, limit: capped(plan.limit) };
3785
- }
3786
- function watchPlan(plan, deliver) {
3787
- let seeded = false;
3788
- let pending = true;
3789
- const shown = () => {
3790
- const seed = seeds.get(plan.key);
3791
- if (seed === undefined || seeded || !pending)
3792
- return;
3793
- seeded = true;
3794
- deliver(seededResult(seed));
3795
- };
3796
- const watchers = seedWatchers.get(plan.key) ?? new Set();
3797
- seedWatchers.set(plan.key, watchers);
3798
- watchers.add(shown);
3799
- const stop = readSide.watch(plan, identityOf(plan), () => {
3800
- const cover = covered(plan);
3801
- awaitPreparation(cover);
3802
- return seedBehind(plan, cover);
3803
- }, (message) => {
3804
- const answered = message;
3805
- pending = whole(answered) && 'pending' in answered.result;
3806
- if (pending && seeds.has(plan.key)) {
3807
- shown();
3808
- return;
3809
- }
3810
- seeded = false;
3811
- deliver(message);
3812
- });
3813
- return () => {
3814
- watchers.delete(shown);
3815
- if (watchers.size === 0)
3816
- seedWatchers.delete(plan.key);
3817
- stop();
3818
- };
3819
- }
3820
- async function searched(input, reach, locked) {
3821
- const asked = searchPlanOf(input);
3822
- const plan = { ...asked, limit: capped(asked.limit) };
3823
- const filter = {
3824
- ...filterOf(plan.documents ?? {}, roomFacts(reach), planReach(reach)),
3825
- locked,
3826
- };
3827
- const unlocking = (filter.rooms ?? [])
3828
- .filter((room) => locked.includes(room))
3829
- .map((room) => ({ room, awaits: 'unlock' }));
3830
- for (;;) {
3831
- const cover = covered(filter);
3832
- awaitPreparation(cover);
3833
- const pending = [
3834
- ...unlocking,
3835
- ...('pending' in cover ? cover.pending : []),
3836
- ];
3837
- const awaited = new Set('pending' in cover ? cover.pending.map(({ room }) => room) : []);
3838
- const held = covered({
3839
- ...filter,
3840
- rooms: reachedRooms(filter).filter((room) => !awaited.has(room)),
3841
- });
3842
- const covering = 'pending' in held ? [] : held.coverage.rooms;
3843
- const unindexed = covering
3844
- .filter(({ room }) => !searchIndex.rooms().has(room))
3845
- .map(({ room }) => room);
3846
- for (const room of unindexed)
3847
- pending.push({ room, awaits: 'index' });
3848
- const listed = conversations.searchable();
3849
- const named = reach !== null && !reach.conversations
3850
- ? []
3851
- : (plan.conversations ?? listed).filter((one) => listed.includes(one) && conversations.acquired(one));
3852
- const waiting = named.filter((one) => !searchIndex.conversations().has(one));
3853
- for (const conversation of waiting)
3854
- pending.push({ conversation, awaits: 'index' });
3855
- if (unindexed.length > 0 || waiting.length > 0)
3856
- index(unindexed, waiting);
3857
- const complete = pending.length === 0 && !('pending' in cover);
3858
- const answering = complete
3859
- ? filter
3860
- : {
3861
- ...filter,
3862
- rooms: covering
3863
- .filter(({ room }) => searchIndex.rooms().has(room))
3864
- .map(({ room }) => room),
3865
- };
3866
- const answered = covered(answering);
3867
- if ('pending' in answered)
3868
- continue;
3869
- const searchedConversations = named.filter((one) => searchIndex.conversations().has(one));
3870
- await readSide.settled();
3871
- const seen = searchIndex.changes();
3872
- await searchIndex.caughtUp();
3873
- const selected = roomsAlone(answering) ? null : await rowsQuery(answering);
3874
- if (selected !== null && 'pending' in selected)
3875
- continue;
3876
- if (searchIndex.changes() !== seen ||
3877
- JSON.stringify(covered(answering)) !== JSON.stringify(answered))
3878
- continue;
3879
- const hits = searchIndex.search(plan, selected === null ? null : selected.documents, searchedConversations, answering.rooms !== null
3880
- ? new Set(answering.rooms)
3881
- : locked.length === 0
3882
- ? null
3883
- : new Set(reachedRooms(answering)), plan.collection
3884
- ? new Map(answered.coverage.rooms.map(({ room }) => [
3885
- room,
3886
- replicas.get(room)?.confirmed.record.typedSelection?.roots ?? [],
3887
- ]))
3888
- : null);
3889
- const coverage = {
3890
- rooms: answered.coverage.rooms,
3891
- conversations: searchedConversations,
3892
- index: searchIndex.generation(),
3893
- overlay: answered.coverage.overlay,
3894
- };
3895
- return complete
3896
- ? { ...hits, coverage }
3897
- : { pending, documents: hits.documents, messages: hits.messages, coverage };
3898
- }
3899
- }
3900
- const watch = (topic, input, deliver) => {
3901
- if (topic === 'room-drafts') {
3902
- const listener = { notify: deliver, ready: false };
3903
- roomDraftListeners.add(listener);
3904
- void exclusive(async () => {
3905
- await openLocal();
3906
- if (closed || !roomDraftListeners.has(listener))
3907
- return;
3908
- listener.ready = true;
3909
- }).then(() => {
3910
- if (closed || !listener.ready || !roomDraftListeners.has(listener))
3911
- return;
3912
- listener.notify(snapshotRoomDrafts());
3913
- }, () => { });
3914
- return () => {
3915
- roomDraftListeners.delete(listener);
3916
- };
3917
- }
3918
- if (topic === 'conversation') {
3919
- return conversations.watch(input[0], input[1], deliver);
3920
- }
3921
- if (topic === 'conversations')
3922
- return conversations.watchList(deliver);
3923
- if (topic === 'agents')
3924
- return conversations.watchAgents(deliver);
3925
- if (topic === 'presentation') {
3926
- const listener = {
3927
- app: input[0],
3928
- notify: deliver,
3929
- ready: false,
3930
- };
3931
- presentationListeners.add(listener);
3932
- void exclusive(async () => {
3933
- await openLocal();
3934
- }).then(() => {
3935
- if (closed || !presentationListeners.has(listener))
3936
- return;
3937
- listener.ready = true;
3938
- listener.notify(presentationOf(listener.app));
3939
- }, () => { });
3940
- return () => {
3941
- presentationListeners.delete(listener);
3942
- };
3943
- }
3944
- if (topic === 'readiness') {
3945
- return watchReadiness({ target: '', code: 'stored', capacity: null, search: 'unused' }, null, deliver);
3946
- }
3947
- if (topic === 'rooms') {
3948
- roomListeners.add(deliver);
3949
- deliver(listed());
3950
- return () => {
3951
- roomListeners.delete(deliver);
3952
- };
3953
- }
3954
- if (topic === 'connection-refusal') {
3955
- refusalListeners.add(deliver);
3956
- deliver(refusal);
3957
- return () => {
3958
- refusalListeners.delete(deliver);
3959
- };
3960
- }
3961
- if (topic === 'storage-loss') {
3962
- storageLossListeners.add(deliver);
3963
- deliver(storageLoss);
3964
- return () => {
3965
- storageLossListeners.delete(deliver);
3966
- };
3967
- }
3968
- if (topic === 'sync-status') {
3969
- statusListeners.add(deliver);
3970
- deliver(shown);
3971
- return () => {
3972
- statusListeners.delete(deliver);
3973
- };
3974
- }
3975
- if (topic === 'service-mode') {
3976
- serviceModeListeners.add(deliver);
3977
- deliver(serviceMode);
3978
- return () => {
3979
- serviceModeListeners.delete(deliver);
3980
- };
3981
- }
3982
- if (topic === 'member') {
3983
- memberListeners.add(deliver);
3984
- deliver(member);
3985
- return () => {
3986
- memberListeners.delete(deliver);
3987
- };
3988
- }
3989
- if (topic === 'queue') {
3990
- const queue = { locator: input[0], notify: deliver };
3991
- queueSubscriptions.add(queue);
3992
- queue.notify(entriesOf(queue.locator));
3993
- return () => {
3994
- queueSubscriptions.delete(queue);
3995
- };
3996
- }
3997
- return watchPlan(planned(input[0], null), deliver);
3998
- };
3999
- const md = {
4000
- loaded() {
4001
- return openLocal().then(() => undefined);
4002
- },
4003
- rooms() {
4004
- return listed();
4005
- },
4006
- query: ((input) => rowsQuery(planned(input, null))),
4007
- search: (input) => searched(input, null, []),
4008
- types(locator) {
4009
- return {
4010
- collection: modelTypes(modelOf(locator)),
4011
- typedSelection: rooms.get(locator)?.typedSelection === undefined ||
4012
- rooms.get(locator)?.typedSelection === null
4013
- ? null
4014
- : modelTypes(modelOf(locator, 'typed-selection')),
4015
- };
4016
- },
4017
- roomDraft: {
4018
- list() {
4019
- return exclusive(async () => {
4020
- await openLocal();
4021
- return snapshotRoomDrafts();
4022
- }).then((listed) => {
4023
- publishRoomDrafts(true);
4024
- return listed;
4025
- });
4026
- },
4027
- read(room, path) {
4028
- const record = roomDrafts.get(room)?.get(path);
4029
- return record === undefined ? null : roomDraftOf(record);
4030
- },
4031
- write(room, path, revision, input) {
4032
- return exclusive(async () => {
4033
- const parts = readParts(input);
4034
- if (path === '' || normalize(path) !== path)
4035
- throw runtimeError('room-draft-malformed');
4036
- const local = await openLocal();
4037
- const current = roomDrafts.get(room)?.get(path);
4038
- if ((current?.revision ?? null) !== revision) {
4039
- return staleWrite(current === undefined ? null : roomDraftOf(current));
4040
- }
4041
- const file = parts.file === undefined
4042
- ? undefined
4043
- : await heldFile(parts.file.blob, binaryBase(replicas.get(room)?.visible, path));
4044
- const record = {
4045
- locator: room,
4046
- path,
4047
- revision: roomDraftRevision(),
4048
- parts: held(current?.parts, parts, file),
4049
- returned: current?.returned ?? null,
4050
- };
4051
- await local.keepRoomDraft(record);
4052
- rememberRoomDraft(record);
4053
- publishChangeSet(changeSet(room, null, null, { drafts: [path] }));
4054
- return { outcome: 'written', roomDraft: roomDraftOf(record) };
4055
- });
4056
- },
4057
- discard(room, path, revision) {
4058
- return exclusive(async () => {
4059
- const local = await openLocal();
4060
- const current = roomDrafts.get(room)?.get(path);
4061
- if (current === undefined || current.revision !== revision) {
4062
- return staleWrite(current === undefined ? null : roomDraftOf(current));
4063
- }
4064
- await local.discardRoomDraft(room, path);
4065
- forgetRoomDraft(room, path);
4066
- publishChangeSet(changeSet(room, null, null, { drafts: [path] }));
4067
- moveTo({ ...status, ...attention() });
4068
- return { outcome: 'written', roomDraft: null };
4069
- });
4070
45
  },
4071
46
  },
4072
- conversation: conversations.surface,
4073
- chatDraft: conversations.chatDraft,
4074
- presentation: {
4075
- read(app) {
4076
- return exclusive(async () => {
4077
- await openLocal();
4078
- return presentationOf(app);
4079
- });
4080
- },
4081
- write(app, value) {
4082
- return keepPresentation(app, () => structuredClone(value));
47
+ roomTypes,
48
+ builtIn,
49
+ typedPaths,
50
+ persistence: shell.persistence,
51
+ lost: presence.lost,
52
+ losing: presence.losing,
53
+ opening: (local) => open(runtime, local),
54
+ unpublished: uncaught,
55
+ changed(set) {
56
+ if (set.unindexed.length > 0)
57
+ prepare(runtime, set.unindexed);
58
+ for (const locator of set.due)
59
+ submitLater(runtime, locator);
60
+ return publishChangeSet(runtime, set);
61
+ },
62
+ deliverReadiness: (owed, rooms) => deliverOwedReadiness(runtime, owed, rooms),
63
+ spaceFreed: () => spaceFreed(runtime),
64
+ });
65
+ const recovery = (options.recovery ?? createRecovery()).scope(ROOM_ATTEMPTS);
66
+ const runtime = {
67
+ store,
68
+ socket,
69
+ presence,
70
+ recovery,
71
+ retries,
72
+ shell,
73
+ localSaves: adapter.localSaves === true,
74
+ roomTypes,
75
+ builtIn,
76
+ typedPaths,
77
+ writeRule: (declaration) => writeRule(declaration, adapter.pathRule ?? (() => true), adapter.localSaves === true),
78
+ usableWhenHeld: options.usableWhenHeld ?? [],
79
+ build: options.build ?? '',
80
+ conversations: createLiveConversations({
81
+ call: (name, input, attempt) => invokeAction(runtime, name, input, { attempt }),
82
+ history: (request) => readConversationHistory(runtime, request),
83
+ durably: store.durably,
84
+ local: store.open,
85
+ again: () => {
86
+ void socket.ready.then(() => scheduleCurrency(runtime));
4083
87
  },
4084
- edit(app, members) {
4085
- return keepPresentation(app, (held) => Object.fromEntries([
4086
- ...Object.entries(plain(held) ? held : {}).filter(([member]) => !Object.hasOwn(members, member)),
4087
- ...Object.entries(structuredClone(members)).filter(([, value]) => value !== null),
4088
- ]));
88
+ settled: () => {
89
+ show(runtime);
4089
90
  },
4090
- },
4091
- save(room, named, writtenBy) {
4092
- return exclusive(() => saveRoomDrafts(room, named, writtenBy));
4093
- },
4094
- saveParts(room, parts, writtenBy) {
4095
- return exclusive(() => saveParts(room, parts, writtenBy));
4096
- },
4097
- history(locator, path, query) {
4098
- return readHistory(locator, path, query);
4099
- },
4100
- resolve(room, path, destination) {
4101
- return resolveReference(room, path, destination);
4102
- },
4103
- binaryFile: {
4104
- read: readBinaryPath,
4105
- link: linkBinaryPath,
4106
- readReference: readBinaryReference,
4107
- },
4108
- async call(name, input) {
4109
- await ready;
4110
- const room = calledRooms(name, input).find((one) => locked(one));
4111
- return room === undefined ? recoveredAction(name, input) : lockedRoom(room);
4112
- },
4113
- reached(locator, roomVersion, path) {
4114
- return path === undefined
4115
- ? reachedBy(locator, roomVersion)
4116
- : writtenAfter(locator, roomVersion, path);
4117
- },
4118
- log() {
4119
- return journal.export();
4120
- },
4121
- persistence() {
4122
- return persistence === 'granted';
4123
- },
4124
- async retry() {
4125
- journal.record('retry');
4126
- unindexable.clear();
4127
- queueReadiness();
4128
- resume();
4129
- },
4130
- observe: observing(watch),
4131
- async reauthorize() {
4132
- if (refusal === null || !refusal.reauthorizationOffered)
4133
- return;
4134
- journal.record('connection reauthorize');
4135
- await Promise.all([...lanes.values()]
4136
- .filter((held) => held.generation === generation)
4137
- .map((held) => held.chain));
4138
- await mutations;
4139
- authorization = undefined;
4140
- discoveryPaused = false;
4141
- if (options.adapter.roomStream === undefined)
4142
- await sync('unstreamed');
4143
- else
4144
- await task(OPENING_LANE, ensureAuthorization);
4145
- },
4146
- };
4147
- const reachable = {
4148
- md,
4149
- watch,
4150
- referrerScope: (referrer) => options.adapter.referrerScope(referrer),
4151
- plan: planned,
4152
- query: (plan) => rowsQuery(plan),
4153
- watchPlan,
4154
- search: searched,
4155
- watchReadiness,
4156
- locked,
4157
- lockedRooms,
4158
- watchLocks,
4159
- located,
4160
- };
4161
- return {
4162
- md,
4163
- seed,
4164
- stop,
4165
- lose: loseRooms,
4166
- watch,
4167
- persisted(answer) {
4168
- if (answer === persistence)
4169
- return;
4170
- persistence = answer;
4171
- journal.record(`persistence ${answer}`);
4172
- queueReadiness();
4173
- },
4174
- within: (reach, port) => narrowed(reachable, reach, port),
91
+ stream: socket.conversations,
92
+ publish: store.changed,
93
+ online: socket.reached,
94
+ full: store.space.full,
95
+ closed: socket.closed,
96
+ unanswered: () => resendLater(runtime),
97
+ heard: (operation, lost) => socket.lanes.settle(operation, lost),
98
+ recovery: recovery.scope(),
99
+ retries,
100
+ }),
101
+ liveQueries: createLiveQueries((plan, cover) => answeredPlan(runtime, plan, cover), store.covering),
102
+ figures: createFigures({
103
+ cover: () => figuresCover(runtime),
104
+ rooms: (rooms, since) => roomTallies(runtime, rooms, since),
105
+ conversations: (conversations, since) => store.ask({ kind: 'conversation.tallies', conversations, since }),
106
+ }),
107
+ lastAnswers: readAnswers({
108
+ database: store,
109
+ build: options.build ?? '',
110
+ unkept: adapter.unkeptReads ?? [],
111
+ leading: adapter.leadingReads ?? [],
112
+ recovery: recovery.scope(),
113
+ retries,
114
+ call: (name, input, attempt) => called(runtime, name, input, attempt),
115
+ online: socket.reached,
116
+ streaming: socket.isOpen,
117
+ closed: socket.closed,
118
+ full: store.space.full,
119
+ filled: () => filled(runtime),
120
+ }),
121
+ discover: () => discover(runtime),
4175
122
  };
123
+ start(runtime, options.signal);
124
+ return composedRuntime(runtime);
4176
125
  }