@moq/net 0.4.8 → 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 (662) 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 -1
  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 -31
  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 -138
  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 -1
  33. package/bandwidth_api.js.map +1 -1
  34. package/broadcast.d.ts +62 -36
  35. package/broadcast.d.ts.map +1 -1
  36. package/broadcast.js +556 -172
  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 +20 -12
  47. package/connection/accept.d.ts.map +1 -1
  48. package/connection/accept.js +97 -129
  49. package/connection/accept.js.map +1 -1
  50. package/connection/browser.d.ts.map +1 -1
  51. package/connection/browser.js +28 -19
  52. package/connection/browser.js.map +1 -1
  53. package/connection/connect.d.ts +119 -23
  54. package/connection/connect.d.ts.map +1 -1
  55. package/connection/connect.js +535 -216
  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 -80
  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 -108
  72. package/connection/goaway.js.map +1 -1
  73. package/connection/handshake.d.ts +32 -6
  74. package/connection/handshake.d.ts.map +1 -1
  75. package/connection/handshake.js +97 -20
  76. package/connection/handshake.js.map +1 -1
  77. package/connection/index.d.ts +3 -6
  78. package/connection/index.d.ts.map +1 -1
  79. package/connection/index.js +1 -2
  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 +137 -58
  86. package/connection/pool.d.ts.map +1 -1
  87. package/connection/pool.js +281 -117
  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 -233
  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 -8
  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 -4
  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 -46
  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 -1
  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 -37
  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 -2
  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 -307
  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 -64
  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 -35
  199. package/ietf/aliases.js.map +1 -1
  200. package/ietf/cluster.d.ts +3 -3
  201. package/ietf/cluster.js +14 -62
  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 -143
  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 -100
  213. package/ietf/error.js.map +1 -1
  214. package/ietf/fetch.d.ts +91 -35
  215. package/ietf/fetch.d.ts.map +1 -1
  216. package/ietf/fetch.js +172 -93
  217. package/ietf/fetch.js.map +1 -1
  218. package/ietf/filter.d.ts +20 -30
  219. package/ietf/filter.d.ts.map +1 -1
  220. package/ietf/filter.js +140 -171
  221. package/ietf/filter.js.map +1 -1
  222. package/ietf/goaway.d.ts +11 -9
  223. package/ietf/goaway.d.ts.map +1 -1
  224. package/ietf/goaway.js +22 -35
  225. package/ietf/goaway.js.map +1 -1
  226. package/ietf/hidden.js +1 -1
  227. package/ietf/hidden.js.map +1 -1
  228. package/ietf/index.d.ts +2 -14
  229. package/ietf/index.d.ts.map +1 -1
  230. package/ietf/index.js +4 -14
  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 -40
  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 +17 -3
  245. package/ietf/namespace.d.ts.map +1 -1
  246. package/ietf/namespace.js +78 -26
  247. package/ietf/namespace.js.map +1 -1
  248. package/ietf/object.d.ts +194 -32
  249. package/ietf/object.d.ts.map +1 -1
  250. package/ietf/object.js +405 -178
  251. package/ietf/object.js.map +1 -1
  252. package/ietf/parameters.d.ts +22 -42
  253. package/ietf/parameters.d.ts.map +1 -1
  254. package/ietf/parameters.js +260 -472
  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 -4
  259. package/ietf/priority.js.map +1 -1
  260. package/ietf/properties.d.ts +5 -4
  261. package/ietf/properties.d.ts.map +1 -1
  262. package/ietf/properties.js +78 -48
  263. package/ietf/properties.js.map +1 -1
  264. package/ietf/publish.d.ts +22 -30
  265. package/ietf/publish.d.ts.map +1 -1
  266. package/ietf/publish.js +45 -139
  267. package/ietf/publish.js.map +1 -1
  268. package/ietf/publish_namespace.d.ts +46 -69
  269. package/ietf/publish_namespace.d.ts.map +1 -1
  270. package/ietf/publish_namespace.js +66 -184
  271. package/ietf/publish_namespace.js.map +1 -1
  272. package/ietf/publisher.js +1800 -600
  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 +3 -27
  279. package/ietf/request.d.ts.map +1 -1
  280. package/ietf/request.js +41 -78
  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 -16
  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 +4 -29
  291. package/ietf/setup.d.ts.map +1 -1
  292. package/ietf/setup.js +6 -117
  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 -14
  299. package/ietf/solicit.js.map +1 -1
  300. package/ietf/subscribe.d.ts +48 -41
  301. package/ietf/subscribe.d.ts.map +1 -1
  302. package/ietf/subscribe.js +118 -239
  303. package/ietf/subscribe.js.map +1 -1
  304. package/ietf/subscribe_namespace.d.ts +13 -76
  305. package/ietf/subscribe_namespace.d.ts.map +1 -1
  306. package/ietf/subscribe_namespace.js +30 -201
  307. package/ietf/subscribe_namespace.js.map +1 -1
  308. package/ietf/subscriber.js +1839 -536
  309. package/ietf/subscriber.js.map +1 -1
  310. package/ietf/token.js +105 -27
  311. package/ietf/token.js.map +1 -1
  312. package/ietf/track.d.ts +25 -22
  313. package/ietf/track.d.ts.map +1 -1
  314. package/ietf/track.js +48 -61
  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 -48
  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 +25 -10
  325. package/index.d.ts.map +1 -1
  326. package/index.js +19 -6
  327. package/index.js.map +1 -1
  328. package/internal.d.ts +1512 -64
  329. package/internal.d.ts.map +1 -1
  330. package/internal.js +557 -79
  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 +124 -63
  341. package/lite/announce.d.ts.map +1 -1
  342. package/lite/announce.js +384 -158
  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 -77
  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 -9
  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 +1 -1
  389. package/lite/goaway.d.ts.map +1 -1
  390. package/lite/goaway.js +5 -13
  391. package/lite/goaway.js.map +1 -1
  392. package/lite/group.d.ts +64 -13
  393. package/lite/group.d.ts.map +1 -1
  394. package/lite/group.js +108 -30
  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 +2 -1
  401. package/lite/index.d.ts.map +1 -1
  402. package/lite/index.js +2 -1
  403. package/lite/index.js.map +1 -1
  404. package/lite/message.d.ts +9 -1
  405. package/lite/message.d.ts.map +1 -1
  406. package/lite/message.js +28 -44
  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 -105
  411. package/lite/priority.js.map +1 -1
  412. package/lite/probe.d.ts.map +1 -1
  413. package/lite/probe.js +9 -0
  414. package/lite/probe.js.map +1 -1
  415. package/lite/publisher.d.ts +10 -1
  416. package/lite/publisher.d.ts.map +1 -1
  417. package/lite/publisher.js +2548 -437
  418. package/lite/publisher.js.map +1 -1
  419. package/lite/routed.d.ts +59 -0
  420. package/lite/routed.d.ts.map +1 -0
  421. package/lite/routed.js +564 -0
  422. package/lite/routed.js.map +1 -0
  423. package/lite/session.d.ts +1 -27
  424. package/lite/session.d.ts.map +1 -1
  425. package/lite/session.js +0 -99
  426. package/lite/session.js.map +1 -1
  427. package/lite/setup.d.ts +29 -2
  428. package/lite/setup.d.ts.map +1 -1
  429. package/lite/setup.js +95 -21
  430. package/lite/setup.js.map +1 -1
  431. package/lite/stream.d.ts +5 -11
  432. package/lite/stream.d.ts.map +1 -1
  433. package/lite/stream.js +5 -1
  434. package/lite/stream.js.map +1 -1
  435. package/lite/subscribe.d.ts +475 -75
  436. package/lite/subscribe.d.ts.map +1 -1
  437. package/lite/subscribe.js +1373 -142
  438. package/lite/subscribe.js.map +1 -1
  439. package/lite/subscriber.d.ts +7 -44
  440. package/lite/subscriber.d.ts.map +1 -1
  441. package/lite/subscriber.js +3290 -515
  442. package/lite/subscriber.js.map +1 -1
  443. package/lite/track.d.ts +24 -9
  444. package/lite/track.d.ts.map +1 -1
  445. package/lite/track.js +116 -37
  446. package/lite/track.js.map +1 -1
  447. package/lite/tracks.d.ts +55 -0
  448. package/lite/tracks.d.ts.map +1 -0
  449. package/lite/tracks.js +114 -0
  450. package/lite/tracks.js.map +1 -0
  451. package/lite/version.d.ts +132 -24
  452. package/lite/version.d.ts.map +1 -1
  453. package/lite/version.js +378 -33
  454. package/lite/version.js.map +1 -1
  455. package/meta.d.ts +77 -0
  456. package/meta.d.ts.map +1 -0
  457. package/meta.js +130 -0
  458. package/meta.js.map +1 -0
  459. package/meta_api.d.ts +7 -0
  460. package/meta_api.d.ts.map +1 -0
  461. package/meta_api.js +7 -0
  462. package/meta_api.js.map +1 -0
  463. package/mint.d.ts +28 -0
  464. package/mint.d.ts.map +1 -0
  465. package/mint.js +66 -0
  466. package/mint.js.map +1 -0
  467. package/open.d.ts +63 -0
  468. package/open.d.ts.map +1 -0
  469. package/open.js +250 -0
  470. package/open.js.map +1 -0
  471. package/origin.d.ts +392 -140
  472. package/origin.d.ts.map +1 -1
  473. package/origin.js +2533 -686
  474. package/origin.js.map +1 -1
  475. package/package.json +8 -13
  476. package/path.d.ts +51 -51
  477. package/path.d.ts.map +1 -1
  478. package/path.js +210 -57
  479. package/path.js.map +1 -1
  480. package/payload.d.ts +33 -0
  481. package/payload.d.ts.map +1 -0
  482. package/payload.js +65 -0
  483. package/payload.js.map +1 -0
  484. package/prefix.d.ts +152 -0
  485. package/prefix.d.ts.map +1 -0
  486. package/prefix.js +349 -0
  487. package/prefix.js.map +1 -0
  488. package/priority.d.ts +8 -0
  489. package/priority.d.ts.map +1 -0
  490. package/priority.js +185 -0
  491. package/priority.js.map +1 -0
  492. package/queue.d.ts +2 -0
  493. package/queue.d.ts.map +1 -0
  494. package/queue.js +46 -0
  495. package/queue.js.map +1 -0
  496. package/ranges.d.ts +36 -0
  497. package/ranges.d.ts.map +1 -0
  498. package/ranges.js +312 -0
  499. package/ranges.js.map +1 -0
  500. package/rescale.d.ts +24 -0
  501. package/rescale.d.ts.map +1 -0
  502. package/rescale.js +39 -0
  503. package/rescale.js.map +1 -0
  504. package/resume.d.ts +55 -0
  505. package/resume.d.ts.map +1 -0
  506. package/resume.js +4173 -0
  507. package/resume.js.map +1 -0
  508. package/resume.test-util.d.ts +2 -0
  509. package/resume.test-util.d.ts.map +1 -0
  510. package/resume.test-util.js +25 -0
  511. package/resume.test-util.js.map +1 -0
  512. package/skips.d.ts +48 -0
  513. package/skips.d.ts.map +1 -0
  514. package/skips.js +182 -0
  515. package/skips.js.map +1 -0
  516. package/stream.d.ts +75 -37
  517. package/stream.d.ts.map +1 -1
  518. package/stream.js +236 -92
  519. package/stream.js.map +1 -1
  520. package/subscription.test-util.d.ts +2 -0
  521. package/subscription.test-util.d.ts.map +1 -0
  522. package/subscription.test-util.js +49 -0
  523. package/subscription.test-util.js.map +1 -0
  524. package/tail.d.ts +23 -14
  525. package/tail.d.ts.map +1 -1
  526. package/tail.js +224 -97
  527. package/tail.js.map +1 -1
  528. package/time.d.ts +41 -102
  529. package/time.d.ts.map +1 -1
  530. package/time.js +129 -91
  531. package/time.js.map +1 -1
  532. package/timed.d.ts +21 -0
  533. package/timed.d.ts.map +1 -0
  534. package/timed.js +2 -0
  535. package/timed.js.map +1 -0
  536. package/track.d.ts +577 -245
  537. package/track.d.ts.map +1 -1
  538. package/track.js +7306 -771
  539. package/track.js.map +1 -1
  540. package/track_api.d.ts +7 -0
  541. package/track_api.d.ts.map +1 -0
  542. package/track_api.js +7 -0
  543. package/track_api.js.map +1 -0
  544. package/util/abort.d.ts +1 -0
  545. package/util/abort.d.ts.map +1 -1
  546. package/util/abort.js +23 -1
  547. package/util/abort.js.map +1 -1
  548. package/util/announce.d.ts +4 -0
  549. package/util/announce.d.ts.map +1 -0
  550. package/util/announce.js +11 -0
  551. package/util/announce.js.map +1 -0
  552. package/util/bigint.d.ts +3 -0
  553. package/util/bigint.d.ts.map +1 -0
  554. package/util/bigint.js +8 -0
  555. package/util/bigint.js.map +1 -0
  556. package/util/change.d.ts +12 -0
  557. package/util/change.d.ts.map +1 -0
  558. package/util/change.js +18 -0
  559. package/util/change.js.map +1 -0
  560. package/util/deadline.d.ts +2 -0
  561. package/util/deadline.d.ts.map +1 -0
  562. package/util/deadline.js +108 -0
  563. package/util/deadline.js.map +1 -0
  564. package/util/decode_error.d.ts +3 -0
  565. package/util/decode_error.d.ts.map +1 -0
  566. package/util/decode_error.js +11 -0
  567. package/util/decode_error.js.map +1 -0
  568. package/util/demand.d.ts +8 -0
  569. package/util/demand.d.ts.map +1 -0
  570. package/util/demand.js +24 -0
  571. package/util/demand.js.map +1 -0
  572. package/util/given_up.d.ts +2 -0
  573. package/util/given_up.d.ts.map +1 -0
  574. package/util/given_up.js +101 -0
  575. package/util/given_up.js.map +1 -0
  576. package/util/hex.d.ts +6 -0
  577. package/util/hex.d.ts.map +1 -1
  578. package/util/hex.js +19 -4
  579. package/util/hex.js.map +1 -1
  580. package/util/key.d.ts +15 -0
  581. package/util/key.d.ts.map +1 -0
  582. package/util/key.js +38 -0
  583. package/util/key.js.map +1 -0
  584. package/util/limits.d.ts +2 -0
  585. package/util/limits.d.ts.map +1 -0
  586. package/util/limits.js +76 -0
  587. package/util/limits.js.map +1 -0
  588. package/util/observed.d.ts +23 -0
  589. package/util/observed.d.ts.map +1 -0
  590. package/util/observed.js +122 -0
  591. package/util/observed.js.map +1 -0
  592. package/util/sorted.d.ts +2 -0
  593. package/util/sorted.d.ts.map +1 -0
  594. package/util/sorted.js +149 -0
  595. package/util/sorted.js.map +1 -0
  596. package/util/timeout.d.ts +2 -1
  597. package/util/timeout.d.ts.map +1 -1
  598. package/util/timeout.js +13 -9
  599. package/util/timeout.js.map +1 -1
  600. package/util/timer.d.ts +2 -0
  601. package/util/timer.d.ts.map +1 -0
  602. package/util/timer.js +19 -0
  603. package/util/timer.js.map +1 -0
  604. package/util/utf8.d.ts +2 -0
  605. package/util/utf8.d.ts.map +1 -1
  606. package/util/utf8.js +7 -1
  607. package/util/utf8.js.map +1 -1
  608. package/util/varint.d.ts.map +1 -1
  609. package/util/varint.js +8 -1
  610. package/util/varint.js.map +1 -1
  611. package/util/watch.d.ts +8 -0
  612. package/util/watch.d.ts.map +1 -0
  613. package/util/watch.js +38 -0
  614. package/util/watch.js.map +1 -0
  615. package/util/yield.d.ts +2 -0
  616. package/util/yield.d.ts.map +1 -0
  617. package/util/yield.js +31 -0
  618. package/util/yield.js.map +1 -0
  619. package/varint.d.ts +0 -29
  620. package/varint.d.ts.map +1 -1
  621. package/varint.js +7 -28
  622. package/varint.js.map +1 -1
  623. package/varint_api.d.ts +7 -0
  624. package/varint_api.d.ts.map +1 -0
  625. package/varint_api.js +7 -0
  626. package/varint_api.js.map +1 -0
  627. package/version.d.ts +2 -0
  628. package/version.d.ts.map +1 -0
  629. package/version.js +4 -0
  630. package/version.js.map +1 -0
  631. package/window.d.ts +570 -0
  632. package/window.d.ts.map +1 -0
  633. package/window.js +1677 -0
  634. package/window.js.map +1 -0
  635. package/wire.d.ts +145 -30
  636. package/wire.d.ts.map +1 -1
  637. package/wire.js +27 -0
  638. package/wire.js.map +1 -1
  639. package/connection/established.d.ts +0 -53
  640. package/connection/established.d.ts.map +0 -1
  641. package/connection/established.js +0 -2
  642. package/connection/established.js.map +0 -1
  643. package/ietf/adapter.d.ts +0 -75
  644. package/ietf/adapter.d.ts.map +0 -1
  645. package/ietf/adapter.js +0 -699
  646. package/ietf/adapter.js.map +0 -1
  647. package/lite/datagram_stream.d.ts +0 -8
  648. package/lite/datagram_stream.d.ts.map +0 -1
  649. package/lite/datagram_stream.js +0 -43
  650. package/lite/datagram_stream.js.map +0 -1
  651. package/lite/fetch.d.ts +0 -28
  652. package/lite/fetch.d.ts.map +0 -1
  653. package/lite/fetch.js +0 -78
  654. package/lite/fetch.js.map +0 -1
  655. package/util/log.d.ts +0 -5
  656. package/util/log.d.ts.map +0 -1
  657. package/util/log.js +0 -16
  658. package/util/log.js.map +0 -1
  659. package/zod.d.ts +0 -13
  660. package/zod.d.ts.map +0 -1
  661. package/zod.js +0 -18
  662. package/zod.js.map +0 -1
