@moq/net 0.4.7 → 0.22.0

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 (664) hide show
  1. package/README.md +7 -1
  2. package/announce.d.ts +1 -1
  3. package/announce.d.ts.map +1 -1
  4. package/announce.js +1 -2
  5. package/announce.js.map +1 -1
  6. package/announced.d.ts +51 -47
  7. package/announced.d.ts.map +1 -1
  8. package/announced.js +183 -32
  9. package/announced.js.map +1 -1
  10. package/announced.test-util.d.ts +2 -0
  11. package/announced.test-util.d.ts.map +1 -0
  12. package/announced.test-util.js +27 -0
  13. package/announced.test-util.js.map +1 -0
  14. package/auth.d.ts +64 -0
  15. package/auth.d.ts.map +1 -0
  16. package/auth.js +20 -0
  17. package/auth.js.map +1 -0
  18. package/auth_gate.d.ts +2 -0
  19. package/auth_gate.d.ts.map +1 -0
  20. package/auth_gate.js +24 -0
  21. package/auth_gate.js.map +1 -0
  22. package/auth_session.d.ts +49 -0
  23. package/auth_session.d.ts.map +1 -0
  24. package/auth_session.js +1097 -0
  25. package/auth_session.js.map +1 -0
  26. package/bandwidth.d.ts +129 -25
  27. package/bandwidth.d.ts.map +1 -1
  28. package/bandwidth.js +410 -139
  29. package/bandwidth.js.map +1 -1
  30. package/bandwidth_api.d.ts +1 -1
  31. package/bandwidth_api.d.ts.map +1 -1
  32. package/bandwidth_api.js +1 -2
  33. package/bandwidth_api.js.map +1 -1
  34. package/broadcast.d.ts +64 -38
  35. package/broadcast.d.ts.map +1 -1
  36. package/broadcast.js +556 -173
  37. package/broadcast.js.map +1 -1
  38. package/cache.d.ts +103 -0
  39. package/cache.d.ts.map +1 -0
  40. package/cache.js +254 -0
  41. package/cache.js.map +1 -0
  42. package/claim.test-util.d.ts +5 -0
  43. package/claim.test-util.d.ts.map +1 -0
  44. package/claim.test-util.js +13 -0
  45. package/claim.test-util.js.map +1 -0
  46. package/connection/accept.d.ts +21 -13
  47. package/connection/accept.d.ts.map +1 -1
  48. package/connection/accept.js +97 -130
  49. package/connection/accept.js.map +1 -1
  50. package/connection/browser.d.ts.map +1 -1
  51. package/connection/browser.js +28 -20
  52. package/connection/browser.js.map +1 -1
  53. package/connection/connect.d.ts +120 -24
  54. package/connection/connect.d.ts.map +1 -1
  55. package/connection/connect.js +535 -217
  56. package/connection/connect.js.map +1 -1
  57. package/connection/dials.d.ts +45 -0
  58. package/connection/dials.d.ts.map +1 -0
  59. package/connection/dials.js +109 -0
  60. package/connection/dials.js.map +1 -0
  61. package/connection/endpoint.d.ts +60 -0
  62. package/connection/endpoint.d.ts.map +1 -0
  63. package/connection/endpoint.js +114 -0
  64. package/connection/endpoint.js.map +1 -0
  65. package/connection/forward.d.ts +7 -1
  66. package/connection/forward.d.ts.map +1 -1
  67. package/connection/forward.js +265 -81
  68. package/connection/forward.js.map +1 -1
  69. package/connection/goaway.d.ts +16 -9
  70. package/connection/goaway.d.ts.map +1 -1
  71. package/connection/goaway.js +22 -95
  72. package/connection/goaway.js.map +1 -1
  73. package/connection/handshake.d.ts +34 -8
  74. package/connection/handshake.d.ts.map +1 -1
  75. package/connection/handshake.js +97 -21
  76. package/connection/handshake.js.map +1 -1
  77. package/connection/index.d.ts +4 -7
  78. package/connection/index.d.ts.map +1 -1
  79. package/connection/index.js +1 -3
  80. package/connection/index.js.map +1 -1
  81. package/connection/liveness.d.ts +14 -0
  82. package/connection/liveness.d.ts.map +1 -0
  83. package/connection/liveness.js +30 -0
  84. package/connection/liveness.js.map +1 -0
  85. package/connection/pool.d.ts +142 -63
  86. package/connection/pool.d.ts.map +1 -1
  87. package/connection/pool.js +281 -118
  88. package/connection/pool.js.map +1 -1
  89. package/connection/reload.d.ts +60 -12
  90. package/connection/reload.d.ts.map +1 -1
  91. package/connection/reload.js +859 -234
  92. package/connection/reload.js.map +1 -1
  93. package/connection/session.d.ts +91 -0
  94. package/connection/session.d.ts.map +1 -0
  95. package/connection/session.js +2 -0
  96. package/connection/session.js.map +1 -0
  97. package/connection/stats.d.ts +20 -11
  98. package/connection/stats.d.ts.map +1 -1
  99. package/connection/stats.js +64 -9
  100. package/connection/stats.js.map +1 -1
  101. package/connection/ticker.d.ts +4 -0
  102. package/connection/ticker.d.ts.map +1 -0
  103. package/connection/ticker.js +66 -0
  104. package/connection/ticker.js.map +1 -0
  105. package/connection/tokens.d.ts +2 -0
  106. package/connection/tokens.d.ts.map +1 -0
  107. package/connection/tokens.js +404 -0
  108. package/connection/tokens.js.map +1 -0
  109. package/connection/transport.d.ts.map +1 -1
  110. package/connection/transport.js +4 -5
  111. package/connection/transport.js.map +1 -1
  112. package/connection/withdrawal.d.ts +2 -0
  113. package/connection/withdrawal.d.ts.map +1 -0
  114. package/connection/withdrawal.js +23 -0
  115. package/connection/withdrawal.js.map +1 -0
  116. package/consume.js +213 -47
  117. package/consume.js.map +1 -1
  118. package/cover.d.ts +59 -0
  119. package/cover.d.ts.map +1 -0
  120. package/cover.js +375 -0
  121. package/cover.js.map +1 -0
  122. package/datagram.d.ts +70 -11
  123. package/datagram.d.ts.map +1 -1
  124. package/datagram.js +317 -2
  125. package/datagram.js.map +1 -1
  126. package/datagram_stream.d.ts +18 -0
  127. package/datagram_stream.d.ts.map +1 -0
  128. package/datagram_stream.js +67 -0
  129. package/datagram_stream.js.map +1 -0
  130. package/defined.test-util.d.ts +2 -0
  131. package/defined.test-util.d.ts.map +1 -0
  132. package/defined.test-util.js +7 -0
  133. package/defined.test-util.js.map +1 -0
  134. package/delivered.d.ts +75 -0
  135. package/delivered.d.ts.map +1 -0
  136. package/delivered.js +228 -0
  137. package/delivered.js.map +1 -0
  138. package/demand.d.ts +173 -0
  139. package/demand.d.ts.map +1 -0
  140. package/demand.js +582 -0
  141. package/demand.js.map +1 -0
  142. package/drops.d.ts +93 -0
  143. package/drops.d.ts.map +1 -0
  144. package/drops.js +283 -0
  145. package/drops.js.map +1 -0
  146. package/error.d.ts +120 -21
  147. package/error.d.ts.map +1 -1
  148. package/error.js +230 -38
  149. package/error.js.map +1 -1
  150. package/errors.d.ts +2 -2
  151. package/errors.d.ts.map +1 -1
  152. package/errors.js +2 -3
  153. package/errors.js.map +1 -1
  154. package/fill.d.ts +174 -0
  155. package/fill.d.ts.map +1 -0
  156. package/fill.js +760 -0
  157. package/fill.js.map +1 -0
  158. package/flate/decoder.d.ts +2 -0
  159. package/flate/decoder.d.ts.map +1 -0
  160. package/flate/decoder.js +63 -0
  161. package/flate/decoder.js.map +1 -0
  162. package/flate/encoder.d.ts +2 -0
  163. package/flate/encoder.d.ts.map +1 -0
  164. package/flate/encoder.js +64 -0
  165. package/flate/encoder.js.map +1 -0
  166. package/flate/group.d.ts +34 -0
  167. package/flate/group.d.ts.map +1 -0
  168. package/flate/group.js +140 -0
  169. package/flate/group.js.map +1 -0
  170. package/frame.d.ts +80 -0
  171. package/frame.d.ts.map +1 -0
  172. package/frame.js +296 -0
  173. package/frame.js.map +1 -0
  174. package/frame.test-util.d.ts +5 -0
  175. package/frame.test-util.d.ts.map +1 -0
  176. package/frame.test-util.js +9 -0
  177. package/frame.test-util.js.map +1 -0
  178. package/group.d.ts +108 -45
  179. package/group.d.ts.map +1 -1
  180. package/group.js +1616 -308
  181. package/group.js.map +1 -1
  182. package/group_api.d.ts +7 -0
  183. package/group_api.d.ts.map +1 -0
  184. package/group_api.js +7 -0
  185. package/group_api.js.map +1 -0
  186. package/hop.d.ts +62 -76
  187. package/hop.d.ts.map +1 -1
  188. package/hop.js +92 -65
  189. package/hop.js.map +1 -1
  190. package/identity.d.ts +39 -0
  191. package/identity.d.ts.map +1 -0
  192. package/identity.js +47 -0
  193. package/identity.js.map +1 -0
  194. package/ietf/active_count.d.ts +2 -0
  195. package/ietf/active_count.d.ts.map +1 -0
  196. package/ietf/active_count.js +30 -0
  197. package/ietf/active_count.js.map +1 -0
  198. package/ietf/aliases.js +69 -36
  199. package/ietf/aliases.js.map +1 -1
  200. package/ietf/cluster.d.ts +3 -3
  201. package/ietf/cluster.js +14 -55
  202. package/ietf/cluster.js.map +1 -1
  203. package/ietf/connection.d.ts +1 -31
  204. package/ietf/connection.d.ts.map +1 -1
  205. package/ietf/connection.js +305 -144
  206. package/ietf/connection.js.map +1 -1
  207. package/ietf/datagram.d.ts +60 -0
  208. package/ietf/datagram.d.ts.map +1 -0
  209. package/ietf/datagram.js +152 -0
  210. package/ietf/datagram.js.map +1 -0
  211. package/ietf/error.d.ts +3 -3
  212. package/ietf/error.js +82 -101
  213. package/ietf/error.js.map +1 -1
  214. package/ietf/fetch.d.ts +93 -37
  215. package/ietf/fetch.d.ts.map +1 -1
  216. package/ietf/fetch.js +172 -94
  217. package/ietf/fetch.js.map +1 -1
  218. package/ietf/filter.d.ts +21 -31
  219. package/ietf/filter.d.ts.map +1 -1
  220. package/ietf/filter.js +140 -172
  221. package/ietf/filter.js.map +1 -1
  222. package/ietf/goaway.d.ts +12 -10
  223. package/ietf/goaway.d.ts.map +1 -1
  224. package/ietf/goaway.js +22 -36
  225. package/ietf/goaway.js.map +1 -1
  226. package/ietf/hidden.js +1 -2
  227. package/ietf/hidden.js.map +1 -1
  228. package/ietf/index.d.ts +8 -20
  229. package/ietf/index.d.ts.map +1 -1
  230. package/ietf/index.js +4 -15
  231. package/ietf/index.js.map +1 -1
  232. package/ietf/join.d.ts +7 -0
  233. package/ietf/join.d.ts.map +1 -0
  234. package/ietf/join.js +234 -0
  235. package/ietf/join.js.map +1 -0
  236. package/ietf/message.d.ts +18 -2
  237. package/ietf/message.d.ts.map +1 -1
  238. package/ietf/message.js +60 -41
  239. package/ietf/message.js.map +1 -1
  240. package/ietf/message.test-util.d.ts +6 -0
  241. package/ietf/message.test-util.d.ts.map +1 -0
  242. package/ietf/message.test-util.js +13 -0
  243. package/ietf/message.test-util.js.map +1 -0
  244. package/ietf/namespace.d.ts +19 -5
  245. package/ietf/namespace.d.ts.map +1 -1
  246. package/ietf/namespace.js +78 -27
  247. package/ietf/namespace.js.map +1 -1
  248. package/ietf/object.d.ts +195 -33
  249. package/ietf/object.d.ts.map +1 -1
  250. package/ietf/object.js +405 -179
  251. package/ietf/object.js.map +1 -1
  252. package/ietf/parameters.d.ts +25 -45
  253. package/ietf/parameters.d.ts.map +1 -1
  254. package/ietf/parameters.js +260 -473
  255. package/ietf/parameters.js.map +1 -1
  256. package/ietf/priority.d.ts +17 -2
  257. package/ietf/priority.d.ts.map +1 -1
  258. package/ietf/priority.js +19 -5
  259. package/ietf/priority.js.map +1 -1
  260. package/ietf/properties.d.ts +6 -5
  261. package/ietf/properties.d.ts.map +1 -1
  262. package/ietf/properties.js +78 -49
  263. package/ietf/properties.js.map +1 -1
  264. package/ietf/publish.d.ts +25 -33
  265. package/ietf/publish.d.ts.map +1 -1
  266. package/ietf/publish.js +45 -140
  267. package/ietf/publish.js.map +1 -1
  268. package/ietf/publish_namespace.d.ts +49 -72
  269. package/ietf/publish_namespace.d.ts.map +1 -1
  270. package/ietf/publish_namespace.js +66 -185
  271. package/ietf/publish_namespace.js.map +1 -1
  272. package/ietf/publisher.js +1800 -601
  273. package/ietf/publisher.js.map +1 -1
  274. package/ietf/range.d.ts +2 -0
  275. package/ietf/range.d.ts.map +1 -0
  276. package/ietf/range.js +222 -0
  277. package/ietf/range.js.map +1 -0
  278. package/ietf/request.d.ts +6 -30
  279. package/ietf/request.d.ts.map +1 -1
  280. package/ietf/request.js +41 -79
  281. package/ietf/request.js.map +1 -1
  282. package/ietf/request_stream.d.ts +1 -6
  283. package/ietf/request_stream.d.ts.map +1 -1
  284. package/ietf/request_stream.js +306 -17
  285. package/ietf/request_stream.js.map +1 -1
  286. package/ietf/session.d.ts +41 -0
  287. package/ietf/session.d.ts.map +1 -0
  288. package/ietf/session.js +65 -0
  289. package/ietf/session.js.map +1 -0
  290. package/ietf/setup.d.ts +5 -30
  291. package/ietf/setup.d.ts.map +1 -1
  292. package/ietf/setup.js +6 -118
  293. package/ietf/setup.js.map +1 -1
  294. package/ietf/setup_options.d.ts +31 -0
  295. package/ietf/setup_options.d.ts.map +1 -0
  296. package/ietf/setup_options.js +138 -0
  297. package/ietf/setup_options.js.map +1 -0
  298. package/ietf/solicit.js +4 -15
  299. package/ietf/solicit.js.map +1 -1
  300. package/ietf/subscribe.d.ts +52 -45
  301. package/ietf/subscribe.d.ts.map +1 -1
  302. package/ietf/subscribe.js +118 -240
  303. package/ietf/subscribe.js.map +1 -1
  304. package/ietf/subscribe_namespace.d.ts +16 -79
  305. package/ietf/subscribe_namespace.d.ts.map +1 -1
  306. package/ietf/subscribe_namespace.js +30 -202
  307. package/ietf/subscribe_namespace.js.map +1 -1
  308. package/ietf/subscriber.js +1839 -537
  309. package/ietf/subscriber.js.map +1 -1
  310. package/ietf/token.js +105 -28
  311. package/ietf/token.js.map +1 -1
  312. package/ietf/track.d.ts +27 -24
  313. package/ietf/track.d.ts.map +1 -1
  314. package/ietf/track.js +48 -62
  315. package/ietf/track.js.map +1 -1
  316. package/ietf/version.d.ts +13 -42
  317. package/ietf/version.d.ts.map +1 -1
  318. package/ietf/version.js +22 -49
  319. package/ietf/version.js.map +1 -1
  320. package/implementation.d.ts +2 -0
  321. package/implementation.d.ts.map +1 -0
  322. package/implementation.js +5 -0
  323. package/implementation.js.map +1 -0
  324. package/index.d.ts +34 -19
  325. package/index.d.ts.map +1 -1
  326. package/index.js +19 -7
  327. package/index.js.map +1 -1
  328. package/internal.d.ts +1515 -67
  329. package/internal.d.ts.map +1 -1
  330. package/internal.js +557 -80
  331. package/internal.js.map +1 -1
  332. package/ledger.d.ts +23 -0
  333. package/ledger.d.ts.map +1 -0
  334. package/ledger.js +247 -0
  335. package/ledger.js.map +1 -0
  336. package/listing.d.ts +132 -0
  337. package/listing.d.ts.map +1 -0
  338. package/listing.js +486 -0
  339. package/listing.js.map +1 -0
  340. package/lite/announce.d.ts +127 -66
  341. package/lite/announce.d.ts.map +1 -1
  342. package/lite/announce.js +384 -159
  343. package/lite/announce.js.map +1 -1
  344. package/lite/announce_stream.d.ts +2 -0
  345. package/lite/announce_stream.d.ts.map +1 -0
  346. package/lite/announce_stream.js +92 -0
  347. package/lite/announce_stream.js.map +1 -0
  348. package/lite/answer.d.ts +22 -0
  349. package/lite/answer.d.ts.map +1 -0
  350. package/lite/answer.js +301 -0
  351. package/lite/answer.js.map +1 -0
  352. package/lite/auth.d.ts +45 -0
  353. package/lite/auth.d.ts.map +1 -0
  354. package/lite/auth.js +204 -0
  355. package/lite/auth.js.map +1 -0
  356. package/lite/compat.d.ts +31 -0
  357. package/lite/compat.d.ts.map +1 -0
  358. package/lite/compat.js +86 -0
  359. package/lite/compat.js.map +1 -0
  360. package/lite/connection.d.ts +1 -45
  361. package/lite/connection.d.ts.map +1 -1
  362. package/lite/connection.js +360 -78
  363. package/lite/connection.js.map +1 -1
  364. package/lite/datagram-end.d.ts +26 -0
  365. package/lite/datagram-end.d.ts.map +1 -0
  366. package/lite/datagram-end.js +30 -0
  367. package/lite/datagram-end.js.map +1 -0
  368. package/lite/datagram.d.ts +73 -8
  369. package/lite/datagram.d.ts.map +1 -1
  370. package/lite/datagram.js +144 -10
  371. package/lite/datagram.js.map +1 -1
  372. package/lite/duration.d.ts +6 -0
  373. package/lite/duration.d.ts.map +1 -0
  374. package/lite/duration.js +14 -0
  375. package/lite/duration.js.map +1 -0
  376. package/lite/error.d.ts +9 -0
  377. package/lite/error.d.ts.map +1 -0
  378. package/lite/error.js +24 -0
  379. package/lite/error.js.map +1 -0
  380. package/lite/fills.d.ts +162 -0
  381. package/lite/fills.d.ts.map +1 -0
  382. package/lite/fills.js +486 -0
  383. package/lite/fills.js.map +1 -0
  384. package/lite/fit.d.ts +49 -0
  385. package/lite/fit.d.ts.map +1 -0
  386. package/lite/fit.js +305 -0
  387. package/lite/fit.js.map +1 -0
  388. package/lite/goaway.d.ts +2 -2
  389. package/lite/goaway.d.ts.map +1 -1
  390. package/lite/goaway.js +5 -14
  391. package/lite/goaway.js.map +1 -1
  392. package/lite/group.d.ts +67 -16
  393. package/lite/group.d.ts.map +1 -1
  394. package/lite/group.js +108 -31
  395. package/lite/group.js.map +1 -1
  396. package/lite/identity.d.ts +25 -0
  397. package/lite/identity.d.ts.map +1 -0
  398. package/lite/identity.js +79 -0
  399. package/lite/identity.js.map +1 -0
  400. package/lite/index.d.ts +14 -13
  401. package/lite/index.d.ts.map +1 -1
  402. package/lite/index.js +2 -2
  403. package/lite/index.js.map +1 -1
  404. package/lite/message.d.ts +10 -2
  405. package/lite/message.d.ts.map +1 -1
  406. package/lite/message.js +28 -45
  407. package/lite/message.js.map +1 -1
  408. package/lite/priority.d.ts +9 -2
  409. package/lite/priority.d.ts.map +1 -1
  410. package/lite/priority.js +11 -106
  411. package/lite/priority.js.map +1 -1
  412. package/lite/probe.d.ts +2 -2
  413. package/lite/probe.d.ts.map +1 -1
  414. package/lite/probe.js +9 -1
  415. package/lite/probe.js.map +1 -1
  416. package/lite/publisher.d.ts +10 -1
  417. package/lite/publisher.d.ts.map +1 -1
  418. package/lite/publisher.js +2548 -438
  419. package/lite/publisher.js.map +1 -1
  420. package/lite/routed.d.ts +59 -0
  421. package/lite/routed.d.ts.map +1 -0
  422. package/lite/routed.js +564 -0
  423. package/lite/routed.js.map +1 -0
  424. package/lite/session.d.ts +2 -28
  425. package/lite/session.d.ts.map +1 -1
  426. package/lite/session.js +0 -100
  427. package/lite/session.js.map +1 -1
  428. package/lite/setup.d.ts +32 -5
  429. package/lite/setup.d.ts.map +1 -1
  430. package/lite/setup.js +95 -22
  431. package/lite/setup.js.map +1 -1
  432. package/lite/stream.d.ts +5 -11
  433. package/lite/stream.d.ts.map +1 -1
  434. package/lite/stream.js +5 -2
  435. package/lite/stream.js.map +1 -1
  436. package/lite/subscribe.d.ts +478 -78
  437. package/lite/subscribe.d.ts.map +1 -1
  438. package/lite/subscribe.js +1373 -143
  439. package/lite/subscribe.js.map +1 -1
  440. package/lite/subscriber.d.ts +7 -44
  441. package/lite/subscriber.d.ts.map +1 -1
  442. package/lite/subscriber.js +3290 -516
  443. package/lite/subscriber.js.map +1 -1
  444. package/lite/track.d.ts +27 -12
  445. package/lite/track.d.ts.map +1 -1
  446. package/lite/track.js +116 -38
  447. package/lite/track.js.map +1 -1
  448. package/lite/tracks.d.ts +55 -0
  449. package/lite/tracks.d.ts.map +1 -0
  450. package/lite/tracks.js +114 -0
  451. package/lite/tracks.js.map +1 -0
  452. package/lite/version.d.ts +132 -24
  453. package/lite/version.d.ts.map +1 -1
  454. package/lite/version.js +378 -34
  455. package/lite/version.js.map +1 -1
  456. package/meta.d.ts +77 -0
  457. package/meta.d.ts.map +1 -0
  458. package/meta.js +130 -0
  459. package/meta.js.map +1 -0
  460. package/meta_api.d.ts +7 -0
  461. package/meta_api.d.ts.map +1 -0
  462. package/meta_api.js +7 -0
  463. package/meta_api.js.map +1 -0
  464. package/mint.d.ts +28 -0
  465. package/mint.d.ts.map +1 -0
  466. package/mint.js +66 -0
  467. package/mint.js.map +1 -0
  468. package/open.d.ts +63 -0
  469. package/open.d.ts.map +1 -0
  470. package/open.js +250 -0
  471. package/open.js.map +1 -0
  472. package/origin.d.ts +394 -142
  473. package/origin.d.ts.map +1 -1
  474. package/origin.js +2533 -687
  475. package/origin.js.map +1 -1
  476. package/package.json +8 -13
  477. package/path.d.ts +51 -51
  478. package/path.d.ts.map +1 -1
  479. package/path.js +210 -58
  480. package/path.js.map +1 -1
  481. package/payload.d.ts +33 -0
  482. package/payload.d.ts.map +1 -0
  483. package/payload.js +65 -0
  484. package/payload.js.map +1 -0
  485. package/prefix.d.ts +152 -0
  486. package/prefix.d.ts.map +1 -0
  487. package/prefix.js +349 -0
  488. package/prefix.js.map +1 -0
  489. package/priority.d.ts +8 -0
  490. package/priority.d.ts.map +1 -0
  491. package/priority.js +185 -0
  492. package/priority.js.map +1 -0
  493. package/queue.d.ts +2 -0
  494. package/queue.d.ts.map +1 -0
  495. package/queue.js +46 -0
  496. package/queue.js.map +1 -0
  497. package/ranges.d.ts +36 -0
  498. package/ranges.d.ts.map +1 -0
  499. package/ranges.js +312 -0
  500. package/ranges.js.map +1 -0
  501. package/rescale.d.ts +24 -0
  502. package/rescale.d.ts.map +1 -0
  503. package/rescale.js +39 -0
  504. package/rescale.js.map +1 -0
  505. package/resume.d.ts +55 -0
  506. package/resume.d.ts.map +1 -0
  507. package/resume.js +4173 -0
  508. package/resume.js.map +1 -0
  509. package/resume.test-util.d.ts +2 -0
  510. package/resume.test-util.d.ts.map +1 -0
  511. package/resume.test-util.js +25 -0
  512. package/resume.test-util.js.map +1 -0
  513. package/skips.d.ts +48 -0
  514. package/skips.d.ts.map +1 -0
  515. package/skips.js +182 -0
  516. package/skips.js.map +1 -0
  517. package/stream.d.ts +78 -40
  518. package/stream.d.ts.map +1 -1
  519. package/stream.js +236 -93
  520. package/stream.js.map +1 -1
  521. package/subscription.test-util.d.ts +2 -0
  522. package/subscription.test-util.d.ts.map +1 -0
  523. package/subscription.test-util.js +49 -0
  524. package/subscription.test-util.js.map +1 -0
  525. package/tail.d.ts +23 -14
  526. package/tail.d.ts.map +1 -1
  527. package/tail.js +224 -98
  528. package/tail.js.map +1 -1
  529. package/time.d.ts +41 -102
  530. package/time.d.ts.map +1 -1
  531. package/time.js +129 -92
  532. package/time.js.map +1 -1
  533. package/timed.d.ts +21 -0
  534. package/timed.d.ts.map +1 -0
  535. package/timed.js +2 -0
  536. package/timed.js.map +1 -0
  537. package/track.d.ts +578 -246
  538. package/track.d.ts.map +1 -1
  539. package/track.js +7306 -772
  540. package/track.js.map +1 -1
  541. package/track_api.d.ts +7 -0
  542. package/track_api.d.ts.map +1 -0
  543. package/track_api.js +7 -0
  544. package/track_api.js.map +1 -0
  545. package/util/abort.d.ts +1 -0
  546. package/util/abort.d.ts.map +1 -1
  547. package/util/abort.js +23 -2
  548. package/util/abort.js.map +1 -1
  549. package/util/announce.d.ts +4 -0
  550. package/util/announce.d.ts.map +1 -0
  551. package/util/announce.js +11 -0
  552. package/util/announce.js.map +1 -0
  553. package/util/bigint.d.ts +3 -0
  554. package/util/bigint.d.ts.map +1 -0
  555. package/util/bigint.js +8 -0
  556. package/util/bigint.js.map +1 -0
  557. package/util/change.d.ts +12 -0
  558. package/util/change.d.ts.map +1 -0
  559. package/util/change.js +18 -0
  560. package/util/change.js.map +1 -0
  561. package/util/deadline.d.ts +2 -0
  562. package/util/deadline.d.ts.map +1 -0
  563. package/util/deadline.js +108 -0
  564. package/util/deadline.js.map +1 -0
  565. package/util/decode_error.d.ts +3 -0
  566. package/util/decode_error.d.ts.map +1 -0
  567. package/util/decode_error.js +11 -0
  568. package/util/decode_error.js.map +1 -0
  569. package/util/demand.d.ts +8 -0
  570. package/util/demand.d.ts.map +1 -0
  571. package/util/demand.js +24 -0
  572. package/util/demand.js.map +1 -0
  573. package/util/given_up.d.ts +2 -0
  574. package/util/given_up.d.ts.map +1 -0
  575. package/util/given_up.js +101 -0
  576. package/util/given_up.js.map +1 -0
  577. package/util/hex.d.ts +6 -0
  578. package/util/hex.d.ts.map +1 -1
  579. package/util/hex.js +19 -5
  580. package/util/hex.js.map +1 -1
  581. package/util/key.d.ts +15 -0
  582. package/util/key.d.ts.map +1 -0
  583. package/util/key.js +38 -0
  584. package/util/key.js.map +1 -0
  585. package/util/limits.d.ts +2 -0
  586. package/util/limits.d.ts.map +1 -0
  587. package/util/limits.js +76 -0
  588. package/util/limits.js.map +1 -0
  589. package/util/observed.d.ts +23 -0
  590. package/util/observed.d.ts.map +1 -0
  591. package/util/observed.js +122 -0
  592. package/util/observed.js.map +1 -0
  593. package/util/sorted.d.ts +2 -0
  594. package/util/sorted.d.ts.map +1 -0
  595. package/util/sorted.js +149 -0
  596. package/util/sorted.js.map +1 -0
  597. package/util/timeout.d.ts +2 -1
  598. package/util/timeout.d.ts.map +1 -1
  599. package/util/timeout.js +13 -10
  600. package/util/timeout.js.map +1 -1
  601. package/util/timer.d.ts +2 -0
  602. package/util/timer.d.ts.map +1 -0
  603. package/util/timer.js +19 -0
  604. package/util/timer.js.map +1 -0
  605. package/util/u64.js +0 -1
  606. package/util/utf8.d.ts +2 -0
  607. package/util/utf8.d.ts.map +1 -1
  608. package/util/utf8.js +7 -2
  609. package/util/utf8.js.map +1 -1
  610. package/util/varint.d.ts.map +1 -1
  611. package/util/varint.js +8 -2
  612. package/util/varint.js.map +1 -1
  613. package/util/watch.d.ts +8 -0
  614. package/util/watch.d.ts.map +1 -0
  615. package/util/watch.js +38 -0
  616. package/util/watch.js.map +1 -0
  617. package/util/yield.d.ts +2 -0
  618. package/util/yield.d.ts.map +1 -0
  619. package/util/yield.js +31 -0
  620. package/util/yield.js.map +1 -0
  621. package/varint.d.ts +0 -29
  622. package/varint.d.ts.map +1 -1
  623. package/varint.js +7 -29
  624. package/varint.js.map +1 -1
  625. package/varint_api.d.ts +7 -0
  626. package/varint_api.d.ts.map +1 -0
  627. package/varint_api.js +7 -0
  628. package/varint_api.js.map +1 -0
  629. package/version.d.ts +2 -0
  630. package/version.d.ts.map +1 -0
  631. package/version.js +4 -0
  632. package/version.js.map +1 -0
  633. package/window.d.ts +570 -0
  634. package/window.d.ts.map +1 -0
  635. package/window.js +1677 -0
  636. package/window.js.map +1 -0
  637. package/wire.d.ts +150 -35
  638. package/wire.d.ts.map +1 -1
  639. package/wire.js +27 -1
  640. package/wire.js.map +1 -1
  641. package/connection/established.d.ts +0 -53
  642. package/connection/established.d.ts.map +0 -1
  643. package/connection/established.js +0 -3
  644. package/connection/established.js.map +0 -1
  645. package/ietf/adapter.d.ts +0 -75
  646. package/ietf/adapter.d.ts.map +0 -1
  647. package/ietf/adapter.js +0 -700
  648. package/ietf/adapter.js.map +0 -1
  649. package/lite/datagram_stream.d.ts +0 -8
  650. package/lite/datagram_stream.d.ts.map +0 -1
  651. package/lite/datagram_stream.js +0 -44
  652. package/lite/datagram_stream.js.map +0 -1
  653. package/lite/fetch.d.ts +0 -28
  654. package/lite/fetch.d.ts.map +0 -1
  655. package/lite/fetch.js +0 -79
  656. package/lite/fetch.js.map +0 -1
  657. package/util/log.d.ts +0 -5
  658. package/util/log.d.ts.map +0 -1
  659. package/util/log.js +0 -17
  660. package/util/log.js.map +0 -1
  661. package/zod.d.ts +0 -13
  662. package/zod.d.ts.map +0 -1
  663. package/zod.js +0 -19
  664. package/zod.js.map +0 -1