package/group.js CHANGED
@@ -3,42 +3,257 @@
3
3
  *
4
4
  * @module
5
5
  */
6
- import { Once, Signal } from "@moq/signals";
7
- import { FrameTooLarge, GroupTooLarge, TooFarBehind } from "./error.js";
8
- import { hooks } from "./internal.js";
9
- import { Timestamp } from "./time.js";
10
- /** Maximum bytes of frames in a group. A write that would exceed this aborts with {@link GroupTooLarge}. */
11
- export const MAX_GROUP_CACHE_BYTES = 32 * 1024 * 1024;
12
- /** Maximum number of frames in a group. 8192 is the largest legal group; the 8193rd write is {@link GroupTooLarge}. */
13
- export const MAX_GROUP_FRAMES = 8192;
6
+ import { now } from "@moq/clock";
7
+ import { Derived, Once, race, Signal } from "@moq/signals";
8
+ import { FrameTooLarge, ProtocolViolation, StreamCode, StreamError, TimestampMismatch } from "./error.js";
9
+ import { Compression, encodable, stored } from "./flate/group.js";
10
+ import { Chunked, chunkChanged, EMPTY, evicted, joined, makeConsumer as makeFrameConsumer, makeProducer as makeFrameProducer, payloadBytes, pollChunk, WAIT, } from "./frame.js";
11
+ import { timestampObjectId } from "./ietf/object.js";
12
+ import { hooks, } from "./internal.js";
13
+ import { Queue } from "./queue.js";
14
+ import { rescaleIn } from "./rescale.js";
15
+ import { floorAt } from "./time.js";
16
+ import { checkKey, RESERVED } from "./util/key.js";
17
+ import { MAX_FRAME_BYTES } from "./util/limits.js";
18
+ import { watchVia } from "./util/watch.js";
19
+ // A live tail budget, including a conservative charge for each frame's object and queue slot.
20
+ const TAIL_BYTES = 32 * 1024 * 1024;
21
+ const FRAME_BYTES = 256;
22
+ function frameBytes(frame) {
23
+ if (frame instanceof Chunked)
24
+ return FRAME_BYTES + frame.retained;
25
+ const slice = stored(frame);
26
+ return FRAME_BYTES + (slice ? slice.payload.length + slice.inflated : frame.payload.byteLength);
27
+ }
28
+ // Whether a frame's head was shed, so it can no longer be read from its start.
29
+ function headShed(frame) {
30
+ return frame instanceof Chunked && frame.base > 0;
31
+ }
14
32
  /** Reactive backing state shared by the group producer and one consumer. */
15
33
  class GroupState {
16
- sequence;
17
- frames = new Signal([]);
34
+ start;
35
+ frames = new Signal(new Queue());
18
36
  closed = new Once();
19
- total = new Signal(0); // The total number of frames in the group thus far
20
- // Absolute sequence of the frame at the front of `frames`, advanced by a read: the
21
- // sequence the next read returns.
22
- start = 0;
37
+ // Where the group ends, in its track's timescale, once its producer finished it whole: set
38
+ // before a clean `closed`, and undefined when it only closed.
39
+ end;
40
+ // Counts frames after they enter the queue. An open DEFLATE frame enters on commit.
41
+ total = new Signal(0);
42
+ // Mirrors share the source's open frame without holding its producer handle.
43
+ open = new Signal(undefined);
44
+ // Index of the frame at the front of `frames`, advanced by a read: the index the next
45
+ // read returns.
46
+ index = 0;
47
+ // The wire offset this copy began at; unlike `start`, reads never advance it.
48
+ offset = 0;
23
49
  cacheBytes = 0;
24
- // The first frame's timestamp, retained after reads.
50
+ // The source copy's access record in its track's cache, while cached. A mirror shares its
51
+ // source's, so its reads count as accesses.
52
+ charge;
53
+ compressed;
54
+ flate;
55
+ // The owning track's info, which every frame's timestamp must `rescaleIn` to: a timed track's
56
+ // frames carry a timestamp its scale holds, a scale-less track's the unscaled group key.
57
+ // Undefined for a group no track has claimed yet, which takes either.
58
+ track;
59
+ // The first frame's timestamp, retained after reads. Media time only: a scale-less group
60
+ // never has one, so it says nothing about whether a frame was written.
25
61
  timestamp;
26
- // The newest frame's timestamp: where a reader that has taken every frame sits.
62
+ // The highest frame timestamp, which is the last one.
27
63
  latest;
28
- constructor(sequence) {
29
- this.sequence = sequence;
64
+ // Accepted below the track's eviction watermark, where nothing proves where it starts,
65
+ // so this mirror drives no media-time expiry.
66
+ unverified = false;
67
+ // When the group joined the track this mirror belongs to, at this hop: the wall clock a
68
+ // superseded predecessor ages from. Per track, since one group can join several. A group
69
+ // no track holds arrived when it was created.
70
+ created = now();
71
+ // Called with the frame count on every write, synchronously: a track's largest must not
72
+ // trail a write that already returned, as a batched `total` notification would.
73
+ progress = new Set();
74
+ shedRead;
75
+ // Tells the group this copy was mirrored from whether its reader will still read it, so a
76
+ // copy buffered for a reader that passed it stops keeping the group wanted.
77
+ reads;
78
+ // Stops the group teeing into this mirror from watching it close.
79
+ unwatch;
80
+ // The first frame the group teeing into this mirror wrote here. A copy that took over a failed
81
+ // one tees from where that one stopped, so the frames below came from the failed copy.
82
+ from = 0;
83
+ // The last frame whose moq-timestamp Object ID was derived from frame 0, with that ID, so a
84
+ // join's Largest Object resumes the derivation instead of redoing it (see `timedId`). Shared
85
+ // with every mirror, which holds the same frame objects at the same indices, so each join's
86
+ // fresh mirror resumes it too. Valid while that frame object still sits at its index: a
87
+ // mirror can drop a frame cut short. Weak, so a frame shed from the tail frees its payload.
88
+ timedLast = {};
89
+ constructor(start) {
90
+ this.start = start;
91
+ }
92
+ get pendingHeader() {
93
+ if (!this.flate || this.closed.peek() !== undefined)
94
+ return undefined;
95
+ const open = this.open.peek();
96
+ return open?.kind === "deflate" && open.index === this.total.peek() ? open : undefined;
97
+ }
98
+ get frameCount() {
99
+ return this.total.peek() + Number(this.pendingHeader !== undefined);
100
+ }
101
+ get firstTimestamp() {
102
+ const stamp = this.pendingHeader?.info.timestamp;
103
+ return this.timestamp ?? (stamp?.scale !== undefined ? stamp : undefined);
104
+ }
105
+ get latestTimestamp() {
106
+ const header = this.pendingHeader;
107
+ if (!header)
108
+ return this.latest;
109
+ const stamp = header.info.timestamp;
110
+ return stamp.scale === undefined ? undefined : stamp;
30
111
  }
31
112
  }
113
+ // A written frame and when it landed. It keeps the writer's frame rather than copying it, so a
114
+ // lazy payload is read only when a reader takes it.
115
+ class Landed {
116
+ created;
117
+ #frame;
118
+ constructor(frame, created) {
119
+ this.#frame = frame;
120
+ this.created = created;
121
+ }
122
+ get payload() {
123
+ return this.#frame.payload;
124
+ }
125
+ get timestamp() {
126
+ return this.#frame.timestamp;
127
+ }
128
+ }
129
+ // A metadata copy's frame: its header alone, an empty payload with the declared plain size
130
+ // beside it, as a metadata subscription delivers it.
131
+ class Header {
132
+ payload = EMPTY;
133
+ timestamp;
134
+ size;
135
+ created;
136
+ constructor(timestamp, size, created) {
137
+ this.timestamp = timestamp;
138
+ this.size = size;
139
+ this.created = created;
140
+ }
141
+ }
142
+ // Refuse a frame whose timestamp the track's timeline refuses, or that names another group's key.
143
+ function checkTimed(track, start, frame) {
144
+ if (track)
145
+ rescaleIn(track, frame.timestamp, start);
146
+ }
147
+ /**
148
+ * The moq-timestamp Object IDs (draft-lcurley-moq-timestamp) of the frames `state` holds, in order
149
+ * from frame 0, with each timestamp in `timescale`: undefined when it no longer holds frame 0, so
150
+ * nothing proves them. Mirrors the Rust `GroupState::timed_ids`.
151
+ */
152
+ function timedIds(state, timescale) {
153
+ if (state.index !== 0)
154
+ return undefined;
155
+ const ids = [];
156
+ let prior;
157
+ for (const frame of state.frames.peek()) {
158
+ if (frame.timestamp.scale === undefined)
159
+ return undefined;
160
+ prior = timestampObjectId(state.start, prior, BigInt(floorAt(frame.timestamp, timescale))).id;
161
+ ids.push(prior);
162
+ }
163
+ const header = state.pendingHeader;
164
+ if (header) {
165
+ const stamp = header.info.timestamp;
166
+ if (stamp.scale === undefined)
167
+ return undefined;
168
+ ids.push(timestampObjectId(state.start, prior, BigInt(floorAt(stamp, timescale))).id);
169
+ }
170
+ return ids;
171
+ }
172
+ /**
173
+ * The moq-timestamp Object ID of frame `index`, as `timedIds` derives it, resumed from the last
174
+ * one derived. Mirrors the Rust `GroupState::timed_id`.
175
+ */
176
+ function timedId(state, timescale, index) {
177
+ if (state.index !== 0 || index < 0)
178
+ return undefined;
179
+ const frames = state.frames.peek();
180
+ const memo = state.timedLast.current;
181
+ const held = memo?.frame.deref();
182
+ const resume = memo !== undefined &&
183
+ held !== undefined &&
184
+ memo.timescale === timescale &&
185
+ memo.index <= index &&
186
+ frames.at(memo.index) === held;
187
+ let prior = resume ? memo.id : undefined;
188
+ // The last queued frame derived, published once the scan ends: one weak reference per lookup.
189
+ let last;
190
+ for (let at = resume ? memo.index + 1 : 0; at <= index; at++) {
191
+ const frame = frames.at(at);
192
+ // The open DEFLATE frame's header counts at its index before the frame enters the queue.
193
+ const header = at === frames.length ? state.pendingHeader : undefined;
194
+ const stamp = frame?.timestamp ?? header?.info.timestamp;
195
+ if (stamp?.scale === undefined)
196
+ return undefined;
197
+ prior = timestampObjectId(state.start, prior, BigInt(floorAt(stamp, timescale))).id;
198
+ if (frame)
199
+ last = { index: at, frame, id: prior };
200
+ }
201
+ if (last)
202
+ state.timedLast.current = { timescale, index: last.index, frame: new WeakRef(last.frame), id: last.id };
203
+ return prior;
204
+ }
32
205
  function appendFrame(state, frame) {
33
206
  if (state.closed.peek() !== undefined)
34
207
  throw new Error("group is closed");
35
- state.timestamp ??= frame.timestamp;
36
- state.latest = frame.timestamp;
37
- state.cacheBytes += frame.payload.byteLength;
38
- state.frames.mutate((frames) => {
39
- frames.push(frame);
40
- });
41
- state.total.update((total) => total + 1);
208
+ // Media time only: a scale-less frame's key says nothing about when it presents.
209
+ const timed = frame.timestamp.scale === undefined ? undefined : frame.timestamp;
210
+ state.timestamp ??= timed;
211
+ if (timed === undefined)
212
+ state.latest = undefined;
213
+ else if (state.latest === undefined || state.latest.isBefore(timed))
214
+ state.latest = timed;
215
+ const index = state.total.peek();
216
+ // A metadata reader that took the open frame's header has already passed this index.
217
+ if (index >= state.index) {
218
+ state.frames.mutate((frames) => {
219
+ frames.push(frame);
220
+ });
221
+ }
222
+ state.total.set(index + 1);
223
+ for (const fn of state.progress)
224
+ fn(index + 1);
225
+ }
226
+ let makeDemand;
227
+ /**
228
+ * A watch-only view of a group's mirror readers, including coalesced fetches.
229
+ *
230
+ * @internal The sessions' own fetch coalescing is its only consumer.
231
+ */
232
+ export class Demand {
233
+ /** The start of the group this handle watches. */
234
+ start;
235
+ #wanted;
236
+ #state;
237
+ constructor(start, wanted, state) {
238
+ this.start = start;
239
+ this.#wanted = wanted;
240
+ this.#state = state;
241
+ }
242
+ static {
243
+ makeDemand = (start, wanted, state) => new Demand(start, wanted, state);
244
+ }
245
+ /**
246
+ * Whether a reader will still read the group: a mirror handed out or fetched, or one a track
247
+ * buffers for a reader that has yet to reach it. Mirrors the Rust fill's held runs plus its
248
+ * group consumers.
249
+ */
250
+ get wanted() {
251
+ return this.#wanted;
252
+ }
253
+ /** The group's clean close or abort error. */
254
+ get closed() {
255
+ return this.#state.closed;
256
+ }
42
257
  }
43
258
  /**
44
259
  * The write side of an ordered stream of frames within a track.
@@ -46,28 +261,249 @@ function appendFrame(state, frame) {
46
261
  * @public
47
262
  */
48
263
  export class Producer {
49
- /** Sequence number of this group within its track. */
50
- sequence;
264
+ /** Where this group starts, in its track's timescale: its key on the track. */
265
+ start;
51
266
  #state;
267
+ // Each open mirror, with whether its reader will still read it.
52
268
  #mirrors;
53
- // Whether any mirror reader is attached (see {@link used}). Fetch coalescing watches it to
269
+ // How many open mirrors a reader will still read.
270
+ #readers = 0;
271
+ // Whether a reader will still read it (see {@link Demand.wanted}). Fetch coalescing watches it to
54
272
  // cancel an abandoned download; a group can stay open indefinitely (a catalog or JSON stream),
55
273
  // so this is what stops a reader-less fetch instead of the stream ending on its own.
56
- #used = new Signal(false);
57
- // When the group was created or last written. Retention ages a group from this,
58
- // not from its creation, so a group still being filled is never reclaimed.
59
- #activity = performance.now();
60
- constructor(sequence) {
61
- this.#state = new GroupState(sequence);
62
- this.sequence = sequence;
274
+ #wanted = new Signal(false);
275
+ #demand;
276
+ // Exclusive cap on the frame count, set when the track ends inside this group: a write
277
+ // past the track's end is refused rather than served as content that does not exist.
278
+ #limit;
279
+ // The tracks this group joined before its first frame, each checking that frame's
280
+ // timestamp against its neighbors' starts.
281
+ #admits;
282
+ // Called as the group aborts, before any signal subscriber runs (see `hooks.onGroupAbort`).
283
+ #aborted;
284
+ // Duplicates waiting on this received copy (see `hooks.holdGroup`). Failing while held, it
285
+ // keeps its mirrors open for the duplicate that takes over to tee into.
286
+ #holds = 0;
287
+ // Whether a timed frame 0 must sit at the group's key (see `hooks.keyGroup`).
288
+ #keyed = false;
289
+ // A metadata copy, holding each frame's header alone (see `hooks.metaGroup`).
290
+ #meta = false;
291
+ constructor(start) {
292
+ if (checkKey(start) >= RESERVED)
293
+ throw new RangeError(`group start out of range: ${start}`);
294
+ this.#state = new GroupState(start);
295
+ this.start = start;
296
+ this.#demand = makeDemand(start, this.#wanted, this.#state);
63
297
  }
64
- /**
65
- * When the group was created or last written, in `performance.now()` milliseconds.
66
- *
67
- * @internal Track retention only.
68
- */
69
- get activity() {
70
- return this.#activity;
298
+ static {
299
+ hooks.bindGroupCompression = (group, compressed) => {
300
+ // A metadata copy holds no payload to compress, whatever its track declares.
301
+ if (group.#meta)
302
+ return;
303
+ const state = group.#state;
304
+ if (state.compressed === compressed)
305
+ return;
306
+ if (state.compressed !== undefined)
307
+ throw new ProtocolViolation("group compression disagrees with its track");
308
+ if (compressed && state.index !== 0)
309
+ throw new ProtocolViolation("compressed group lacks its prefix");
310
+ if (compressed && Array.from(state.frames.peek()).some((frame) => frame instanceof Chunked))
311
+ throw new ProtocolViolation("compressed group holds a streamed frame");
312
+ // A frame written before the track chose compression is encoded and sent whole too.
313
+ if (compressed && Array.from(state.frames.peek()).some((frame) => !encodable(frame.payload.byteLength)))
314
+ throw new FrameTooLarge();
315
+ state.compressed = compressed;
316
+ if (!compressed)
317
+ return;
318
+ const flate = new Compression();
319
+ flate.failed = (error) => group.#end(error);
320
+ state.flate = flate;
321
+ const frames = Array.from(state.frames.peek(), (frame) => flate.push(frame));
322
+ state.frames.set(new Queue(frames));
323
+ state.cacheBytes = frames.reduce((bytes, frame) => bytes + frameBytes(frame), 0);
324
+ for (const mirror of group.#mirrors?.keys() ?? []) {
325
+ mirror.frames.set(new Queue(frames.slice(mirror.index - state.index)));
326
+ mirror.flate = flate;
327
+ mirror.compressed = true;
328
+ }
329
+ group.#trim();
330
+ if (state.closed.peek() !== undefined)
331
+ flate.finish();
332
+ };
333
+ hooks.groupOffset = (group) => group.#state.offset;
334
+ hooks.groupWholeEnd = (group) => (group.#state.closed.peek() === null ? group.#state.end : undefined);
335
+ hooks.groupSpan = (group) => {
336
+ const state = group.#state;
337
+ const closed = state.closed.peek();
338
+ return {
339
+ started: state.frameCount > state.offset || closed !== undefined,
340
+ failed: closed instanceof Error,
341
+ first: state.unverified || state.offset !== 0 ? undefined : state.firstTimestamp,
342
+ latest: state.unverified ? undefined : state.latestTimestamp,
343
+ };
344
+ };
345
+ hooks.groupUnplacedFrom = (group) => group.#state.closed.peek() === null ? undefined : group.#highest(group.#state.latestTimestamp);
346
+ hooks.groupWrites = (group) => {
347
+ const state = group.#state;
348
+ return state.flate ? new Derived([state.total, state.open], () => state.frameCount) : state.total;
349
+ };
350
+ hooks.groupHeadless = (group) => group.#state.index > 0 || headShed(group.#state.frames.peek().first);
351
+ hooks.holdGroup = (group) => {
352
+ group.#holds++;
353
+ let held = true;
354
+ return () => {
355
+ if (!held)
356
+ return;
357
+ held = false;
358
+ if (--group.#holds === 0)
359
+ group.#failHeld();
360
+ };
361
+ };
362
+ hooks.succeedGroup = (next, failed) => {
363
+ const error = failed.#state.closed.peek();
364
+ if (!(error instanceof Error))
365
+ throw new Error("group has not failed");
366
+ const state = next.#state;
367
+ for (const [mirror, reads] of failed.#mirrors ?? []) {
368
+ failed.#unmirror(mirror);
369
+ // The successor continues a mirror from the frame it reached, so it must hold that
370
+ // frame from its start. Compression binds a group to its prefix, so a compressed
371
+ // successor starts at 0.
372
+ if (mirror.closed.peek() !== undefined)
373
+ continue;
374
+ const lost = state.index === mirror.total.peek() && headShed(state.frames.peek().first);
375
+ if (state.closed.peek() !== undefined || state.index > mirror.total.peek() || lost) {
376
+ mirror.closed.set(error);
377
+ continue;
378
+ }
379
+ // Its unread frames count against the tail it continues in, as they would on one copy, so a
380
+ // chain of takeovers cannot grow a stalled reader's buffer: past the tail, it is behind it.
381
+ let unread = 0;
382
+ for (const frame of mirror.frames.peek())
383
+ unread += frameBytes(frame);
384
+ if (unread > TAIL_BYTES) {
385
+ mirror.frames.set(new Queue());
386
+ mirror.cacheBytes = 0;
387
+ mirror.flate = undefined;
388
+ mirror.closed.set(evicted());
389
+ continue;
390
+ }
391
+ mirror.from = mirror.total.peek();
392
+ mirror.charge = state.charge;
393
+ if (state.compressed) {
394
+ mirror.flate = state.flate;
395
+ mirror.open = state.open;
396
+ // A reader may still be watching the replaced copy's open-frame signal.
397
+ mirror.frames.mutate(() => { });
398
+ }
399
+ let index = state.index;
400
+ for (const frame of state.frames.peek())
401
+ if (index++ >= mirror.from)
402
+ appendFrame(mirror, frame);
403
+ next.#attach(mirror, reads);
404
+ }
405
+ };
406
+ hooks.startGroup = (group, start) => {
407
+ if (!Number.isSafeInteger(start) || start < 0)
408
+ throw new RangeError("invalid group frame start");
409
+ const state = group.#state;
410
+ if (state.total.peek() !== 0 || state.closed.peek() !== undefined || group.#mirrors?.size)
411
+ throw new Error("group already started");
412
+ if (start !== 0 && state.compressed)
413
+ throw new ProtocolViolation("compressed group lacks its prefix");
414
+ state.index = state.offset = start;
415
+ state.total.set(start);
416
+ };
417
+ hooks.writeGroupFrame = (group, frame, inflated) => group.#writeFrame(frame, inflated);
418
+ hooks.metaGroup = (group) => {
419
+ const state = group.#state;
420
+ if (state.total.peek() !== 0 || state.closed.peek() !== undefined || state.compressed !== undefined)
421
+ throw new Error("group already started");
422
+ group.#meta = true;
423
+ };
424
+ hooks.groupMeta = (group) => group.#meta;
425
+ hooks.keyGroup = (group) => {
426
+ group.#keyed = true;
427
+ };
428
+ hooks.writeGroupHeader = (group, timestamp, size) => group.#writeHeader(timestamp, size);
429
+ hooks.groupCacheBytes = (group) => group.#state.flate?.bytes ?? group.#state.cacheBytes;
430
+ hooks.groupFrameCount = (group) => group.#state.frameCount;
431
+ hooks.groupLastTimedId = (group, timescale) => {
432
+ const state = group.#state;
433
+ const last = state.frameCount - 1;
434
+ if (last < 0)
435
+ return undefined;
436
+ const id = timedId(state, timescale, last);
437
+ if (id !== undefined)
438
+ return id;
439
+ // A copy without frame 0 answers its last timestamp's offset, which the ID is never below.
440
+ const latest = state.latestTimestamp;
441
+ if (latest === undefined)
442
+ return undefined;
443
+ const offset = BigInt(floorAt(latest, timescale)) - state.start;
444
+ return offset > 0n ? offset : 0n;
445
+ };
446
+ hooks.groupSourceTimedId = (group, index, timescale) => timedId(group.#state, timescale, index);
447
+ hooks.groupTimedFrame = (group, id, timescale) => {
448
+ const state = group.#state;
449
+ const ids = timedIds(state, timescale);
450
+ if (!ids)
451
+ return undefined;
452
+ const index = ids.findIndex((timed) => timed >= id);
453
+ return index === -1 ? state.frameCount : index;
454
+ };
455
+ hooks.groupProgress = (group, fn) => {
456
+ const state = group.#state;
457
+ fn(state.frameCount);
458
+ state.progress.add(fn);
459
+ return () => state.progress.delete(fn);
460
+ };
461
+ hooks.bindGroupTimed = (group, track) => {
462
+ const state = group.#state;
463
+ const timed = track.timescale != null;
464
+ if (state.track !== undefined && (state.track.timescale != null) === timed)
465
+ return;
466
+ // Another track already holds it to the opposite timedness, empty or not.
467
+ if (state.track !== undefined)
468
+ throw new TimestampMismatch();
469
+ for (const frame of state.frames.peek())
470
+ checkTimed(track, state.start, frame);
471
+ state.track = track;
472
+ };
473
+ hooks.admitGroupStart = (group, admit) => {
474
+ group.#admits ??= [];
475
+ group.#admits.push(admit);
476
+ };
477
+ hooks.onGroupAbort = (group, fn) => {
478
+ group.#aborted ??= [];
479
+ group.#aborted.push(fn);
480
+ };
481
+ hooks.abortGroup = (group, error) => group.#end(error);
482
+ hooks.overRefresh = (group, ratio) => {
483
+ const state = group.#state;
484
+ if (state.offset !== 0)
485
+ return false;
486
+ const first = state.frames.peek().first;
487
+ // A shed front, whole frames or the first frame's head, cannot be replayed.
488
+ if (state.index > 0 || headShed(first))
489
+ return true;
490
+ if (first === undefined)
491
+ return false;
492
+ const head = payloadBytes(first);
493
+ const bytes = state.flate?.stored ?? state.cacheBytes - state.frames.peek().length * FRAME_BYTES;
494
+ return bytes - head > head * ratio;
495
+ };
496
+ hooks.chargeGroup = (group, charge) => {
497
+ group.#state.charge = charge;
498
+ };
499
+ hooks.limitGroup = (group, frames) => {
500
+ // A closed group takes no more frames, but one already past the cap still
501
+ // contradicts the end.
502
+ if (group.#state.frameCount > frames) {
503
+ throw new ProtocolViolation(`group ${group.start} already holds a frame past the track's end`);
504
+ }
505
+ group.#limit = frames;
506
+ };
71
507
  }
72
508
  /**
73
509
  * Settles once the group closes: `null` on a clean close, or the abort {@link Error}.
@@ -78,7 +514,7 @@ export class Producer {
78
514
  }
79
515
  /** A read handle for this group. */
80
516
  consume() {
81
- return makeConsumer(this.#state);
517
+ return this.mirror();
82
518
  }
83
519
  /**
84
520
  * Create an independent read handle that receives every frame written here.
@@ -89,180 +525,628 @@ export class Producer {
89
525
  * @internal Track fan-out and fetch coalescing only. Use {@link consume} instead.
90
526
  */
91
527
  mirror() {
92
- const dst = new GroupState(this.sequence);
528
+ const dst = new GroupState(this.start);
93
529
  dst.timestamp = this.#state.timestamp;
94
530
  dst.latest = this.#state.latest;
95
- for (const frame of this.#state.frames.peek())
96
- appendFrame(dst, frame);
97
- dst.start = this.#state.start;
531
+ dst.timedLast = this.#state.timedLast;
532
+ dst.flate = this.#state.flate;
533
+ dst.open = this.#state.open;
534
+ dst.compressed = this.#state.compressed;
535
+ dst.charge = this.#state.charge;
536
+ // A track restamps its own mirror with when the group joined it.
537
+ dst.created = this.#state.created;
538
+ if (this.#state.index === this.#state.offset && !headShed(this.#state.frames.peek().first)) {
539
+ for (const frame of this.#state.frames.peek())
540
+ appendFrame(dst, frame);
541
+ }
542
+ else {
543
+ dst.flate = undefined;
544
+ const closed = this.#state.closed.peek();
545
+ dst.closed.set(closed instanceof Error ? closed : evicted());
546
+ }
547
+ dst.index = dst.closed.peek() instanceof Error ? this.#state.offset : this.#state.index;
548
+ dst.offset = this.#state.offset;
98
549
  // The replay only covers what is still buffered, so the count has to come from the
99
- // source: it is what names a frame's absolute sequence, and what a publisher reads
550
+ // source: it is what names a frame's absolute index, and what a publisher reads
100
551
  // to resolve the live edge.
101
552
  dst.total.set(this.#state.total.peek());
553
+ if (dst.closed.peek() !== undefined)
554
+ return makeConsumer(dst);
102
555
  const closed = this.#state.closed.peek();
103
556
  if (closed !== undefined) {
557
+ dst.end = this.#state.end;
104
558
  dst.closed.set(closed);
105
559
  return makeConsumer(dst);
106
560
  }
107
- this.#mirrors ??= new Set();
108
- this.#mirrors.add(dst);
109
- this.#used.set(true);
561
+ this.#attach(dst, true);
562
+ return makeConsumer(dst);
563
+ }
564
+ // Tee later writes into `dst`, counting its reader if it `reads`.
565
+ #attach(dst, reads) {
566
+ this.#mirrors ??= new Map();
567
+ const mirrors = this.#mirrors;
568
+ mirrors.set(dst, reads);
569
+ if (reads)
570
+ this.#readers++;
571
+ this.#wanted.set(this.#readers > 0);
572
+ dst.reads = (reads) => {
573
+ const was = mirrors.get(dst);
574
+ if (was === undefined || was === reads)
575
+ return;
576
+ mirrors.set(dst, reads);
577
+ this.#readers += reads ? 1 : -1;
578
+ this.#wanted.set(this.#readers > 0);
579
+ };
110
580
  // Track this mirror's close eagerly (not just lazily on the next write) so demand drops the
111
581
  // moment the last reader leaves, letting an abandoned fetch cancel even with no more frames.
112
- const dispose = dst.closed.subscribe((c) => {
113
- if (c === undefined)
114
- return;
115
- this.#mirrors?.delete(dst);
116
- this.#used.set((this.#mirrors?.size ?? 0) > 0);
117
- dispose();
582
+ dst.unwatch = dst.closed.subscribe((c) => {
583
+ if (c !== undefined)
584
+ this.#unmirror(dst);
118
585
  });
119
- return makeConsumer(dst);
120
586
  }
121
587
  /**
122
- * Whether any mirror reader is currently attached.
588
+ * Watch the mirror readers attached to this group.
123
589
  *
124
- * Pairs with {@link unused}. Fetch coalescing watches it to cancel a download once every reader
125
- * has gone: a group can stay open indefinitely (a catalog track, a JSON stream), so it can't
126
- * rely on the stream ending on its own.
127
- *
128
- * @internal Track fan-out and fetch coalescing only.
590
+ * @internal The sessions' own fetch coalescing is its only consumer.
129
591
  */
130
- get used() {
131
- return this.#used;
592
+ demand() {
593
+ return this.#demand;
594
+ }
595
+ // Stop teeing into `mirror`, which closed, and stop counting its reader.
596
+ #unmirror(mirror) {
597
+ const reads = this.#mirrors?.get(mirror);
598
+ if (reads === undefined)
599
+ return;
600
+ this.#mirrors?.delete(mirror);
601
+ // A consumer that outlives the group must not pin it, and its buffers, through this.
602
+ mirror.reads = undefined;
603
+ mirror.unwatch?.();
604
+ mirror.unwatch = undefined;
605
+ if (reads)
606
+ this.#readers--;
607
+ this.#wanted.set(this.#readers > 0);
608
+ }
609
+ /** Writes a frame to the group. */
610
+ writeFrame(frame) {
611
+ this.#writeFrame(frame);
132
612
  }
133
613
  /**
134
- * Resolves once no mirror reader remains (or the group closes).
614
+ * Start a frame of `info.size` bytes, written in pieces, as Rust's `create_frame`.
135
615
  *
136
- * @internal Track fan-out and fetch coalescing only.
616
+ * Readers can stream it as it is written (see {@link Consumer.nextFrame}), so a frame
617
+ * of any size is held only within the group's retained tail. No other frame can be
618
+ * written until this one finishes.
137
619
  */
138
- async unused() {
139
- while (this.#used.peek() && this.#state.closed.peek() === undefined) {
140
- await Signal.race(this.#used, this.#state.closed);
620
+ createFrame(info) {
621
+ if (this.#meta)
622
+ throw new Error("a metadata group holds no payload");
623
+ const { size, timestamp } = info;
624
+ if (!Number.isSafeInteger(size) || size < 0)
625
+ throw new RangeError("invalid frame size");
626
+ const frame = { payload: EMPTY, timestamp };
627
+ const flate = this.#state.flate;
628
+ if (flate) {
629
+ // A compressed frame is encoded whole once written, as `writeFrame` does.
630
+ if (!encodable(size))
631
+ throw new FrameTooLarge();
632
+ const scaled = this.#rescale(frame);
633
+ const commits = this.#admit(scaled);
634
+ const pending = {
635
+ kind: "deflate",
636
+ index: this.#state.total.peek(),
637
+ info: { size, timestamp: scaled.timestamp },
638
+ };
639
+ const payload = new Uint8Array(size);
640
+ let written = 0;
641
+ const open = makeFrameProducer(info, {
642
+ written: () => written,
643
+ write: (chunk) => {
644
+ if (this.#state.open.peek() !== pending)
645
+ throw new Error("group is closed");
646
+ payload.set(chunk, written);
647
+ written += chunk.byteLength;
648
+ },
649
+ finish: () => {
650
+ if (this.#state.open.peek() !== pending)
651
+ throw new Error("group is closed");
652
+ const slice = flate.push(new Landed({ payload, timestamp: scaled.timestamp }, now()));
653
+ this.#state.open.set(undefined);
654
+ this.#append(slice, undefined);
655
+ return this;
656
+ },
657
+ abort: (error) => this.#end(error),
658
+ });
659
+ this.#state.open.set(pending);
660
+ this.#recordAdmission(commits);
661
+ for (const fn of this.#state.progress)
662
+ fn(pending.index + 1);
663
+ return open;
141
664
  }
665
+ const commits = this.#admit(frame);
666
+ const entry = new Chunked(info);
667
+ const pending = { kind: "plain", frame: entry };
668
+ this.#append(entry, commits);
669
+ const open = makeFrameProducer(info, {
670
+ written: () => entry.written.peek(),
671
+ write: (chunk) => {
672
+ if (this.#state.open.peek() !== pending)
673
+ throw new Error("group is closed");
674
+ const bytes = entry.write(chunk);
675
+ this.#state.cacheBytes += bytes;
676
+ this.#state.charge?.touch();
677
+ this.#trim();
678
+ this.#state.charge?.settle();
679
+ },
680
+ finish: () => {
681
+ if (this.#state.open.peek() !== pending)
682
+ throw new Error("group is closed");
683
+ this.#state.open.set(undefined);
684
+ entry.created = now();
685
+ this.#state.charge?.touch();
686
+ entry.done.set(null);
687
+ // Wake whole-frame readers waiting for it to complete.
688
+ this.#state.frames.mutate(() => { });
689
+ for (const mirror of this.#mirrors?.keys() ?? [])
690
+ mirror.frames.mutate(() => { });
691
+ return this;
692
+ },
693
+ abort: (error) => this.#end(error),
694
+ });
695
+ this.#state.open.set(pending);
696
+ return open;
142
697
  }
143
- /** Writes a frame to the group. */
144
- writeFrame(frame) {
145
- // Closed first: a write after a clean close at the cap would otherwise take the
146
- // overflow path, wipe committed frames, and leave readers with an empty success.
698
+ #writeFrame(frame, inflated) {
699
+ if (this.#meta)
700
+ throw new Error("a metadata group holds no payload");
701
+ // A plain frame written whole is the writer's own buffer, at any size. A compressed one
702
+ // is sent whole, so its slice must fit: a received one as declared, a local one encoded.
703
+ const size = frame.payload.byteLength;
704
+ if (this.#state.flate && (inflated === undefined ? !encodable(size) : size > MAX_FRAME_BYTES))
705
+ throw new FrameTooLarge();
706
+ if ((inflated ?? 0) > MAX_FRAME_BYTES)
707
+ throw new FrameTooLarge();
708
+ frame = this.#rescale(frame);
709
+ const commits = this.#admit(frame);
710
+ if (inflated !== undefined && (!this.#state.flate || !Number.isSafeInteger(inflated) || inflated < 0))
711
+ throw new ProtocolViolation("unexpected inflated frame size");
712
+ const created = now();
713
+ frame = new Landed(frame, created);
714
+ if (this.#state.flate) {
715
+ frame = this.#state.flate.push(frame, inflated);
716
+ }
717
+ this.#append(frame, commits);
718
+ }
719
+ // Write the header of a frame of `size` plain bytes into a metadata copy: no payload, so it
720
+ // costs the cache only its slot.
721
+ #writeHeader(timestamp, size) {
722
+ if (!this.#meta)
723
+ throw new Error("a payload group takes no header alone");
724
+ const frame = this.#rescale({ payload: EMPTY, timestamp });
725
+ const commits = this.#admit(frame);
726
+ this.#append(new Header(frame.timestamp, size, now()), commits);
727
+ }
728
+ // `frame` held in the track's timescale, rounded down, as Rust's `write_frame` holds it: two
729
+ // starts within one unit tie, as they do once on the wire.
730
+ #rescale(frame) {
731
+ const track = this.#state.track;
732
+ if (!track)
733
+ return frame;
734
+ const rescaled = rescaleIn(track, frame.timestamp, this.#state.start);
735
+ const moved = rescaled.scale !== frame.timestamp.scale || rescaled.value !== frame.timestamp.value;
736
+ return moved ? { payload: frame.payload, timestamp: rescaled } : frame;
737
+ }
738
+ // Check that the next frame may be written, returning what records its admission.
739
+ #admit(frame) {
740
+ // Refuse further writes before inspecting or changing committed content.
147
741
  if (this.#state.closed.peek() !== undefined)
148
742
  throw new Error("group is closed");
149
- // A frame past the cache cap would make the group exceed its budget by itself, so
150
- // accepting it would report success for a write nothing can ever read. Rust rejects
151
- // it up front with `Error::FrameTooLarge`; do the same rather than silently dropping it.
152
- if (frame.payload.byteLength > MAX_GROUP_CACHE_BYTES)
153
- throw new FrameTooLarge();
154
- if (this.#state.total.peek() >= MAX_GROUP_FRAMES ||
155
- this.#state.cacheBytes + frame.payload.byteLength > MAX_GROUP_CACHE_BYTES) {
156
- const err = new GroupTooLarge();
157
- this.#state.frames.set([]);
158
- this.#state.cacheBytes = 0;
159
- if (this.#mirrors) {
160
- for (const mirror of this.#mirrors) {
161
- mirror.frames.set([]);
162
- mirror.cacheBytes = 0;
163
- }
164
- }
165
- this.close(err);
166
- throw err;
743
+ if (this.#state.open.peek())
744
+ throw new Error("a frame is still being written");
745
+ if (this.#state.total.peek() === Number.MAX_SAFE_INTEGER)
746
+ throw new ProtocolViolation("group frame index exceeds the safe integer range");
747
+ checkTimed(this.#state.track, this.#state.start, frame);
748
+ // A group's timestamps never decrease, so lite-07 carries them as unsigned deltas and a
749
+ // moq-transport Object ID as their offset from the start.
750
+ const { latest, track } = this.#state;
751
+ if (latest !== undefined && frame.timestamp.scale !== undefined) {
752
+ // Compared as the wire carries them, at the track's timescale rounded down.
753
+ const below = track?.timescale == null
754
+ ? frame.timestamp.isBefore(latest)
755
+ : floorAt(frame.timestamp, track.timescale) < floorAt(latest, track.timescale);
756
+ if (below)
757
+ throw new TimestampMismatch();
167
758
  }
168
- this.#activity = performance.now();
759
+ if (this.#limit !== undefined && this.#state.total.peek() >= this.#limit) {
760
+ throw new Error(`frame ${this.#state.total.peek()} is past the track's end`);
761
+ }
762
+ // A keyed group's timed frame 0 sits at its key, which names the group, or lite-07 could
763
+ // not carry it.
764
+ if (this.#keyed &&
765
+ this.#state.total.peek() === 0 &&
766
+ track?.timescale != null &&
767
+ frame.timestamp.scale !== undefined &&
768
+ BigInt(floorAt(frame.timestamp, track.timescale)) !== this.#state.start)
769
+ throw new TimestampMismatch();
770
+ // Frame 0 must fit between its neighbors in every track it joined, checked before
771
+ // any of them records it, so a refusal leaves the group and its tracks as they were.
772
+ if (this.#admits && frame.timestamp.scale !== undefined && this.#state.total.peek() === 0) {
773
+ const start = frame.timestamp;
774
+ return this.#admits.map((admit) => admit(start));
775
+ }
776
+ return undefined;
777
+ }
778
+ #append(frame, commits) {
779
+ this.#state.cacheBytes += frameBytes(frame);
780
+ this.#state.charge?.touch();
169
781
  appendFrame(this.#state, frame);
170
- if (this.#mirrors) {
171
- for (const mirror of this.#mirrors) {
172
- if (mirror.closed.peek() !== undefined)
173
- this.#mirrors.delete(mirror);
174
- else
175
- appendFrame(mirror, frame);
782
+ this.#recordAdmission(commits);
783
+ const index = this.#state.total.peek() - 1;
784
+ for (const mirror of this.#mirrors?.keys() ?? []) {
785
+ if (mirror.closed.peek() !== undefined)
786
+ this.#unmirror(mirror);
787
+ // A mirror taken over from a failed copy already holds the frames that copy wrote.
788
+ else if (index >= mirror.total.peek())
789
+ appendFrame(mirror, frame);
790
+ }
791
+ this.#trim();
792
+ // Past the frame's own bookkeeping: the track's idle scan may evict other groups.
793
+ this.#state.charge?.settle();
794
+ }
795
+ #recordAdmission(commits) {
796
+ if (!commits)
797
+ return;
798
+ this.#admits = undefined;
799
+ for (const commit of commits)
800
+ commit();
801
+ }
802
+ // Shed the front past the live tail budget.
803
+ #trim() {
804
+ const state = this.#state;
805
+ const frames = state.frames.peek();
806
+ const bytes = state.cacheBytes;
807
+ while (state.cacheBytes > TAIL_BYTES) {
808
+ const front = frames.first;
809
+ if (!front)
810
+ break;
811
+ // A chunked front frame sheds its sealed segments first, keeping only its newest.
812
+ const freed = front instanceof Chunked ? front.shed() : 0;
813
+ if (freed > 0) {
814
+ state.cacheBytes -= freed;
815
+ continue;
176
816
  }
817
+ // The newest frame stays readable: its writer holds it whole anyway.
818
+ if (frames.length === 1)
819
+ break;
820
+ this.#shift();
177
821
  }
822
+ this.#shedMirrors(bytes);
178
823
  }
179
- /** Write a string as a single UTF-8 encoded frame, stamped with {@link Timestamp.now}. */
180
- writeString(str) {
181
- this.writeFrame({ payload: new TextEncoder().encode(str), timestamp: Timestamp.now() });
824
+ // Drop the front frame.
825
+ #shift() {
826
+ const state = this.#state;
827
+ const front = state.frames.peek().shift();
828
+ state.cacheBytes -= frameBytes(front);
829
+ if (front instanceof Chunked)
830
+ front.release();
831
+ state.index++;
182
832
  }
183
- /** Write a value as a single JSON-encoded frame, stamped with {@link Timestamp.now}. */
184
- writeJson(json) {
185
- this.writeString(JSON.stringify(json));
833
+ // Release what the front shed since it held `bytes`, and end the mirrors that can no longer
834
+ // read from their start.
835
+ #shedMirrors(bytes) {
836
+ const state = this.#state;
837
+ const frames = state.frames.peek();
838
+ if (state.cacheBytes === bytes)
839
+ return;
840
+ state.flate?.shed(state.index);
841
+ const lost = headShed(frames.first);
842
+ for (const mirror of this.#mirrors?.keys() ?? []) {
843
+ // A mirror that has not taken the front frame can no longer read it from its start.
844
+ if (mirror.closed.peek() !== undefined)
845
+ continue;
846
+ const front = Math.max(mirror.index, mirror.from);
847
+ if (front > state.index || (front === state.index && !lost))
848
+ continue;
849
+ mirror.frames.set(new Queue());
850
+ mirror.cacheBytes = 0;
851
+ mirror.flate = undefined;
852
+ mirror.closed.set(evicted());
853
+ this.#unmirror(mirror);
854
+ }
186
855
  }
187
- /** Write a boolean as a single one-byte frame, stamped with {@link Timestamp.now}. */
188
- writeBool(bool) {
189
- this.writeFrame({ payload: new Uint8Array([bool ? 1 : 0]), timestamp: Timestamp.now() });
856
+ /**
857
+ * Ends the group without saying where it ends, returning it as {@link Finished}: every frame
858
+ * written reaches its readers, but they can't tell the group is whole. Idempotent, as the
859
+ * Rust `group::Producer::finish`.
860
+ */
861
+ finish() {
862
+ this.#end(null);
863
+ return this;
190
864
  }
191
- /** True once the group has been closed. */
192
- get isClosed() {
193
- return this.#state.closed.peek() !== undefined;
865
+ /**
866
+ * Ends the group whole at `end`, the exclusive end of its presentation in the track's
867
+ * timescale, returning it as {@link Finished}, as the Rust `group::Producer::finish_at`. An
868
+ * `end` below the group's start, or below its highest frame timestamp, throws
869
+ * {@link TimestampMismatch}; one equal to either is accepted.
870
+ */
871
+ finishAt(end) {
872
+ if (end < this.start || end < this.#highest(this.#state.latest))
873
+ throw new TimestampMismatch();
874
+ if (this.#state.closed.peek() === undefined)
875
+ this.#state.end = end;
876
+ this.#end(null);
877
+ return this;
878
+ }
879
+ // The highest frame timestamp in the track's timescale, or the start when there is none to
880
+ // compare: no frame is timed, or no track says which timescale `end` is in.
881
+ #highest(latest) {
882
+ const track = this.#state.track;
883
+ if (latest === undefined || track?.timescale == null)
884
+ return this.start;
885
+ // A streamed frame keeps the timestamp it was created with, in any scale.
886
+ return BigInt(floorAt(latest, track.timescale));
887
+ }
888
+ /**
889
+ * Gives the group up for now, as dropping a Rust `group::Producer` unfinished does: readers that
890
+ * have not drained it end with `StreamCode.Cancel`, and the track lets it go as it would an
891
+ * evicted group, so a reader that still wants it asks a fill for it again, though an end declared
892
+ * above it settles clean only once the group is created again whole, skipped, or dropped. A no-op
893
+ * once the group finished, aborted, or skipped. Mirrors the Rust `group::Producer::abort`.
894
+ */
895
+ abort() {
896
+ this.#end(new StreamError(StreamCode.Cancel, { message: "group aborted" }));
194
897
  }
195
- /** Closes the group, optionally with an error to abort readers. */
196
- close(abort) {
898
+ /**
899
+ * Declares that the group will never exist: readers that have not drained it end with
900
+ * `StreamCode.Skip`, and its track records the key skipped for good, refusing to create it again,
901
+ * which a relay forwards. A no-op once the group finished, aborted, or skipped. Mirrors the Rust
902
+ * `group::Producer::skip`.
903
+ */
904
+ skip() {
905
+ this.#end(new StreamError(StreamCode.Skip, { message: "group skipped" }));
906
+ }
907
+ #end(outcome) {
197
908
  if (this.#state.closed.peek() !== undefined)
198
909
  return;
199
- this.#state.closed.set(abort ?? null);
200
- if (this.#mirrors) {
201
- for (const mirror of this.#mirrors) {
202
- if (mirror.closed.peek() === undefined)
203
- mirror.closed.set(abort ?? null);
910
+ // A frame cut short leaves the group incomplete, so even a clean end fails it.
911
+ let cut;
912
+ const open = this.#state.open.peek();
913
+ if (open) {
914
+ this.#state.open.set(undefined);
915
+ outcome ??= new Error("group finished while a frame was being written");
916
+ if (open.kind === "plain")
917
+ cut = open.frame;
918
+ }
919
+ const held = outcome !== null && this.#holds > 0;
920
+ // A held copy's duplicate continues each mirror from the frame it reached, so a mirror
921
+ // drops the frame cut short before its reader takes it. One whose reader took it lost it.
922
+ if (held && cut) {
923
+ const index = this.#state.total.peek() - 1;
924
+ for (const mirror of this.#mirrors?.keys() ?? []) {
925
+ // A mirror taken over past the cut frame never got it from this copy.
926
+ if (index < mirror.from)
927
+ continue;
928
+ if (mirror.frames.peek().last === cut) {
929
+ mirror.frames.mutate((frames) => frames.pop());
930
+ mirror.total.update((total) => total - 1);
931
+ }
932
+ else if (mirror.closed.peek() === undefined)
933
+ mirror.closed.set(outcome);
934
+ }
935
+ }
936
+ cut?.done.set(outcome);
937
+ this.#state.flate?.finish();
938
+ this.#state.closed.set(outcome);
939
+ if (!held)
940
+ this.#failHeld();
941
+ if (outcome)
942
+ for (const fn of this.#aborted ?? [])
943
+ fn(outcome);
944
+ this.#aborted = undefined;
945
+ }
946
+ // End the open mirrors, once this copy closed and no duplicate held for it can take over.
947
+ #failHeld() {
948
+ const outcome = this.#state.closed.peek();
949
+ if (outcome === undefined)
950
+ return;
951
+ for (const mirror of this.#mirrors?.keys() ?? []) {
952
+ if (mirror.closed.peek() === undefined) {
953
+ if (outcome === null)
954
+ mirror.end = this.#state.end;
955
+ mirror.closed.set(outcome);
204
956
  }
205
- this.#mirrors.clear();
957
+ this.#unmirror(mirror);
206
958
  }
207
959
  }
208
960
  }
209
961
  let makeConsumer;
210
- // A consumer can finish from its own expiry verdict or from the shared group state. Keep
211
- // one stable public handle while letting peek() observe either source synchronously, before
212
- // signal subscribers run in the next microtask.
962
+ // `Consumer.expired`: judges the drift budget only while something listens, so racing it once
963
+ // per write leaks nothing, and a group nobody watches pays nothing. The verdict latches.
964
+ class Expired {
965
+ #judge;
966
+ #changed;
967
+ #listeners = new Set();
968
+ // The drift inputs watched while anything listens.
969
+ #unwatch;
970
+ constructor(judge, changed) {
971
+ this.#judge = judge;
972
+ this.#changed = changed;
973
+ }
974
+ peek() {
975
+ return this.#judge();
976
+ }
977
+ subscribe(fn) {
978
+ this.#listeners.add(fn);
979
+ this.#watch();
980
+ return () => {
981
+ this.#listeners.delete(fn);
982
+ if (this.#listeners.size === 0)
983
+ this.#stop();
984
+ };
985
+ }
986
+ watch(fn) {
987
+ return watchVia(this, fn);
988
+ }
989
+ changed(fn) {
990
+ if (!fn)
991
+ return new Promise((resolve) => this.changed(resolve));
992
+ const dispose = this.subscribe((value) => {
993
+ dispose();
994
+ fn(value);
995
+ });
996
+ return dispose;
997
+ }
998
+ // biome-ignore lint/suspicious/noThenProperty: Expired is intentionally awaitable.
999
+ then(onFulfilled, onRejected) {
1000
+ return new Promise((resolve) => {
1001
+ const value = this.peek();
1002
+ if (value)
1003
+ resolve(value);
1004
+ else
1005
+ this.changed((value) => value && resolve(value));
1006
+ }).then(onFulfilled, onRejected);
1007
+ }
1008
+ // Watch the current drift inputs again, since an adopted copy brings its own.
1009
+ refresh() {
1010
+ if (!this.#unwatch)
1011
+ return;
1012
+ this.#stop();
1013
+ this.#watch();
1014
+ }
1015
+ #watch() {
1016
+ if (this.#unwatch)
1017
+ return;
1018
+ this.#unwatch = this.#changed().map((changed) => changed.subscribe(() => this.#check()));
1019
+ // Judging arms the wall-clock wakeup; a verdict already reached notifies after `subscribe`
1020
+ // returns, as a signal would.
1021
+ if (this.peek())
1022
+ queueMicrotask(() => this.#check());
1023
+ }
1024
+ #check() {
1025
+ const value = this.peek();
1026
+ if (!value)
1027
+ return;
1028
+ this.#stop();
1029
+ const listeners = [...this.#listeners];
1030
+ this.#listeners.clear();
1031
+ for (const fn of listeners)
1032
+ fn(value);
1033
+ }
1034
+ #stop() {
1035
+ for (const dispose of this.#unwatch ?? [])
1036
+ dispose();
1037
+ this.#unwatch = undefined;
1038
+ }
1039
+ }
1040
+ // A consumer can finish from its own verdict or from the shared group state. Keep one stable
1041
+ // public handle while letting peek() observe either source synchronously, before signal
1042
+ // subscribers run in the next microtask. The source is re-read on every check, since a
1043
+ // recovered group moves to another copy's state, and `final` says whether its value ends the
1044
+ // consumer: a failure recovery can still continue does not, so it never reaches a caller. Built
1045
+ // on first read, which only a caller holding the group makes: a reader attaches its recovery
1046
+ // (`hooks.recoverGroup`) before handing the group out, and the track's own scans read
1047
+ // `hooks.groupFailed` instead. A front serving another front is the exception: the inner front
1048
+ // holds the handle before the outer attaches its recovery, so attaching rebuilds a handle that
1049
+ // latched a failure, and the inner front alone keeps the failure it saw.
1050
+ //
1051
+ // `final` may judge a short close (see `Consumer.#continues`) when told to `look`: a handle that
1052
+ // `looks` does whenever its caller peeks or awaits it, as a read would, and an internal watcher's
1053
+ // never does, leaving the judgment to the reader.
213
1054
  class CombinedClosed {
214
1055
  #preferred;
215
1056
  #source;
216
- #sourceCleanReady;
1057
+ #final;
1058
+ #looks;
1059
+ // Callers watching it now, so a change they wake for is a look: one per live subscription,
1060
+ // and one for good per awaited promise, which waits until the handle settles.
1061
+ #watchers = 0;
217
1062
  #value = new Once();
218
- #dispose;
219
- constructor(preferred, source, sourceCleanReady) {
1063
+ #watched;
1064
+ // The watcher on `#watched`, replaced when a recovery moves to another copy's state.
1065
+ #unwatch;
1066
+ #dispose = [];
1067
+ constructor(preferred, source, final, looks) {
220
1068
  this.#preferred = preferred;
221
1069
  this.#source = source;
222
- this.#sourceCleanReady = sourceCleanReady;
223
- if (this.#sync())
1070
+ this.#final = final;
1071
+ this.#looks = looks;
1072
+ if (this.#sync(false))
224
1073
  return;
225
- const dispose = [preferred.changed(() => this.#sync()), source.changed(() => this.#sync())];
226
- this.#dispose = () => {
227
- for (const close of dispose)
228
- close();
229
- };
1074
+ this.#dispose.push(preferred.changed(() => this.#sync(this.#watchers > 0)));
230
1075
  }
231
- #sync() {
1076
+ #sync(look) {
232
1077
  if (this.#value.peek() !== undefined)
233
1078
  return true;
234
1079
  const preferred = this.#preferred.peek();
235
- const source = this.#source.peek();
1080
+ const source = this.#source();
1081
+ const current = source.peek();
236
1082
  const value = preferred !== undefined
237
1083
  ? preferred
238
- : source instanceof Error || this.#sourceCleanReady()
239
- ? source
1084
+ : current !== undefined && this.#final(current, look && this.#looks)
1085
+ ? current
240
1086
  : undefined;
241
- if (value === undefined)
1087
+ // Judging a short close final refreshes this handle, which may have settled it already.
1088
+ if (this.#value.peek() !== undefined)
1089
+ return true;
1090
+ if (value === undefined) {
1091
+ if (this.#watched !== source) {
1092
+ this.#unwatch?.();
1093
+ this.#watched = source;
1094
+ this.#unwatch = source.changed(() => this.#sync(this.#watchers > 0));
1095
+ }
242
1096
  return false;
1097
+ }
243
1098
  this.#value.set(value);
244
- this.#dispose?.();
245
- this.#dispose = undefined;
1099
+ for (const dispose of this.#dispose)
1100
+ dispose();
1101
+ this.#dispose = [];
1102
+ this.#unwatch?.();
1103
+ this.#unwatch = undefined;
1104
+ this.#watched = undefined;
246
1105
  return true;
247
1106
  }
248
1107
  refresh() {
249
- this.#sync();
1108
+ this.#sync(this.#watchers > 0);
1109
+ }
1110
+ // The value it settled with, without looking again.
1111
+ latched() {
1112
+ return this.#value.peek();
250
1113
  }
251
1114
  peek() {
252
- this.#sync();
1115
+ this.#sync(true);
253
1116
  return this.#value.peek();
254
1117
  }
255
1118
  changed(fn) {
256
- this.#sync();
257
- return fn ? this.#value.changed(fn) : this.#value.changed();
1119
+ if (!fn) {
1120
+ this.#watchers++;
1121
+ this.#sync(true);
1122
+ return this.#value.changed();
1123
+ }
1124
+ return this.#watch(() => this.#value.changed(fn));
258
1125
  }
259
1126
  subscribe(fn) {
260
- this.#sync();
261
- return this.#value.subscribe(fn);
1127
+ return this.#watch(() => this.#value.subscribe(fn));
1128
+ }
1129
+ watch(fn) {
1130
+ return this.#watch(() => this.#value.watch(fn));
1131
+ }
1132
+ // Counts a subscription as watching until its caller disposes it, as a race does once decided.
1133
+ #watch(subscribe) {
1134
+ this.#watchers++;
1135
+ this.#sync(true);
1136
+ const dispose = subscribe();
1137
+ let live = true;
1138
+ return () => {
1139
+ if (live) {
1140
+ live = false;
1141
+ this.#watchers--;
1142
+ }
1143
+ dispose();
1144
+ };
262
1145
  }
263
1146
  // biome-ignore lint/suspicious/noThenProperty: CombinedClosed is intentionally awaitable.
264
1147
  then(onFulfilled, onRejected) {
265
- this.#sync();
1148
+ this.#watchers++;
1149
+ this.#sync(true);
266
1150
  return this.#value.then(onFulfilled, onRejected);
267
1151
  }
268
1152
  }
@@ -275,22 +1159,68 @@ class CombinedClosed {
275
1159
  * @public
276
1160
  */
277
1161
  export class Consumer {
278
- /** Sequence number of this group within its track. */
279
- sequence;
1162
+ /** Where this group starts, in its track's timescale: its key on the track. */
1163
+ start;
280
1164
  #state;
1165
+ // The copy it was mirrored from, which that copy's cache evicts.
1166
+ #mirrored;
281
1167
  #expiry;
282
- // Sticky verdicts, set once. `#ended` is a drained group the budget gave up on,
283
- // which is indistinguishable from one that ended: nothing was lost, so it reads as
284
- // the end of the group. `#terminal` is a failure, including a budget that gave up
285
- // while content was still unread.
286
- #ended = false;
287
- #terminal;
1168
+ // The budget in milliseconds the group was judged stale under, once it was.
1169
+ #staleUnder;
1170
+ // Carries the group across its logical track's route changes; see `resume.ts`.
1171
+ #recover;
1172
+ // Judges a short close the recovery left open again once its route changes, which may leave
1173
+ // the close standing, so a caller awaiting `closed` without reading sees that too.
1174
+ #rejudge;
1175
+ // A replacement asked for while the copy being read stalls, raced against that copy.
1176
+ #attempt;
1177
+ // The frame a replacement copy resumes at: frames below it were read from an earlier copy.
1178
+ #skip = 0;
1179
+ // One past the last frame handed to this reader's caller: frames a filtered read discarded
1180
+ // below its `from` were never delivered.
1181
+ #delivered = 0;
1182
+ // This reader's own failure, set once, including a budget that gave up on the group: it
1183
+ // ends the consumer whatever its copy does. See `#fail`.
288
1184
  #verdict = new Once();
289
1185
  #closed;
290
- #pendingFrames = 0;
1186
+ // Settles as `#closed` does, for internal watchers, which never judge a short close.
1187
+ #quiet;
1188
+ // Settles once {@link done}: its reader read or released everything it holds.
1189
+ #finished;
1190
+ #expired;
1191
+ // Closed by its reader, which ends it whatever is left unread.
1192
+ #released = false;
1193
+ // A short close (see `#continues`) was judged final: no route read on past it.
1194
+ #ended = false;
1195
+ // Settles once this reader is released, made only when something waits on it.
1196
+ #releasing;
1197
+ // The arrival of the copy first read, kept once a replacement copy is adopted.
1198
+ #created;
1199
+ // The last frame handed out to stream before it completed. Cut short, it is lost, so no
1200
+ // other copy can continue the group past it.
1201
+ #streamed;
291
1202
  constructor(state) {
292
1203
  this.#state = state;
293
- this.sequence = state.sequence;
1204
+ this.#mirrored = state;
1205
+ this.start = state.start;
1206
+ }
1207
+ /**
1208
+ * When the group joined its track at this hop, before its first frame, on the installed
1209
+ * clock: its header was received, or it was fetched or created here.
1210
+ *
1211
+ * A reader that gets to the group late still measures from when it landed, as
1212
+ * {@link Frame.created} does for each frame. A consumer resumed onto a replacement copy
1213
+ * keeps the original group's arrival.
1214
+ */
1215
+ get created() {
1216
+ return this.#created ?? this.#state.created;
1217
+ }
1218
+ /**
1219
+ * Where the group ends in its track's timescale, once its producer finished it whole with
1220
+ * {@link Producer.finishAt}'s `end`: undefined while it is open, or when it ended without one.
1221
+ */
1222
+ get end() {
1223
+ return this.#state.closed.peek() === null ? this.#state.end : undefined;
294
1224
  }
295
1225
  /**
296
1226
  * Settles when this consumer reaches a terminal state: `null` after a clean close has no
@@ -298,20 +1228,187 @@ export class Consumer {
298
1228
  * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.
299
1229
  */
300
1230
  get closed() {
301
- this.#closed ??= new CombinedClosed(this.#verdict, this.#state.closed, () => this.#state.frames.peek().length === 0 && this.#pendingFrames === 0);
1231
+ this.#closed ??= this.#makeClosed(true);
302
1232
  return this.#closed;
303
1233
  }
1234
+ #makeClosed(looks) {
1235
+ return new CombinedClosed(this.#verdict, () => this.#state.closed, (value, look) => value instanceof Error
1236
+ ? !this.#recovers(value)
1237
+ : (this.#released || this.#bufferedFrames().length === 0) && !this.#continues(look), looks);
1238
+ }
1239
+ // Settles with its terminal state once {@link done}, unlike {@link closed}, which a failure
1240
+ // settles while frames are still unread. Internal, so it never judges a short close itself.
1241
+ #done() {
1242
+ this.#finished ??= new CombinedClosed(this.#verdict, () => this.#state.closed, (value) => (value instanceof Error ? !this.#recovers(value) : !this.#continues(false)) &&
1243
+ (this.#released || this.#bufferedFrames().length === 0), false);
1244
+ return this.#finished;
1245
+ }
1246
+ #refresh() {
1247
+ this.#closed?.refresh();
1248
+ this.#quiet?.refresh();
1249
+ this.#finished?.refresh();
1250
+ }
1251
+ /**
1252
+ * Settles with a `StreamError` of code `Old` once the subscription's live max gives up
1253
+ * on this group, even after every frame was read or the group closed: a publisher still
1254
+ * writing or draining it races its writes against this, and against {@link closed}
1255
+ * settling with an error, and abandons the stream once either does. Peek it synchronously
1256
+ * (`undefined` while within budget), or race it, which stops watching the budget once the
1257
+ * race ends.
1258
+ *
1259
+ * @internal Wire publishers only.
1260
+ */
1261
+ get expired() {
1262
+ this.#expired ??= new Expired(() => {
1263
+ this.#expire();
1264
+ const verdict = this.#verdict.peek();
1265
+ return verdict instanceof StreamError && verdict.code === StreamCode.Old ? verdict : undefined;
1266
+ }, () => this.#expiry?.changed ?? []);
1267
+ return this.#expired;
1268
+ }
1269
+ /**
1270
+ * The budget in milliseconds this group was judged stale under, `NO_MAX_DELAY` for the
1271
+ * publisher's max age, or undefined while it was not, or by a budget it does not know.
1272
+ *
1273
+ * @internal Wire publishers only.
1274
+ */
1275
+ get staleUnder() {
1276
+ return this.#staleUnder;
1277
+ }
1278
+ // The failure that ends this reader, as `closed` would settle with it, without building that
1279
+ // handle: a track's scans read this, so none latches a failure before a reader attaches the
1280
+ // recovery that continues past it.
1281
+ #failed() {
1282
+ const verdict = this.#verdict.peek();
1283
+ if (verdict)
1284
+ return verdict;
1285
+ const closed = this.#state.closed.peek();
1286
+ return closed instanceof Error && !this.#recovers(closed) ? closed : undefined;
1287
+ }
1288
+ // Whether a failure of the copy being read may still be continued from another route.
1289
+ #recovers(failed) {
1290
+ return (!this.#verdict.peek() && !this.#torn() && this.#recover?.wants({ kind: "failed", error: failed }) === true);
1291
+ }
1292
+ // Whether the read may go on past a close of the copy being read that names no end (a FIN
1293
+ // without GROUP_END), with every frame it delivered read: the group may hold more, which the
1294
+ // route that replaced the copy reads on from. A read that reaches the close (`decide`) judges
1295
+ // it, once: it goes on while a newer route serves or is being spliced in, and otherwise ends
1296
+ // there for good, so every later look agrees. Until then it may go on, so the end is not yet final.
1297
+ #continues(decide) {
1298
+ if (this.#ended || this.#released || !this.#recover || this.#verdict.peek())
1299
+ return false;
1300
+ const state = this.#state;
1301
+ if (state.closed.peek() !== null || state.end !== undefined || this.#bufferedFrames().length > 0)
1302
+ return false;
1303
+ if (!decide)
1304
+ return true;
1305
+ if (!this.#torn() && this.#recover.wants({ kind: "closed" })) {
1306
+ this.#rejudge ??= this.#recover.changed.changed(() => {
1307
+ this.#rejudge = undefined;
1308
+ this.#refresh();
1309
+ });
1310
+ return true;
1311
+ }
1312
+ this.#end();
1313
+ return false;
1314
+ }
1315
+ // Judge a short close final. One below a frame an earlier copy delivered is no end of
1316
+ // this read, since no route said the group ends there, so it fails the reader instead: with
1317
+ // the error a recovery that found nothing `failed` with, Old once its budget gave up, or
1318
+ // NotFound.
1319
+ #end(expired = false, failed) {
1320
+ if (this.#delivered > this.#state.total.peek()) {
1321
+ this.#fail(failed ??
1322
+ new StreamError(expired ? StreamCode.Old : StreamCode.NotFound, {
1323
+ message: `group ${this.start} closed below frame ${this.#delivered}`,
1324
+ }));
1325
+ }
1326
+ else {
1327
+ this.#ended = true;
1328
+ }
1329
+ this.#refresh();
1330
+ }
1331
+ // Read on past a short close (see `#continues`) from the route that replaced the copy, within
1332
+ // the reader's budget, which ends the group there as it would a stall. Returns whether to look
1333
+ // again. Unless it may `decide`, a close no route took over yet is left for the next read to
1334
+ // judge, as a wait for readability is no read.
1335
+ async #readOn(decide) {
1336
+ if (!this.#continues(false) || (!decide && !this.#recover?.wants({ kind: "closed" })) || !this.#continues(true))
1337
+ return false;
1338
+ if (this.#expiry?.expired()) {
1339
+ this.#end(true);
1340
+ return false;
1341
+ }
1342
+ await this.#resume({ kind: "closed" });
1343
+ return true;
1344
+ }
1345
+ // Whether a frame handed out to stream was cut short.
1346
+ #torn() {
1347
+ const done = this.#streamed?.done.peek();
1348
+ return done !== undefined && done !== null;
1349
+ }
304
1350
  static {
305
1351
  makeConsumer = (state) => new Consumer(state);
306
- hooks.groupTimestamp = (group) => group.#state.timestamp;
307
- hooks.groupLatest = (group) => group.#state.latest;
1352
+ hooks.releaseGroupReader = (group, abort) => group.#release(abort);
1353
+ hooks.groupDone = (group) => group.#done();
1354
+ hooks.groupFinished = (group) => group.#state.closed;
1355
+ hooks.groupClosed = (group) => {
1356
+ group.#quiet ??= group.#makeClosed(false);
1357
+ return group.#quiet;
1358
+ };
1359
+ hooks.groupReleased = (group) => {
1360
+ if (group.#released)
1361
+ return Promise.resolve();
1362
+ group.#releasing ??= Promise.withResolvers();
1363
+ return group.#releasing.promise;
1364
+ };
1365
+ hooks.readsMirrored = (group) => group.#state === group.#mirrored;
1366
+ hooks.groupReads = (group, reads) => group.#mirrored.reads?.(reads);
1367
+ hooks.groupTimestamp = (group) => group.#state.unverified || group.#state.offset !== 0 ? undefined : group.#state.firstTimestamp;
1368
+ hooks.groupLatest = (group) => (group.#state.unverified ? undefined : group.#state.latestTimestamp);
1369
+ hooks.unverifyGroup = (group) => {
1370
+ group.#state.unverified = true;
1371
+ };
1372
+ hooks.groupArrived = (group) => group.#state.created;
1373
+ hooks.skipGroupFrames = (group) => {
1374
+ while (!group.#verdict.peek() && group.#readBufferedFrame(false, "stream")) { }
1375
+ };
1376
+ hooks.groupIndex = (group) => group.#index();
1377
+ hooks.groupTimedId = (group, index, timescale) => timedId(group.#state, timescale, index);
1378
+ hooks.groupSettledFrames = (group) => group.#state.closed.peek() === null ? group.#state.total.peek() : undefined;
1379
+ hooks.groupFirstFrame = (group) => group.#state.offset;
1380
+ hooks.groupStarted = (group) => group.#state.frameCount > group.#state.offset || group.#state.closed.peek() !== undefined;
1381
+ hooks.groupFate = (group) => {
1382
+ const state = group.#state;
1383
+ return () => {
1384
+ const closed = state.closed.peek();
1385
+ return closed instanceof Error ? closed : undefined;
1386
+ };
1387
+ };
1388
+ hooks.arriveGroup = (group, at) => {
1389
+ group.#state.created = at;
1390
+ };
308
1391
  hooks.expireGroup = (group, expiry) => {
309
1392
  group.#expiry = expiry;
310
1393
  };
311
- hooks.guardGroup = (group, operation) => group.#guard(operation);
312
- hooks.readGroupFrame = (group, from) => group.#readFramePosition(true, from);
313
- hooks.evictGroup = (group) => {
314
- group.#evict();
1394
+ hooks.groupExpiry = (group) => group.#expiry;
1395
+ hooks.groupFailed = (group) => group.#failed();
1396
+ hooks.recoverGroup = (group, recover) => {
1397
+ group.#recover = recover;
1398
+ // A front serving another front attaches its recovery after the inner one handed the
1399
+ // group out, whose reads may have latched a failure this recovery continues past.
1400
+ if (group.#verdict.peek() === undefined) {
1401
+ if (group.#closed?.latched() instanceof Error)
1402
+ group.#closed = undefined;
1403
+ if (group.#quiet?.latched() instanceof Error)
1404
+ group.#quiet = undefined;
1405
+ }
1406
+ };
1407
+ hooks.readGroupFrame = (group, compressed, from = 0, header = false) => group.#readFrame(from, compressed, true, header);
1408
+ hooks.evictGroup = (group, lost) => group.#evict(lost);
1409
+ hooks.refreshGroup = (group) => group.#state.charge?.touch();
1410
+ hooks.onShedRead = (group, notify) => {
1411
+ group.#state.shedRead = notify;
315
1412
  };
316
1413
  }
317
1414
  // Evaluate the drift budget for a read that has nothing buffered and is about to
@@ -319,125 +1416,254 @@ export class Consumer {
319
1416
  // that has stalled while the live edge moved on, not a reader slower than the wire.
320
1417
  // Returns true if a verdict was just reached, so the caller re-checks.
321
1418
  //
322
- // `unread` is for a caller that still holds content the reader has not seen (a
323
- // publisher part-way through writing a frame): giving up there is a truncation, so
324
- // it fails rather than ending.
325
- #expire(unread = false) {
326
- if (this.#terminal || this.#ended)
1419
+ // A reader that took every frame still fails with Old: the producer never finished
1420
+ // the group, so a clean end would pass the prefix off as the whole group.
1421
+ #expire() {
1422
+ if (this.#verdict.peek())
327
1423
  return false;
328
1424
  if (this.#state.closed.peek() instanceof Error)
329
1425
  return false;
330
1426
  if (!this.#expiry?.expired())
331
1427
  return false;
332
- if (unread) {
333
- this.#terminal = new Error("group exceeded the subscription max age budget");
334
- }
335
- else {
336
- this.#ended = true;
337
- }
338
- if (this.#verdict.peek() === undefined)
339
- this.#verdict.set(this.#terminal ?? null);
1428
+ this.#staleUnder = this.#expiry.budget?.();
1429
+ this.#fail(new StreamError(StreamCode.Old, {
1430
+ message: "group exceeded the subscription max delay budget",
1431
+ }));
340
1432
  return true;
341
1433
  }
342
- // Takes a thunk rather than a started promise, so a group already past its budget
343
- // never begins the write: an abandoned write would reject later with no handler.
344
- #guard(operation) {
345
- this.#expire(true);
346
- if (this.#terminal)
347
- return Promise.reject(this.#terminal);
348
- const expiry = this.#expiry;
349
- if (!expiry)
350
- return operation();
351
- return new Promise((resolve, reject) => {
352
- let settled = false;
353
- const disposes = [];
354
- const finish = (fn) => {
355
- if (settled)
356
- return;
357
- settled = true;
358
- for (const dispose of disposes)
359
- dispose();
360
- fn();
361
- };
362
- const check = () => {
363
- this.#expire(true);
364
- if (this.#terminal) {
365
- const error = this.#terminal;
366
- finish(() => reject(error));
367
- }
368
- };
369
- for (const changed of expiry.changed)
370
- disposes.push(changed.subscribe(check));
371
- operation().then((value) => finish(() => resolve(value)), (error) => finish(() => reject(error)));
372
- check();
373
- });
1434
+ // Fail this reader with `error`, unless it already failed: the first verdict stands.
1435
+ #fail(error) {
1436
+ if (this.#verdict.peek() === undefined)
1437
+ this.#verdict.set(error instanceof Error ? error : new Error(String(error)));
1438
+ return this.#verdict.peek();
374
1439
  }
375
- #evict() {
376
- const frames = this.#state.frames.peek();
1440
+ #evict(lost) {
1441
+ // A group read on from another copy is that copy's to reclaim.
1442
+ if (this.#state !== this.#mirrored)
1443
+ return false;
1444
+ const frames = this.#bufferedFrames();
377
1445
  if (frames.length > 0) {
378
1446
  // Unread content is going away either way. If the budget had already given up
379
1447
  // on this group that is the more specific reason, so ask it first; otherwise
380
- // the reader simply lagged behind the cache.
381
- this.#expire(true);
382
- if (!this.#terminal && !this.#ended) {
383
- this.#terminal = new TooFarBehind();
384
- if (this.#verdict.peek() === undefined)
385
- this.#verdict.set(this.#terminal);
386
- }
1448
+ // the cache reclaimed it before the reader got to it.
1449
+ this.#expire();
1450
+ this.#fail(lost);
387
1451
  }
388
1452
  if (frames.length > 0) {
389
- this.#state.start += frames.length;
1453
+ this.#state.index += frames.length;
390
1454
  }
391
1455
  this.#state.cacheBytes = 0;
392
- this.#state.frames.set([]);
1456
+ this.#state.flate = undefined;
1457
+ this.#state.frames.set(new Queue());
1458
+ // A failed copy holds nothing more to reclaim, and its recovery may still continue the group.
1459
+ const closed = this.#state.closed.peek();
1460
+ return !(closed instanceof Error && this.#recovers(closed));
1461
+ }
1462
+ // The next change a parked read waits for.
1463
+ #changed(header = false) {
1464
+ const changed = [this.#state.frames, this.#state.closed];
1465
+ if (header && this.#state.flate)
1466
+ changed.push(this.#state.open);
1467
+ if (this.#expiry)
1468
+ changed.push(...this.#expiry.changed);
1469
+ if (this.#recover)
1470
+ changed.push(this.#recover.changed);
1471
+ return Signal.race(...changed);
393
1472
  }
394
- async #changed() {
395
- if (!this.#expiry) {
396
- await Signal.race(this.#state.frames, this.#state.closed);
1473
+ // Continue from the serving route's copy once the one being read looks past itself for
1474
+ // `cause`. Returns whether the read should look again; throws the error that ends the group
1475
+ // once nothing can continue it, except past a short close, which then ends where it closed.
1476
+ async #resume(cause, header = false) {
1477
+ const recover = this.#recover;
1478
+ if (this.#torn() || !recover?.wants(cause))
1479
+ return false;
1480
+ // A stall's attempt learns nothing of a failure or close since: ask again with it.
1481
+ if (cause.kind !== "stalled" && this.#attempt && this.#attempt.cause !== cause.kind)
1482
+ this.#abandon();
1483
+ let attempt = this.#attempt;
1484
+ if (!attempt) {
1485
+ const abort = new AbortController();
1486
+ const started = { cause: cause.kind, abort, result: Promise.resolve(), settled: false };
1487
+ started.result = recover.replace(this.#index(), cause, abort.signal).then((replacement) => {
1488
+ started.settled = true;
1489
+ // Abandoned while it was out: nobody reads it.
1490
+ if (abort.signal.aborted)
1491
+ replacement.discard();
1492
+ else
1493
+ started.replacement = replacement;
1494
+ }, (err) => {
1495
+ started.settled = true;
1496
+ if (abort.signal.aborted)
1497
+ return;
1498
+ if (cause.kind === "closed")
1499
+ this.#end(false, err);
1500
+ else
1501
+ this.#fail(err);
1502
+ });
1503
+ attempt = started;
1504
+ this.#attempt = attempt;
1505
+ }
1506
+ // A failed copy never delivers again. A stalled one may first, and a short close waits on the
1507
+ // reader's budget too.
1508
+ if (cause.kind === "failed")
1509
+ await attempt.result;
1510
+ else
1511
+ await race([attempt.result, this.#changed(header)]);
1512
+ // The copy being read moved first: look again, keeping the attempt out.
1513
+ if (!attempt.settled)
1514
+ return true;
1515
+ if (this.#attempt === attempt)
1516
+ this.#attempt = undefined;
1517
+ // Taken once: a concurrent read awaiting the same attempt looks again instead.
1518
+ const replacement = attempt.replacement;
1519
+ attempt.replacement = undefined;
1520
+ if (!replacement)
1521
+ return true;
1522
+ if (cause.kind === "stalled" &&
1523
+ (this.#bufferedFrames().length > 0 ||
1524
+ (header && this.#pendingHeader()) ||
1525
+ this.#state.closed.peek() !== undefined)) {
1526
+ // The copy being read delivered or ended meanwhile; keep reading it.
1527
+ replacement.discard();
1528
+ return true;
1529
+ }
1530
+ this.#adopt(replacement);
1531
+ return true;
1532
+ }
1533
+ // The next frame this consumer reads: past what it read, and what a copy it adopted repeats.
1534
+ #index() {
1535
+ return Math.max(this.#state.index, this.#skip);
1536
+ }
1537
+ // Give up a replacement still being asked for, or one nobody adopted: the group ended without it.
1538
+ #abandon() {
1539
+ const attempt = this.#attempt;
1540
+ if (!attempt)
1541
+ return;
1542
+ this.#attempt = undefined;
1543
+ attempt.abort.abort();
1544
+ attempt.replacement?.discard();
1545
+ }
1546
+ // Read the rest of the group from `replacement`, from the frame this one reached.
1547
+ #adopt(replacement) {
1548
+ const next = replacement.group.#state;
1549
+ const index = this.#index();
1550
+ if (next.index > index) {
1551
+ replacement.discard();
1552
+ this.#fail(new Error(`group ${this.start} cannot resume at frame ${index}`));
397
1553
  return;
398
1554
  }
399
- await Signal.race(this.#state.frames, this.#state.closed, ...this.#expiry.changed);
1555
+ replacement.adopt();
1556
+ // The copy left behind stops teeing into the state this consumer read.
1557
+ if (this.#state.closed.peek() === undefined)
1558
+ this.#state.closed.set(null);
1559
+ this.#created ??= this.#state.created;
1560
+ this.#state = next;
1561
+ this.#expiry = replacement.expiry;
1562
+ this.#skip = index;
1563
+ this.#refresh();
1564
+ this.#expired?.refresh();
400
1565
  }
401
- #readBufferedFrame(pending = false) {
1566
+ // The unread frames. Every look at the buffer goes through here, so readiness, reads and
1567
+ // `done` agree on what is left.
1568
+ #bufferedFrames() {
402
1569
  const frames = this.#state.frames.peek();
1570
+ // A resumed copy repeats the frames an earlier one already delivered.
1571
+ while (this.#state.index < this.#skip && frames.length > 0) {
1572
+ frames.shift();
1573
+ this.#state.index++;
1574
+ }
1575
+ return frames;
1576
+ }
1577
+ // Whether the next frame can be read whole without waiting.
1578
+ #ready() {
1579
+ const front = this.#bufferedFrames().first;
1580
+ return front !== undefined && !(front instanceof Chunked && front.done.peek() === undefined);
1581
+ }
1582
+ #pendingHeader() {
1583
+ const pending = this.#state.pendingHeader;
1584
+ return pending?.index === this.#index() ? pending : undefined;
1585
+ }
1586
+ // Take the next frame whole, or as chunks when it is a chunked frame `streaming` reads, or
1587
+ // one still being written that a `collect` read gathers itself. A `header` read takes a chunked
1588
+ // frame without its payload, so no payload is in flight for a failure to tear. A plain whole
1589
+ // read leaves an incomplete frame buffered.
1590
+ #readBufferedFrame(compressed = false, take = "whole") {
1591
+ const frames = this.#bufferedFrames();
1592
+ const closed = this.#state.closed.peek();
1593
+ if (closed instanceof StreamError && closed.code === StreamCode.Evicted) {
1594
+ const notify = this.#state.shedRead;
1595
+ this.#state.shedRead = undefined;
1596
+ notify?.();
1597
+ }
1598
+ const front = frames.first;
1599
+ if (!front) {
1600
+ const pending = take === "header" ? this.#pendingHeader() : undefined;
1601
+ if (!pending)
1602
+ return undefined;
1603
+ this.#state.index = this.#delivered = pending.index + 1;
1604
+ this.#refresh();
1605
+ this.#state.charge?.touch();
1606
+ const { timestamp, size } = pending.info;
1607
+ return { index: pending.index, frame: { timestamp, payload: EMPTY }, inflated: size };
1608
+ }
1609
+ if (front instanceof Chunked) {
1610
+ if (take === "stream" || take === "header" || (take === "collect" && front.done.peek() === undefined)) {
1611
+ frames.shift();
1612
+ const index = this.#state.index++;
1613
+ this.#delivered = index + 1;
1614
+ if (take !== "header")
1615
+ this.#streamed = front;
1616
+ this.#refresh();
1617
+ this.#state.charge?.touch();
1618
+ return { index, frame: front, chunks: makeFrameConsumer(index, front) };
1619
+ }
1620
+ if (front.done.peek() === undefined)
1621
+ return undefined;
1622
+ }
403
1623
  const buffered = frames.shift();
404
- if (!buffered)
405
- return undefined;
406
- const sequence = this.#state.start++;
407
- if (pending)
408
- this.#pendingFrames++;
409
- let completed = false;
410
- return {
411
- sequence,
412
- frame: buffered,
413
- complete: () => {
414
- if (completed)
415
- return;
416
- completed = true;
417
- if (pending)
418
- this.#pendingFrames--;
419
- this.#closed?.refresh();
420
- },
421
- };
1624
+ const slice = compressed ? stored(buffered) : undefined;
1625
+ let frame;
1626
+ try {
1627
+ frame = {
1628
+ payload: slice?.payload ?? buffered.payload,
1629
+ timestamp: buffered.timestamp,
1630
+ created: buffered.created,
1631
+ };
1632
+ }
1633
+ catch (error) {
1634
+ const verdict = this.#fail(error);
1635
+ this.#refresh();
1636
+ throw verdict;
1637
+ }
1638
+ if (frames.length === 0 && this.#state.closed.peek() !== undefined)
1639
+ this.#state.flate = undefined;
1640
+ const index = this.#state.index++;
1641
+ this.#delivered = index + 1;
1642
+ this.#refresh();
1643
+ this.#state.charge?.touch();
1644
+ return { index, frame, inflated: buffered instanceof Header ? buffered.size : slice?.inflated };
422
1645
  }
423
- /** True once no further frames can be read: the group has closed and every buffered frame is read. */
1646
+ /** True once no further frames can be read: this handle or the group has closed, and every buffered frame is read. */
424
1647
  get done() {
425
- return (this.#terminal !== undefined ||
426
- this.#ended ||
427
- (this.#state.frames.peek().length === 0 && this.#state.closed.peek() !== undefined));
1648
+ return (this.#verdict.peek() !== undefined ||
1649
+ (this.#bufferedFrames().length === 0 && (this.#released || this.#settled())));
428
1650
  }
429
- /** True once the group has been closed, regardless of whether buffered frames remain unread. Synchronous complement to the {@link closed} promise. */
430
- get isClosed() {
431
- return this.#terminal !== undefined || this.#ended || this.#state.closed.peek() !== undefined;
1651
+ // Whether the copy being read ended, for good: a failure recovery may continue is not an end,
1652
+ // nor a short close the read goes on past.
1653
+ #settled() {
1654
+ const closed = this.#state.closed.peek();
1655
+ if (closed === null)
1656
+ return !this.#continues(true);
1657
+ return closed !== undefined && !this.#recovers(closed);
432
1658
  }
433
1659
  /**
434
1660
  * How many frames the group has held, including any already read.
435
1661
  *
436
- * It is also the next frame's sequence number, so `frameCount - 1` names the newest
1662
+ * It is also the next frame's index, so `frameCount - 1` names the newest
437
1663
  * frame written so far. A publisher snapshots it to resolve the track's live edge.
438
1664
  */
439
1665
  get frameCount() {
440
- return this.#state.total.peek();
1666
+ return this.#state.frameCount;
441
1667
  }
442
1668
  /**
443
1669
  * Reads the next already-buffered frame without blocking.
@@ -447,35 +1673,44 @@ export class Consumer {
447
1673
  * end-of-group: check {@link done} to tell "no frame buffered yet" from "finished".
448
1674
  */
449
1675
  tryReadFrame() {
450
- if (this.#terminal || this.#ended)
1676
+ if (this.#verdict.peek())
451
1677
  return undefined;
452
- const read = this.#readBufferedFrame();
453
- read?.complete();
454
- return read?.frame;
1678
+ return this.#readBufferedFrame()?.frame;
455
1679
  }
456
- /** Like {@link tryReadFrame} but also reports the frame's sequence number within the group. */
457
- tryReadFrameSequence() {
458
- if (this.#terminal || this.#ended)
1680
+ /** Like {@link tryReadFrame} but also reports the frame's index within the group. */
1681
+ tryReadFrameIndex() {
1682
+ if (this.#verdict.peek())
459
1683
  return undefined;
460
1684
  const read = this.#readBufferedFrame();
461
1685
  if (!read)
462
1686
  return undefined;
463
- read.complete();
464
- return { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };
1687
+ return { index: read.index, ...read.frame };
465
1688
  }
466
1689
  /** Resolves once {@link readFrame} would not block. */
467
1690
  async readable() {
468
1691
  for (;;) {
469
- if (this.#terminal || this.#ended)
1692
+ if (this.#verdict.peek()) {
1693
+ this.#abandon();
470
1694
  return;
471
- if (this.#state.frames.peek().length > 0)
1695
+ }
1696
+ if (this.#ready())
472
1697
  return;
473
- if (this.#state.closed.peek() !== undefined) {
474
- this.#closed?.refresh();
1698
+ const closed = this.#state.closed.peek();
1699
+ if (closed instanceof Error && (await this.#resume({ kind: "failed", error: closed })))
1700
+ continue;
1701
+ if (closed === null && (await this.#readOn(false)))
1702
+ continue;
1703
+ if (closed !== undefined) {
1704
+ this.#abandon();
1705
+ this.#refresh();
475
1706
  return;
476
1707
  }
477
- if (this.#expire())
1708
+ if (this.#released || this.#expire())
478
1709
  return;
1710
+ if (this.#recover?.wants({ kind: "stalled" })) {
1711
+ await this.#resume({ kind: "stalled" });
1712
+ continue;
1713
+ }
479
1714
  await this.#changed();
480
1715
  }
481
1716
  }
@@ -484,68 +1719,142 @@ export class Consumer {
484
1719
  * Treat the returned frame bytes as read-only; they are shared with other consumers.
485
1720
  */
486
1721
  async readFrame() {
487
- return (await this.#readFramePosition())?.frame;
1722
+ return (await this.#readFrame(0))?.frame;
1723
+ }
1724
+ /**
1725
+ * Reads the next frame along with its index within the group.
1726
+ * Treat the returned frame bytes as read-only; they are shared with other consumers.
1727
+ */
1728
+ async readFrameIndex(options) {
1729
+ const read = await this.#readFrame(options?.from ?? 0);
1730
+ if (!read)
1731
+ return undefined;
1732
+ return { index: read.index, ...read.frame };
1733
+ }
1734
+ /**
1735
+ * Reads the next frame as it arrives, as Rust's `next_frame`: resolves once its header is
1736
+ * buffered, without waiting for its payload. Use it for a frame too large to hold whole.
1737
+ */
1738
+ async nextFrame() {
1739
+ const read = await this.#readFrame(0, false, true);
1740
+ if (!read)
1741
+ return undefined;
1742
+ return read.chunks ?? makeFrameConsumer(read.index, read.frame);
488
1743
  }
489
- async #readFramePosition(pending = false, from = 0) {
1744
+ async #readFrame(from, compressed = false, streaming = false, header = false) {
490
1745
  for (;;) {
491
- if (this.#terminal)
492
- throw this.#terminal;
493
- if (this.#ended)
494
- return;
495
- const read = this.#readBufferedFrame(pending);
1746
+ const verdict = this.#verdict.peek();
1747
+ if (verdict) {
1748
+ this.#abandon();
1749
+ throw verdict;
1750
+ }
1751
+ // A whole read streams a frame still being written into its own buffer, rather
1752
+ // than waiting for it whole while the group sheds its head.
1753
+ const delivered = this.#delivered;
1754
+ const read = this.#readBufferedFrame(compressed, header ? "header" : streaming ? "stream" : "collect");
496
1755
  if (read) {
497
- if (read.sequence < from) {
498
- read.complete();
1756
+ if (read.index < from) {
1757
+ if (read.chunks)
1758
+ this.#streamed = undefined;
1759
+ this.#delivered = delivered;
499
1760
  continue;
500
1761
  }
501
- if (!pending)
502
- read.complete();
1762
+ if (read.chunks && !streaming && !header)
1763
+ return this.#join(read.index, read.chunks);
503
1764
  return read;
504
1765
  }
505
1766
  const closed = this.#state.closed.peek();
506
- if (closed instanceof Error)
1767
+ if (closed instanceof Error) {
1768
+ if (await this.#resume({ kind: "failed", error: closed }))
1769
+ continue;
1770
+ this.#abandon();
507
1771
  throw closed;
1772
+ }
508
1773
  if (closed !== undefined) {
509
- this.#closed?.refresh();
1774
+ // Closed short after a newer route took over, which may hold more. A close that
1775
+ // failed the reader throws above.
1776
+ if ((await this.#readOn(true)) || this.#verdict.peek())
1777
+ continue;
1778
+ // The copy finished the group: a replacement asked for meanwhile is moot.
1779
+ this.#abandon();
1780
+ this.#refresh();
510
1781
  return;
511
1782
  }
512
1783
  // Nothing buffered and the group is still open: this wait is the stall the
513
1784
  // drift budget bounds, and the only place it applies.
514
1785
  if (this.#expire())
515
1786
  continue;
516
- await this.#changed();
1787
+ // A stall while a newer route serves looks there too.
1788
+ if (this.#recover?.wants({ kind: "stalled" })) {
1789
+ await this.#resume({ kind: "stalled" }, header);
1790
+ continue;
1791
+ }
1792
+ await this.#changed(header);
1793
+ }
1794
+ }
1795
+ // Read a streamed frame whole. Losing any of it ends this reader, since the frame is gone.
1796
+ async #join(index, chunks) {
1797
+ const parts = [];
1798
+ let size = 0;
1799
+ try {
1800
+ for (;;) {
1801
+ const verdict = this.#verdict.peek();
1802
+ if (verdict)
1803
+ throw verdict;
1804
+ const chunk = pollChunk(chunks);
1805
+ if (chunk === undefined)
1806
+ break;
1807
+ if (chunk !== WAIT) {
1808
+ parts.push(chunk);
1809
+ size += chunk.byteLength;
1810
+ continue;
1811
+ }
1812
+ // A released reader stops waiting on a frame its producer may never finish.
1813
+ if (this.#released) {
1814
+ const closed = this.#state.closed.peek();
1815
+ if (closed instanceof Error)
1816
+ throw closed;
1817
+ return undefined;
1818
+ }
1819
+ // A frame stalled partway is the stall the drift budget bounds, as an empty group is.
1820
+ if (this.#expire())
1821
+ continue;
1822
+ await Signal.race(...chunkChanged(chunks), this.#state.closed, ...(this.#expiry?.changed ?? []));
1823
+ }
1824
+ const payload = parts.length === 0 ? EMPTY : joined(parts, size);
1825
+ return { index, frame: { payload, timestamp: chunks.timestamp, created: chunks.created } };
1826
+ }
1827
+ catch (error) {
1828
+ const verdict = this.#fail(error);
1829
+ this.#refresh();
1830
+ throw verdict;
517
1831
  }
518
1832
  }
519
1833
  /**
520
- * Reads the next frame along with its sequence number within the group.
521
- * Treat the returned frame bytes as read-only; they are shared with other consumers.
1834
+ * Release this handle, like dropping a Rust consumer. Never changes the group for other
1835
+ * readers or the producer. It drains what it buffered and then ends. Idempotent.
522
1836
  */
523
- async readFrameSequence(options) {
524
- const read = await this.#readFramePosition(false, options?.from ?? 0);
525
- if (!read)
526
- return undefined;
527
- return { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };
1837
+ close() {
1838
+ this.#release(undefined);
528
1839
  }
529
- /** Reads the next frame and decodes its payload as a UTF-8 string. */
530
- async readString() {
531
- const frame = await this.readFrame();
532
- return frame ? new TextDecoder().decode(frame.payload) : undefined;
533
- }
534
- /** Reads the next frame and parses its payload as JSON. */
535
- async readJson() {
536
- const frame = await this.readString();
537
- return frame ? JSON.parse(frame) : undefined;
538
- }
539
- /** Reads the next frame and decodes its payload as a one-byte boolean. */
540
- async readBool() {
541
- const frame = await this.readFrame();
542
- return frame ? frame.payload[0] === 1 : undefined;
543
- }
544
- /** Closes the group, optionally with an error to abort readers. Idempotent. */
545
- close(abort) {
546
- if (this.#state.closed.peek() !== undefined)
547
- return; // already closed
548
- this.#state.closed.set(abort ?? null);
1840
+ // Release this reader, failing it with `abort` if given. Every reader owns its mirrored
1841
+ // state, so closing that state drops its demand without touching the producer.
1842
+ #release(abort) {
1843
+ // A copy failure recovery was continuing past ends with the abort instead.
1844
+ if (abort && this.#recover && this.#state.closed.peek() instanceof Error) {
1845
+ this.#fail(abort);
1846
+ }
1847
+ this.#abandon();
1848
+ this.#rejudge?.();
1849
+ this.#rejudge = undefined;
1850
+ this.#recover?.close?.();
1851
+ this.#recover = undefined;
1852
+ // Closing is terminal for this reader, even with frames still unread.
1853
+ this.#released = true;
1854
+ this.#releasing?.resolve();
1855
+ if (this.#state.closed.peek() === undefined)
1856
+ this.#state.closed.set(abort ?? null);
1857
+ this.#refresh();
549
1858
  }
550
1859
  }
551
1860
  //# sourceMappingURL=group.js.map