package/resume.js ADDED
@@ -0,0 +1,4173 @@
1
+ /**
2
+ * Serve a front's logical track straight from its routes' copies. Mirrors `model::resume` in
3
+ * `rs/moq-net`.
4
+ *
5
+ * A {@link Front} is one broadcast served through one route at a time: the origin re-sources it
6
+ * when another route of the same identity takes over, since routes with one identity serve one
7
+ * stream and so hold the same groups and frames. A reader of a logical track reads the
8
+ * serving route's copy directly, through its own subscription: nothing is copied, and with one
9
+ * route it is a passthrough.
10
+ *
11
+ * When the front switches, each reader subscribes to the new copy from the newest group it
12
+ * handed out. A replaced copy keeps delivering until the new copy delivers its first group, then
13
+ * is bounded just below it (or at the newest group handed out, if later), so a group only the old
14
+ * route got after the switch is not lost. It is kept while it may still deliver a group under its
15
+ * bound the reader lacks (unread, or still landing within the grace a passed group is waited for),
16
+ * and while a group still read is read from it or may continue from it (it holds that group, or may
17
+ * yet get it). Nothing under the bound is waited for past the reader's budget.
18
+ *
19
+ * A new copy is asked from where the reader got to, so it never has the groups below the reader's
20
+ * local floor that the copies it replaced cached. Lowering that floor asks the newest route for
21
+ * them through a backfill: another copy of that route, bounded to the groups the floor newly
22
+ * covers, and kept like a replaced copy. A switch asks the same way for the groups below where the
23
+ * reader got to that it still lacks, from the lowest one: one late, reordered, or in flight on the
24
+ * replaced route still arrives within the reader's budget, as it would on one cursor.
25
+ *
26
+ * A group carries on across the switch through its {@link Recover}: once its copy stalls while a
27
+ * newer route serves, it continues from the serving route's copy of the same group at the same
28
+ * frame, found in that copy's cache or fetched from it. Once its copy fails, any other copy still
29
+ * holding the group continues it first, since a group's name fixes its content.
30
+ *
31
+ * A group is handed out once however many copies deliver it: the reader skips any key its
32
+ * subscriber already handed out, the same record that keeps a direct reader from taking a
33
+ * re-created group twice.
34
+ *
35
+ * A reader asked for dispositions reports what the serving copy gave up, other than a route
36
+ * failure, once no copy it replaced may still deliver it, and counts it as handed out so no copy
37
+ * serves it later.
38
+ *
39
+ * The logical track ends cleanly once its serving copy does and no group the reader lacks may
40
+ * still land below that end on a copy it replaced. Its `closed` settles, and the reader keeps each
41
+ * copy only while it holds something left to read, as a direct reader keeps its buffer. It follows
42
+ * the route only for the groups still read, so one whose route dies continues from the copy served
43
+ * next, and leaves it once it holds nothing left to read. Its end is the first one any copy
44
+ * declared, which a later mid-group end may refine; a copy declaring another breaks the track's
45
+ * identity, which hurts only its own broadcast, so nothing checks that copies agree.
46
+ *
47
+ * @module
48
+ */
49
+ import { Duration, Instant, now, sleepUntil } from "@moq/clock";
50
+ import { race, Signal } from "@moq/signals";
51
+ import * as broadcast from "./broadcast.js";
52
+ import { Delivered } from "./delivered.js";
53
+ import { samePlaced } from "./demand.js";
54
+ import { NotFound, Retry, retry, SessionError, StreamCode, StreamError, sessionClosed } from "./error.js";
55
+ import { finalKey, hooks, insertDrops, insertRun, NO_MAX_DELAY, removeRun, runGaps, settles, skipHole, staleHole, } from "./internal.js";
56
+ import { grace } from "./ledger.js";
57
+ import { keyOf } from "./listing.js";
58
+ import { Skips } from "./skips.js";
59
+ import * as track from "./track.js";
60
+ import { max, min, UNBOUNDED } from "./util/key.js";
61
+ import { AT_KEYS, asked, EMPTY, isEmpty, liveMillis, policyOf, rangesPolicy, rangeTime, SINCE_ZERO, sameSpans, UNHELD, Window, widest, withPolicy, } from "./window.js";
62
+ import { metaWireOf, registerWire, wireOf } from "./wire.js";
63
+ /** A copy claiming the same content with different metadata: refused rather than reinterpreted. */
64
+ class Incompatible extends Error {
65
+ constructor(name) {
66
+ super(`track ${name} changed its properties across routes`);
67
+ this.name = "Incompatible";
68
+ }
69
+ }
70
+ /**
71
+ * Whether `err` is the route failing to deliver rather than judging what it carried, so a new copy
72
+ * may fix it. Mirrors the Rust `Error::retryable`.
73
+ *
74
+ * @internal
75
+ */
76
+ export function routeFailed(err) {
77
+ return retry(err) !== Retry.Never;
78
+ }
79
+ // Whether `err` from `source` judges its route rather than the track: a received route that lost
80
+ // the content refuses nothing, and the read waits for the next route. A local broadcast's word is
81
+ // the track's verdict. Mirrors the Rust front's `strands`.
82
+ function strands(err, source) {
83
+ return unroutable(err) && !source.local;
84
+ }
85
+ // Whether `err` says the route is going away rather than that it gave up on the copy: its
86
+ // answer is no verdict, and the next route is asked. Mirrors the Rust front's `closing`.
87
+ function closing(err) {
88
+ if (err instanceof StreamError)
89
+ return err.code === StreamCode.GoingAway || err.code === StreamCode.SessionClosed;
90
+ return err instanceof SessionError || sessionClosed(err);
91
+ }
92
+ // A source losing its route to the content: only another route continues it. Mirrors the Rust
93
+ // `Error::unroutable`.
94
+ function unroutable(err) {
95
+ return retry(err) === Retry.Reroute;
96
+ }
97
+ // A copy's delivery failure says nothing about its content. A terminal track verdict does.
98
+ // Mirrors the Rust `copy_failed`.
99
+ function copyFailed(copy) {
100
+ const error = copy.sub.closed.peek();
101
+ return error instanceof Error && routeFailed(error);
102
+ }
103
+ // Whether the copy's route failed, even after its declared end settled, which ends its readers
104
+ // cleanly: a group it closed short may hold more on the route replacing it. Only a route going
105
+ // away counts then: a subscription reset alone leaves the route serving, and nothing replaces
106
+ // it. Mirrors the Rust `route_lost`, whose copies abort after their end only with the session.
107
+ function routeLost(copy) {
108
+ const aborted = hooks.trackAborted(copy.sub);
109
+ return copyFailed(copy) || (aborted !== undefined && closing(aborted));
110
+ }
111
+ // Every `track.Info` field, so one added later fails to compile until it is listed here. `ietf` is
112
+ // compared, like Rust's moq-transport `properties`.
113
+ const INFO_FIELDS = Object.keys({
114
+ compression: true,
115
+ timescale: true,
116
+ maxAge: true,
117
+ priority: true,
118
+ refresh: true,
119
+ ietf: true,
120
+ });
121
+ /** Two copies claiming the same content must agree on all of it, like Rust's `Info` equality. */
122
+ function compatible(a, b) {
123
+ return INFO_FIELDS.every((field) => {
124
+ const [l, r] = [a[field], b[field]];
125
+ if (field === "refresh") {
126
+ const [x, y] = [a.refresh.interval, b.refresh.interval];
127
+ return a.refresh.ratio === b.refresh.ratio && (x === null || y === null ? x === y : x.eq(y));
128
+ }
129
+ return Duration.is(l) && Duration.is(r) ? l.eq(r) : l === r;
130
+ });
131
+ }
132
+ /**
133
+ * Ask `source` what track `name` is, abandoning the question once `retired` aborts. A caller's
134
+ * `hold` keeps the track wanted until it or `retired` aborts; without one, only until the answer.
135
+ */
136
+ function ask(source, name, retired, hold) {
137
+ if (hold)
138
+ return source.wire.resolveTrackInfo(name, AbortSignal.any([hold, retired]));
139
+ const query = new AbortController();
140
+ const onRetire = () => query.abort(retired.reason);
141
+ if (retired.aborted)
142
+ onRetire();
143
+ else
144
+ retired.addEventListener("abort", onRetire, { once: true });
145
+ return source.wire.resolveTrackInfo(name, query.signal).finally(() => {
146
+ retired.removeEventListener("abort", onRetire);
147
+ query.abort();
148
+ });
149
+ }
150
+ let sources = 0;
151
+ /** One route's broadcast, held while the front serves it or a reader still reads a copy of it. */
152
+ class Source {
153
+ /**
154
+ * Names this source where it outlives its route, as a front's record of who said what a
155
+ * track is: a reference there would keep a retired route's session reachable.
156
+ */
157
+ id = sources++;
158
+ wire;
159
+ /** What a metadata reader reads of it: its metadata copies where it keeps them apart, else `wire`. */
160
+ meta;
161
+ /** The table's handle this was served from, so serving it again is a no-op. */
162
+ from;
163
+ /** The local broadcast rather than a received route: its word on a track is the verdict. */
164
+ local;
165
+ #consumer;
166
+ #holds = 0;
167
+ #claimLost;
168
+ constructor(from, local = false, claimLost) {
169
+ this.from = from;
170
+ this.local = local;
171
+ this.#claimLost = claimLost;
172
+ this.#consumer = from.clone();
173
+ this.wire = wireOf(this.#consumer);
174
+ this.meta = metaWireOf(this.#consumer);
175
+ }
176
+ /**
177
+ * Whether this is a lite-07 peer's claim whose identity lost the path: its refusal of a copy
178
+ * that delivered nothing is final, since nothing else of its identity answers for it. Mirrors
179
+ * the Rust front's `claim_lost`.
180
+ */
181
+ claimLost() {
182
+ return this.#claimLost?.() ?? false;
183
+ }
184
+ retain() {
185
+ this.#holds++;
186
+ }
187
+ release() {
188
+ if (this.#holds === 0)
189
+ throw new Error("route released more often than retained");
190
+ if (--this.#holds === 0)
191
+ this.#consumer.close();
192
+ }
193
+ }
194
+ /** What the front says about one logical track: the copy to read now, and how it ended. */
195
+ class Route {
196
+ name;
197
+ /** Whether it serves the track's metadata copy, which each source keeps apart or not. */
198
+ meta;
199
+ /** Bumped whenever `source` changes, so a reader can tell a replacement apart. */
200
+ generation = 0;
201
+ /** The serving route's broadcast; undefined between routes or once the front let go. */
202
+ source;
203
+ /** The last broadcast served, kept between routes: what a replacement must match. */
204
+ served;
205
+ /** No front is left to replace the copy: readers follow it to its end. */
206
+ concluded = false;
207
+ /** The front refused the replacement: the track ends with this once the serving copy runs out. */
208
+ refusal;
209
+ /**
210
+ * The source serving before the replacements that have yet to deliver, held until a copy of
211
+ * `source` delivers: a reader arriving meanwhile reads it too, as the readers before it do, so
212
+ * a replacement failing first leaves it serving. The Rust front only swaps once one delivers.
213
+ */
214
+ incumbent;
215
+ /**
216
+ * The source a read idles on, having lost the route, and whether its copy delivered first;
217
+ * cleared once asked again or replaced.
218
+ */
219
+ #stranded;
220
+ /**
221
+ * The source the front is splicing in while its copy's info is in flight: a short close on the
222
+ * serving copy waits for it rather than standing. Mirrors the Rust route's `staged`.
223
+ */
224
+ staged;
225
+ /** Bumped on every change above, waking parked reads. */
226
+ changed = new Signal(0);
227
+ readers = new Set();
228
+ /** What any copy of the track declared skipped, which outlives that copy. */
229
+ skips = new Skips();
230
+ /** Called once the last reader leaves. */
231
+ idle = () => { };
232
+ /** Called once a reader subscribes a copy, or moves one onto a new source. */
233
+ copied = () => { };
234
+ constructor(name, meta) {
235
+ this.name = name;
236
+ this.meta = meta;
237
+ }
238
+ /** The copy of this track `source` serves. */
239
+ view(source) {
240
+ return this.meta ? source.meta : source.wire;
241
+ }
242
+ #bump() {
243
+ this.changed.update((n) => n + 1);
244
+ }
245
+ /** Serve the track from `source` from now on, subscribing every reader to it. */
246
+ serve(source) {
247
+ // A refusal ends the track: no later source continues it, compatible or not.
248
+ if (this.concluded || this.refusal || this.source === source)
249
+ return;
250
+ this.#stranded = undefined;
251
+ this.generation++;
252
+ // An undelivered source hands over the incumbent it held, not itself.
253
+ if (!this.incumbent)
254
+ this.#hold(this.source);
255
+ this.source = source;
256
+ this.served = source;
257
+ this.#bump();
258
+ for (const reader of [...this.readers])
259
+ reader.sync();
260
+ }
261
+ /**
262
+ * Serve `to` again in place of `from`, a replacement whose copy failed before delivering, even
263
+ * past a refusal or a conclusion: `to` served before it, and concluding only stops a future
264
+ * source taking over. Returns whether `to` serves again.
265
+ */
266
+ revert(from, to) {
267
+ // A concluded route serves nothing new, but the failed replacement was still its last.
268
+ if (this.source !== from && !(this.concluded && this.source === undefined))
269
+ return false;
270
+ this.generation++;
271
+ this.#hold(undefined);
272
+ this.source = to;
273
+ this.served = to;
274
+ this.#bump();
275
+ for (const reader of [...this.readers])
276
+ reader.sync();
277
+ return true;
278
+ }
279
+ /**
280
+ * Between routes: readers wait for the next one, keeping what they have. The source that served
281
+ * stays the incumbent until a later one delivers, as a replacement's would.
282
+ */
283
+ park() {
284
+ if (!this.source) {
285
+ if (this.staged)
286
+ this.unstage(this.staged);
287
+ return;
288
+ }
289
+ this.staged = undefined;
290
+ this.generation++;
291
+ if (!this.incumbent)
292
+ this.#hold(this.source);
293
+ this.source = undefined;
294
+ this.#bump();
295
+ }
296
+ /** The front asks `source` to take over, until {@link unstage} settles it. */
297
+ stage(source) {
298
+ this.staged = source;
299
+ this.#bump();
300
+ }
301
+ /** The front settled whether `source` takes over, unless a later stage replaced it. */
302
+ unstage(source) {
303
+ if (this.staged !== source)
304
+ return;
305
+ this.staged = undefined;
306
+ this.#bump();
307
+ }
308
+ /**
309
+ * A read idles on `source`, which lost the route after its copy `delivered` or not, until the
310
+ * table moves: see {@link Front.moved}.
311
+ */
312
+ strand(source, delivered) {
313
+ this.#stranded = { source, delivered };
314
+ }
315
+ /** The read idling on a lost route, which the table moving now ends, if any. */
316
+ unstrand() {
317
+ const stranded = this.#stranded;
318
+ this.#stranded = undefined;
319
+ return stranded;
320
+ }
321
+ /** Subscribe every reader afresh to the source that still serves, once its copy failed. */
322
+ resubscribe() {
323
+ if (!this.source)
324
+ return;
325
+ this.generation++;
326
+ this.#bump();
327
+ for (const reader of [...this.readers])
328
+ reader.sync();
329
+ }
330
+ /** End the track once the serving copy runs out, rather than replacing it. */
331
+ refuse(err) {
332
+ this.refusal ??= err;
333
+ this.#bump();
334
+ }
335
+ /**
336
+ * No front will replace the serving copy. Same generation: a reader on the copy keeps it as
337
+ * the serving one, while a reader arriving later finds nothing to read.
338
+ */
339
+ conclude() {
340
+ if (this.concluded)
341
+ return;
342
+ this.concluded = true;
343
+ this.staged = undefined;
344
+ this.#hold(undefined);
345
+ this.source = undefined;
346
+ this.#bump();
347
+ }
348
+ /** A copy of `source` delivered: it no longer needs the source it replaced. */
349
+ delivered(source) {
350
+ if (source === this.source)
351
+ this.#hold(undefined);
352
+ }
353
+ #hold(incumbent) {
354
+ incumbent?.retain();
355
+ this.incumbent?.release();
356
+ this.incumbent = incumbent;
357
+ }
358
+ leave(reader) {
359
+ if (!this.readers.delete(reader) || this.readers.size > 0)
360
+ return;
361
+ // Nobody reads the track, so nothing is left to protect from the replacement.
362
+ this.#hold(undefined);
363
+ this.idle();
364
+ }
365
+ }
366
+ /**
367
+ * Subscribe to a route's copy, or to a failed stand-in when that route can no longer serve. A
368
+ * copy parks past the end of a bounded window: the logical reader judges that end across its
369
+ * copies; see {@link Reader.exhausted}.
370
+ */
371
+ function subscribe(wire, name, subscription) {
372
+ try {
373
+ return hooks.parked(wire.subscribe(name, subscription));
374
+ }
375
+ catch (err) {
376
+ const failed = hooks.pendingTrack(name);
377
+ hooks.abortTrack(failed, err instanceof Error ? err : new Error(String(err)));
378
+ return hooks.parked(failed.subscribe(subscription));
379
+ }
380
+ }
381
+ /**
382
+ * Take a copy's next group, in sequence or arrival order. With `dispositions`, a run the copy gives
383
+ * up on the way comes back first; see {@link Dispositions}.
384
+ */
385
+ function take(copy, ordered, floor, dispositions = false, admit) {
386
+ return ordered ? hooks.tryNextGroup(copy.sub, floor, admit) : hooks.tryRecvGroup(copy.sub, dispositions);
387
+ }
388
+ /** Where `copy` stopped offering the groups below, which only a backfill of its route reads. */
389
+ function resumePoint(copy) {
390
+ return copy.dropped === undefined ? copy.floor : max(copy.floor ?? 0n, copy.dropped);
391
+ }
392
+ /**
393
+ * The time start of `range` that a copy asked from `floor` raised to it, if any: that copy's
394
+ * resolution says nothing of which group holds it, which only a copy asked from below it places.
395
+ * Mirrors the Rust `raised`.
396
+ */
397
+ function raised(range, floor) {
398
+ const start = range && rangeTime(range);
399
+ return floor !== undefined && start !== undefined && start < floor ? start : undefined;
400
+ }
401
+ /** The first group past where `copy` was replaced: 0 for one replaced before any group. */
402
+ function copyEnd(copy) {
403
+ if (copy.until === undefined)
404
+ return undefined;
405
+ return copy.until === null ? 0n : copy.until + 1n;
406
+ }
407
+ /** One reader's subscription to a logical track; see the module docs. */
408
+ class Reader {
409
+ route;
410
+ #shell;
411
+ /** The route generation last read. */
412
+ #generation;
413
+ /** The reader's preferences as last mirrored into its copies; see {@link #follow}. */
414
+ #mirrored;
415
+ /**
416
+ * Oldest first, except that a backfill goes before the copy of the route it backfills: the last
417
+ * one is the serving route's own, when it is subscribed.
418
+ */
419
+ #copies = [];
420
+ /** The reader's ranges, and the {@link #window} they resolved to. */
421
+ #resolution;
422
+ /** The reader's cursor the copies were last bounded at: a lower start asks for a backfill. */
423
+ #bounded;
424
+ /** The newest group handed out: where a new copy is asked to start. */
425
+ #newest;
426
+ /**
427
+ * The skipped run from the start of each key run the cursor keeps out of a gap under the serving
428
+ * copy's resume point, recorded as the copies declare it, so it outlives the copy and the cache
429
+ * that held it. Only that run, at most two a gap however many routes come and go: the rest is
430
+ * asked of the serving route again; see {@link #asking}.
431
+ */
432
+ #skipped = new Delivered();
433
+ /**
434
+ * Set once the route changed, so the serving copy's resume point may pass over groups the
435
+ * reader lacks. Kept until the gaps are backfilled; see {@link #backfillGaps}.
436
+ */
437
+ #resumed = false;
438
+ /**
439
+ * The groups a backfill of route `generation` failed to get, which that route is not asked
440
+ * for again until the route or the reader's preferences change: a backfill it refuses would
441
+ * only fail again, and asking each read would spin. Mirrors the Rust `Reader::refused`.
442
+ */
443
+ #refused;
444
+ /** Bumped when this reader subscribes a new copy or a copy's last lease ends, waking its parked reads. */
445
+ #changed = new Signal(0);
446
+ #dispose = [];
447
+ #closed = false;
448
+ /**
449
+ * Set once the logical track ended cleanly: the reader drains what its copies hold and follows
450
+ * the route only for the groups still read; see {@link #rerouted}. Holds the serving copy's
451
+ * largest then, kept once that copy goes.
452
+ */
453
+ #ended;
454
+ /**
455
+ * Copies of the routes served after the track ended, newest last, subscribed only while a group
456
+ * handed out is still read: they continue it off a route that dies, and hand out nothing.
457
+ * Mirrors the Rust `Phase::Finished { routed }`.
458
+ */
459
+ #rerouted = [];
460
+ /**
461
+ * The first end any copy declared: the logical track's, whichever copy serves. A copy declaring
462
+ * another breaks the track's identity, which hurts only its own broadcast, so nothing checks that
463
+ * copies agree.
464
+ */
465
+ #declared;
466
+ /** The subscriber's record of groups handed out, as the last read passed it. */
467
+ #delivered = new Delivered();
468
+ /** Runs the serving copy gave up and the reader has yet to report; see {@link #tryDrop}. */
469
+ #drops = [];
470
+ /** The route's {@link Skips} revision {@link trySkip} last folded in. */
471
+ #skipsSeen = 0;
472
+ /** The cursor and window {@link trySkip} last folded the route's skips in under. */
473
+ #skipsView;
474
+ /** Runs of the route's skips folded in and not reported yet, highest first, never more than it holds. */
475
+ #skipsQueued = [];
476
+ /** A copy that declared the track's end ran out cleanly at it, even if since let go. */
477
+ #settled = false;
478
+ /** Whether groups were ever asked for; until then the reader keeps no replaced copy. */
479
+ #groupsRead = false;
480
+ /** The groups handed out and still read, which other copies may back; see {@link #backs}. */
481
+ out = new Set();
482
+ /**
483
+ * What a group moved onto another copy is judged within: this reader's window below its cursor
484
+ * cap, not the copy's own subscription, which starts at the switch's boundary. Mirrors the Rust
485
+ * `Recover::window`.
486
+ */
487
+ within;
488
+ /** Every group handed out and still open, which ends with the reader. */
489
+ #open = new Set();
490
+ /** The soonest deadline a read waits on, armed to wake it then. */
491
+ #wall;
492
+ /** Records the properties a copy committed, and which source it came from. */
493
+ #record;
494
+ /** The first frame of each group the reader reads whole from, applied to every copy; see `hooks.wholeGroups`. */
495
+ #whole;
496
+ /** `parent` is the newest copy of the reader this one forks, if any. */
497
+ constructor(route, shell, record, parent) {
498
+ this.route = route;
499
+ this.#shell = shell;
500
+ this.within = {
501
+ contains: (key) => this.#inWindow(key),
502
+ openFrom: () => this.#window().openFrom(),
503
+ budget: () => this.#readerBudget(),
504
+ end: () => shell.cursor.peek().end,
505
+ changed: [shell.cursor, shell.subscription],
506
+ };
507
+ this.#record = record;
508
+ this.#mirrored = shell.subscription.peek();
509
+ this.#bounded = shell.cursor.peek();
510
+ route.readers.add(this);
511
+ this.#dispose.push(shell.subscription.subscribe(() => this.#follow()), shell.cursor.subscribe(() => this.#follow()));
512
+ // A fork starts on its parent's newest copy, at that copy's generation: the copy keeps its
513
+ // retained groups even where no route serves the track, between routes or once the front
514
+ // concluded.
515
+ if (parent) {
516
+ this.#generation = parent.generation;
517
+ const asked = {};
518
+ const copy = {
519
+ generation: parent.generation,
520
+ source: parent.source,
521
+ sub: parent.sub.fork(this.#wire(asked)),
522
+ ...asked,
523
+ replaced: false,
524
+ lease: 0,
525
+ };
526
+ this.#add(copy);
527
+ this.#joinIncumbent(copy);
528
+ }
529
+ // Subscribed to the serving copy at once, so groups it has now are the reader's even if
530
+ // the route changes before the first read, and to each copy after.
531
+ this.sync();
532
+ }
533
+ /**
534
+ * Follow the route: apply the reader's preferences and cursor to its copies, subscribe to a
535
+ * new copy, and mark the ones it replaced.
536
+ */
537
+ sync() {
538
+ if (this.#closed)
539
+ return;
540
+ this.#follow();
541
+ if (this.#ended) {
542
+ this.#reroute();
543
+ return;
544
+ }
545
+ const route = this.route;
546
+ if (this.#generation === route.generation)
547
+ return;
548
+ this.#generation = route.generation;
549
+ // What a former route gave up is no verdict on the one that serves now.
550
+ this.#drops = [];
551
+ const source = route.source;
552
+ if (!source)
553
+ return;
554
+ // The new copy starts at the boundary, so a lower group no replaced copy holds is asked of
555
+ // its route once a read says which; see #backfillGaps.
556
+ this.#resumed = true;
557
+ // One subscription split at one boundary: the largest group any copy holds, never below one
558
+ // handed out. The new copy starts there, and each copy it replaces is capped there now, so
559
+ // it finishes the groups up to it and sends nothing newer.
560
+ const boundary = this.#boundary();
561
+ // Cloned handles share closed, so a returning route reuses its subscription and
562
+ // leases rather than replaying its cache and retaining another copy per flap. The newest
563
+ // is the route's own copy, not a backfill of it.
564
+ // A copy that failed is never reused: the route subscribes afresh after one.
565
+ const index = this.#copies.findLastIndex((copy) => copy.source.from.closed === source.from.closed && !(copy.sub.closed.peek() instanceof Error));
566
+ const [returning] = index === -1 ? [] : this.#copies.splice(index, 1);
567
+ if (boundary !== undefined) {
568
+ for (const copy of this.#copies) {
569
+ // Harvested as it is replaced, so a reader joining now finds its skips too.
570
+ if (!copy.replaced)
571
+ this.#keepSkips(copy);
572
+ copy.replaced = true;
573
+ this.#cap(copy, boundary);
574
+ }
575
+ }
576
+ else {
577
+ // Nothing held nor handed out: nothing to split, so the new copy serves it all. Kept and
578
+ // asked for nothing, a copy's subscription would end with the track, and a fetch then
579
+ // landing a later group would read as the whole of it. Only the incumbent's copy stays,
580
+ // uncapped until the new copy delivers (see #observe), as the Rust front splices a
581
+ // replacement only then; the rest go, as the Rust `Reader::sync` drops them.
582
+ const incumbent = route.incumbent;
583
+ this.#dropCopies((copy) => copy.source.from.closed !== incumbent?.from.closed);
584
+ for (const copy of this.#copies) {
585
+ if (!copy.replaced)
586
+ this.#keepSkips(copy);
587
+ copy.replaced = true;
588
+ }
589
+ }
590
+ if (returning) {
591
+ const copy = returning;
592
+ source.retain();
593
+ copy.source.release();
594
+ copy.source = source;
595
+ copy.generation = route.generation;
596
+ copy.replaced = false;
597
+ copy.until = undefined;
598
+ copy.since = undefined;
599
+ copy.done = undefined;
600
+ copy.drains = undefined;
601
+ // Resume where a fresh copy would: a group it buffered while replaced, below the
602
+ // boundary, is the capped copies' to deliver.
603
+ if (boundary !== undefined)
604
+ copy.floor = max(copy.floor ?? 0n, boundary);
605
+ copy.backfill = undefined;
606
+ this.#update(copy);
607
+ this.#bound(copy);
608
+ this.#copies.push(copy);
609
+ this.wake();
610
+ route.copied();
611
+ return;
612
+ }
613
+ const asked = { floor: boundary };
614
+ const serving = {
615
+ generation: route.generation,
616
+ source,
617
+ // The wire request carries the floor from the first message: some sessions read the
618
+ // demand only once.
619
+ sub: subscribe(route.view(source), route.name, this.#wire(asked)),
620
+ ...asked,
621
+ replaced: false,
622
+ lease: 0,
623
+ };
624
+ this.#add(serving);
625
+ this.#joinIncumbent(serving);
626
+ }
627
+ /**
628
+ * Arriving before the serving copy delivered, read the source it replaced too, as the readers
629
+ * before this one still do.
630
+ */
631
+ #joinIncumbent(serving) {
632
+ const route = this.route;
633
+ const incumbent = route.incumbent;
634
+ if (!incumbent || serving.source !== route.source)
635
+ return;
636
+ if (hooks.latestKey(serving.sub) !== undefined) {
637
+ this.#delivering(serving);
638
+ return;
639
+ }
640
+ if (this.#copies.some((copy) => copy.source.from.closed === incumbent.from.closed))
641
+ return;
642
+ const asked = { floor: serving.floor };
643
+ this.#add({
644
+ generation: serving.generation - 1,
645
+ source: incumbent,
646
+ sub: subscribe(route.view(incumbent), route.name, this.#wire(asked)),
647
+ ...asked,
648
+ replaced: true,
649
+ lease: 0,
650
+ }, this.#copies.indexOf(serving));
651
+ }
652
+ /**
653
+ * Once the track ended, subscribe the serving route's copy for the groups still read, from the
654
+ * lowest, should the route have moved past the copies the reader holds: their recoveries
655
+ * continue there. Nothing is handed out from it, so the reader stays on the copy the track
656
+ * ended on.
657
+ */
658
+ #reroute() {
659
+ const route = this.route;
660
+ const source = route.source;
661
+ if (source && this.out.size > 0 && !this.copy(route.generation)) {
662
+ let floor;
663
+ for (const recover of this.out)
664
+ floor = min(floor ?? recover.key, recover.key);
665
+ const asked = { floor };
666
+ const copy = {
667
+ generation: route.generation,
668
+ source,
669
+ sub: subscribe(route.view(source), route.name, this.#wire(asked)),
670
+ ...asked,
671
+ replaced: false,
672
+ lease: 0,
673
+ };
674
+ source.retain();
675
+ this.#bound(copy);
676
+ this.#rerouted.push(copy);
677
+ }
678
+ this.#unroute();
679
+ }
680
+ /**
681
+ * Let go of the rerouted copies no group still read needs: each one a newer route superseded,
682
+ * and every one once none is read. Once the ended reader holds nothing left to hand out either,
683
+ * it leaves the route.
684
+ */
685
+ #unroute() {
686
+ if (!this.#ended)
687
+ return;
688
+ const newest = this.out.size > 0 ? this.#rerouted.at(-1) : undefined;
689
+ this.#rerouted = this.#rerouted.filter((copy) => {
690
+ if (copy === newest || copy.lease > 0)
691
+ return true;
692
+ this.#drop(copy);
693
+ return false;
694
+ });
695
+ if (this.out.size === 0 && this.#copies.length === 0)
696
+ this.route.leave(this);
697
+ }
698
+ /**
699
+ * Where a switch splits the subscription: the largest group any copy holds, never below the
700
+ * newest handed out. `undefined` while neither exists, when the new copy is asked for the ranges
701
+ * as the copies it replaces were, and they go. Mirrors the Rust `Reader::boundary`.
702
+ */
703
+ #boundary() {
704
+ let boundary = this.#newest;
705
+ for (const copy of this.#copies) {
706
+ const latest = hooks.latestKey(copy.sub);
707
+ if (latest !== undefined && (boundary === undefined || latest > boundary))
708
+ boundary = latest;
709
+ }
710
+ return boundary;
711
+ }
712
+ /**
713
+ * Take nothing past group `until` from replaced `copy`, and ask for nothing past it on the wire:
714
+ * the copy replacing it starts there. A cap only narrows. Mirrors the Rust `Copy::cap`, by group
715
+ * only: a JS switch resumes no group partway, so it has no frame to stop the old copy at.
716
+ */
717
+ #cap(copy, until) {
718
+ if (copy.until === null || (copy.until !== undefined && copy.until <= until))
719
+ return;
720
+ copy.until = until;
721
+ this.#update(copy);
722
+ this.#bound(copy);
723
+ }
724
+ /** Read `copy` as the newest one, or at `index`, recording the properties it commits. */
725
+ #add(copy, index = this.#copies.length) {
726
+ const { source } = copy;
727
+ this.#stamp(copy);
728
+ source.retain();
729
+ this.#readWhole(copy);
730
+ this.#bound(copy);
731
+ this.#copies.splice(index, 0, copy);
732
+ this.route.copied();
733
+ const shell = this.#shell;
734
+ const record = this.#record;
735
+ copy.sub.info().then((info) => {
736
+ record(info, source);
737
+ shell.commit(info);
738
+ }, () => {
739
+ // A terminal refusal before metadata is the subscription's answer too. An info
740
+ // reader never polls the group cursor that would otherwise propagate it.
741
+ if (this.#shell.info() === undefined)
742
+ this.#end((copy) => copy.sub.closed.peek());
743
+ });
744
+ copy.sub.finished().then(
745
+ // A copy already let go says nothing more about the track.
746
+ (end) => {
747
+ if (!this.#copies.includes(copy))
748
+ return;
749
+ this.#declare(end);
750
+ this.#learnEnd();
751
+ }, () => { });
752
+ void copy.sub.closed.then(async (closed) => {
753
+ // The serving copy closing cleanly is the logical track's end, once nothing it replaced
754
+ // may still deliver below it.
755
+ if (closed !== null)
756
+ return;
757
+ for (;;) {
758
+ this.sync();
759
+ if (this.#closed || this.#serving() !== copy || this.#conclude())
760
+ return;
761
+ await new Promise((resolve) => {
762
+ const dispose = this.changed(() => {
763
+ dispose();
764
+ resolve();
765
+ });
766
+ });
767
+ }
768
+ });
769
+ this.#changed.update((n) => n + 1);
770
+ }
771
+ /**
772
+ * What `copy` is asked for: the reader's own preferences, from its floor and through its
773
+ * replacement. Mirrors the Rust `Copy::wire`.
774
+ */
775
+ #wire(copy) {
776
+ const preferences = this.#shell.subscription.peek() ?? track.Subscription.default();
777
+ const ranges = preferences.ranges ?? [{}];
778
+ if (copy.sub && copy.from !== undefined && sameSpans(copy.from, ranges)) {
779
+ // A range keeps its first resolution: the copy re-resolves its clamped wire, so its own
780
+ // resolution of a capped or floored request would move the endpoints for good.
781
+ const own = hooks.servingResolved(copy.sub);
782
+ const kept = copy.resolved ?? [];
783
+ copy.resolved = ranges.map((_, index) => kept[index] ?? own[index]);
784
+ }
785
+ else if (copy.sub) {
786
+ // Replaced ranges resolve against its cache now, as any subscriber's do.
787
+ copy.from = ranges;
788
+ copy.resolved = hooks.resolveRanges(copy.sub, { ...preferences, ranges });
789
+ }
790
+ else if (copy.from === undefined || !sameSpans(copy.from, ranges)) {
791
+ // A new copy starts from where the reader's ranges resolved.
792
+ copy.from = ranges;
793
+ copy.resolved = this.#window().resolved();
794
+ }
795
+ // A live join placed already, here or where the reader's own request came from, is asked
796
+ // placed, so the copy starts it there and still expires it under its max.
797
+ const wire = asked(ranges, copy.floor, copyEnd(copy), copy.resolved ?? [], preferences.placed);
798
+ const { placed: _, ...rest } = preferences;
799
+ return wire.placed.size > 0
800
+ ? { ...rest, ranges: wire.ranges, placed: wire.placed }
801
+ : { ...rest, ranges: wire.ranges };
802
+ }
803
+ /**
804
+ * The reader's ranges resolved, a time start or live join where the first copy to place it
805
+ * placed it, whatever its failover cap: that bounds what the copy delivers, not where the ranges
806
+ * resolve. Kept once placed, past that copy being let go. A range stays as first held, unplaced,
807
+ * while its start waits on a copy to place it. A copy resolves a time start against the groups
808
+ * it holds, which may place it below where the reader's window did: the window decides what is
809
+ * handed out. Mirrors the Rust `Reader::window`.
810
+ */
811
+ #window() {
812
+ const ranges = this.#ranges();
813
+ const placed = this.#shell.subscription.peek()?.placed;
814
+ let resolution = this.#resolution;
815
+ if (!resolution ||
816
+ (resolution.from !== ranges && !sameSpans(resolution.from, ranges)) ||
817
+ !samePlaced(resolution.placed, placed)) {
818
+ resolution = this.#fresh(ranges);
819
+ this.#resolution = resolution;
820
+ }
821
+ if (resolution.window.settled)
822
+ return resolution.window;
823
+ for (const copy of this.#copies) {
824
+ if (resolution.window.settled)
825
+ break;
826
+ // A copy whose delivery failed places a time start past its last group as if nothing
827
+ // followed, but the front's next copy continues the track: only that copy knows which
828
+ // group holds it, until the track concludes.
829
+ if (!this.route.concluded && copyFailed(copy))
830
+ continue;
831
+ if (!copy.from || !sameSpans(copy.from, ranges))
832
+ continue;
833
+ // A closed copy's subscriber is no longer updated, so its own resolution is of the ranges
834
+ // it had then; the one it took when asked for these answers instead.
835
+ const own = copy.sub.closed.peek() === undefined ? hooks.servingResolved(copy.sub) : (copy.resolved ?? []);
836
+ const cap = copyEnd(copy);
837
+ // A failover cap at or below where a range starts empties the copy's range, which then
838
+ // says nothing of where the reader's own range starts. One at or below where it ends cut
839
+ // that end short, so it says nothing of where the reader's range ends.
840
+ const resolved = own.map((at, index) => {
841
+ // A copy asked from above a range's time start says nothing of where it starts: a
842
+ // backfill asked from below places it; see #backfillGaps.
843
+ if (!at || raised(ranges[index], copy.floor) !== undefined)
844
+ return undefined;
845
+ if (cap !== undefined && at.end !== undefined && at.end <= at.start)
846
+ return undefined;
847
+ return cap === undefined || (at.end !== undefined && at.end < cap) ? at : { ...at, end: undefined };
848
+ });
849
+ this.#resolve(resolved);
850
+ }
851
+ return resolution.window;
852
+ }
853
+ /**
854
+ * A resolution of the reader's `ranges` with nothing placed but a live join already placed where
855
+ * its preferences say, as each copy is asked to place it. Mirrors the Rust `mirrored_window`.
856
+ */
857
+ #fresh(ranges) {
858
+ const placed = this.#shell.subscription.peek()?.placed;
859
+ const joining = (key) => {
860
+ const at = placed?.get(Number(key));
861
+ return at === undefined ? SINCE_ZERO : { at };
862
+ };
863
+ const keyed = ranges.map((range, index) => [BigInt(index), range]);
864
+ return { from: ranges, placed, window: Window.keyed(keyed, undefined, UNHELD, joining) };
865
+ }
866
+ /**
867
+ * The time starts of the unsettled ranges that the serving copy's resume point raised, by key:
868
+ * no copy asked from there places them, only a backfill from below. Mirrors the Rust
869
+ * `Reader::raised`.
870
+ */
871
+ #raised() {
872
+ const raisedAt = new Map();
873
+ const floor = this.#copies.at(-1)?.floor;
874
+ const window = this.#resolution?.window;
875
+ if (floor === undefined || !window || window.settled)
876
+ return raisedAt;
877
+ const ranges = this.#ranges();
878
+ for (const key of window.unsettled()) {
879
+ const time = raised(ranges[Number(key)], floor);
880
+ if (time !== undefined)
881
+ raisedAt.set(key, time);
882
+ }
883
+ return raisedAt;
884
+ }
885
+ /**
886
+ * Place each unsettled {@link #window} range where a copy resolved it, on its own: one whose
887
+ * start still waits leaves the rest placed, so a publisher names their starts. Mirrors the Rust
888
+ * `Reader::resolve`.
889
+ */
890
+ #resolve(resolved) {
891
+ const resolution = this.#resolution;
892
+ if (!resolution)
893
+ return;
894
+ const placed = [];
895
+ for (const key of resolution.window.unsettled()) {
896
+ const range = resolution.from[Number(key)];
897
+ if (range === undefined)
898
+ continue;
899
+ const at = resolved[Number(key)];
900
+ if (!at) {
901
+ // A range the copy left unresolved keeps its time start or live join, which only a copy
902
+ // can place.
903
+ const unplaced = (rangeTime(range) ?? 0n) > 0n || liveMillis(range) !== undefined;
904
+ // Placed as it is: nothing of it waits on a copy.
905
+ if (!unplaced || isEmpty(range))
906
+ placed.push([key, range]);
907
+ continue;
908
+ }
909
+ if (range.end !== undefined && at.end === 0n) {
910
+ placed.push([key, EMPTY]);
911
+ continue;
912
+ }
913
+ const out = {};
914
+ // One that reached back to the oldest group still does, as on a plain reader; a live join
915
+ // starts where the copy placed it.
916
+ if (at.floored)
917
+ out.start = at.start;
918
+ if (range.end !== undefined)
919
+ out.end = at.end === undefined ? range.end : at.end - 1n;
920
+ placed.push([key, out]);
921
+ }
922
+ if (placed.length > 0)
923
+ resolution.window.edit([], placed, undefined, AT_KEYS);
924
+ }
925
+ /** The reader's ranges, as its preferences name them. */
926
+ #ranges() {
927
+ return (this.#shell.subscription.peek() ?? track.Subscription.default()).ranges ?? [{}];
928
+ }
929
+ /** Whether the reader's window names `key`; see {@link #window}. */
930
+ #inWindow(key) {
931
+ return this.#window().contains(key);
932
+ }
933
+ /**
934
+ * Whether the reader's window and cursor name a group from `floor` up to `key` that `delivered`
935
+ * lacks and that may yet land on `copy`: one outside the cursor never lands on a copy, nor one
936
+ * `copy` declares skipped, nor any on a failed copy, which receives nothing more. Mirrors the
937
+ * Rust `Reader::owes_below`.
938
+ */
939
+ #owesBelow(copy, floor, key, delivered) {
940
+ if (copy.sub.closed.peek() instanceof Error)
941
+ return false;
942
+ const cursor = this.#shell.cursor.peek();
943
+ return this.#window()
944
+ .runs(max(floor, cursor.start), min(key, cursor.end ?? key))
945
+ .some((run) => [...delivered.gaps(run.start, run.end)].some((gap) => {
946
+ for (let at = gap.start; at < gap.end;) {
947
+ const past = hooks.holeEnd(copy.sub, at, false);
948
+ if (past === undefined || past <= at)
949
+ return true;
950
+ at = past;
951
+ }
952
+ return false;
953
+ }));
954
+ }
955
+ /**
956
+ * Whether a fill other than `next`, the copy an ordered read is about to hand out `key` from,
957
+ * still owes a group below `key` that `delivered` lacks, the reader's window and cursor name, and
958
+ * the reader or a copy has not recorded skipped, as its own ordered read waits for it: one a fill
959
+ * of its route has yet to answer, or its received route's live feed owes within the budget. Each
960
+ * fill judges its own drops: another route giving a group up says nothing of this one. Arms that
961
+ * read's wakeups, which wake this one. Mirrors the Rust `Reader::fill_owes_below`.
962
+ */
963
+ #fillOwesBelow(next, key, delivered) {
964
+ const floor = delivered.runEnd(0n) ?? 0n;
965
+ const cursor = this.#shell.cursor.peek();
966
+ for (const copy of this.#copies) {
967
+ if (!copy.fills || copy === next || !this.#feeds(copy))
968
+ continue;
969
+ const start = max(floor, copy.backfill ? cursor.start : max(cursor.start, copy.floor ?? 0n));
970
+ const end = min(min(key, copyEnd(copy) ?? key), cursor.end ?? key);
971
+ if (start >= end)
972
+ continue;
973
+ const skipped = this.skippedIn(start, end);
974
+ for (const run of this.#window().runs(start, end)) {
975
+ for (const gap of delivered.gaps(run.start, run.end)) {
976
+ for (const open of runGaps(skipped, gap.start, gap.end)) {
977
+ if (hooks.owes(copy.sub, open.start, open.end))
978
+ return true;
979
+ }
980
+ }
981
+ }
982
+ }
983
+ return false;
984
+ }
985
+ #update(copy) {
986
+ // A closed copy still resolves replaced ranges against the groups it holds, for the window.
987
+ const wire = this.#wire(copy);
988
+ if (copy.sub.closed.peek() === undefined) {
989
+ // Restated, as the reader's ranges were, unless they only retuned a live join's max: a join
990
+ // whose max alone changed is then placed afresh rather than retuned where the copy placed
991
+ // the old one. Mirrors the Rust `Copy::ask_whole`.
992
+ if (this.#shell.retuned())
993
+ copy.sub.update(wire);
994
+ else
995
+ hooks.restateSubscriber(copy.sub, wire);
996
+ this.#stamp(copy);
997
+ }
998
+ else {
999
+ // Its ranges stay as resolved when it closed, but the groups it still holds are picked in
1000
+ // the reader's Group Order: each takes the reader's policy, which keeps where it resolved.
1001
+ // Mirrors the Rust `Copy::send`, which edits every copy.
1002
+ const policy = rangesPolicy(wire.ranges ?? []);
1003
+ const prefs = hooks.preferences(copy.sub);
1004
+ const held = prefs.held();
1005
+ const add = [];
1006
+ const placed = new Map();
1007
+ for (const [index, [key, range]] of [...prefs.entries()].entries()) {
1008
+ const at = held[index].placed;
1009
+ if (at !== undefined)
1010
+ placed.set(key, at);
1011
+ const { priority, order } = policyOf(range);
1012
+ if (priority !== policy.priority || order !== policy.order)
1013
+ add.push([key, withPolicy(range, policy)]);
1014
+ }
1015
+ if (add.length > 0)
1016
+ hooks.editSubscriber(copy.sub, { retire: [], add, placed });
1017
+ }
1018
+ }
1019
+ /**
1020
+ * Note each live join `copy` is asked for as the reader added it, so an answer the copy recorded
1021
+ * since places it, even one recorded before this subscription. The copy keys its ranges by
1022
+ * position, as the reader's are ordered. Mirrors the Rust `Copy::stamp`.
1023
+ */
1024
+ #stamp(copy) {
1025
+ const since = this.#shell.since().map((tick, index) => [BigInt(index), tick]);
1026
+ hooks.stampSubscriber(copy.sub, since);
1027
+ }
1028
+ /**
1029
+ * Apply the reader's preferences and cursor to every copy once they changed. Their signals
1030
+ * notify a microtask after a change, so every read applies them first too: a copy then picks
1031
+ * and judges its groups by what the reader holds now, such as a just-lowered live {@link track.Live.max} or
1032
+ * replaced ranges, not its last ones. Mirrors the Rust `Reader::sync`.
1033
+ */
1034
+ #follow() {
1035
+ const subscription = this.#shell.subscription.peek();
1036
+ if (subscription !== this.#mirrored) {
1037
+ this.#mirrored = subscription;
1038
+ // New preferences may ask what a backfill failed to get.
1039
+ this.#refused = undefined;
1040
+ for (const copy of [...this.#copies, ...this.#rerouted])
1041
+ this.#update(copy);
1042
+ // A copy just resolved replaced ranges against its cache, before its failover cap raised
1043
+ // them, so the reader takes that resolution now, the newest copy's first.
1044
+ const ranges = this.#ranges();
1045
+ if (this.#resolution && !sameSpans(this.#resolution.from, ranges)) {
1046
+ // The serving copy's resume point may cut off groups the new ranges cover.
1047
+ this.#resumed = true;
1048
+ this.#resolution = this.#fresh(ranges);
1049
+ for (let index = this.#copies.length - 1; index >= 0; index--) {
1050
+ if (this.#resolution.window.settled)
1051
+ break;
1052
+ const copy = this.#copies[index];
1053
+ // As in #window, a failed copy leaves the placement to the copy continuing the track.
1054
+ if (!this.route.concluded && copyFailed(copy))
1055
+ continue;
1056
+ if (copy.from && sameSpans(copy.from, ranges))
1057
+ this.#resolve(copy.resolved ?? []);
1058
+ }
1059
+ }
1060
+ }
1061
+ const cursor = this.#shell.cursor.peek();
1062
+ if (cursor === this.#bounded)
1063
+ return;
1064
+ const passed = this.#bounded.start;
1065
+ this.#bounded = cursor;
1066
+ for (const copy of [...this.#copies, ...this.#rerouted])
1067
+ this.#bound(copy);
1068
+ if (cursor.start < passed)
1069
+ this.#backfill(cursor.start, passed);
1070
+ if (this.#ended)
1071
+ this.#letGo(this.#delivered);
1072
+ }
1073
+ /**
1074
+ * Apply the reader's group cursor to `copy`, never below the copy's own resume point: groups
1075
+ * under it were handed out by an earlier route, or never owed. A backfill has none: the
1076
+ * reader's window and what it handed out decide what it takes.
1077
+ */
1078
+ #bound(copy) {
1079
+ const cursor = this.#shell.cursor.peek();
1080
+ const start = copy.backfill ? cursor.start : max(cursor.start, copy.floor ?? 0n);
1081
+ const replaced = copyEnd(copy);
1082
+ const end = replaced === undefined ? cursor.end : min(cursor.end ?? replaced, replaced);
1083
+ copy.sub.withRange({
1084
+ start: { included: start },
1085
+ end: end === undefined ? undefined : { excluded: end },
1086
+ });
1087
+ }
1088
+ /**
1089
+ * Ask the newest copy's route for the groups from `start` up to `passed` under that copy's
1090
+ * resume point, which a lowered floor newly covers. The copies that cached them may be gone,
1091
+ * and that copy never asked for them, so a bounded copy of the same route asks for just those.
1092
+ * One asked from a `raised` time start also reads the group holding it, under `start`.
1093
+ */
1094
+ #backfill(start, passed, raised = false) {
1095
+ const newest = this.#copies.at(-1);
1096
+ const resumed = newest && resumePoint(newest);
1097
+ if (this.#closed || this.#ended || !newest || resumed === undefined)
1098
+ return;
1099
+ const end = min(passed, resumed);
1100
+ // An ordered reader never goes back, nor does any reader past its budget.
1101
+ if (this.#delivered.covers(start, end))
1102
+ return;
1103
+ // What a backfill of this route already failed to get, it would fail to get again.
1104
+ const refused = this.#refused;
1105
+ if (refused?.generation === newest.generation && refused.start <= start && end <= refused.end)
1106
+ return;
1107
+ // A floor lowered again asks once. A copy that dropped a group from `start` on no longer
1108
+ // offers it, so it asks for nothing there.
1109
+ const closed = newest.source.from.closed;
1110
+ const asks = (copy) => {
1111
+ const point = resumePoint(copy);
1112
+ return (copy.source.from.closed === closed && copy.floor !== undefined && point !== undefined && point <= start);
1113
+ };
1114
+ if (this.#copies.some((copy) => asks(copy) && (copyEnd(copy) ?? UNBOUNDED) >= end))
1115
+ return;
1116
+ // A later resume point widens the route's backfill rather than asking again, so flaps over
1117
+ // a gap keep one per route, reading again one that ran out. Waited for as long as a new one
1118
+ // would be.
1119
+ const widened = this.#copies
1120
+ .slice(0, -1)
1121
+ .find((copy) => !(copy.done instanceof Error) && copy.until !== undefined && asks(copy));
1122
+ if (widened) {
1123
+ widened.until = end - 1n;
1124
+ widened.since = now();
1125
+ widened.done = undefined;
1126
+ widened.fills = true;
1127
+ if (raised)
1128
+ widened.backfill = true;
1129
+ this.#update(widened);
1130
+ this.#bound(widened);
1131
+ this.wake();
1132
+ return;
1133
+ }
1134
+ const backfill = {
1135
+ floor: start,
1136
+ backfill: raised ? true : undefined,
1137
+ until: end - 1n,
1138
+ };
1139
+ this.#add({
1140
+ generation: newest.generation,
1141
+ source: newest.source,
1142
+ sub: subscribe(this.route.view(newest.source), this.route.name, this.#wire(backfill)),
1143
+ ...backfill,
1144
+ // Bounded from the start: everything it may deliver is older than what the reader
1145
+ // already read, so it is waited for no longer than the reader's budget.
1146
+ replaced: true,
1147
+ since: now(),
1148
+ lease: 0,
1149
+ fills: true,
1150
+ }, this.#copies.length - 1);
1151
+ }
1152
+ /**
1153
+ * Ask the serving route for the groups below its copy's resume point that the reader still
1154
+ * lacks: a late or reordered one, or one in flight on the route it replaced, as one cursor on
1155
+ * the logical track would still get. From the lowest gap within the reader's cursor and window,
1156
+ * which decide what it reads, so groups already handed out are not asked for again below it. A
1157
+ * gap past the reader's budget was already forgotten as handed out. A lowered cursor asks
1158
+ * through {@link #backfill} itself. A time start the resume point raised is asked from its time,
1159
+ * so the backfill places it at the group holding it, as the route would for a plain reader.
1160
+ * Mirrors the Rust `Reader::backfill_gaps`.
1161
+ */
1162
+ #backfillGaps(delivered) {
1163
+ if (!this.#resumed)
1164
+ return;
1165
+ const window = this.#window();
1166
+ const raisedAt = this.#raised();
1167
+ // Kept until a copy places the ranges, but those whose start the resume point raised, which
1168
+ // only the backfill places: only then can the gaps they cover be judged.
1169
+ let floor = window.floor();
1170
+ const serving = this.#copies.at(-1);
1171
+ const resumed = serving && resumePoint(serving);
1172
+ if (floor === undefined && raisedAt.size !== window.unsettled().size) {
1173
+ // The gaps wait for the other ranges to place, but an owed raised start is asked now: its
1174
+ // backfill places it whatever they wait on, and a later ask finds it.
1175
+ if (resumed === undefined)
1176
+ return;
1177
+ let start;
1178
+ for (const time of raisedAt.values()) {
1179
+ if (!delivered.covers(time, resumed))
1180
+ start = start === undefined ? time : min(start, time);
1181
+ }
1182
+ if (start !== undefined)
1183
+ this.#backfill(start, resumed, true);
1184
+ return;
1185
+ }
1186
+ if (floor === undefined) {
1187
+ if (raisedAt.size === 0)
1188
+ return;
1189
+ floor = window.runs()[0]?.start ?? 0n;
1190
+ }
1191
+ // A raised start whose groups from its time the reader already holds or passed owes nothing
1192
+ // under the resume point: placed at its time, it hands out what the group holding it would,
1193
+ // as none under it goes out.
1194
+ const owed = [];
1195
+ const placed = [];
1196
+ const ranges = this.#ranges();
1197
+ for (const [key, time] of raisedAt) {
1198
+ if (resumed !== undefined && !delivered.covers(time, resumed)) {
1199
+ owed.push(time);
1200
+ continue;
1201
+ }
1202
+ const end = ranges[Number(key)]?.end;
1203
+ placed[Number(key)] = { start: time, end: end === undefined ? undefined : end + 1n, floored: true };
1204
+ }
1205
+ if (placed.length > 0) {
1206
+ this.#resolve(placed);
1207
+ // What the starts placed hold of the history a fold took unjudged is owed before the walk
1208
+ // below judges the gaps.
1209
+ this.#reopenFolded(delivered);
1210
+ }
1211
+ this.#resumed = false;
1212
+ if (resumed === undefined)
1213
+ return;
1214
+ // A group a replaced copy drains (see #mayDrain) is that copy's: the serving route is asked
1215
+ // from the lowest one none drains.
1216
+ const cursor = this.#shell.cursor.peek().start;
1217
+ // Each replaced copy's staleness verdict, taken once for the whole walk.
1218
+ const taking = new Map(this.#copies.filter((copy) => copy.replaced).map((copy) => [copy, hooks.taking(copy.sub)]));
1219
+ // The copy left to drain group `key`, if any.
1220
+ const drains = (key) => this.#copies.find((copy) => this.#mayDrain(copy, key, cursor, taking.get(copy)));
1221
+ let start;
1222
+ // Copies an earlier walk left keys to, whose set this walk's keys may now leave unsorted.
1223
+ const merged = new Set();
1224
+ for (const gap of delivered.gaps(max(floor, cursor), resumed)) {
1225
+ let key = gap.start;
1226
+ for (; key < gap.end; key++) {
1227
+ const copy = drains(key);
1228
+ if (!copy)
1229
+ break;
1230
+ // Added to what earlier walks left.
1231
+ if (copy.drains?.size)
1232
+ merged.add(copy);
1233
+ copy.drains ??= new Set();
1234
+ copy.drains.add(key);
1235
+ }
1236
+ if (key < gap.end) {
1237
+ start = key;
1238
+ break;
1239
+ }
1240
+ }
1241
+ // Kept ascending, so an ordered read's rescan stops at the group it hands out.
1242
+ for (const copy of merged) {
1243
+ copy.drains = new Set([...(copy.drains ?? [])].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)));
1244
+ }
1245
+ // A raised start is asked from its time whatever the local floor, so the backfill places it,
1246
+ // and the group holding it is read once the floor lets it.
1247
+ for (const time of owed)
1248
+ start = start === undefined ? time : min(start, time);
1249
+ if (start === undefined)
1250
+ return;
1251
+ // The group holding a time start at or past where it is asked from may lie under it.
1252
+ const from = start;
1253
+ const raised = this.#ranges().some((range) => {
1254
+ const time = rangeTime(range);
1255
+ return time !== undefined && from <= time && time < resumed;
1256
+ });
1257
+ this.#backfill(start, resumed, raised);
1258
+ }
1259
+ /** Wake parked reads, so they look again and let go of what nothing needs. */
1260
+ wake() {
1261
+ this.#changed.update((n) => n + 1);
1262
+ }
1263
+ /** The newest open copy this reader holds of `source`'s broadcast. */
1264
+ copyOn(source) {
1265
+ return this.#copies.findLast((copy) => copy.source.from.closed === source.from.closed && copy.sub.closed.peek() === undefined);
1266
+ }
1267
+ /**
1268
+ * The reader's copy of the route at `generation`, if it subscribed one, rather than a backfill of
1269
+ * it: once the track ended, the one rerouted for the groups still read.
1270
+ */
1271
+ copy(generation) {
1272
+ const matches = (copy) => copy.generation === generation;
1273
+ return this.#copies.findLast(matches) ?? this.#rerouted.findLast(matches);
1274
+ }
1275
+ /**
1276
+ * The copies other than `except` whose track still holds group `key` unfailed, newest first: the
1277
+ * rerouted ones too, which continue a group though they hand none out.
1278
+ */
1279
+ holding(key, except) {
1280
+ const copies = [...this.#copies, ...this.#rerouted];
1281
+ const holding = [];
1282
+ for (let index = copies.length - 1; index >= 0; index--) {
1283
+ const copy = copies[index];
1284
+ if (copy !== except && hooks.holdsGroup(copy.sub, key))
1285
+ holding.push(copy);
1286
+ }
1287
+ return holding;
1288
+ }
1289
+ cachedGroup(key, from = 0) {
1290
+ for (let index = this.#copies.length - 1; index >= 0; index--) {
1291
+ const copy = this.#copies[index];
1292
+ const group = hooks.cachedGroup(copy.sub, key, from);
1293
+ if (group)
1294
+ return this.#handOut(copy, group);
1295
+ }
1296
+ return undefined;
1297
+ }
1298
+ // A frame's moq-timestamp Object ID follows from the group's content alone, so any copy that
1299
+ // proves it gives the same answer: read from each copy's cached group, newest copy first,
1300
+ // never mirrored, since a mirror replays every frame the group holds.
1301
+ cachedTimedId(key, index, timescale) {
1302
+ for (let at = this.#copies.length - 1; at >= 0; at--) {
1303
+ const copy = this.#copies[at];
1304
+ const id = copy && hooks.cachedTimedId(copy.sub, key, index, timescale);
1305
+ if (id !== undefined)
1306
+ return id;
1307
+ }
1308
+ return undefined;
1309
+ }
1310
+ // A group a replaced copy delivered landed all the same, so every copy counts.
1311
+ landed(start, end) {
1312
+ let landed;
1313
+ for (const copy of this.#copies) {
1314
+ const arrived = hooks.landed(copy.sub, start, end);
1315
+ if (arrived && (!landed || arrived.gt(landed)))
1316
+ landed = arrived;
1317
+ }
1318
+ return landed;
1319
+ }
1320
+ judgedGroup(key) {
1321
+ for (let index = this.#copies.length - 1; index >= 0; index--) {
1322
+ const copy = this.#copies[index];
1323
+ const group = hooks.cachedGroup(copy.sub, key);
1324
+ if (!group)
1325
+ continue;
1326
+ // Judged by the copy it is read from: this reader's own timeline stays empty.
1327
+ hooks.expireGroup(group, hooks.staleAt(copy.sub, key));
1328
+ return this.#handOut(copy, group);
1329
+ }
1330
+ return undefined;
1331
+ }
1332
+ /**
1333
+ * `copy` handed out `key`. The serving copy's first group bounds the incumbent copies a switch
1334
+ * left uncapped, just below it, unless they go (see {@link #delivering}): one a reader joining
1335
+ * mid-switch reads (see {@link #joinIncumbent}), and one a switch before any group kept. What
1336
+ * they hold under it may be groups the new route never has, and what is at or above it the new
1337
+ * route delivers. Never below a group already handed out. A group it replays, already handed
1338
+ * out, bounds nothing: the incumbent may still hold the next. Nor does a backfill of the
1339
+ * serving route.
1340
+ */
1341
+ #observe(copy, key) {
1342
+ copy.delivered = true;
1343
+ if (copy.replaced || copy.generation !== this.#generation)
1344
+ return;
1345
+ if (this.#delivering(copy))
1346
+ return;
1347
+ const bound = max(this.#newest ?? -1n, key - 1n);
1348
+ for (const replaced of this.#copies) {
1349
+ if (replaced === copy || !replaced.replaced || replaced.until !== undefined)
1350
+ continue;
1351
+ replaced.until = bound < 0n ? null : bound;
1352
+ replaced.since = now();
1353
+ this.#update(replaced);
1354
+ this.#bound(replaced);
1355
+ }
1356
+ }
1357
+ /**
1358
+ * Serving `copy` delivers, which is when the Rust front splices it in. With nothing held nor
1359
+ * handed out, the replaced copies a switch left uncapped have nothing to drain, so they go, as
1360
+ * the Rust `Reader::sync` drops them on a switch without a boundary. Whether they went.
1361
+ */
1362
+ #delivering(copy) {
1363
+ this.route.delivered(copy.source);
1364
+ if (this.#newest !== undefined)
1365
+ return false;
1366
+ if (this.#copies.some((other) => other !== copy && hooks.latestKey(other.sub) !== undefined))
1367
+ return false;
1368
+ this.#dropCopies((other) => other.replaced && other.until === undefined);
1369
+ return true;
1370
+ }
1371
+ /** Let go of every copy `drops` picks, learning first any end one declared, which outlives it. */
1372
+ #dropCopies(drops) {
1373
+ this.#learnEnd();
1374
+ this.#copies = this.#copies.filter((copy) => {
1375
+ if (!drops(copy))
1376
+ return true;
1377
+ this.#drop(copy);
1378
+ return false;
1379
+ });
1380
+ }
1381
+ #deliverable(copy, key, delivered) {
1382
+ const end = copyEnd(copy);
1383
+ if (end !== undefined && key >= end)
1384
+ return false;
1385
+ // A range a copy placed during this read may hold a group a fold counted handed out.
1386
+ if (delivered.unjudged(key) && this.#window().holds(key))
1387
+ this.#reopenFolded(delivered);
1388
+ return !delivered.has(key);
1389
+ }
1390
+ // Whether a copy's next group, `key`, waits for the reader's window to be placed, which decides
1391
+ // whether it goes out: a failed copy's, until a copy continuing the track places it, and a
1392
+ // backfill's that no range placed so far holds, since only a placed range bounds the groups under
1393
+ // the resume point. Mirrors the Rust `Reader::poll_first`.
1394
+ #waits(copy, key) {
1395
+ if (!this.#mayWait(copy))
1396
+ return false;
1397
+ const failed = !this.route.concluded && copyFailed(copy);
1398
+ const window = this.#window();
1399
+ return window.pending && (failed || !window.holds(key));
1400
+ }
1401
+ // Whether the hold in `#waits` can apply to a copy at all, so only those peek before taking.
1402
+ #mayWait(copy) {
1403
+ return (!this.route.concluded && copyFailed(copy)) || copy.backfill === true;
1404
+ }
1405
+ tryGroup(ordered, delivered, dispositions, admit) {
1406
+ this.#delivered = delivered;
1407
+ this.sync();
1408
+ this.#learnEnd();
1409
+ if (this.#closed)
1410
+ return { kind: "done" };
1411
+ this.#groupsRead = true;
1412
+ this.#reopenFolded(delivered);
1413
+ this.#reopen();
1414
+ this.#backfillGaps(delivered);
1415
+ if (dispositions) {
1416
+ const dropped = this.#tryDrop(delivered);
1417
+ if (dropped)
1418
+ return dropped;
1419
+ }
1420
+ // The first group any copy holds next: the lowest for an ordered read, else the first in
1421
+ // the subscription's Group Order. A replaced copy's buffered group comes before a later one
1422
+ // the serving copy already has. An arrival read still delivers a lower group that truly
1423
+ // arrives later.
1424
+ // A copy no switch replaced refusing the ranges fails the read before any copy hands out a
1425
+ // group, as the Rust `Reader::poll_first` meets it in the same pass as the groups: the serving
1426
+ // copy, or the last one while the front parks between routes.
1427
+ for (const copy of this.#copies) {
1428
+ if (copy.replaced || !this.#feeds(copy))
1429
+ continue;
1430
+ const refused = hooks.refused(copy.sub);
1431
+ if (refused)
1432
+ return { kind: "error", error: refused, refused: true };
1433
+ }
1434
+ let owing;
1435
+ for (;;) {
1436
+ const first = this.#first(ordered, delivered, admit);
1437
+ owing = first.owing;
1438
+ const next = first.next;
1439
+ if (!next)
1440
+ break;
1441
+ // An ordered hand-out passes every key below it: a group a copy was left to drain there, or
1442
+ // the candidate itself, that it no longer drains is asked of the serving route first.
1443
+ if (ordered && first.key !== undefined) {
1444
+ const resumed = this.#resumed;
1445
+ this.#rescanDrains(delivered, first.key);
1446
+ if (this.#resumed && !resumed && this.#window().floor() !== undefined) {
1447
+ return this.tryGroup(ordered, delivered, dispositions, admit);
1448
+ }
1449
+ // The fill's answer, its track giving the group up, or the budget wakes the read.
1450
+ if (this.#fillOwesBelow(next, first.key, delivered))
1451
+ return { kind: "idle" };
1452
+ }
1453
+ const recv = this.#take(next, ordered, dispositions, admit);
1454
+ if (recv.kind === "drop") {
1455
+ const dropped = this.#tryDrop(delivered);
1456
+ if (dropped)
1457
+ return dropped;
1458
+ continue;
1459
+ }
1460
+ if (recv.kind === "group") {
1461
+ // The take may pass the offered group, such as one missing its head, for a later one
1462
+ // the window leaves out: judge the group it got.
1463
+ const key = recv.group.start;
1464
+ const deliverable = this.#deliverable(next, key, delivered);
1465
+ if (!deliverable || !this.#inWindow(key)) {
1466
+ if (deliverable)
1467
+ this.#skip(next, key);
1468
+ recv.group.close();
1469
+ continue;
1470
+ }
1471
+ this.#observe(next, key);
1472
+ return { kind: "group", group: this.#handOut(next, recv.group) };
1473
+ }
1474
+ // The lowest buffered group keeps its place while its copy waits on a hole.
1475
+ // A newer copy must not pass it and permanently discard it from sequence order.
1476
+ if (ordered && recv.kind === "idle")
1477
+ return recv;
1478
+ break;
1479
+ }
1480
+ // The failed copies holding a group back for a placement, which still report their failure.
1481
+ const held = new Set();
1482
+ // Whether a replaced copy failed this pass, owing the serving route a backfill.
1483
+ let owed = false;
1484
+ // The serving copy first: it is the one that keeps delivering.
1485
+ for (let index = this.#copies.length - 1; index >= 0; index--) {
1486
+ const copy = this.#copies[index];
1487
+ if (!this.#feeds(copy) || owing.includes(copy))
1488
+ continue;
1489
+ for (;;) {
1490
+ const newest = this.#newest === undefined ? undefined : this.#newest + 1n;
1491
+ // Its group stays there until placed, but how it ran out is still judged below. It got
1492
+ // a group, so its route did not refuse the track.
1493
+ const peeked = this.#mayWait(copy) ? hooks.peekGroup(copy.sub, ordered, newest) : undefined;
1494
+ if (peeked !== undefined && this.#waits(copy, peeked)) {
1495
+ copy.delivered = true;
1496
+ held.add(copy);
1497
+ break;
1498
+ }
1499
+ const recv = this.#take(copy, ordered, dispositions, admit);
1500
+ if (recv.kind === "drop") {
1501
+ const dropped = this.#tryDrop(delivered);
1502
+ if (dropped)
1503
+ return dropped;
1504
+ continue;
1505
+ }
1506
+ if (recv.kind === "group") {
1507
+ const key = recv.group.start;
1508
+ const deliverable = this.#deliverable(copy, key, delivered);
1509
+ if (!deliverable || !this.#inWindow(key)) {
1510
+ if (deliverable)
1511
+ this.#skip(copy, key);
1512
+ recv.group.close();
1513
+ continue;
1514
+ }
1515
+ this.#observe(copy, key);
1516
+ return { kind: "group", group: this.#handOut(copy, recv.group) };
1517
+ }
1518
+ // Drained: the track ended as the copy did, which is not cleanly when its
1519
+ // session went away short of the declared end.
1520
+ if (recv.kind === "done") {
1521
+ const closed = copy.sub.closed.peek();
1522
+ copy.done = closed instanceof Error ? closed : hooks.arrived(copy.sub);
1523
+ if (!(closed instanceof Error) && hooks.subscriberEnd(copy.sub))
1524
+ this.#settled = true;
1525
+ }
1526
+ else if (recv.kind === "error") {
1527
+ // A copy still serving that refuses the reader's ranges fails the read until they
1528
+ // change, as the read that met it says, so it is not done; a copy it replaced refusing
1529
+ // leaves the rest to the one now serving. Mirrors the Rust `Reader::poll_first`.
1530
+ if (recv.refused && !copy.replaced)
1531
+ return recv;
1532
+ copy.done = recv.error;
1533
+ }
1534
+ else if (this.#drained(copy, delivered))
1535
+ copy.done = hooks.arrived(copy.sub);
1536
+ // What a replaced copy that just failed still had to drain is asked of the serving route.
1537
+ if (copy.replaced && copy.done instanceof Error) {
1538
+ this.#resumed = true;
1539
+ owed = true;
1540
+ // A backfill of the serving route that failed is not asked of that route again.
1541
+ const end = copyEnd(copy);
1542
+ if (copy.generation === this.#generation && copy.floor !== undefined && end !== undefined) {
1543
+ this.#refused = { generation: copy.generation, start: copy.floor, end };
1544
+ }
1545
+ }
1546
+ break;
1547
+ }
1548
+ }
1549
+ const resumed = this.#resumed;
1550
+ // Nothing to hand out, so a group a copy was left to drain and no longer drains is asked of
1551
+ // the serving route now, as a cursor asks a fill only once it holds nothing to read: a
1552
+ // backlog draining meanwhile costs no rescan per group.
1553
+ this.#rescanDrains(delivered);
1554
+ this.#letGo(delivered);
1555
+ // A copy that stopped draining a group, or was let go with one, owes the serving route a
1556
+ // backfill: ask now.
1557
+ if (this.#resumed && !resumed)
1558
+ owed = true;
1559
+ // A replaced copy that failed or was let go with a group to drain this pass owes the
1560
+ // serving route a backfill once the window is placed: ask now, before any end, since its
1561
+ // close already fired and no later group is sure to wake the read. A backfill that failed
1562
+ // is not asked again (`#refused`), so this ends. Mirrors the Rust `Reader::poll_first`.
1563
+ if (owed && this.#resumed && this.#window().floor() !== undefined) {
1564
+ return this.tryGroup(ordered, delivered, dispositions, admit);
1565
+ }
1566
+ // A copy that ran out or was let go no longer holds back a drop.
1567
+ if (dispositions) {
1568
+ const dropped = this.#tryDrop(delivered);
1569
+ if (dropped)
1570
+ return dropped;
1571
+ }
1572
+ const generation = this.route.generation;
1573
+ const end = this.#end((copy) => {
1574
+ if (typeof copy.done === "number")
1575
+ return null;
1576
+ const failed = held.has(copy) ? copy.sub.closed.peek() : undefined;
1577
+ return copy.done ?? (failed instanceof Error ? failed : undefined);
1578
+ });
1579
+ // A revert serves the copy the failed replacement capped again, which may hold the next
1580
+ // group already.
1581
+ if (end.kind === "idle" && this.route.generation !== generation) {
1582
+ return this.tryGroup(ordered, delivered, dispositions, admit);
1583
+ }
1584
+ return end;
1585
+ }
1586
+ hasUnreadGroup(start, end, delivered) {
1587
+ return this.#copies.some((copy) => hooks.hasUnreadGroup(copy.sub, start, end, delivered));
1588
+ }
1589
+ /**
1590
+ * Whether the reader's bounded {@link #window} has nothing left to deliver, once no replaced
1591
+ * copy may still deliver a group under its bound: every group of the whole window is handed out
1592
+ * (in `delivered`) or accounted for, as {@link #accounts} judges. Mirrors the Rust
1593
+ * `Reader::exhausted`.
1594
+ */
1595
+ exhausted(delivered, ordered) {
1596
+ const serving = this.#judging(delivered);
1597
+ if (!serving)
1598
+ return false;
1599
+ // The reader's own window, as its copies placed it: the subscriber's leaves its anchors to them.
1600
+ const window = this.#window();
1601
+ delivered.reopen(window);
1602
+ const end = window.end();
1603
+ if (end === undefined || window.pending)
1604
+ return false;
1605
+ const gaps = window.runs(window.floor() ?? 0n, end).flatMap((run) => [...delivered.gaps(run.start, run.end)]);
1606
+ return this.#accounts(serving, delivered, gaps, ordered);
1607
+ }
1608
+ /**
1609
+ * Whether every key of `gaps`, which `delivered` lacks, is accounted for, once no replaced copy
1610
+ * may still deliver a group under its bound; see {@link #accounts}.
1611
+ */
1612
+ accounts(delivered, gaps, ordered) {
1613
+ const serving = this.#judging(delivered);
1614
+ return serving !== undefined && this.#accounts(serving, delivered, gaps, ordered);
1615
+ }
1616
+ /**
1617
+ * The serving copy, once the reader may judge what is accounted for: a route between copies,
1618
+ * a backfill still to ask, or a replaced copy that may still deliver leaves nothing to judge.
1619
+ * Lets go of the copies nothing needs any more either way.
1620
+ */
1621
+ #judging(delivered) {
1622
+ this.sync();
1623
+ if (this.#closed || this.#ended || this.#resumed)
1624
+ return undefined;
1625
+ const serving = this.#copies.at(-1);
1626
+ if (!serving || serving.replaced || serving.done !== undefined || serving.generation !== this.#generation) {
1627
+ return undefined;
1628
+ }
1629
+ return this.#letGo(delivered) ? undefined : serving;
1630
+ }
1631
+ /**
1632
+ * Whether every key of `gaps`, which `delivered` lacks, is accounted for.
1633
+ *
1634
+ * Under the serving copy's resume point, a key the cursor admits was the copies' it replaced, each
1635
+ * let go once it had nothing more. One it keeps out stays owed, as on one cursor, until a copy held
1636
+ * now declares it skipped or the asked copy's fills give it up, and the serving route is asked for those no copy does (see
1637
+ * {@link #ask}), so its answer settles them however many copies came and went. The serving copy
1638
+ * judges the rest by where it placed the reader's ranges itself: a time a copy held no group for
1639
+ * places the reader's window at the time itself, wider than any group the serving copy reads.
1640
+ * Mirrors the Rust `Reader::accounts`.
1641
+ */
1642
+ #accounts(serving, delivered, gaps, ordered) {
1643
+ const window = this.#window();
1644
+ if (window.end() === undefined || window.pending)
1645
+ return false;
1646
+ const resumed = resumePoint(serving) ?? 0n;
1647
+ const open = [];
1648
+ const above = [];
1649
+ for (const gap of gaps) {
1650
+ for (const run of this.#keptOut(gap, resumed)) {
1651
+ for (const unknown of this.#unskipped(run))
1652
+ insertRun(open, unknown.start, unknown.end);
1653
+ }
1654
+ const split = min(max(resumed, gap.start), gap.end);
1655
+ if (split < gap.end)
1656
+ above.push({ start: split, end: gap.end });
1657
+ }
1658
+ if (open.length > 0) {
1659
+ // What the asked copy's fills gave up is accounted for, as on one cursor.
1660
+ let owed = open;
1661
+ for (const gone of this.#ask(open))
1662
+ owed = removeRun(owed, gone.start, gone.end);
1663
+ if (owed.length > 0)
1664
+ return false;
1665
+ }
1666
+ return hooks.accountsFor(serving.sub, delivered, above, ordered);
1667
+ }
1668
+ /**
1669
+ * The parts of `gap` under the serving copy's resume point `resumed` that the cursor keeps out:
1670
+ * owed, as on one cursor, until a copy declares them skipped. Mirrors the Rust `Reader::kept_out`.
1671
+ */
1672
+ #keptOut(gap, resumed) {
1673
+ const cursor = this.#shell.cursor.peek();
1674
+ const split = min(max(resumed, gap.start), gap.end);
1675
+ return [
1676
+ { start: gap.start, end: min(split, cursor.start) },
1677
+ { start: cursor.end === undefined ? split : max(cursor.end, gap.start), end: split },
1678
+ ].filter((run) => run.start < run.end);
1679
+ }
1680
+ /** The parts of `run` neither recorded nor declared skipped by a copy held now. */
1681
+ #unskipped(run) {
1682
+ const held = new Delivered();
1683
+ for (const skip of this.skippedIn(run.start, run.end))
1684
+ held.addRun(skip.start, skip.end);
1685
+ return [...held.gaps(run.start, run.end)];
1686
+ }
1687
+ /**
1688
+ * Ask the serving route for the hull of `open`, the keys the cursor keeps out that are neither
1689
+ * recorded nor declared skipped by a copy held now. Its answer settles each such key as it would on one
1690
+ * cursor: a skip, or a fill that gives it up, accounts for it, while a group or a drop leaves it owed. A copy of that route
1691
+ * already asked for them, kept by {@link #letGo} until {@link #skipped} records them, asks nothing
1692
+ * more, so neither a reader waiting on the answer nor one a group holds open asks again. Its
1693
+ * track may forget a skip it answered before the rest lands, so it asks its fills for those it
1694
+ * cannot prove, returning the keys of `open` those fills gave up. Mirrors the Rust `Reader::ask`.
1695
+ */
1696
+ #ask(open) {
1697
+ const givenUp = [];
1698
+ const first = open.at(0);
1699
+ const last = open.at(-1);
1700
+ if (!first || !last)
1701
+ return givenUp;
1702
+ const keys = { start: first.start, end: last.end };
1703
+ this.#backfill(keys.start, keys.end);
1704
+ const serving = this.#copies.at(-1);
1705
+ if (!serving)
1706
+ return givenUp;
1707
+ for (const copy of this.#copies.slice(0, -1)) {
1708
+ const end = copyEnd(copy);
1709
+ if (copyAskedFor(copy, serving, keys.start) && end !== undefined && end >= keys.end) {
1710
+ for (const gone of hooks.askUnproven(copy.sub, open))
1711
+ insertRun(givenUp, gone.start, gone.end);
1712
+ }
1713
+ }
1714
+ return givenUp;
1715
+ }
1716
+ tryDrop(delivered, passing) {
1717
+ this.#delivered = delivered;
1718
+ this.sync();
1719
+ this.#learnEnd();
1720
+ return this.#tryDrop(delivered, passing);
1721
+ }
1722
+ /**
1723
+ * The next run the serving copy gave up that `delivered` lacks and no other copy may still
1724
+ * deliver. Only the serving copy's verdicts count; a copy it replaced may still deliver what
1725
+ * is under its bound, so a run there waits until that copy no longer feeds. Mirrors the
1726
+ * Rust `Reader::poll_drop`.
1727
+ */
1728
+ #tryDrop(delivered, passing = 0n) {
1729
+ if (this.#closed)
1730
+ return undefined;
1731
+ // Below what the reader handed out or passed, no copy's drop is reported, so each copy's
1732
+ // record folds there, even one that hands out nothing while the reader returns gaps.
1733
+ const at = delivered.runEnd(0n) ?? 0n;
1734
+ for (const copy of this.#copies)
1735
+ hooks.fold(copy.sub, at);
1736
+ const serving = this.#serving();
1737
+ if (serving) {
1738
+ // A received stale run queued here that a new upstream subscription superseded since is
1739
+ // unknown again: the copy no longer holds it.
1740
+ for (const run of this.#drops) {
1741
+ if (!run.received)
1742
+ continue;
1743
+ const held = hooks.staleHeld(serving.sub, run.start, run.end);
1744
+ for (const gap of runGaps(held, run.start, run.end))
1745
+ this.#drops = removeRun(this.#drops, gap.start, gap.end);
1746
+ }
1747
+ this.#collectDrops(serving);
1748
+ }
1749
+ this.#drops = this.#drops.filter((run) => !delivered.covers(run.start, run.end));
1750
+ const cursor = this.#shell.cursor.peek();
1751
+ const feeding = this.#feeding(serving);
1752
+ for (const run of this.#drops) {
1753
+ const end = min(run.end, cursor.end ?? run.end);
1754
+ for (const gap of delivered.gaps(max(run.start, cursor.start), end)) {
1755
+ const [open] = gap.start < passing
1756
+ ? [{ start: gap.start, end: min(gap.end, passing) }]
1757
+ : runGaps(feeding, gap.start, gap.end);
1758
+ if (open) {
1759
+ // Report once without marking it delivered: a late fill may still land.
1760
+ this.#drops = removeRun(this.#drops, open.start, open.end);
1761
+ return { kind: "drop", ...open, reason: run.reason, maxAge: run.maxAge };
1762
+ }
1763
+ }
1764
+ }
1765
+ return undefined;
1766
+ }
1767
+ // The groups a copy other than `serving` may still deliver, whose drops wait on it.
1768
+ #feeding(serving) {
1769
+ const cursor = this.#shell.cursor.peek();
1770
+ const feeding = [];
1771
+ for (const copy of this.#copies) {
1772
+ if (copy === serving || !this.#feeds(copy))
1773
+ continue;
1774
+ // A backfill owes what the reader's window hands out below its floor too, as #bound reads it.
1775
+ const start = copy.backfill ? cursor.start : max(cursor.start, copy.floor ?? 0n);
1776
+ insertRun(feeding, start, copyEnd(copy) ?? UNBOUNDED);
1777
+ }
1778
+ return feeding;
1779
+ }
1780
+ /**
1781
+ * The first run of `[start, end)` that settles the reader, that no copy may still deliver and
1782
+ * the reader has not been handed, as `trySkip` and `#tryDrop` would report it: a skip this
1783
+ * reader kept from a copy it let go, or the serving copy's drop. Mirrors the Rust
1784
+ * `Reader::next_settled_drop`.
1785
+ */
1786
+ nextSettledDrop(start, end) {
1787
+ this.sync();
1788
+ const delivered = this.#delivered;
1789
+ // Judged after retention, as the drop poll is: a lowered start may need a replaced copy again, so
1790
+ // it feeds.
1791
+ this.#letGo(delivered);
1792
+ // No route serving yet gave no verdict yet, which is not the same as none; once the front
1793
+ // concluded without one, none comes.
1794
+ const serving = this.#serving();
1795
+ if (!serving)
1796
+ return this.route.concluded ? undefined : "pending";
1797
+ const cursor = this.#shell.cursor.peek();
1798
+ start = max(start, cursor.start);
1799
+ end = min(end, cursor.end ?? end);
1800
+ const feeding = this.#feeding(serving);
1801
+ const window = this.#window();
1802
+ // The retained skips and the serving copy's drops are walked each from its own cursor, and each
1803
+ // candidate is looked up once and kept until it is judged.
1804
+ let [skips, drops] = [start, start];
1805
+ let skip;
1806
+ let drop;
1807
+ for (;;) {
1808
+ if (!skip && skips < end) {
1809
+ skip = this.route.skips.held({ start: skips, end });
1810
+ skips = end;
1811
+ }
1812
+ // Only up to the next skip, which goes first, so a walk past many skips never scans the
1813
+ // copy's drops beyond each one again.
1814
+ const until = skip ? max(skip.start, drops) : end;
1815
+ if (!drop && drops < until) {
1816
+ const found = hooks.nextSettledDrop(serving.sub, drops, until);
1817
+ if (found === "pending")
1818
+ return "pending";
1819
+ drop = found;
1820
+ drops = until;
1821
+ }
1822
+ // The serving copy may never have learned a skip this reader kept, which goes first where
1823
+ // both start, as trySkip reports it first.
1824
+ let held;
1825
+ const kept = skip !== undefined && !(drop && drop.start < skip.start);
1826
+ if (skip && kept) {
1827
+ [held, skip] = [{ ...skipHole(), ...skip }, undefined];
1828
+ }
1829
+ else if (drop) {
1830
+ // Judged only up to the next skip, so passing a drop that is no verdict never steps over
1831
+ // that skip. The rest is looked up again. A skip goes whole: whatever it returns settles
1832
+ // every key it covers, a drop there included.
1833
+ [held, drop] = [{ ...drop, end: skip ? min(drop.end, skip.start) : drop.end }, undefined];
1834
+ }
1835
+ else
1836
+ return undefined;
1837
+ let open;
1838
+ // Within the reader's window, as trySkip clips it.
1839
+ if (held.reason === "skip") {
1840
+ for (const clipped of window.runs(held.start, held.end)) {
1841
+ open = delivered.gaps(clipped.start, clipped.end).next().value;
1842
+ if (open)
1843
+ break;
1844
+ }
1845
+ }
1846
+ else if (!(held.reason === "drop" && copyFailed(serving))) {
1847
+ // A drop from a copy whose route failed is no verdict, as #queueDrop judges it: another
1848
+ // route may deliver. Mirrors the Rust `route_failed` filter.
1849
+ for (const gap of delivered.gaps(held.start, held.end)) {
1850
+ open = runGaps(feeding, gap.start, gap.end)[0];
1851
+ if (open)
1852
+ break;
1853
+ }
1854
+ }
1855
+ if (open)
1856
+ return { ...held, start: open.start, end: open.end };
1857
+ if (kept)
1858
+ skips = held.end;
1859
+ else
1860
+ drops = held.end;
1861
+ }
1862
+ }
1863
+ // Queue every run the serving copy gave up since the last call. An ordered read calls it before
1864
+ // the copy hands out a group too: that hand-out folds the copy's record past the keys below it,
1865
+ // where it would no longer report a run it gave up there, as the Rust `take_drops_below` finds.
1866
+ #collectDrops(serving) {
1867
+ // Folded in at once: a peer controls how many runs a drain returns. The copy reports each key
1868
+ // once, so they are disjoint.
1869
+ const runs = [];
1870
+ for (let dropped = hooks.tryDrop(serving.sub); dropped; dropped = hooks.tryDrop(serving.sub)) {
1871
+ const run = this.#dropRun(serving, dropped);
1872
+ if (run)
1873
+ runs.push(run);
1874
+ }
1875
+ runs.sort((a, b) => (a.start < b.start ? -1 : a.start > b.start ? 1 : 0));
1876
+ this.#drops = insertDrops(this.#drops, runs);
1877
+ }
1878
+ // Queue a run the serving copy gave up, to report once no other copy may still deliver it.
1879
+ #queueDrop(serving, dropped) {
1880
+ const run = this.#dropRun(serving, dropped);
1881
+ if (run)
1882
+ this.#drops = insertDrops(this.#drops, [run]);
1883
+ }
1884
+ // The run to queue for one the serving copy gave up, if it says anything of the track.
1885
+ #dropRun(serving, dropped) {
1886
+ // A copy failing is no verdict: another route or a fill may still deliver the group, and one
1887
+ // it failed while buffered is handed out to continue through its recovery. Only a skip it
1888
+ // failed with, or a stale verdict, says anything of the track.
1889
+ if (dropped.failed && dropped.reason === "drop")
1890
+ return undefined;
1891
+ if (dropped.start >= dropped.end)
1892
+ return undefined;
1893
+ // A stale run the copy holds came from its upstream, which a new subscription may supersede.
1894
+ const received = dropped.maxAge !== undefined && hooks.staleHeld(serving.sub, dropped.start, dropped.end).length > 0;
1895
+ const { start, end, reason, maxAge, cap, refusal } = dropped;
1896
+ return { start, end, reason, maxAge, cap, received, own: undefined, refusal };
1897
+ }
1898
+ // Take `copy`'s next group past the newest handed out. Under `dispositions`, the serving copy
1899
+ // returns first what its budget skips on the way, which is queued, so a publisher hears of it
1900
+ // before the group, as from a direct reader; only the serving copy's verdicts count. A failed
1901
+ // group still comes out, to continue through its recovery.
1902
+ #take(copy, ordered, dispositions, admit) {
1903
+ const newest = this.#newest === undefined ? undefined : this.#newest + 1n;
1904
+ if (ordered && copy === this.#serving())
1905
+ this.#collectDrops(copy);
1906
+ const serving = dispositions ? this.#serving() : undefined;
1907
+ const recv = take(copy, ordered, newest, copy === serving && "budget", admit);
1908
+ if (recv.kind === "drop" && serving)
1909
+ this.#queueDrop(serving, recv);
1910
+ return recv;
1911
+ }
1912
+ // Whether `copy`, bounded where it was replaced, ran out under that bound: its track ended, no
1913
+ // fill still owes it a group, and it holds nothing there unread. Its subscriber would park on a
1914
+ // group past the bound instead, as one past a local cap waits for it to rise, but the reader
1915
+ // moves this bound itself by asking again. Mirrors the Rust arrival cursor ending on a complete
1916
+ // track. Judged right after a read, which records whether it waits on a fill.
1917
+ #drained(copy, delivered) {
1918
+ const end = copyEnd(copy);
1919
+ if (end === undefined || hooks.awaitsFill(copy.sub))
1920
+ return false;
1921
+ const start = max(this.#shell.cursor.peek().start, copy.floor ?? 0n);
1922
+ return hooks.spent(copy.sub, start, end, delivered);
1923
+ }
1924
+ // A copy that ran out cleanly still takes a group in flight below its end while the read stays
1925
+ // open, as a cursor still reading it would. One landing on the serving copy may lie under its
1926
+ // resume point, which is not that copy's to read, and a backfill that already ran out was let
1927
+ // go: ask its route again. Mirrors the Rust `Reader::poll_first`.
1928
+ #reopen() {
1929
+ const serving = this.#serving();
1930
+ for (const copy of this.#copies) {
1931
+ if (typeof copy.done !== "number" || hooks.arrived(copy.sub) <= copy.done)
1932
+ continue;
1933
+ copy.done = undefined;
1934
+ if (copy === serving && !copy.replaced && copy.floor !== undefined)
1935
+ this.#resumed = true;
1936
+ }
1937
+ }
1938
+ // Re-arm the walk once a group a walk left a copy to drain, which the reader still lacks, no
1939
+ // longer drains there: evicted, given up as stale, or its copy failed or spent its budget. The
1940
+ // serving route is then asked for it after all, as a cursor on the track would ask again. Costs
1941
+ // the groups left to drain, each one a copy holds. Mirrors the Rust `Reader::rescan_drains`.
1942
+ //
1943
+ // With `through`, only the groups up to that key, which an ordered read checks before it hands
1944
+ // it out and passes those below: the copy offering it may hold it without its head, so not
1945
+ // drain it. Each copy keeps its keys ascending, so this costs the groups handed out since.
1946
+ #rescanDrains(delivered, through) {
1947
+ const cursor = this.#shell.cursor.peek().start;
1948
+ for (const copy of this.#copies) {
1949
+ if (copy.drains === undefined)
1950
+ continue;
1951
+ let taking;
1952
+ let drains = true;
1953
+ for (const key of copy.drains) {
1954
+ if (delivered.has(key)) {
1955
+ copy.drains.delete(key);
1956
+ continue;
1957
+ }
1958
+ if (through !== undefined && key > through)
1959
+ break;
1960
+ taking ??= hooks.taking(copy.sub);
1961
+ if (this.#mayDrain(copy, key, cursor, taking))
1962
+ continue;
1963
+ drains = false;
1964
+ break;
1965
+ }
1966
+ if (drains)
1967
+ continue;
1968
+ copy.drains = undefined;
1969
+ this.#resumed = true;
1970
+ }
1971
+ }
1972
+ // Whether `copy` drains group `key` for a reader whose cursor starts at `cursor`: replaced and
1973
+ // still read, holding the group's head under its cap and inside its own ranges, and its read
1974
+ // `taking` still offers it. A copy that failed or spent its drain budget delivers nothing more,
1975
+ // even while a read still leases it, and one holding a group without its head may give that
1976
+ // group up, so neither drains. Mirrors the Rust `Copy::may_drain`.
1977
+ #mayDrain(copy, key, cursor, taking) {
1978
+ return (copy.replaced &&
1979
+ this.#feeds(copy) &&
1980
+ (copy.backfill ? cursor : max(cursor, copy.floor ?? 0n)) <= key &&
1981
+ key < (copyEnd(copy) ?? UNBOUNDED) &&
1982
+ taking?.(key) === true &&
1983
+ !copyFailed(copy) &&
1984
+ hooks.holdsGroup(copy.sub, key, true));
1985
+ }
1986
+ // Whether `copy` may still feed groups: its channel has not run out, and what it holds is
1987
+ // within the reader's budget, which ends a full budget after a newer group superseded it.
1988
+ #feeds(copy) {
1989
+ return copy.done === undefined && !this.#expired(copy, this.#budget());
1990
+ }
1991
+ // `copy` gave up `key`, a group outside the reader's window, for good: a widened window asks
1992
+ // its route again for it.
1993
+ #skip(copy, key) {
1994
+ copy.dropped = max(copy.dropped ?? 0n, key + 1n);
1995
+ }
1996
+ // The copy whose next group is the first deliverable one in the reader's window, dropping any
1997
+ // it holds next that are not, and the copies whose ordered cursor is left on such a group
1998
+ // because the window still owes a lower one that may yet land there. First is the lowest for an
1999
+ // ordered read, else the first in the subscription's Group Order. Mirrors the Rust `poll_first`.
2000
+ // A group at or past `admit` (ordered reads only) stays next, unjudged.
2001
+ #first(ordered, delivered, admit) {
2002
+ let first;
2003
+ const owing = [];
2004
+ const floor = ordered ? (delivered.runEnd(0n) ?? 0n) : 0n;
2005
+ const ascending = ordered || rangesPolicy(this.#shell.subscription.peek()?.ranges ?? []).order === "ascending";
2006
+ for (const copy of this.#copies) {
2007
+ if (!this.#feeds(copy))
2008
+ continue;
2009
+ for (;;) {
2010
+ const key = hooks.peekGroup(copy.sub, ordered, this.#newest === undefined ? undefined : this.#newest + 1n);
2011
+ // At or past `admit`, it stays next, unjudged.
2012
+ if (key === undefined || this.#waits(copy, key) || (admit !== undefined && key >= admit))
2013
+ break;
2014
+ const deliverable = this.#deliverable(copy, key, delivered);
2015
+ if (deliverable && this.#inWindow(key)) {
2016
+ // A tie goes to the newer copy, so the serving one hands out its first group and
2017
+ // bounds the copies it replaced.
2018
+ if (!first || (ascending ? key <= first.key : key >= first.key))
2019
+ first = { copy, key };
2020
+ break;
2021
+ }
2022
+ // Skipping an ordered cursor past a group the window still owes below would lose it.
2023
+ if (ordered && deliverable && this.#owesBelow(copy, floor, key, delivered)) {
2024
+ owing.push(copy);
2025
+ break;
2026
+ }
2027
+ const recv = take(copy, ordered, this.#newest === undefined ? undefined : this.#newest + 1n);
2028
+ if (recv.kind !== "group")
2029
+ break;
2030
+ if (deliverable)
2031
+ this.#skip(copy, recv.group.start);
2032
+ recv.group.close();
2033
+ }
2034
+ }
2035
+ return { next: first?.copy, key: first?.key, owing };
2036
+ }
2037
+ /**
2038
+ * Whether the track ended, once the serving copy's channel (as `done` reads it) ran out:
2039
+ * cleanly, or with a verdict a route failure does not excuse.
2040
+ */
2041
+ #end(done) {
2042
+ const route = this.route;
2043
+ const last = this.#copies.at(-1);
2044
+ const serving = last?.generation === this.#generation ? last : undefined;
2045
+ const ended = serving ? done(serving) : undefined;
2046
+ // The serving copy drained a complete track: that is its end, whichever route would
2047
+ // serve it next. Once the track ended, a copy let go held nothing more.
2048
+ if (serving ? ended === null : this.#ended)
2049
+ return this.#conclude() ? { kind: "done" } : { kind: "idle" };
2050
+ if (ended instanceof Error) {
2051
+ // A copy it replaced finished the track and the reader owes nothing below that end:
2052
+ // the track ended cleanly whoever serves it now. Mirrors the Rust front. The failing
2053
+ // copy's own end, or one whose copy failed short of it, never settled.
2054
+ const end = this.#learnEnd();
2055
+ const owed = max(this.#shell.cursor.peek().start, (this.#newest ?? -1n) + 1n);
2056
+ const settled = this.#settled ||
2057
+ this.#copies.some((copy) => copy !== serving &&
2058
+ hooks.subscriberEnd(copy.sub) !== undefined &&
2059
+ hooks.peekLargest(copy.sub).ended &&
2060
+ !(copy.sub.closed.peek() instanceof Error));
2061
+ if (end && settled && finalKey(end) <= owed)
2062
+ return this.#conclude() ? { kind: "done" } : { kind: "idle" };
2063
+ if (serving && this.#revert(serving, ended))
2064
+ return { kind: "idle" };
2065
+ // A refusal from a route that still serves is the track's answer.
2066
+ if (!routeFailed(ended))
2067
+ return this.#fail(ended);
2068
+ if (route.refusal)
2069
+ return this.#fail(route.refusal);
2070
+ // The route that failed it still serves and is not going away, so no move replaces
2071
+ // the copy. As in the Rust front, a received route that lost the content judged the
2072
+ // route, not the track: the read waits for the next route, since asking the same one
2073
+ // again could only replace the withdrawal's cause with a refusal, and that route's
2074
+ // news follows on the same session. A local broadcast's word is the track's verdict.
2075
+ // Otherwise one that delivered nothing is the route refusing the track, and one that
2076
+ // did is subscribed afresh. A concluded route has no front left to move it, so its
2077
+ // loss ends the read.
2078
+ if (serving && route.source === serving.source && !closing(ended)) {
2079
+ // Unless a claim whose identity lost the path refused a copy that delivered nothing:
2080
+ // that refusal stands, and the requester resolves the winner anew.
2081
+ const stands = !serving.delivered && serving.source.claimLost();
2082
+ if (!route.concluded && strands(ended, serving.source) && !stands) {
2083
+ route.strand(serving.source, serving.delivered ?? false);
2084
+ return { kind: "idle" };
2085
+ }
2086
+ if (!serving.delivered) {
2087
+ route.refuse(ended);
2088
+ return this.#fail(ended);
2089
+ }
2090
+ if (unroutable(ended))
2091
+ return this.#fail(ended);
2092
+ route.resubscribe();
2093
+ }
2094
+ }
2095
+ // Refused before any copy fed it: nothing will.
2096
+ if (!last && route.refusal)
2097
+ return this.#fail(route.refusal);
2098
+ if (route.concluded) {
2099
+ // No front is left to replace the copy: the track ends as it does.
2100
+ if (!serving)
2101
+ return this.#fail(dropped());
2102
+ if (ended instanceof Error)
2103
+ return this.#fail(ended);
2104
+ }
2105
+ return { kind: "idle" };
2106
+ }
2107
+ /**
2108
+ * A replacement that failed before its copy held a group never ends the track while a copy it
2109
+ * replaced still feeds it: that copy serves again, and the failure is the replacement refusing
2110
+ * the track unless its route is going away. Judged by the copy, whatever this reader's window
2111
+ * took from it, as the Rust front does.
2112
+ */
2113
+ #revert(serving, failed) {
2114
+ if (hooks.latestKey(serving.sub) !== undefined)
2115
+ return false;
2116
+ // One that ran out under its cap still serves once the revert lifts the cap.
2117
+ const incumbent = this.#copies.findLast((copy) => copy.replaced &&
2118
+ copy.source !== serving.source &&
2119
+ !(copy.done instanceof Error) &&
2120
+ copy.sub.closed.peek() === undefined);
2121
+ if (!incumbent || !this.route.revert(serving.source, incumbent.source))
2122
+ return false;
2123
+ if (!closing(failed)) {
2124
+ // A replacement losing its route judged the route: the replaced copy keeps feeding the
2125
+ // read, which asks the replacement again once the table moves, as the Rust front does.
2126
+ if (strands(failed, serving.source) && !serving.source.claimLost())
2127
+ this.route.strand(serving.source, false);
2128
+ else
2129
+ this.route.refuse(failed);
2130
+ }
2131
+ return true;
2132
+ }
2133
+ #fail(error) {
2134
+ this.#shell.close(error);
2135
+ return { kind: "error", error };
2136
+ }
2137
+ /**
2138
+ * End the logical track cleanly, once its serving copy did and nothing it replaced may still
2139
+ * deliver a group below that end: settle `closed`, keeping each copy only while it holds
2140
+ * something left to read. The other channel's backlog stays readable. The reader follows the
2141
+ * route only for the groups still read, and {@link #unroute} leaves it once it reads and holds
2142
+ * nothing. Whether the track ended.
2143
+ */
2144
+ #conclude() {
2145
+ if (this.#closed)
2146
+ return false;
2147
+ if (this.#ended)
2148
+ return true;
2149
+ // Learned before any copy that knows it goes.
2150
+ this.#learnEnd();
2151
+ const serving = this.#serving();
2152
+ if (serving)
2153
+ this.#boundAtEnd(serving);
2154
+ // A group a copy no longer drains, which no read since has asked of the serving route, and
2155
+ // any walk an earlier pass queued: asked here, since a caller awaiting only the close may
2156
+ // never read, and the end then waits for it as for any copy that may still deliver.
2157
+ this.#rescanDrains(this.#delivered);
2158
+ if (this.#resumed && this.#window().floor() !== undefined)
2159
+ this.#backfillGaps(this.#delivered);
2160
+ if (this.#letGo(this.#delivered) || this.#closed)
2161
+ return false;
2162
+ // A copy let go with a group to drain: asked the same way, then judged again, since a
2163
+ // backfill a cache answers at once may leave nothing to wait for.
2164
+ if (this.#resumed && this.#window().floor() !== undefined)
2165
+ return this.#conclude();
2166
+ this.#ended = {
2167
+ largest: serving && hooks.peekLargest(serving.sub).largest,
2168
+ object: serving && hooks.objectLargest(serving.sub),
2169
+ ended: true,
2170
+ };
2171
+ this.#shell.close();
2172
+ this.#letGo(this.#delivered);
2173
+ this.wake();
2174
+ return true;
2175
+ }
2176
+ /**
2177
+ * Drop the copies nothing needs any more. A replaced one goes by {@link #retains}. One not yet
2178
+ * replaced stays, even between routes: it is still the newest copy there is, until the track
2179
+ * ended and it holds nothing left to read. Whether a group the reader lacks may still land on
2180
+ * a replaced one, which a clean end waits for.
2181
+ *
2182
+ * So does the copy of the serving route asked furthest from where {@link #asking} starts: it is
2183
+ * the ask {@link #accounts} makes, waiting on that route's answer, and letting it go would only
2184
+ * ask again. Only that one, since every ask starts there: an ask from lower down covers what the
2185
+ * copies asked before it did, so a range moved again and again keeps one.
2186
+ */
2187
+ #letGo(delivered) {
2188
+ // An end a copy declared outlives the copy.
2189
+ this.#learnEnd();
2190
+ if (this.#closed)
2191
+ return false;
2192
+ const last = this.#copies.at(-1);
2193
+ const edge = last && hooks.latestKey(last.sub);
2194
+ const cursor = this.#shell.cursor.peek();
2195
+ const asking = this.#asking(delivered);
2196
+ let asked;
2197
+ if (asking !== undefined && last && !last.replaced) {
2198
+ for (const copy of this.#copies) {
2199
+ if (!copy.replaced || !copyAskedFor(copy, last, asking))
2200
+ continue;
2201
+ if (!asked || (copyEnd(copy) ?? UNBOUNDED) >= (copyEnd(asked) ?? UNBOUNDED))
2202
+ asked = copy;
2203
+ }
2204
+ }
2205
+ let waits = false;
2206
+ this.#copies = this.#copies.filter((copy) => {
2207
+ if (!copy.replaced) {
2208
+ if (!this.#ended || copy.lease > 0)
2209
+ return true;
2210
+ const start = max(cursor.start, copy.floor ?? 0n);
2211
+ if (!hooks.spent(copy.sub, start, undefined, delivered))
2212
+ return true;
2213
+ // A group read from a copy it replaced may still continue from it.
2214
+ if (this.#backs(copy, true, grace(Duration.millis(this.#budget()))))
2215
+ return true;
2216
+ }
2217
+ else {
2218
+ const retains = this.#retains(copy, delivered, edge);
2219
+ if (retains === "wait")
2220
+ waits = true;
2221
+ if (retains || copy === asked)
2222
+ return true;
2223
+ // Let go with a group a walk left it to drain, which it gave up by its own verdict:
2224
+ // the serving route is asked for it after all, as when the copy's cache loses it.
2225
+ if ([...(copy.drains ?? [])].some((key) => !delivered.has(key)))
2226
+ this.#resumed = true;
2227
+ }
2228
+ this.#drop(copy);
2229
+ return false;
2230
+ });
2231
+ this.#unroute();
2232
+ return waits;
2233
+ }
2234
+ /**
2235
+ * Where {@link #accounts} asks the serving route from: the first key of a bounded window under
2236
+ * the serving copy's resume point that `delivered` lacks and the cursor keeps out, past the
2237
+ * skipped run {@link #skipped} records from the start of each run of them. Records those runs
2238
+ * first, from what every copy held now declares, so an answer is kept before the cache that holds
2239
+ * it forgets it. A reader whose cursor keeps nothing out, or that follows one route, pays
2240
+ * nothing. Mirrors the Rust `Reader::asking`.
2241
+ */
2242
+ #asking(delivered) {
2243
+ const serving = this.#copies.at(-1);
2244
+ const cursor = this.#shell.cursor.peek();
2245
+ const window = this.#window();
2246
+ const resumed = serving && !serving.replaced ? resumePoint(serving) : undefined;
2247
+ if (resumed === undefined || window.end() === undefined || (cursor.start === 0n && cursor.end === undefined)) {
2248
+ this.#skipped = new Delivered();
2249
+ return undefined;
2250
+ }
2251
+ const kept = new Delivered();
2252
+ let asking;
2253
+ for (const run of window.runs(window.floor() ?? 0n, resumed)) {
2254
+ for (const gap of delivered.gaps(run.start, run.end)) {
2255
+ for (const out of this.#keptOut(gap, resumed)) {
2256
+ const first = this.skippedIn(out.start, out.end)[0];
2257
+ const start = first?.start === out.start ? first.end : out.start;
2258
+ if (start > out.start)
2259
+ kept.addRun(out.start, start);
2260
+ if (start < out.end)
2261
+ asking ??= start;
2262
+ }
2263
+ }
2264
+ }
2265
+ this.#skipped = kept;
2266
+ return asking;
2267
+ }
2268
+ /**
2269
+ * How the reader still needs replaced `copy`: `"wait"` while a group the reader lacks may still
2270
+ * land on it, `"keep"` while it holds one unread or backs a group handed out. `edge` is the
2271
+ * newest group the serving copy has.
2272
+ */
2273
+ #retains(copy, delivered, edge) {
2274
+ // Until the first group read, no cached copy needs to be retained.
2275
+ if (!this.#groupsRead)
2276
+ return undefined;
2277
+ // An incumbent not yet bounded may still feed a group the new copy never has.
2278
+ if (copy.until === undefined && copy.done === undefined)
2279
+ return "wait";
2280
+ const end = copyEnd(copy);
2281
+ // Superseded once the serving copy has a group past the bound.
2282
+ if (copy.since === undefined && end !== undefined && edge !== undefined && edge >= end)
2283
+ copy.since = now();
2284
+ const budget = this.#budget();
2285
+ // One whose wire names every start waits for it to, however long that takes.
2286
+ const wait = hooks.provenTrack(copy.sub) ? undefined : grace(Duration.millis(budget));
2287
+ // What is under the bound is past the reader's budget a full budget after a newer group
2288
+ // superseded it, landed or not.
2289
+ if (copy.done === undefined && end !== undefined && !this.#expired(copy, budget)) {
2290
+ const cursor = this.#shell.cursor.peek();
2291
+ // From where it was asked to start, or else from what it first got. A backfill owes what
2292
+ // the reader's window hands out below its floor too.
2293
+ const start = copy.backfill ? cursor.start : max(cursor.start, copy.floor ?? 0n);
2294
+ const floor = copy.floor !== undefined;
2295
+ // A group still to land in the reader's window is waited for, as a gap is, but not one a
2296
+ // copy declared skipped: its publisher never produced it, so no route will.
2297
+ const lands = (run) => runGaps(this.skippedIn(run.start, run.end), run.start, run.end).some((open) => hooks.mayLand(copy.sub, { ...open, floor, grace: wait, delivered }));
2298
+ if (this.#window().runs(start, end).some(lands))
2299
+ return "wait";
2300
+ const owes = copy.fills ? this.#fillOwes(copy, start, end, delivered) : undefined;
2301
+ if (owes === "wait")
2302
+ return "wait";
2303
+ if (owes === "keep" || hooks.hasUnreadGroup(copy.sub, cursor.start, end, delivered))
2304
+ return "keep";
2305
+ }
2306
+ // Until the serving copy holds a group, a failure of it serves this one again; see #revert.
2307
+ // Only after a group still to land is waited for, so a clean end of the serving copy
2308
+ // waits for it too.
2309
+ const serving = this.#serving();
2310
+ if (serving &&
2311
+ serving.source !== copy.source &&
2312
+ hooks.latestKey(serving.sub) === undefined &&
2313
+ !(copy.done instanceof Error)) {
2314
+ return "keep";
2315
+ }
2316
+ if (copy.lease > 0)
2317
+ return "keep";
2318
+ const lands = !this.#expired(copy, wait?.asMillis() ?? Number.POSITIVE_INFINITY);
2319
+ return this.#backs(copy, lands, wait) ? "keep" : undefined;
2320
+ }
2321
+ /**
2322
+ * How fill `copy` still owes what the reader lacks of `[start, end)` under the serving copy's
2323
+ * resume point, no copy declared skipped, and its own subscription has not accounted for: those
2324
+ * come as fills below where the route's feed starts, which `mayLand` never waits for, so letting
2325
+ * it go would leave them unasked. `"wait"` while some of it no other replaced copy still feeds,
2326
+ * else `"keep"`: a replaced copy that runs out without a group leaves it to this fill. Mirrors
2327
+ * the Rust `Retain::owed`.
2328
+ */
2329
+ #fillOwes(copy, start, end, delivered) {
2330
+ const serving = this.#copies.at(-1);
2331
+ const resumed = serving && !serving.replaced ? resumePoint(serving) : undefined;
2332
+ const until = min(end, resumed ?? 0n);
2333
+ if (start >= until)
2334
+ return undefined;
2335
+ const lacking = [];
2336
+ for (const run of this.#window().runs(start, until)) {
2337
+ for (const gap of delivered.gaps(run.start, run.end)) {
2338
+ for (const run of runGaps(this.skippedIn(gap.start, gap.end), gap.start, gap.end))
2339
+ lacking.push(run);
2340
+ }
2341
+ }
2342
+ if (lacking.length === 0 || hooks.accountsFor(copy.sub, delivered, lacking, false))
2343
+ return undefined;
2344
+ // A closed fill gets nothing more, so it owes nothing; the caller still keeps it while it holds
2345
+ // an unread group.
2346
+ if (copy.sub.closed.peek() !== undefined)
2347
+ return undefined;
2348
+ const cursor = this.#shell.cursor.peek();
2349
+ let unfed = lacking;
2350
+ for (const other of this.#copies) {
2351
+ if (other === copy || !other.replaced || other.fills || !this.#feeds(other))
2352
+ continue;
2353
+ const fed = { start: max(cursor.start, other.floor ?? 0n), end: copyEnd(other) ?? UNBOUNDED };
2354
+ unfed = unfed.flatMap((run) => runGaps([fed], run.start, run.end));
2355
+ }
2356
+ return unfed.length > 0 ? "wait" : "keep";
2357
+ }
2358
+ /**
2359
+ * Whether `copy` holds a group still read, or may yet get it within `wait` when it `lands`: a
2360
+ * failure of the copy that group is read from continues here.
2361
+ */
2362
+ #backs(copy, lands, wait) {
2363
+ for (const recover of this.out) {
2364
+ const key = recover.key;
2365
+ if (hooks.holdsGroup(copy.sub, key))
2366
+ return true;
2367
+ // A group at or past where it was asked to start may land even before its first
2368
+ // arrival; without a floor, only what follows its first arrival can.
2369
+ const asked = copy.floor !== undefined && (copy.backfill || copy.floor <= key);
2370
+ const land = { start: key, end: key + 1n, floor: asked, grace: wait };
2371
+ if (lands && hooks.mayLand(copy.sub, land))
2372
+ return true;
2373
+ }
2374
+ return false;
2375
+ }
2376
+ /**
2377
+ * `serving` ended cleanly, so nothing newer supersedes what the copies it replaced still carry
2378
+ * under their caps: the budget for it runs from now. An incumbent not yet bounded is bounded at
2379
+ * that end, so a group it still carries below the end is waited for and nothing past it.
2380
+ */
2381
+ #boundAtEnd(serving) {
2382
+ const declared = this.#declared;
2383
+ const until = declared !== undefined
2384
+ ? finalKey(declared) - 1n
2385
+ : max(this.#newest ?? -1n, hooks.latestKey(serving.sub) ?? -1n);
2386
+ for (const copy of this.#copies) {
2387
+ if (!copy.replaced)
2388
+ continue;
2389
+ copy.since ??= now();
2390
+ if (copy.until !== undefined)
2391
+ continue;
2392
+ copy.until = until < 0n ? null : until;
2393
+ this.#update(copy);
2394
+ this.#bound(copy);
2395
+ }
2396
+ }
2397
+ /**
2398
+ * The reader's widest budget in milliseconds, how far behind any group may fall before it is
2399
+ * skipped, as its own ranges set it: a copy is let go as a whole, so it waits out the widest.
2400
+ * Mirrors the Rust `Mirrored::widest`.
2401
+ */
2402
+ #budget() {
2403
+ return widest(this.#ranges());
2404
+ }
2405
+ /**
2406
+ * How long each group stays worth delivering, as the reader's own ranges set it, placed where its
2407
+ * copies resolved them: the window places a live join as a time start, whose groups still go
2408
+ * stale past its max. Mirrors the Rust `Reader::budget`.
2409
+ */
2410
+ #readerBudget() {
2411
+ const window = this.#window();
2412
+ const ranges = new Map(this.#ranges().map((range, index) => [BigInt(index), range]));
2413
+ return window.budgetOf(ranges);
2414
+ }
2415
+ /**
2416
+ * The groups the reader's ranges resolve to and the cap its cursor stops at, undefined while a
2417
+ * live join waits on a first group. Mirrors the Rust `Recover::window`.
2418
+ */
2419
+ coverage() {
2420
+ const window = this.#window();
2421
+ if (window.pending)
2422
+ return undefined;
2423
+ return { runs: window.runs(), cap: this.#shell.cursor.peek().end };
2424
+ }
2425
+ /**
2426
+ * Whether `within` passed since `copy` was superseded; see {@link Copy.since}. Arms a wakeup
2427
+ * for then, so a read waiting on the copy looks again.
2428
+ */
2429
+ #expired(copy, within) {
2430
+ if (copy.since === undefined)
2431
+ return false;
2432
+ // Plain nanoseconds: an unenforced budget is infinite, which no Duration holds.
2433
+ const at = copy.since.since(Instant.ZERO).asNanos() + within * 1_000_000;
2434
+ if (now().since(Instant.ZERO).asNanos() >= at)
2435
+ return true;
2436
+ this.#wakeAt(at);
2437
+ return false;
2438
+ }
2439
+ // Wake parked reads at `at`, unless a wakeup is already armed sooner.
2440
+ #wakeAt(at) {
2441
+ if (this.#closed || !Number.isFinite(at) || (this.#wall && this.#wall.at <= at))
2442
+ return;
2443
+ this.#wall?.timer.abort();
2444
+ const timer = new AbortController();
2445
+ this.#wall = { at, timer };
2446
+ // A wakeup is never a reason to hold a Node/Bun process open.
2447
+ void sleepUntil(Instant.ZERO.saturatingAdd(Duration.nanos(at)), { signal: timer.signal, ref: false }).then(() => {
2448
+ if (timer.signal.aborted)
2449
+ return;
2450
+ this.#wall = undefined;
2451
+ this.wake();
2452
+ }, () => { });
2453
+ }
2454
+ #drop(copy, abort) {
2455
+ // Including what it learned since it was replaced, under its bound or not.
2456
+ this.#keepSkips(copy);
2457
+ copy.sub.close(abort);
2458
+ copy.source.release();
2459
+ }
2460
+ // Keep every skip `copy` declared on the route, before the reader stops holding it: a skip is the
2461
+ // content's own. Mirrors the Rust `Skips::learn` calls in `Reader`.
2462
+ #keepSkips(copy) {
2463
+ this.route.skips.learn(hooks.skippedIn(copy.sub, 0n, UNBOUNDED));
2464
+ }
2465
+ /**
2466
+ * The next run of the route's skips within the cursor and the window that `report` has yet to
2467
+ * report, as it reports it. A skip is the content's own, so no copy holds it back, as one may
2468
+ * hold back the serving copy's drops. Folds in only the runs added since the last call, or every
2469
+ * one once the cursor or the window moved. Mirrors the Rust `Reader::poll_skip`.
2470
+ */
2471
+ trySkip(report) {
2472
+ this.sync();
2473
+ if (this.#closed)
2474
+ return undefined;
2475
+ const { start, end = UNBOUNDED } = this.#shell.cursor.peek();
2476
+ const window = this.#window();
2477
+ const view = `${start}:${end}:${window
2478
+ .runs(start, end)
2479
+ .map((run) => `${run.start}-${run.end}`)
2480
+ .join(",")}`;
2481
+ const skips = this.route.skips;
2482
+ const all = this.#skipsView !== view;
2483
+ const found = skips.since(this.#skipsSeen, all, start, end);
2484
+ // Highest first, so the lowest is popped and a remainder pushed back without moving the rest.
2485
+ if (all) {
2486
+ this.#skipsQueued = found.reverse();
2487
+ }
2488
+ else if (found.length > 0) {
2489
+ const queued = this.#skipsQueued.reverse();
2490
+ for (const run of found)
2491
+ insertRun(queued, run.start, run.end);
2492
+ this.#skipsQueued = queued.reverse();
2493
+ }
2494
+ this.#skipsSeen = skips.revision;
2495
+ this.#skipsView = view;
2496
+ for (let run = this.#skipsQueued.pop(); run; run = this.#skipsQueued.pop()) {
2497
+ // A run forgotten since is unknown again, not skipped.
2498
+ const held = skips.held(run);
2499
+ if (!held)
2500
+ continue;
2501
+ if (held.end < run.end)
2502
+ this.#skipsQueued.push({ start: held.end, end: run.end });
2503
+ const [clipped] = window.runs(held.start, held.end);
2504
+ if (!clipped)
2505
+ continue;
2506
+ if (clipped.end < held.end)
2507
+ this.#skipsQueued.push({ start: clipped.end, end: held.end });
2508
+ const reported = report(clipped.start, clipped.end);
2509
+ if (!reported)
2510
+ continue;
2511
+ if (reported.end < clipped.end)
2512
+ this.#skipsQueued.push({ start: reported.end, end: clipped.end });
2513
+ return reported;
2514
+ }
2515
+ return undefined;
2516
+ }
2517
+ #handOut(copy, group) {
2518
+ hooks.settleIfDropping(copy.sub, group.start);
2519
+ this.#newest = max(this.#newest ?? 0n, group.start);
2520
+ // Another copy holding the group, now or once it lands there, is where a failure continues
2521
+ // it, so it stays while the group is read; see #backs. Recorded even with one copy, since a
2522
+ // later route's copy may come to hold it.
2523
+ const recover = new Recover(this, group, copy);
2524
+ hooks.recoverGroup(group, recover);
2525
+ recover.watch(group);
2526
+ // Closed with the reader, as a direct reader's close reaches the groups it handed out.
2527
+ this.#open.add(group);
2528
+ void hooks.groupClosed(group).then(() => this.#open.delete(group));
2529
+ return group;
2530
+ }
2531
+ /** A group handed out ended or moved copies: let go of what nothing needs any more. */
2532
+ freed() {
2533
+ // Once the track ended, no read may come to let go of a copy.
2534
+ if (this.#ended)
2535
+ this.#letGo(this.#delivered);
2536
+ // A parked read lets go of a replaced copy nothing needs any more.
2537
+ this.wake();
2538
+ }
2539
+ changed(fn) {
2540
+ let fired = false;
2541
+ const disposes = [];
2542
+ const dispose = () => {
2543
+ fired = true;
2544
+ for (const close of disposes)
2545
+ close();
2546
+ };
2547
+ const once = () => {
2548
+ if (fired)
2549
+ return;
2550
+ dispose();
2551
+ fn();
2552
+ };
2553
+ disposes.push(this.route.changed.changed(once), this.#changed.changed(once), this.route.skips.changed.changed(once));
2554
+ for (const copy of this.#copies)
2555
+ disposes.push(hooks.groupChanged(copy.sub, once));
2556
+ return dispose;
2557
+ }
2558
+ wholeGroups(frameOf) {
2559
+ this.#whole = frameOf;
2560
+ for (const copy of this.#copies)
2561
+ this.#readWhole(copy);
2562
+ }
2563
+ // Have `copy` read whole groups, except one the reader already handed out, as from a copy it
2564
+ // replaced: that group continues through its recovery, and no copy waits on its head.
2565
+ #readWhole(copy) {
2566
+ const whole = this.#whole;
2567
+ if (whole)
2568
+ hooks.wholeGroups(copy.sub, (key) => (this.#delivered.has(key) ? undefined : whole(key)));
2569
+ }
2570
+ forgetPastBudget(delivered) {
2571
+ this.forgetPast(delivered, { budget: this.#readerBudget(), ranges: this.#placed() });
2572
+ }
2573
+ // The reader's window once nothing waits on a copy to place a live join.
2574
+ #placed() {
2575
+ const window = this.#window();
2576
+ return window.pending ? undefined : window;
2577
+ }
2578
+ // Take back what a fold counted as handed out in `delivered` before any range held it, which the
2579
+ // reader's ranges, as its copies placed them so far, now owe. Each read does so before it judges
2580
+ // what the copies hold, since the copies place a range only once a group arrives for it.
2581
+ #reopenFolded(delivered) {
2582
+ delivered.reopen(this.#window());
2583
+ }
2584
+ untell(start, end) {
2585
+ for (const copy of this.#copies)
2586
+ hooks.untell(copy.sub, start, end);
2587
+ }
2588
+ // Judged on the newest copy, but never past a group a replaced copy still feeding the reader,
2589
+ // or that would under a wider budget, holds unread: as one cursor keeps what it owes, since a
2590
+ // late group there may be fresh by its own successor on that copy. A widened budget reads an
2591
+ // expired copy again, so only a copy whose channel ran out is passed over, and only a group
2592
+ // stale even at the track's max age, which bounds every budget: a lease on the copy never
2593
+ // holds back the fold for good. Nor past `keep`, an outer reader's own such group.
2594
+ forgetPast(delivered, terms, keep) {
2595
+ const newest = this.#copies.at(-1);
2596
+ if (!newest)
2597
+ return;
2598
+ let kept = keep;
2599
+ for (const copy of this.#copies) {
2600
+ if (copy === newest || !copy.replaced || copy.done !== undefined)
2601
+ continue;
2602
+ const key = hooks.lowestBuffered(copy.sub, delivered, true);
2603
+ if (key !== undefined)
2604
+ kept = min(kept ?? key, key);
2605
+ }
2606
+ hooks.forgetPastBudget(newest.sub, delivered, terms, kept);
2607
+ }
2608
+ // The same key is the same group on every copy, so it bounds group `key` whichever copy holds it.
2609
+ keyAfter(key) {
2610
+ let after;
2611
+ for (const copy of this.#copies) {
2612
+ const next = hooks.keyAfter(copy.sub, key);
2613
+ if (next !== undefined)
2614
+ after = min(after ?? next, next);
2615
+ }
2616
+ return after;
2617
+ }
2618
+ // A copy it replaced refusing leaves the rest to the copy now serving. Mirrors the Rust
2619
+ // `resume::Subscriber::refused`.
2620
+ refused() {
2621
+ for (const copy of this.#copies) {
2622
+ if (copy.replaced)
2623
+ continue;
2624
+ const refused = hooks.refused(copy.sub);
2625
+ if (refused)
2626
+ return refused;
2627
+ }
2628
+ return undefined;
2629
+ }
2630
+ lowestBuffered(delivered, fresh) {
2631
+ let lowest;
2632
+ for (const copy of this.#copies) {
2633
+ const key = hooks.lowestBuffered(copy.sub, delivered, fresh);
2634
+ if (key !== undefined)
2635
+ lowest = min(lowest ?? key, key);
2636
+ }
2637
+ return lowest;
2638
+ }
2639
+ latest() {
2640
+ let latest;
2641
+ for (const copy of this.#copies) {
2642
+ const key = hooks.latestKey(copy.sub);
2643
+ if (key !== undefined && (latest === undefined || key > latest))
2644
+ latest = key;
2645
+ }
2646
+ return latest;
2647
+ }
2648
+ #serving() {
2649
+ const last = this.#copies.at(-1);
2650
+ return last?.generation === this.#generation ? last : undefined;
2651
+ }
2652
+ // The logical track's end, learning it from any copy that declared one.
2653
+ #learnEnd() {
2654
+ for (const copy of this.#copies) {
2655
+ const end = hooks.subscriberEnd(copy.sub);
2656
+ if (end)
2657
+ this.#declare(end);
2658
+ }
2659
+ return this.#declared;
2660
+ }
2661
+ // Record `end` as the logical track's end, unless a copy declared one first. A mid-group end
2662
+ // refines the group boundary it falls just before, as a wire end may.
2663
+ #declare(end) {
2664
+ if (this.#closed)
2665
+ return;
2666
+ const declared = this.#declared;
2667
+ if (!declared) {
2668
+ this.#declared = end;
2669
+ this.wake();
2670
+ }
2671
+ else if (declared.frame === 0 && end.frame !== 0 && finalKey(declared) === finalKey(end)) {
2672
+ this.#declared = end;
2673
+ }
2674
+ }
2675
+ start() {
2676
+ this.sync();
2677
+ const serving = this.#serving();
2678
+ return serving && hooks.sourceStart(serving.sub);
2679
+ }
2680
+ /** Whether the copy serving now places ranges as its publisher would; see `hooks.placesAsUpstream`. */
2681
+ placesAsUpstream() {
2682
+ this.sync();
2683
+ const serving = this.#serving();
2684
+ return serving !== undefined && hooks.placesAsUpstream(serving.sub);
2685
+ }
2686
+ /** Whether the copy serving now knows where the live feed is; see `hooks.knowsEdge`. */
2687
+ knowsEdge() {
2688
+ this.sync();
2689
+ const serving = this.#serving();
2690
+ return serving !== undefined && hooks.knowsEdge(serving.sub);
2691
+ }
2692
+ end() {
2693
+ this.sync();
2694
+ return this.#learnEnd();
2695
+ }
2696
+ skippedBelow(key) {
2697
+ this.sync();
2698
+ const copies = this.#copies.reduce((longest, copy) => max(longest, hooks.skippedBelow(copy.sub, key)), 0n);
2699
+ return max(copies, this.route.skips.skippedBelow(key));
2700
+ }
2701
+ /** Whether a route's copy serves the reader now. */
2702
+ serving() {
2703
+ this.sync();
2704
+ return this.#serving() !== undefined;
2705
+ }
2706
+ /**
2707
+ * Ask the serving copy's fills for `unproven`, kept-out keys a containing front's reader owes, as
2708
+ * that reader asks a plain copy, returning what they gave up, so a key this front's route cannot
2709
+ * fill ends the outer read too. Mirrors the Rust `Resume::ask_unproven`.
2710
+ */
2711
+ askUnproven(unproven) {
2712
+ const serving = this.#copies.at(-1);
2713
+ return serving ? hooks.askUnproven(serving.sub, unproven) : [];
2714
+ }
2715
+ // What the reader recorded or any copy held now declared skipped: a skip is final for the whole
2716
+ // track, so an outer front reading this one as a copy counts it, and asks for the rest as it would
2717
+ // of any route.
2718
+ skippedIn(start, end) {
2719
+ const skipped = new Delivered();
2720
+ for (const run of runsIn(this.#skipped, start, end))
2721
+ skipped.addRun(run.start, run.end);
2722
+ for (const copy of this.#copies) {
2723
+ for (const run of copySkips(copy, start, end))
2724
+ skipped.addRun(run.start, run.end);
2725
+ }
2726
+ for (const run of this.route.skips.skippedIn(start, end))
2727
+ skipped.addRun(run.start, run.end);
2728
+ return runsIn(skipped, start, end);
2729
+ }
2730
+ // A copy this front replaced may still land a group its serving copy never will, so an outer
2731
+ // front reading this one as a copy waits on every copy still kept, each past where it starts
2732
+ // and under its bound. Mirrors the Rust `Subscriber::may_land`.
2733
+ /** Whether the serving route's copy names every start on its wire. */
2734
+ proven() {
2735
+ const serving = this.#serving();
2736
+ return serving !== undefined && hooks.provenTrack(serving.sub);
2737
+ }
2738
+ owes(start, end) {
2739
+ for (const copy of this.#copies) {
2740
+ const from = copy.backfill || copy.floor === undefined ? start : max(start, copy.floor);
2741
+ const bound = copyEnd(copy);
2742
+ const to = bound === undefined ? end : min(end, bound);
2743
+ if (from < to && hooks.owes(copy.sub, from, to))
2744
+ return true;
2745
+ }
2746
+ return false;
2747
+ }
2748
+ mayLand(land) {
2749
+ for (const copy of this.#copies) {
2750
+ const start = copy.backfill || copy.floor === undefined ? land.start : max(land.start, copy.floor);
2751
+ const bound = copyEnd(copy);
2752
+ const end = bound === undefined ? land.end : min(land.end, bound);
2753
+ if (start < end && hooks.mayLand(copy.sub, { ...land, start, end }))
2754
+ return true;
2755
+ }
2756
+ return false;
2757
+ }
2758
+ // The serving route's copy holds what its publisher skipped or gave up; any other copy held or
2759
+ // the route kept, only what was skipped: a replaced copy's drops are that route's own verdict.
2760
+ // Mirrors the Rust `Reader::hole_end`.
2761
+ holeEnd(key, dropped) {
2762
+ const serving = this.#serving();
2763
+ let end = serving && hooks.holeEnd(serving.sub, key, dropped);
2764
+ for (const copy of this.#copies) {
2765
+ if (copy === serving)
2766
+ continue;
2767
+ const past = hooks.holeEnd(copy.sub, key, false);
2768
+ if (past !== undefined)
2769
+ end = max(end ?? past, past);
2770
+ }
2771
+ const kept = this.route.skips.holeEnd(key);
2772
+ return kept === undefined ? end : max(end ?? kept, kept);
2773
+ }
2774
+ wholeEnd(key) {
2775
+ const serving = this.#serving();
2776
+ return serving && hooks.wholeEnd(serving.sub, key);
2777
+ }
2778
+ wholeAround(key) {
2779
+ const serving = this.#serving();
2780
+ return serving && hooks.wholeAround(serving.sub, key);
2781
+ }
2782
+ // A failed serving copy's own resolution is no placement while the front may still replace it:
2783
+ // the reader's ranges stay as placed, pending until a copy continuing the track places them.
2784
+ // Mirrors the Rust reader answering from its window.
2785
+ #placesNothing(serving) {
2786
+ return !this.route.concluded && copyFailed(serving);
2787
+ }
2788
+ // Each copy asks for the reader's ranges in turn, clamped to its floor and replacement.
2789
+ starts(from) {
2790
+ this.sync();
2791
+ const serving = this.#serving();
2792
+ if (!serving)
2793
+ return undefined;
2794
+ if (!this.#placesNothing(serving))
2795
+ return hooks.servingStarts(serving.sub, from);
2796
+ return this.#window().starts(from);
2797
+ }
2798
+ // Where a live join this reader placed at `placed` starts under `budget` milliseconds, on the
2799
+ // serving copy, from what its feed vouches for when `vouch`. Mirrors the Rust
2800
+ // `Subscriber::join_start` on a reader following route copies.
2801
+ joinStart(placed, budget, vouch = false) {
2802
+ this.sync();
2803
+ const serving = this.#serving();
2804
+ return serving ? hooks.joinStart(serving.sub, placed, budget, vouch) : placed;
2805
+ }
2806
+ // The first group the serving copy holds from `placed` up that `budget` milliseconds leave
2807
+ // fresh. Mirrors the Rust `Subscriber::fresh_start` on a reader following route copies.
2808
+ freshStart(placed, budget, cap) {
2809
+ this.sync();
2810
+ const serving = this.#serving();
2811
+ return serving ? hooks.freshStart(serving.sub, placed, budget, cap) : placed;
2812
+ }
2813
+ // The reader's ranges as its window resolved them, whichever copy serves.
2814
+ resolved() {
2815
+ this.sync();
2816
+ return this.#window().resolved();
2817
+ }
2818
+ // The reader's own window, which spans every copy: the serving one starts at the switch's
2819
+ // boundary, so it leaves out what a replaced copy still delivers below it. Mirrors the Rust
2820
+ // `Resume::runs`.
2821
+ runs(start, end) {
2822
+ this.sync();
2823
+ return this.#window().runs(start, end);
2824
+ }
2825
+ // The reader's own window, synced, as `runs` reads it. Mirrors the Rust `Resume::with_window`.
2826
+ window() {
2827
+ this.sync();
2828
+ return this.#window();
2829
+ }
2830
+ // The reader's ranges covering group `key`, by index, each stale past its own budget: the window
2831
+ // places a live join as a time start, whose groups still go stale past its max. Mirrors the Rust
2832
+ // `Reader::covering`.
2833
+ covering(key) {
2834
+ this.sync();
2835
+ const ranges = this.#ranges();
2836
+ return this.#window().covering(key, (index) => ranges[Number(index)]);
2837
+ }
2838
+ // The serving copy's runs leave out the keys below a time start it still waits to place, so its
2839
+ // barrier holds a gap the group containing that start may lie below.
2840
+ gapHeld(at, end) {
2841
+ this.sync();
2842
+ const serving = this.#serving();
2843
+ return serving !== undefined && hooks.gapHeld(serving.sub, at, end);
2844
+ }
2845
+ servingEnd() {
2846
+ this.sync();
2847
+ const serving = this.#serving();
2848
+ return serving && hooks.servingEnd(serving.sub);
2849
+ }
2850
+ /** The first group the logical track's declared end excludes whole, undefined while it is open ended. */
2851
+ finalKey() {
2852
+ this.sync();
2853
+ const end = this.#learnEnd();
2854
+ return end && finalKey(end);
2855
+ }
2856
+ async finished() {
2857
+ for (;;) {
2858
+ this.sync();
2859
+ const end = this.#learnEnd();
2860
+ if (end)
2861
+ return end;
2862
+ const serving = this.#serving();
2863
+ const failed = serving?.sub.closed.peek();
2864
+ // A copy that failed is only the end of the track if no front replaces it, and a
2865
+ // refused replacement leaves the refusal as the answer.
2866
+ if (serving && failed instanceof Error) {
2867
+ if (this.#revert(serving, failed))
2868
+ continue;
2869
+ if (!routeFailed(failed))
2870
+ throw failed;
2871
+ if (this.route.refusal)
2872
+ throw this.route.refusal;
2873
+ if (this.route.concluded)
2874
+ throw failed;
2875
+ }
2876
+ if (!serving && this.route.concluded)
2877
+ throw dropped();
2878
+ const closed = this.#shell.closed.peek();
2879
+ if (closed instanceof Error)
2880
+ throw closed;
2881
+ if (closed !== undefined)
2882
+ throw new Error("track closed before its end was known");
2883
+ await new Promise((resolve) => {
2884
+ const dispose = this.changed(() => {
2885
+ dispose();
2886
+ resolve();
2887
+ });
2888
+ });
2889
+ }
2890
+ }
2891
+ watchError(fn) {
2892
+ let stop = () => { };
2893
+ const check = () => {
2894
+ stop();
2895
+ stop = () => { };
2896
+ this.sync();
2897
+ const copy = this.#serving();
2898
+ if (copy)
2899
+ stop = hooks.watchSubscriberError(copy.sub, fn);
2900
+ const changed = this.route.changed.changed(check);
2901
+ const previous = stop;
2902
+ stop = () => {
2903
+ previous();
2904
+ changed();
2905
+ };
2906
+ };
2907
+ check();
2908
+ return () => stop();
2909
+ }
2910
+ bufferedLargest() {
2911
+ this.sync();
2912
+ const serving = this.#serving();
2913
+ return serving && hooks.bufferedLargest(serving.sub);
2914
+ }
2915
+ /**
2916
+ * The group a {@link tryGroup} with nothing to drop would hand out next, without taking it: the
2917
+ * first any copy offers. A front reading this one as its copy picks across copies by it.
2918
+ */
2919
+ peek(ordered, delivered) {
2920
+ this.#delivered = delivered;
2921
+ this.sync();
2922
+ if (this.#closed)
2923
+ return undefined;
2924
+ // As the take does, so a late group on a copy that ran out is offered here too. A serving
2925
+ // copy it reopens owes a backfill, which the next take asks.
2926
+ this.#reopen();
2927
+ this.#reopenFolded(delivered);
2928
+ const { next } = this.#first(ordered, delivered);
2929
+ if (!next)
2930
+ return undefined;
2931
+ return hooks.peekGroup(next.sub, ordered, this.#newest === undefined ? undefined : this.#newest + 1n);
2932
+ }
2933
+ // Of the copies holding the lowest group, servable if any can serve it, so which copy holds a
2934
+ // group never decides whether it can be served.
2935
+ lowestHeld(from, below, servable) {
2936
+ let lowest;
2937
+ for (const copy of this.#copies) {
2938
+ const held = hooks.lowestHeld(copy.sub, from, lowest ? lowest.key + 1n : below, servable);
2939
+ if (!held)
2940
+ continue;
2941
+ if (held.key === lowest?.key)
2942
+ lowest.servable ||= held.servable;
2943
+ else
2944
+ lowest = held;
2945
+ }
2946
+ return lowest;
2947
+ }
2948
+ objectLargest() {
2949
+ this.sync();
2950
+ const serving = this.#serving();
2951
+ return serving ? hooks.objectLargest(serving.sub) : this.#ended?.object;
2952
+ }
2953
+ largestFinished(position) {
2954
+ this.sync();
2955
+ const serving = this.#serving();
2956
+ return serving !== undefined && hooks.largestFinished(serving.sub, position);
2957
+ }
2958
+ peekLargest() {
2959
+ this.sync();
2960
+ const serving = this.#serving();
2961
+ return serving ? hooks.peekLargest(serving.sub) : (this.#ended ?? { ended: false });
2962
+ }
2963
+ async largest(seen) {
2964
+ for (;;) {
2965
+ this.sync();
2966
+ const serving = this.#serving();
2967
+ const view = serving ? hooks.peekLargest(serving.sub) : this.#ended;
2968
+ const largest = view?.largest;
2969
+ const { start, end } = this.#shell.cursor.peek();
2970
+ // A replacement copy can start below what an earlier one reported.
2971
+ if (largest &&
2972
+ largest.group >= start &&
2973
+ (end === undefined || largest.group < end) &&
2974
+ (!seen || largest.group > seen.group || (largest.group === seen.group && largest.frame > seen.frame)))
2975
+ return largest;
2976
+ // A copy failing is its route failing: the logical track's stream ends only with the
2977
+ // route, or once the serving copy reaches its end cleanly.
2978
+ if (this.#shell.closed.peek() !== undefined)
2979
+ return undefined;
2980
+ if (view?.ended && !(serving?.sub.closed.peek() instanceof Error))
2981
+ return undefined;
2982
+ if ((this.route.concluded || this.route.refusal) && (!serving || view?.ended))
2983
+ return undefined;
2984
+ await new Promise((resolve) => {
2985
+ const disposes = [];
2986
+ const wake = () => {
2987
+ for (const dispose of disposes)
2988
+ dispose();
2989
+ resolve();
2990
+ };
2991
+ disposes.push(this.changed(wake), this.#shell.closed.changed(wake), this.#shell.cursor.changed(wake));
2992
+ if (serving)
2993
+ disposes.push(hooks.largestChanged(serving.sub, wake));
2994
+ });
2995
+ }
2996
+ }
2997
+ ask(ask) {
2998
+ this.sync();
2999
+ const serving = this.#serving();
3000
+ if (serving)
3001
+ hooks.askSubscriber(serving.sub, ask);
3002
+ }
3003
+ // A request outlives the copy it asked: once that copy closes while the logical track is open,
3004
+ // it asks the copy the route serves next, so only the logical track closing rejects it.
3005
+ // Mirrors the Rust `Failover`.
3006
+ async refresh(signal) {
3007
+ // How the copy last asked closed: the track's end once no route serves another.
3008
+ let failed;
3009
+ for (let asked;;) {
3010
+ this.sync();
3011
+ const closed = this.#shell.closed.peek();
3012
+ if (closed !== undefined)
3013
+ throw closed ?? closedBeforeSent(this.route.name);
3014
+ signal?.throwIfAborted();
3015
+ const generation = this.route.generation;
3016
+ if (generation !== asked) {
3017
+ asked = generation;
3018
+ const serving = this.#serving();
3019
+ if (serving) {
3020
+ try {
3021
+ return await this.#request(serving, signal);
3022
+ }
3023
+ catch (err) {
3024
+ if (signal?.aborted)
3025
+ throw err;
3026
+ failed = err;
3027
+ continue;
3028
+ }
3029
+ }
3030
+ // Nothing served when it was called: the next copy's join asks.
3031
+ if (failed === undefined)
3032
+ return;
3033
+ }
3034
+ else if (this.route.concluded || this.route.refusal) {
3035
+ throw failed;
3036
+ }
3037
+ await new Promise((resolve) => {
3038
+ const disposes = [];
3039
+ const wake = () => {
3040
+ for (const dispose of disposes)
3041
+ dispose();
3042
+ signal?.removeEventListener("abort", wake);
3043
+ resolve();
3044
+ };
3045
+ disposes.push(this.route.changed.changed(wake), this.#shell.closed.changed(wake));
3046
+ signal?.addEventListener("abort", wake, { once: true });
3047
+ });
3048
+ }
3049
+ }
3050
+ // Ask `serving` for a refresh, withdrawing it once the logical track closes.
3051
+ async #request(serving, signal) {
3052
+ const asked = new AbortController();
3053
+ const abort = () => asked.abort(signal?.reason);
3054
+ signal?.addEventListener("abort", abort, { once: true });
3055
+ let dispose;
3056
+ const ended = new Promise((_, reject) => {
3057
+ dispose = this.#shell.closed.changed((closed) => {
3058
+ if (closed === undefined)
3059
+ return;
3060
+ reject(closed ?? closedBeforeSent(this.route.name));
3061
+ asked.abort();
3062
+ });
3063
+ });
3064
+ try {
3065
+ return await Promise.race([serving.sub.refresh({ signal: asked.signal }), ended]);
3066
+ }
3067
+ finally {
3068
+ signal?.removeEventListener("abort", abort);
3069
+ dispose?.();
3070
+ }
3071
+ }
3072
+ fork(options) {
3073
+ this.sync();
3074
+ const newest = this.#copies.at(-1);
3075
+ return hooks.resumeSubscriber(this.route.name, options, (shell) => new Reader(this.route, shell, this.#record, newest));
3076
+ }
3077
+ close(abort) {
3078
+ if (this.#closed)
3079
+ return;
3080
+ this.#closed = true;
3081
+ this.#wall?.timer.abort();
3082
+ this.#wall = undefined;
3083
+ for (const dispose of this.#dispose)
3084
+ dispose();
3085
+ this.#dispose = [];
3086
+ // A recovery in flight settles with the group rather than adopting a replacement.
3087
+ for (const group of this.#open)
3088
+ hooks.releaseGroupReader(group, abort);
3089
+ this.#open.clear();
3090
+ for (const copy of [...this.#copies, ...this.#rerouted])
3091
+ this.#drop(copy, abort);
3092
+ this.#copies = [];
3093
+ this.#rerouted = [];
3094
+ this.route.leave(this);
3095
+ // A read still waiting on the reader looks again and finds it closed.
3096
+ this.wake();
3097
+ }
3098
+ }
3099
+ function startFetch(fetchGroup, name, key, generation, signal) {
3100
+ // Its own controller, so a fetch a later route supersedes stops without ending the recovery.
3101
+ const controller = new AbortController();
3102
+ const onAbort = () => controller.abort(signal.reason);
3103
+ signal.addEventListener("abort", onAbort, { once: true });
3104
+ const fetch = {
3105
+ generation,
3106
+ settled: new Signal(false),
3107
+ cancel: () => {
3108
+ signal.removeEventListener("abort", onAbort);
3109
+ controller.abort();
3110
+ if (fetch.outcome && "group" in fetch.outcome)
3111
+ fetch.outcome.group.close();
3112
+ },
3113
+ };
3114
+ fetchGroup(name, key, { signal: controller.signal })
3115
+ .then((group) => {
3116
+ // A copy that already failed continues nothing: that is the route failing again.
3117
+ const failed = group.closed.peek();
3118
+ if (failed instanceof Error) {
3119
+ group.close();
3120
+ fetch.outcome = { error: failed };
3121
+ return;
3122
+ }
3123
+ fetch.outcome = { group };
3124
+ // Abandoned while it was out: nobody reads it.
3125
+ if (controller.signal.aborted)
3126
+ group.close();
3127
+ }, (err) => {
3128
+ fetch.outcome = { error: err instanceof Error ? err : new Error(String(err)) };
3129
+ })
3130
+ .finally(() => {
3131
+ signal.removeEventListener("abort", onAbort);
3132
+ fetch.settled.set(true);
3133
+ });
3134
+ return fetch;
3135
+ }
3136
+ /** Wait for `change`, or throw once `signal` aborts, leaving no listener behind either way. */
3137
+ async function until(change, signal) {
3138
+ signal?.throwIfAborted();
3139
+ if (!signal) {
3140
+ await race([change]);
3141
+ return;
3142
+ }
3143
+ let onAbort = () => { };
3144
+ const abort = new Promise((resolve) => {
3145
+ onAbort = resolve;
3146
+ signal.addEventListener("abort", onAbort, { once: true });
3147
+ });
3148
+ try {
3149
+ await race([change, abort]);
3150
+ }
3151
+ finally {
3152
+ signal.removeEventListener("abort", onAbort);
3153
+ }
3154
+ signal.throwIfAborted();
3155
+ }
3156
+ function closedBeforeSent(name) {
3157
+ return new StreamError(StreamCode.Cancel, { message: `track ${name} closed before the refresh was sent` });
3158
+ }
3159
+ /** Why a group a copy closed short ends there: no route holds more of it. */
3160
+ function standing() {
3161
+ return new StreamError(StreamCode.NotFound, { message: "no route holds more of the group" });
3162
+ }
3163
+ function dropped() {
3164
+ return new StreamError(StreamCode.Cancel, { message: "no route serves the track" });
3165
+ }
3166
+ /** Carries a group across route changes; see the module docs. */
3167
+ class Recover {
3168
+ #reader;
3169
+ key;
3170
+ /** The copy being read, whose subscription this group keeps alive while it is read. */
3171
+ #copy;
3172
+ /** The route generation when `#copy` was acquired; kept separate because `Reader.sync` updates `copy.generation` in place on switch-back. */
3173
+ #generation;
3174
+ /**
3175
+ * The group being read came from the reader's own fetch, judged under the reader's own terms, or
3176
+ * from looking past a copy's too-old verdict once already: its own too old stands, which bounds
3177
+ * the route to one request more per group.
3178
+ */
3179
+ #judged = false;
3180
+ /** The recovery under way looks past a copy's too-old verdict. */
3181
+ #excusing = false;
3182
+ /**
3183
+ * Puts the group on the reader's list of those still read, so the other copies that hold it,
3184
+ * or may yet get it, stay for a failure to continue from.
3185
+ */
3186
+ constructor(reader, group, copy) {
3187
+ this.#reader = reader;
3188
+ this.key = group.start;
3189
+ this.#copy = copy;
3190
+ this.#generation = copy.generation;
3191
+ copy.lease++;
3192
+ reader.out.add(this);
3193
+ }
3194
+ /**
3195
+ * Release the copy once the group ends. Called only after the group carries this recovery:
3196
+ * reading `closed` before then would settle it on a failure recovery could still continue.
3197
+ */
3198
+ watch(group) {
3199
+ void hooks.groupClosed(group).then(() => this.close());
3200
+ }
3201
+ close() {
3202
+ this.#release(this.#reader.out.delete(this));
3203
+ }
3204
+ // Release the copy being read. `wake` says a parked read may let go of a copy anyway.
3205
+ #release(wake = false) {
3206
+ const copy = this.#copy;
3207
+ this.#copy = undefined;
3208
+ const freed = copy !== undefined && --copy.lease === 0;
3209
+ if (wake || freed)
3210
+ this.#reader.freed();
3211
+ }
3212
+ get changed() {
3213
+ return this.#reader.route.changed;
3214
+ }
3215
+ wants(cause) {
3216
+ const copy = this.#copy;
3217
+ if (!copy)
3218
+ return false;
3219
+ const route = this.#reader.route;
3220
+ if (cause.kind === "failed" && this.#undelivered(cause.error, copy))
3221
+ return true;
3222
+ // A refusal is terminal: no route continues a short close, which stands.
3223
+ if (cause.kind === "closed" && route.refusal)
3224
+ return false;
3225
+ // A stall or a short close on a copy whose route failed, or a short close while the front
3226
+ // stages the copy to replace it, looks to the route replacing it. Mirrors the Rust
3227
+ // `Recover::wants`.
3228
+ if (cause.kind === "stalled" && copyFailed(copy))
3229
+ return true;
3230
+ if (cause.kind === "closed" && (routeLost(copy) || route.staged))
3231
+ return true;
3232
+ if (route.concluded)
3233
+ return true;
3234
+ if (route.generation !== this.#generation) {
3235
+ // A route that returned serves the copy being read again, which a stalled group reuses.
3236
+ // A group that closed short (e.g. bare FIN at a Position End cap) will not resume on
3237
+ // the same subscription, so recover by fetching the remaining frames.
3238
+ if (cause.kind === "closed" || this.#reader.copy(route.generation) !== copy) {
3239
+ return true;
3240
+ }
3241
+ this.#generation = route.generation;
3242
+ }
3243
+ return false;
3244
+ }
3245
+ /**
3246
+ * Whether `copy` failed delivering the group rather than judging it, so its own route may be
3247
+ * asked again. Any other failure would repeat on every copy from that route, so only another
3248
+ * route is asked, which bounds a hostile route to one bad answer per route change.
3249
+ */
3250
+ #undelivered(failed, copy) {
3251
+ return routeFailed(failed) || copyFailed(copy) || this.#excuses(failed, copy);
3252
+ }
3253
+ /**
3254
+ * Whether `err` is a too-old verdict from `copy` that is none on the reader: the reader outgrows
3255
+ * the budget it was judged under (see {@link #outgrowsJudging}), and the group being read is no
3256
+ * answer to the reader's own request already. Mirrors the Rust `Recover::excuses`.
3257
+ */
3258
+ #excuses(err, copy) {
3259
+ return (err instanceof StreamError && err.code === StreamCode.Old && !this.#judged && this.#outgrowsJudging(copy));
3260
+ }
3261
+ /**
3262
+ * Whether the reader is wider than the narrowest budget `copy`'s upstream asked, which a group
3263
+ * it reset or dropped as too old may have been judged under: that verdict settles a reader only as a stale
3264
+ * drop does (see {@link settles}), and the route still delivers the group to a request under the
3265
+ * reader's own terms. A cache only makes things faster. Mirrors the Rust
3266
+ * `Recover::outgrows_judging`.
3267
+ */
3268
+ #outgrowsJudging(copy) {
3269
+ const judged = hooks.judgedUnder(copy.sub);
3270
+ if (judged === undefined)
3271
+ return false;
3272
+ const run = { start: this.key, end: this.key + 1n, ...staleHole(judged) };
3273
+ return !settles(run, this.#reader.within.budget(), this.#reader.coverage());
3274
+ }
3275
+ async replace(index, cause, signal) {
3276
+ let fetch;
3277
+ let kept;
3278
+ try {
3279
+ const replacement = await this.#replace({ index, cause, signal }, (next) => {
3280
+ fetch?.cancel();
3281
+ fetch = next;
3282
+ });
3283
+ kept = replacement.group;
3284
+ return replacement;
3285
+ }
3286
+ finally {
3287
+ // A fetch nothing continues from is abandoned, along with whatever it returns.
3288
+ if (fetch?.outcome === undefined || !("group" in fetch.outcome) || fetch.outcome.group !== kept)
3289
+ fetch?.cancel();
3290
+ }
3291
+ }
3292
+ async #replace({ index, cause, signal }, started) {
3293
+ const reader = this.#reader;
3294
+ const route = reader.route;
3295
+ const failed = cause.kind === "failed" ? cause.error : undefined;
3296
+ const closed = cause.kind === "closed";
3297
+ // The copy being read delivers no more of the group.
3298
+ const settled = cause.kind !== "stalled";
3299
+ const reading = this.#copy;
3300
+ this.#excusing = failed !== undefined && reading !== undefined && this.#excuses(failed, reading);
3301
+ let fetch;
3302
+ for (;;) {
3303
+ signal.throwIfAborted();
3304
+ // The serving subscription may still deliver a group its route refused to fetch.
3305
+ let landing;
3306
+ let unwatch;
3307
+ // Subscribe the reader to a new route from its newest group, which is this one or
3308
+ // later, so that route's subscription may deliver the rest of it.
3309
+ reader.sync();
3310
+ const current = this.#copy;
3311
+ if (!current)
3312
+ throw new Error("group closed");
3313
+ // The front refused the route that would continue it: nothing will.
3314
+ if (settled && route.refusal)
3315
+ throw route.refusal;
3316
+ const generation = route.generation;
3317
+ const serving = route.source ? reader.copy(generation) : undefined;
3318
+ const waits = [route.changed];
3319
+ // A failed group continues from any copy still holding it, newest first: its name fixes
3320
+ // its content. A stall only moves to the serving copy, so two stalled copies never trade
3321
+ // the group back and forth.
3322
+ if (failed) {
3323
+ const held = reader.holding(this.key, current)[0];
3324
+ const cached = held && hooks.cachedGroup(held.sub, this.key, index);
3325
+ if (cached)
3326
+ return this.#replacement(cached, held);
3327
+ // A verdict would repeat from the route that gave it.
3328
+ if (generation === this.#generation && !this.#undelivered(failed, current))
3329
+ throw failed;
3330
+ }
3331
+ // An unroutable copy waits for another route rather than asking its own again.
3332
+ const withdrawn = failed !== undefined && generation === this.#generation && unroutable(failed);
3333
+ if (!serving) {
3334
+ // Nothing replaced a copy that closed the group, as when its track parks, so its
3335
+ // close stands, unless its route failed: then it waits for a route as a failed
3336
+ // copy does, unless none will come.
3337
+ if (closed && (!routeLost(current) || route.concluded))
3338
+ throw standing();
3339
+ // Nothing serves: a failed copy waits for a route, unless none will come.
3340
+ if (failed && route.concluded)
3341
+ throw failed;
3342
+ }
3343
+ else if (closed && generation === this.#generation) {
3344
+ // It serves on with no front to replace it, so its close stands, unless its route
3345
+ // failed or the front stages the copy to replace it: then that one may hold more.
3346
+ if ((!routeLost(current) && !route.staged) || route.concluded)
3347
+ throw standing();
3348
+ }
3349
+ else if (generation !== this.#generation || failed) {
3350
+ // The serving route gave the group up, which ends it with that route's error however
3351
+ // a fetch of the rest would answer. A copy that failed dropped its open groups with
3352
+ // it, and a group the route failed is no verdict either.
3353
+ const given = hooks.givenUp(serving.sub, this.key);
3354
+ if (given.error && !routeFailed(given.error) && !copyFailed(serving)) {
3355
+ if (!this.#excuses(given.error, serving))
3356
+ throw given.error;
3357
+ this.#excusing = true;
3358
+ }
3359
+ waits.push(...given.changed);
3360
+ // A newer copy's track caches it: continue from there. On switch-back to the same
3361
+ // copy (whose group closed short under a Position End cap), skip its cached copy
3362
+ // and fetch the remaining frames from `index`.
3363
+ if (!failed && generation !== this.#generation && serving !== current) {
3364
+ const cached = hooks.cachedGroup(serving.sub, this.key, index);
3365
+ if (cached)
3366
+ return this.#replacement(cached, serving);
3367
+ }
3368
+ // Finished history may still continue the group above, and so may a fetch already
3369
+ // answered below. Otherwise a terminal track verdict ends this wait even while a
3370
+ // fetch is still unanswered, and asks for nothing more.
3371
+ const closed = serving.sub.closed.peek();
3372
+ const verdict = closed instanceof Error && !routeFailed(closed) ? closed : undefined;
3373
+ waits.push(serving.sub.closed);
3374
+ // Otherwise ask for it, if the route's version can fetch. The subscription may still
3375
+ // deliver it first. Without FETCH only a copy continues a failed or closed group, and
3376
+ // none holds it, so it ends as the copy left it.
3377
+ const fetchGroup = route.view(serving.source).fetchGroup;
3378
+ if (!fetchGroup && settled)
3379
+ throw verdict ?? failed ?? standing();
3380
+ if (fetchGroup && !verdict && !withdrawn && fetch?.generation !== generation) {
3381
+ fetch = startFetch(fetchGroup, route.name, this.key, generation, signal);
3382
+ started(fetch);
3383
+ }
3384
+ // A fetch from an earlier route answers for that route, not this one.
3385
+ const asked = fetch?.generation === generation ? fetch : undefined;
3386
+ const outcome = asked?.outcome;
3387
+ // An answer carries its own expiry; the verdict and the budget only end the wait.
3388
+ if (outcome && "group" in outcome)
3389
+ return this.#replacement(outcome.group, serving, true);
3390
+ if (verdict)
3391
+ throw verdict;
3392
+ // Judged within the reader's window, as a moved group is: the serving copy's subscription
3393
+ // starts at the boundary, past groups in the window that supersede this one.
3394
+ const stale = hooks.staleAt(serving.sub, this.key, undefined, reader.within);
3395
+ if (stale.expired())
3396
+ throw new StreamError(StreamCode.Old, { message: "group is past the budget" });
3397
+ waits.push(...stale.changed, ...(asked && !asked.outcome ? [asked.settled] : []));
3398
+ // That route failing too waits for the next one, and a refusal is a verdict only for
3399
+ // a copy that delivers no more, once the serving subscription will not deliver the
3400
+ // group either.
3401
+ if (outcome && settled && !routeFailed(outcome.error) && !copyFailed(serving)) {
3402
+ const subscription = serving.sub.subscription.peek();
3403
+ const maxDelay = Duration.millis(widest(subscription?.ranges ?? []));
3404
+ const land = { start: this.key, end: this.key + 1n, floor: true, grace: grace(maxDelay) };
3405
+ if (generation === this.#generation || !hooks.mayLand(serving.sub, land))
3406
+ throw outcome.error;
3407
+ landing = new Promise((resolve) => {
3408
+ unwatch = hooks.groupChanged(serving.sub, resolve);
3409
+ });
3410
+ }
3411
+ }
3412
+ try {
3413
+ const changed = Signal.race(...waits);
3414
+ await until(landing === undefined ? changed : race([changed, landing]), signal);
3415
+ }
3416
+ finally {
3417
+ unwatch?.();
3418
+ }
3419
+ }
3420
+ }
3421
+ #replacement(group, copy, fetched = false) {
3422
+ // Capture the route generation at selection time: `Reader.sync` may rewrite
3423
+ // `copy.generation` in place on a switch-back before `adopt` runs.
3424
+ const generation = copy.generation;
3425
+ return {
3426
+ group,
3427
+ expiry: hooks.staleAt(copy.sub, this.key, undefined, this.#reader.within),
3428
+ adopt: () => {
3429
+ // A later switch must keep this copy subscribed while the recovered group still
3430
+ // reads it, just like a group handed out from that copy directly. Leased first, so
3431
+ // letting go of the copies it leaves never drops it.
3432
+ copy.lease++;
3433
+ this.#release();
3434
+ this.#copy = copy;
3435
+ this.#generation = generation;
3436
+ this.#judged = fetched || this.#excusing;
3437
+ this.#excusing = false;
3438
+ },
3439
+ discard: () => group.close(),
3440
+ };
3441
+ }
3442
+ }
3443
+ /**
3444
+ * A fetched group judged by the publisher's max age alone against a reader's copy of its track on
3445
+ * the route it came from, as the Rust relay judges a fetch landed in that copy's cache. It opens
3446
+ * no subscription, so a fetch-only relay never pulls the track: with no copy, nothing newer is
3447
+ * known here, and the group is never stale.
3448
+ */
3449
+ class FetchExpiry {
3450
+ changed;
3451
+ #find;
3452
+ #key;
3453
+ // The copy judging the group. One that closed still judges by what it held, until another opens.
3454
+ #judging;
3455
+ // Bumped whenever the judging copy's verdict may change.
3456
+ #relay = new Signal(0);
3457
+ #closed = false;
3458
+ constructor(find, copied, key) {
3459
+ this.#find = find;
3460
+ this.#key = key;
3461
+ this.changed = [copied, this.#relay];
3462
+ }
3463
+ expired() {
3464
+ this.#pick();
3465
+ return this.#judging?.expiry.expired() ?? false;
3466
+ }
3467
+ budget() {
3468
+ return this.#judging?.expiry.budget?.() ?? NO_MAX_DELAY;
3469
+ }
3470
+ aged(budget) {
3471
+ this.#pick();
3472
+ return this.#judging?.expiry.aged?.(budget) ?? false;
3473
+ }
3474
+ /** Judge afresh once the group moves to another route: the old route's copy says nothing about it. */
3475
+ moved() {
3476
+ this.#unwatch();
3477
+ this.#judging = undefined;
3478
+ this.#relay.update((n) => n + 1);
3479
+ }
3480
+ /** Stop watching the copy, once nobody reads the group. */
3481
+ close() {
3482
+ this.#closed = true;
3483
+ this.#unwatch();
3484
+ }
3485
+ #pick() {
3486
+ const found = this.#find();
3487
+ if (!found || found.sub === this.#judging?.sub)
3488
+ return;
3489
+ this.#unwatch();
3490
+ const expiry = hooks.staleAt(found.sub, this.#key, true);
3491
+ const bump = () => this.#relay.update((n) => n + 1);
3492
+ const unwatch = this.#closed ? [] : expiry.changed.map((changed) => changed.subscribe(bump));
3493
+ this.#judging = { sub: found.sub, expiry, unwatch };
3494
+ }
3495
+ #unwatch() {
3496
+ for (const dispose of this.#judging?.unwatch ?? [])
3497
+ dispose();
3498
+ if (this.#judging)
3499
+ this.#judging.unwatch = [];
3500
+ }
3501
+ }
3502
+ /**
3503
+ * One broadcast served through one route at a time; see the module docs.
3504
+ *
3505
+ * Its {@link consumer} is the broadcast handed out: every track read through it follows the
3506
+ * front's route. The origin calls {@link serve} as routes of the same identity take over, and
3507
+ * {@link conclude} once none will: readers then follow the last copy to its end.
3508
+ */
3509
+ export class Front {
3510
+ /** The logical broadcast; closing its last handle concludes the front. */
3511
+ consumer;
3512
+ #source;
3513
+ #routes = new Map();
3514
+ /** The metadata copies' routes, kept apart so no payload reader is ever handed one. */
3515
+ #metaRoutes = new Map();
3516
+ /**
3517
+ * Each track's properties as first committed, and the {@link Source.id} of the source that said
3518
+ * so: every later copy must match. Kept for the front's lifetime, so it holds no route.
3519
+ */
3520
+ #info = new Map();
3521
+ /** Bumped whenever the source changes, so an answer from a replaced one is dropped. */
3522
+ #changed = new Signal(0);
3523
+ /** Bumped whenever a reader subscribes a copy, which may judge a fetched group; see {@link FetchExpiry}. */
3524
+ #copied = new Signal(0);
3525
+ /** Aborted once the current source is replaced, retiring what was asked of it. */
3526
+ #retire = new AbortController();
3527
+ #concluded = false;
3528
+ /** The tracks each source was checked against the recorded properties for; see #verify. */
3529
+ #verified = new WeakMap();
3530
+ /** Whether another identity than the one this front serves wins its path. */
3531
+ #superseded;
3532
+ /**
3533
+ * `superseded` says whether another identity than the one the front serves wins its path,
3534
+ * judged over every route the origin holds: a claim's refusal is then final.
3535
+ */
3536
+ constructor(superseded = () => false) {
3537
+ this.#superseded = superseded;
3538
+ this.consumer = makeFrontConsumer(this);
3539
+ void this.consumer.closed.then(() => this.conclude());
3540
+ void this.#list(wireOf(this.consumer).lister());
3541
+ }
3542
+ /**
3543
+ * Answer listings of the front's broadcast with its serving source's listing, while anyone
3544
+ * lists it. A source of the same identity lists the same tracks, so a takeover shows readers
3545
+ * only what differs, once the new source's listing synced.
3546
+ */
3547
+ async #list(lister) {
3548
+ const closed = this.consumer.closed;
3549
+ let listing;
3550
+ const wait = () => race([Signal.race(lister.wanted, this.#changed), closed]);
3551
+ const stop = () => {
3552
+ listing?.reader?.close();
3553
+ listing = undefined;
3554
+ };
3555
+ const read = (reader) => reader.next().then((event) => ({ event }), (err) => ({ err: err instanceof Error ? err : new Error(String(err)) }));
3556
+ // Forwarded as the source reported it, finished or not.
3557
+ const unlist = (listed, stale, event) => {
3558
+ const key = keyOf(event.name, event.type);
3559
+ stale.delete(key);
3560
+ if (!listed.delete(key))
3561
+ return;
3562
+ if (event.kind === "finished")
3563
+ lister.finish(event.name, event.type);
3564
+ else
3565
+ lister.remove(event.name, event.type);
3566
+ };
3567
+ try {
3568
+ for (;;) {
3569
+ if (closed.peek() !== undefined)
3570
+ return;
3571
+ if (!lister.wanted.peek()) {
3572
+ if (listing) {
3573
+ stop();
3574
+ lister.clear();
3575
+ }
3576
+ await wait();
3577
+ continue;
3578
+ }
3579
+ if (this.#concluded) {
3580
+ // No route will serve it again, so nothing more will be listed. A source that
3581
+ // closed ended its listing after the tracks it finished last: those go first.
3582
+ while (listing?.reader && listing.source?.from.closed.peek() !== undefined) {
3583
+ const { event } = await (listing.next ?? read(listing.reader));
3584
+ listing.next = undefined;
3585
+ if (!event)
3586
+ break;
3587
+ if (event.kind === "removed" || event.kind === "finished")
3588
+ unlist(listing.listed, listing.stale, event);
3589
+ }
3590
+ stop();
3591
+ lister.end();
3592
+ continue;
3593
+ }
3594
+ listing ??= { listed: new Map(), stale: new Map() };
3595
+ if (listing.source !== this.#source) {
3596
+ listing.reader?.close();
3597
+ listing.source = this.#source;
3598
+ listing.stale = new Map(listing.listed);
3599
+ listing.next = undefined;
3600
+ try {
3601
+ listing.reader = this.#source?.wire.tracks();
3602
+ }
3603
+ catch (err) {
3604
+ // A closing source lists nothing more; the front moves off it soon.
3605
+ listing.reader = undefined;
3606
+ // A live one refuses: served through a route claiming a prefix, it names
3607
+ // nothing to list. A later reader asks again.
3608
+ if (listing.source && listing.source.from.closed.peek() === undefined) {
3609
+ stop();
3610
+ lister.abort(err instanceof Error ? err : new Error(String(err)));
3611
+ continue;
3612
+ }
3613
+ }
3614
+ }
3615
+ const reader = listing.reader;
3616
+ if (!reader) {
3617
+ await wait();
3618
+ continue;
3619
+ }
3620
+ listing.next ??= read(reader);
3621
+ // One flat race: nested, the wait's registrations stay pending whenever the event wins.
3622
+ // What a change or the close settles with is no event, so the loop looks again.
3623
+ const result = await race([listing.next, Signal.race(lister.wanted, this.#changed), closed]);
3624
+ if (typeof result !== "object" || result === null)
3625
+ continue;
3626
+ listing.next = undefined;
3627
+ // The source was replaced as its answer arrived: the new source's listing supersedes it.
3628
+ if (listing.source !== this.#source)
3629
+ continue;
3630
+ const { event, err } = result;
3631
+ if (err) {
3632
+ // Its readers fail, and a later reader asks again.
3633
+ stop();
3634
+ lister.abort(err);
3635
+ }
3636
+ else if (!event) {
3637
+ // A closing source ended its listing: the front moves to another source, or ends
3638
+ // with it. A live one's handler ended it, as a session does once the peer's
3639
+ // broadcast ended, so the front's listing ends too.
3640
+ if (listing.source?.from.closed.peek() !== undefined) {
3641
+ listing.reader = undefined;
3642
+ }
3643
+ else {
3644
+ stop();
3645
+ lister.end();
3646
+ }
3647
+ }
3648
+ else if (event.kind === "added") {
3649
+ const key = keyOf(event.name, event.type);
3650
+ if (!listing.stale.delete(key) && !listing.listed.has(key)) {
3651
+ listing.listed.set(key, { name: event.name, type: event.type });
3652
+ lister.add(event.name, event);
3653
+ }
3654
+ }
3655
+ else if (event.kind === "removed" || event.kind === "finished") {
3656
+ unlist(listing.listed, listing.stale, event);
3657
+ }
3658
+ else {
3659
+ // What the new source still lacks at its SYNCED is gone.
3660
+ for (const [key, { name, type }] of listing.stale) {
3661
+ listing.listed.delete(key);
3662
+ lister.remove(name, type);
3663
+ }
3664
+ listing.stale.clear();
3665
+ lister.synced();
3666
+ }
3667
+ }
3668
+ }
3669
+ finally {
3670
+ stop();
3671
+ lister.close();
3672
+ }
3673
+ }
3674
+ /**
3675
+ * Serve every track from `from` from now on, once each copy proves compatible. `claim` marks a
3676
+ * lite-07 peer's claim, whose refusal is final once its identity loses the path.
3677
+ */
3678
+ serve(from, local = false, claim = false) {
3679
+ if (this.#concluded || this.#source?.from === from)
3680
+ return;
3681
+ const source = new Source(from, local, claim ? this.#superseded : undefined);
3682
+ source.retain();
3683
+ const previous = this.#source;
3684
+ this.#source = source;
3685
+ this.#retired();
3686
+ for (const route of this.#everyRoute())
3687
+ this.#splice(route, source);
3688
+ previous?.release();
3689
+ }
3690
+ /**
3691
+ * The table moved for the path while the same route still wins, with no takeover pending: a
3692
+ * read stranded on a lost route asks the serving source again, the evidence it waited for.
3693
+ * Unless the serving source is a claim whose identity lost the path: a read it refused before
3694
+ * any copy delivered ends with that refusal, as nothing else of its identity answers for it,
3695
+ * while one that delivered is asked once more and ends on that answer. Mirrors the Rust front's
3696
+ * `unstrand` and `refuse_stranded`.
3697
+ */
3698
+ moved() {
3699
+ const current = this.#source;
3700
+ if (this.#concluded || !current)
3701
+ return;
3702
+ const lost = current.claimLost();
3703
+ for (const route of this.#everyRoute()) {
3704
+ const stranded = route.unstrand();
3705
+ if (!stranded)
3706
+ continue;
3707
+ if (lost && stranded.source === current && !stranded.delivered) {
3708
+ route.refuse(new StreamError(StreamCode.Unroutable, { message: "unroutable" }));
3709
+ continue;
3710
+ }
3711
+ // Read from the serving source: subscribe afresh. Otherwise the read is on a copy the
3712
+ // serving source replaced, which takes over again as any handover does.
3713
+ if (route.source === current)
3714
+ route.resubscribe();
3715
+ else
3716
+ this.#splice(route, current);
3717
+ }
3718
+ }
3719
+ /** Between routes: readers keep what they have and wait for the next one. */
3720
+ park() {
3721
+ if (this.#concluded || !this.#source)
3722
+ return;
3723
+ const previous = this.#source;
3724
+ this.#source = undefined;
3725
+ this.#retired();
3726
+ for (const route of this.#everyRoute())
3727
+ route.park();
3728
+ previous.release();
3729
+ }
3730
+ /** No route will replace the serving one: readers follow it to its end. Idempotent. */
3731
+ conclude() {
3732
+ if (this.#concluded)
3733
+ return;
3734
+ this.#concluded = true;
3735
+ for (const route of this.#everyRoute())
3736
+ route.conclude();
3737
+ this.#source?.release();
3738
+ this.#source = undefined;
3739
+ this.#retired();
3740
+ }
3741
+ // The source changed: wake what waits on it, and retire what was asked of the old one.
3742
+ #retired() {
3743
+ this.#changed.update((n) => n + 1);
3744
+ this.#retire.abort();
3745
+ this.#retire = new AbortController();
3746
+ }
3747
+ // Splice `source`'s copy of a track in, once it claims the same content as the copies before.
3748
+ #splice(route, source) {
3749
+ const recorded = this.#info.get(route.name);
3750
+ const previous = route.served;
3751
+ // The first copy of a track has nothing to match, and the source that said what it is
3752
+ // matches itself.
3753
+ if ((!recorded && !previous) || recorded?.source === source.id) {
3754
+ route.serve(source);
3755
+ return;
3756
+ }
3757
+ // The replaced copy keeps feeding the track while the new one answers. One that has not
3758
+ // answered yet is asked too, so a swap racing its first answer is still checked.
3759
+ source.retain();
3760
+ previous?.retain();
3761
+ route.stage(source);
3762
+ // Abandoned once another route supersedes this one, releasing both.
3763
+ const retired = this.#retire.signal;
3764
+ const expected = recorded
3765
+ ? Promise.resolve(recorded.info)
3766
+ : ask(previous, route.name, retired).then((info) => {
3767
+ this.#record(route.name, info, previous);
3768
+ return info;
3769
+ },
3770
+ // Its route failing is no answer; a refusal is the track's.
3771
+ (err) => {
3772
+ if (routeFailed(err instanceof Error ? err : new Error(String(err))))
3773
+ return undefined;
3774
+ throw err;
3775
+ });
3776
+ Promise.all([expected, ask(source, route.name, retired)])
3777
+ .then(([expected, info]) => {
3778
+ route.unstage(source);
3779
+ if (this.#source !== source)
3780
+ return;
3781
+ // The copy it replaces never answered, so this one says what the track is.
3782
+ if (!expected)
3783
+ this.#record(route.name, info, source);
3784
+ // A copy claiming the same content with different metadata is refused rather
3785
+ // than reinterpreted.
3786
+ if (!expected || compatible(expected, info))
3787
+ route.serve(source);
3788
+ else
3789
+ route.refuse(new Incompatible(route.name));
3790
+ }, (err) => {
3791
+ route.unstage(source);
3792
+ if (this.#source !== source)
3793
+ return;
3794
+ const error = err instanceof Error ? err : new Error(String(err));
3795
+ // A route that lost the content leaves the replaced copy feeding the read, which asks
3796
+ // again once the table moves, as the Rust front's refusal does. A route on its way
3797
+ // out is no verdict: the next one is asked.
3798
+ if (strands(error, source)) {
3799
+ // A claim whose identity lost the path refuses for good.
3800
+ if (source.claimLost())
3801
+ route.refuse(error);
3802
+ else
3803
+ route.strand(source, false);
3804
+ }
3805
+ else if (!routeFailed(error))
3806
+ route.refuse(error);
3807
+ })
3808
+ .finally(() => {
3809
+ source.release();
3810
+ previous?.release();
3811
+ });
3812
+ }
3813
+ // Every logical track's route, payload and metadata copies alike.
3814
+ *#everyRoute() {
3815
+ yield* this.#routes.values();
3816
+ yield* this.#metaRoutes.values();
3817
+ }
3818
+ #route(name, meta) {
3819
+ const routes = meta ? this.#metaRoutes : this.#routes;
3820
+ let route = routes.get(name);
3821
+ if (route)
3822
+ return route;
3823
+ route = new Route(name, meta);
3824
+ const created = route;
3825
+ created.idle = () => {
3826
+ if (routes.get(name) === created)
3827
+ routes.delete(name);
3828
+ };
3829
+ created.copied = () => this.#copied.update((n) => n + 1);
3830
+ routes.set(name, created);
3831
+ // A track whose properties another source already gave is checked like any replacement.
3832
+ if (this.#concluded)
3833
+ created.conclude();
3834
+ else if (this.#source)
3835
+ this.#splice(created, this.#source);
3836
+ return created;
3837
+ }
3838
+ // Check `source` claims the same properties for `name` as recorded, once per source: a fetch
3839
+ // never reads a copy a subscription would refuse.
3840
+ async #verify(name, source) {
3841
+ const recorded = this.#info.get(name);
3842
+ if (recorded?.source === source.id)
3843
+ return;
3844
+ let verified = this.#verified.get(source);
3845
+ if (verified?.has(name))
3846
+ return;
3847
+ const retired = this.#retire.signal;
3848
+ await this.#askServed(name, source, retired);
3849
+ const info = await ask(source, name, retired);
3850
+ // The first answer says what the track is; later sources have to match it.
3851
+ const expected = this.#info.get(name);
3852
+ if (!expected)
3853
+ this.#record(name, info, source);
3854
+ else if (!compatible(expected.info, info))
3855
+ throw new Incompatible(name);
3856
+ verified ??= new Set();
3857
+ verified.add(name);
3858
+ this.#verified.set(source, verified);
3859
+ }
3860
+ // A copy a reader still reads says what the track is before `source` does: one logical track
3861
+ // has one set of properties. Its route failing is no answer; a refusal is the track's.
3862
+ async #askServed(name, source, retired) {
3863
+ const served = this.#routes.get(name)?.served;
3864
+ if (this.#info.has(name) || !served || served === source)
3865
+ return;
3866
+ let info;
3867
+ try {
3868
+ info = await ask(served, name, retired);
3869
+ }
3870
+ catch (err) {
3871
+ if (routeFailed(err instanceof Error ? err : new Error(String(err))))
3872
+ return;
3873
+ throw err;
3874
+ }
3875
+ this.#record(name, info, served);
3876
+ }
3877
+ #record(name, info, source) {
3878
+ if (!this.#info.has(name))
3879
+ this.#info.set(name, { info, source: source.id });
3880
+ }
3881
+ /** Subscribe the logical track `name`, or its metadata copy when `meta`. */
3882
+ subscribe(name, options, meta = false) {
3883
+ if (this.consumer.closed.peek() !== undefined)
3884
+ throw new Error("broadcast is closed");
3885
+ const route = this.#route(name, meta);
3886
+ return hooks.resumeSubscriber(name, options, (shell) => new Reader(route, shell, (info, source) => this.#record(name, info, source)));
3887
+ }
3888
+ /** Whether the serving source's datagram metadata comes from an application. */
3889
+ get localDatagrams() {
3890
+ return this.#source?.wire.localDatagrams ?? false;
3891
+ }
3892
+ /** Whether the serving source keeps a name's stream track and datagram track apart. */
3893
+ get distinguishesKinds() {
3894
+ return this.#source?.wire.distinguishesKinds ?? false;
3895
+ }
3896
+ /** Whether the serving source already publishes a stream track of this name. */
3897
+ publishesTrack(name) {
3898
+ return this.#source?.wire.publishesTrack(name) ?? false;
3899
+ }
3900
+ /** Join the serving source's live datagram track; it holds no cached route copies. */
3901
+ datagrams(name) {
3902
+ if (!this.#source)
3903
+ throw new NotFound(`datagram track ${name}`);
3904
+ return this.#source.wire.datagrams(name);
3905
+ }
3906
+ /** Join an already present datagram track without opening a request. */
3907
+ liveDatagrams(name) {
3908
+ return this.#source?.wire.liveDatagrams(name);
3909
+ }
3910
+ // Wait for the source to change, or `signal` to abort.
3911
+ #next(signal) {
3912
+ return until(Signal.race(this.#changed), signal);
3913
+ }
3914
+ async resolveTrackInfo(name, hold) {
3915
+ for (;;) {
3916
+ const source = this.#source;
3917
+ if (!source) {
3918
+ if (this.#concluded)
3919
+ throw dropped();
3920
+ await this.#next(hold);
3921
+ continue;
3922
+ }
3923
+ source.retain();
3924
+ const retired = this.#retire.signal;
3925
+ let info;
3926
+ try {
3927
+ await this.#askServed(name, source, retired);
3928
+ info = await ask(source, name, retired, hold);
3929
+ }
3930
+ catch (err) {
3931
+ // Another route took over before this one answered: ask it instead.
3932
+ if (retired.aborted && !hold?.aborted && !this.#concluded)
3933
+ continue;
3934
+ const error = err instanceof Error ? err : new Error(String(err));
3935
+ // The route failed: ask the next one, unless none will come.
3936
+ if (!routeFailed(error) || this.#concluded || hold?.aborted)
3937
+ throw error;
3938
+ if (this.#source === source)
3939
+ await this.#next(hold);
3940
+ continue;
3941
+ }
3942
+ finally {
3943
+ source.release();
3944
+ }
3945
+ const recorded = this.#info.get(name);
3946
+ // One logical track has one set of properties, whichever route answers.
3947
+ if (recorded && !compatible(recorded.info, info))
3948
+ throw new Incompatible(name);
3949
+ this.#record(name, info, source);
3950
+ return recorded?.info ?? info;
3951
+ }
3952
+ }
3953
+ largest(name, meta = false, timescale) {
3954
+ const source = this.#source;
3955
+ return source && (meta ? source.meta : source.wire).largest(name, timescale);
3956
+ }
3957
+ async fetchGroup(name, key, options, meta = false) {
3958
+ const target = { name, meta };
3959
+ const fetched = await this.#fetch(target, key, options);
3960
+ let current = fetched.source;
3961
+ // A group fetched over a wire carries no expiry of its own, unlike one a local track
3962
+ // answers: the publisher's max age judges it against a copy of the route it came from.
3963
+ const judge = new FetchExpiry(() => this.#copyOn(target, current), this.#copied, key);
3964
+ const expiry = (group) => hooks.groupExpiry(group) ?? judge;
3965
+ if (!hooks.groupExpiry(fetched.group))
3966
+ hooks.expireGroup(fetched.group, judge);
3967
+ // Too old and evicted judge a subscription's delivery, not whether the group exists, so
3968
+ // neither is a verdict on a fetch: one answered from a group still arriving over a
3969
+ // subscription asks the route again for the rest when that delivery gives up on it.
3970
+ const undelivered = (failed) => routeFailed(failed) ||
3971
+ (failed instanceof StreamError && (failed.code === StreamCode.Old || failed.code === StreamCode.Evicted));
3972
+ // Carried across route changes like a subscribed group, but by fetching again: a fetch has
3973
+ // no copy of its own to find the rest in.
3974
+ hooks.recoverGroup(fetched.group, {
3975
+ changed: this.#changed,
3976
+ wants: (cause) => {
3977
+ if (cause.kind === "failed" && undelivered(cause.error))
3978
+ return true;
3979
+ return this.#source !== undefined && this.#source !== current;
3980
+ },
3981
+ replace: async (_index, cause, signal) => {
3982
+ // A fetch that failed delivering may ask its own route again; a stalled or closed one,
3983
+ // one a verdict ended, or one whose route withdrew only moves to another. A withdrawal
3984
+ // keeps its cause once none will come.
3985
+ const failed = cause.kind === "failed" ? cause.error : undefined;
3986
+ const withdrawn = failed && unroutable(failed) ? failed : undefined;
3987
+ const avoid = failed && undelivered(failed) && !withdrawn ? undefined : current;
3988
+ const next = await this.#fetch(target, key, { ...options, signal }, avoid, withdrawn);
3989
+ // The fetch's hold on its route passes to the group on adoption, or goes with the discard.
3990
+ return {
3991
+ group: next.group,
3992
+ expiry: expiry(next.group),
3993
+ adopt: () => {
3994
+ current.release();
3995
+ current = next.source;
3996
+ judge.moved();
3997
+ // Its fetch may hold its subscription until its reader lets go, and the
3998
+ // reader is now `fetched.group`.
3999
+ void hooks.groupReleased(fetched.group).then(() => next.group.close());
4000
+ },
4001
+ discard: () => {
4002
+ next.group.close();
4003
+ next.source.release();
4004
+ },
4005
+ };
4006
+ },
4007
+ });
4008
+ // Only once the group carries its recovery: reading `closed` or `done` before then would
4009
+ // settle it on a failure recovery could still continue, releasing the route, or ending
4010
+ // the budget's watch, while it is read.
4011
+ void hooks.groupClosed(fetched.group).then(() => current.release());
4012
+ // The budget is watched for as long as the group is read, as the fetch's own subscription is.
4013
+ void hooks.groupDone(fetched.group).then(() => judge.close());
4014
+ return fetched.group;
4015
+ }
4016
+ // The newest open copy of `target` a reader holds of `source`'s broadcast, if any.
4017
+ #copyOn(target, source) {
4018
+ const routes = target.meta ? this.#metaRoutes : this.#routes;
4019
+ for (const reader of routes.get(target.name)?.readers ?? []) {
4020
+ const copy = reader.copyOn(source);
4021
+ if (copy)
4022
+ return copy;
4023
+ }
4024
+ return undefined;
4025
+ }
4026
+ // Fetch a group from whichever route serves the track, asking the next one when a route
4027
+ // fails, and never `avoid`. The source comes back retained for as long as the group is read.
4028
+ // Once no route will come, it ends with `ended`, or as not found.
4029
+ async #fetch(target, key, options, avoid, ended) {
4030
+ const { name, meta } = target;
4031
+ for (;;) {
4032
+ const source = this.#source;
4033
+ if (!source || source === avoid) {
4034
+ if (this.#concluded)
4035
+ throw ended ?? new NotFound(`group ${key}`);
4036
+ await this.#next(options?.signal);
4037
+ continue;
4038
+ }
4039
+ source.retain();
4040
+ // Abandoned once another route takes over, and asked of that one instead.
4041
+ const retired = this.#retire.signal;
4042
+ const signal = options?.signal ? AbortSignal.any([options.signal, retired]) : retired;
4043
+ let refusal;
4044
+ try {
4045
+ // Asked alongside the check that the source claims the track's recorded properties,
4046
+ // rather than a round trip after it: only handing the group out waits for the check.
4047
+ const fetchGroup = (meta ? source.meta : source.wire).fetchGroup;
4048
+ const ahead = new AbortController();
4049
+ let reported;
4050
+ const request = {
4051
+ ...options,
4052
+ signal: AbortSignal.any([signal, ahead.signal]),
4053
+ refused: (error) => {
4054
+ reported = error;
4055
+ },
4056
+ };
4057
+ const fetching = fetchGroup?.(name, key, request);
4058
+ fetching?.catch(() => { });
4059
+ try {
4060
+ await until(this.#verify(name, source), signal);
4061
+ }
4062
+ catch (err) {
4063
+ ahead.abort(err);
4064
+ void fetching?.then((group) => group.close(), () => { });
4065
+ throw err;
4066
+ }
4067
+ if (!fetching)
4068
+ throw new Error("fetch group is not supported by this session's version");
4069
+ const group = await fetching.catch((error) => {
4070
+ // An independent failure while verifying the track may arrive first.
4071
+ refusal = reported;
4072
+ throw error;
4073
+ });
4074
+ // A copy that already failed continues nothing: that is the route failing again.
4075
+ const failed = group.closed.peek();
4076
+ if (failed instanceof Error) {
4077
+ group.close();
4078
+ throw failed;
4079
+ }
4080
+ return { group, source };
4081
+ }
4082
+ catch (err) {
4083
+ source.release();
4084
+ if (retired.aborted && !options?.signal?.aborted && !this.#concluded)
4085
+ continue;
4086
+ if (refusal) {
4087
+ options?.refused?.(refusal);
4088
+ throw refusal;
4089
+ }
4090
+ const error = err instanceof Error ? err : new Error(String(err));
4091
+ // The route failed: ask the next one, unless none will come.
4092
+ if (!routeFailed(error) || this.#concluded || options?.signal?.aborted)
4093
+ throw error;
4094
+ if (this.#source === source)
4095
+ await this.#next(options?.signal);
4096
+ }
4097
+ }
4098
+ }
4099
+ }
4100
+ let makeFrontConsumer;
4101
+ /** A front's logical broadcast: a consumer handle whose tracks follow the front's route. */
4102
+ class FrontConsumer extends broadcast.Consumer {
4103
+ #front;
4104
+ constructor(front, state) {
4105
+ super(state);
4106
+ this.#front = front;
4107
+ const view = wireOf(this);
4108
+ const routed = {
4109
+ ...view,
4110
+ datagrams: (name) => front.datagrams(name),
4111
+ liveDatagrams: (name) => front.liveDatagrams(name),
4112
+ publishesTrack: (name) => front.publishesTrack(name),
4113
+ tracks: view.tracks,
4114
+ lister: view.lister,
4115
+ subscribe: (name, options) => front.subscribe(name, options),
4116
+ resolveTrackInfo: (name, hold) => front.resolveTrackInfo(name, hold),
4117
+ largest: (name, timescale) => front.largest(name, false, timescale),
4118
+ fetchGroup: (name, key, options) => front.fetchGroup(name, key, options),
4119
+ };
4120
+ // Each route's source decides which copy a metadata reader gets; the front keeps the two
4121
+ // apart either way. Both copies claim the same properties, so info is asked once.
4122
+ const meta = {
4123
+ ...routed,
4124
+ subscribe: (name, options) => front.subscribe(name, options, true),
4125
+ largest: (name) => front.largest(name, true),
4126
+ fetchGroup: (name, key, options) => front.fetchGroup(name, key, options, true),
4127
+ };
4128
+ // Read from the serving source when asked, since the route may change and none serves yet.
4129
+ const serving = (wire) => Object.defineProperties(wire, {
4130
+ localDatagrams: { get: () => front.localDatagrams, enumerable: true },
4131
+ distinguishesKinds: { get: () => front.distinguishesKinds, enumerable: true },
4132
+ });
4133
+ serving(meta);
4134
+ registerWire(this, serving({ ...routed, meta: () => meta }));
4135
+ }
4136
+ static {
4137
+ makeFrontConsumer = (front) => new FrontConsumer(front);
4138
+ }
4139
+ // Preserve the subclass, and the front behind it, when a handle is shared.
4140
+ clone() {
4141
+ return new FrontConsumer(this.#front, this.shareState());
4142
+ }
4143
+ }
4144
+ /** The runs of `held` inside `[start, end)`. */
4145
+ function runsIn(held, start, end) {
4146
+ const runs = [];
4147
+ let at = start;
4148
+ for (const gap of held.gaps(start, end)) {
4149
+ if (gap.start > at)
4150
+ runs.push({ start: at, end: gap.start });
4151
+ at = gap.end;
4152
+ }
4153
+ if (at < end)
4154
+ runs.push({ start: at, end });
4155
+ return runs;
4156
+ }
4157
+ /**
4158
+ * Whether `copy` is of `serving`'s route, did not fail, and was asked for group `key`. Mirrors the
4159
+ * Rust `Copy::asked_for`.
4160
+ */
4161
+ function copyAskedFor(copy, serving, key) {
4162
+ return (!(copy.done instanceof Error) &&
4163
+ copy.source.from.closed === serving.source.from.closed &&
4164
+ (copy.floor ?? 0n) <= key &&
4165
+ key < (copyEnd(copy) ?? UNBOUNDED));
4166
+ }
4167
+ /** The parts of `[start, end)` under `copy`'s bound that its publisher skipped. */
4168
+ function copySkips(copy, start, end) {
4169
+ const bound = copyEnd(copy);
4170
+ const to = bound === undefined ? end : min(end, bound);
4171
+ return start < to ? hooks.skippedIn(copy.sub, start, to) : [];
4172
+ }
4173
+ //# sourceMappingURL=resume.js.map