@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
@@ -1,97 +1,175 @@
1
- import { race, Signal } from "@moq/signals";
1
+ import { Duration, yieldNow } from "@moq/clock";
2
+ import { Effect, Once, race, Signal } from "@moq/signals";
2
3
  import * as announce from "../announced.js";
3
4
  import * as broadcast from "../broadcast.js";
4
5
  import { BroadcastCache } from "../consume.js";
5
- import { controlTimeout, error, ProtocolViolation, reason, StreamCode, StreamError, sessionCause } from "../error.js";
6
+ import * as DatagramStream from "../datagram_stream.js";
7
+ import { samePlaced } from "../demand.js";
8
+ import { closeError, error, fromTransport, NotFound, ProtocolViolation, reason, SessionCode, SessionError, StreamCode, StreamError, sessionCause, unauthorized, } from "../error.js";
6
9
  import * as netGroup from "../group.js";
7
- import { Cost, MAX_HOPS, randomHop, routesEqual, stampHops, UNKNOWN_HOP } from "../hop.js";
8
- import { groupBounds, hiddenBelow, scopeCaptures, scopeHead, scopeOverlaps } from "../internal.js";
10
+ import { Cost, MAX_HOPS, routesEqual, UNKNOWN_HOP } from "../hop.js";
11
+ import * as Identity from "../identity.js";
12
+ import { hiddenBelow, hooks, insertRun, NO_MAX_DELAY, removeRun, runGaps, staleHole, } from "../internal.js";
13
+ import { GRACE } from "../ledger.js";
14
+ import * as Mint from "../mint.js";
9
15
  import * as Path from "../path.js";
10
- import { Stream } from "../stream.js";
11
- import { TAIL_GRACE_MS, Tail } from "../tail.js";
16
+ import { sendOrder } from "../priority.js";
17
+ import { Stream, Writer } from "../stream.js";
18
+ import { Tail } from "../tail.js";
12
19
  import * as Time from "../time.js";
13
- import { untilAborted } from "../util/abort.js";
14
- import { TimeoutError, withTimeout } from "../util/timeout.js";
20
+ import { raceAborted, untilAborted } from "../util/abort.js";
21
+ import { closeUnwanted } from "../util/announce.js";
22
+ import { toNumber } from "../util/bigint.js";
23
+ import { Deadline } from "../util/deadline.js";
24
+ import { isAbandoned, unwanted } from "../util/demand.js";
25
+ import { max, min, RESERVED, UNBOUNDED } from "../util/key.js";
26
+ import { LIMITS, SlotMap, Slots } from "../util/limits.js";
27
+ import { Sorted } from "../util/sorted.js";
28
+ import { Budget } from "../util/yield.js";
29
+ import { AT_KEYS, EMPTY, latestAt, placedAsTimes, rangesPolicy, rangesStart, sameRanges, span, Window, widest, wireHeld, wireRanges, wireSpan, } from "../window.js";
15
30
  import { overrideBroadcastWire, wireOf } from "../wire.js";
16
31
  import { AnnounceHistory, AnnounceInit, AnnounceOk, AnnounceRequest, decodeAnnounceBroadcastMaybe, } from "./announce.js";
17
- import { Datagram as DatagramMessage } from "./datagram.js";
18
- import * as DatagramStream from "./datagram_stream.js";
19
- import { Fetch as FetchMessage } from "./fetch.js";
20
- import { frameDecoder, readFrames } from "./group.js";
21
- import { sendOrder } from "./priority.js";
32
+ import { AnnounceStream } from "./announce_stream.js";
33
+ import { Datagram as DatagramMessage, Datagrams, DatagramsInfo, DatagramsUpdate } from "./datagram.js";
34
+ import { closeViolation } from "./error.js";
35
+ import { dropped, passing, RangeFills, refuseRun, Stall, scoped, stale, } from "./fills.js";
36
+ import * as Fit from "./fit.js";
37
+ import { readFrames } from "./group.js";
22
38
  import { Probe } from "./probe.js";
39
+ import { Routed } from "./routed.js";
23
40
  import { ProbeLevel } from "./setup.js";
24
41
  import { StreamId } from "./stream.js";
25
- import { decodeSubscribeResponse, decodeSubscribeResponseMaybe, EMPTY_RANGE, emptyRange, exclusiveGroupEnd, inclusiveGroupEnd, Subscribe, SubscribeUpdate, } from "./subscribe.js";
42
+ import { decodeSubscribeResponse, decodeSubscribeResponseMaybe, EMPTY_RANGE, inclusiveGroupEnd, LiveRanges, requestedRange, Subscribe, SubscribeUpdate, startBuffered, toWireRanges, withPolicy, } from "./subscribe.js";
26
43
  import { TrackInfo, Track as TrackMessage } from "./track.js";
27
- import { hasAnnounceId, hasAnnounceOk, hasDatagrams, hasProbeRtt, hasStreamCount, resolvesStart, restartSupported, Version, } from "./version.js";
28
- // Bound on how long stream-open plus the first response (SUBSCRIBE_OK on older
29
- // drafts, or TRACK_INFO on lite-05+) may take. Browsers cap concurrent QUIC streams
30
- // (Chrome ~100) and we open with waitUntilAvailable, so past the cap the open blocks
31
- // until the peer frees a slot. The timeout turns a stall into a clear error.
32
- const SUBSCRIBE_SETUP_TIMEOUT_MS = 10_000;
33
- // The TRACK stream and implicit SUBSCRIBE acceptance are lite-05+.
34
- function supportsTrackStream(version) {
35
- switch (version) {
36
- case Version.DRAFT_01:
37
- case Version.DRAFT_02:
38
- case Version.DRAFT_03:
39
- case Version.DRAFT_04:
40
- return false;
41
- default:
42
- return true;
43
- }
44
- }
44
+ import { decodeTracksEventMaybe, Tracks as TracksMessage } from "./tracks.js";
45
+ import { fillsFromStart, hasAnnounceId, hasAnnounceOk, hasDatagrams, hasDatagramTracks, hasGroupEnd, hasIdentity, hasLengthFirst, hasMeta, hasOrder, hasProbeRtt, hasRanges, hasRefresh, hasRouteCost, hasRoutes, hasSetupStream, hasSkip, hasSynced, hasTrackStream, hasTracks, keepsSubscribeOpen, resolvesStart, updateSupported, Version, waitsForSubscriberFin, wireTimescale, } from "./version.js";
46
+ // A peer's buffered TRACKS events decode without reaching a task boundary, and a flood of adds
47
+ // and removals of one name never reaches the announces cap: yield so it cannot starve the host.
48
+ const listingBudget = new Budget();
49
+ const datagramBudget = new Budget();
50
+ // The datagrams held for unanswered subscriptions at once, as many as a Rust pass holds: past it,
51
+ // one is dropped and counted rather than stalling the receive queue, which would hold up other
52
+ // tracks' datagrams behind their ends.
53
+ const HELD_DATAGRAMS = 32;
45
54
  /**
46
- * Handles subscribing to broadcasts and managing their lifecycle.
47
- *
55
+ * The identity a session minted for each path a peer advertises without one (every version
56
+ * before lite-07), shared by its announce streams: a peer serves one broadcast at a path at a
57
+ * time, so the path advertised on two streams at once is one stream. The peer ending it on any
58
+ * stream retires its identity, so the next advertisement is a new stream with a fresh one, even
59
+ * while a lagging stream still holds the old: holders alone cannot tell a replacement from
60
+ * continuity. A stream closing only lets go of it. Mirrors `Minted` in rs/moq-net.
48
61
  * @internal
49
62
  */
50
- // What we close a session with on a protocol violation.
51
- //
52
- // The draft names the condition but assigns no numbers, so this is the Rust
53
- // implementation's code for `Error::ProtocolViolation`: matching it is what makes the
54
- // two report the same thing, where the default 0 would tell the peer it closed cleanly.
55
- const PROTOCOL_VIOLATION_CODE = 15;
56
- // WebTransport rejects a close reason over 1024 bytes of UTF-8 by throwing, so a reason
57
- // built from peer-supplied data has to be bounded before it gets there. A broadcast path
58
- // is peer-supplied and long enough to reach this on its own.
59
- const MAX_CLOSE_REASON = 1024;
60
- // The longest prefix of `text` that fits a close reason. `encodeInto` stops on a whole
61
- // code point, so `read` never lands mid-character the way slicing bytes would.
62
- function closeReason(text) {
63
- const encoder = new TextEncoder();
64
- const buf = new Uint8Array(MAX_CLOSE_REASON);
65
- const { read } = encoder.encodeInto(text, buf);
66
- return text.slice(0, read);
63
+ export class Minted {
64
+ #paths = new Map();
65
+ acquire(path) {
66
+ let entry = this.#paths.get(path);
67
+ if (!entry) {
68
+ entry = { identity: Mint.fresh(), holders: 0 };
69
+ this.#paths.set(path, entry);
70
+ }
71
+ entry.holders += 1;
72
+ return entry.identity;
73
+ }
74
+ /**
75
+ * Let go of `identity`, retiring it if the peer `ended` its advertisement. A no-op once
76
+ * another stream's end retired it.
77
+ */
78
+ release(path, identity, ended) {
79
+ const entry = this.#paths.get(path);
80
+ if (entry?.identity !== identity)
81
+ return;
82
+ entry.holders -= 1;
83
+ if (ended || entry.holders === 0)
84
+ this.#paths.delete(path);
85
+ }
86
+ }
87
+ // An announced suffix beneath its interest prefix. Each fits the limits alone, but together they
88
+ // can pass them, which the draft makes a violation.
89
+ function joinAnnounced(prefix, suffix) {
90
+ const path = (prefix === "" ? suffix : suffix === "" ? prefix : `${prefix}/${suffix}`);
91
+ // The wire's own count, which bounds every `/` and so the segments `Path.join` checks too.
92
+ const error = Path.check(path);
93
+ if (error)
94
+ throw new ProtocolViolation(error);
95
+ return path;
96
+ }
97
+ /** The groups a fill's range asks for: absolute at both ends, as `RangeFills` asks them. */
98
+ function fillRun(range) {
99
+ const start = range.start?.absolute;
100
+ const end = range.end?.absolute;
101
+ return start === undefined || end === undefined ? undefined : { start, end };
102
+ }
103
+ // Whether two lists hold the same items in order: values by identity, flat records field by field.
104
+ function sameList(a, b, same = Object.is) {
105
+ return a.length === b.length && a.every((x, i) => same(x, b[i]));
67
106
  }
107
+ const sameRun = (x, y) => x.start === y.start && x.end === y.end;
108
+ const sameJoin = (x, y) => x.min === y.min && x.end === y.end && x.budget === y.budget && x.since === y.since;
109
+ /** Subscribe to the peer and own its receive-side protocol tasks.
110
+ * @internal
111
+ */
68
112
  export class Subscriber {
69
113
  #quic;
114
+ // Advertisements the peer holds live across every announce stream on this session.
115
+ #announces;
116
+ // The identities minted for the paths the peer advertises without one, shared by every
117
+ // announce stream on this session.
118
+ #minted = new Minted();
70
119
  // The version of the connection.
71
120
  version;
72
121
  // Shared with the Publisher so reflected announces can be dropped on receipt.
73
122
  hop;
74
- // Our subscribed tracks. `timescale` resolves once known (from TRACK_INFO on
75
- // lite-05+, or implicit defaults on older drafts); group streams block on it
76
- // before decoding any frame, since a group's QUIC stream can race ahead.
123
+ // Registered only after immutable TRACK_INFO or the older drafts' defaults resolve,
124
+ // so every incoming group and datagram already knows its timestamp framing.
77
125
  #subscribes = new Map();
126
+ #datagrams = new Map();
127
+ #legacyDatagrams = new Map();
128
+ #legacyRequests = new Map();
129
+ // Lite-07 datagram requests sent and not yet answered.
130
+ #unanswered = new Set();
131
+ // Datagrams for a subscription still awaiting its answer, in arrival order, routed a host task
132
+ // later while the rest go on.
133
+ #held = [];
134
+ #heldRouted;
135
+ // Set while the receive loop yields to its budget, which may leave datagrams queued.
136
+ #receiveYield;
137
+ /** Datagrams received for a subscription with no datagram track; see `Stats.datagramsUnrouted`. */
138
+ datagramsUnrouted = 0;
139
+ // A SUBSCRIBE sent alongside its TRACK, until its TRACK_INFO lands: settles with the
140
+ // entry, or `undefined` if it never does.
141
+ #pending = new Map();
78
142
  #subscribeNext = 0n;
143
+ // Lite-07: the claims the peer sends, shared by every `routes()` reader.
144
+ #routed;
79
145
  // Dedup consumed broadcasts per path: repeat consume() calls share one subscription.
80
146
  #consumes = new BroadcastCache();
81
- // A random Hop ID of this connection's own, written as the first hop of any chain that
82
- // names no publisher, so a publisher that reconnects reads as a new one.
83
- #stamp;
84
- // Dedup in-flight one-shot fetches, keyed by [broadcast, track, sequence]. Concurrent (or
85
- // repeat, while still open) fetchGroup() calls for the same group share one FETCH stream and
86
- // each get an independent mirror; the entry is evicted once the group closes.
147
+ #consumeNext = 0;
148
+ // Dedup in-flight one-shot fetches, keyed by [consume, broadcast, identity, track, key].
149
+ // Concurrent (or repeat, while still open) fetchGroup() calls for the same group of one consume
150
+ // share one SUBSCRIBE and each get an independent mirror; the entry is evicted once the
151
+ // group closes.
87
152
  #fetches = new Map();
88
153
  // The peer's PROBE estimates, written as they arrive (Lite03+ only).
89
154
  #probe;
90
155
  // The peer's SETUP (lite-05+), undefined until it arrives. Gates opening the PROBE
91
156
  // stream on the peer having advertised Probe >= Report.
92
157
  #peerSetup;
158
+ // Settles when the peer sends GOAWAY, ranking this session's routes last.
159
+ #goaway;
160
+ // Our price and rank for this link; see {@link Link}.
161
+ #link;
162
+ // What crossing this link adds to a route's cost, settled once known.
163
+ #linkCost;
93
164
  // Distinguishes failures from streams torn down by Subscriber.close().
94
165
  #closed = new AbortController();
166
+ // Shared signal set once `#quic.closed` settles so per-fetch waits can subscribe and dispose
167
+ // without retaining closures on the session-lifetime promise.
168
+ #quicClosed = new Signal(false);
169
+ // Our grant: a subscription it stops covering is cancelled. Undefined until the peer
170
+ // answers, and forever on a version without AUTH, which allows everything.
171
+ #grant;
172
+ #auth;
95
173
  /**
96
174
  * Creates a new Subscriber instance.
97
175
  * @param quic - The WebTransport session to use
@@ -99,53 +177,168 @@ export class Subscriber {
99
177
  * @param origin - Hop id shared with the Publisher
100
178
  * @param probe - Optional sink for the peer's PROBE estimates
101
179
  * @param peerSetup - Optional peer SETUP slot for capability gating (lite-05+)
180
+ * @param goaway - Settles when the peer sends GOAWAY
181
+ * @param grant - The union of our tokens' grants, which bounds what we subscribe to
182
+ * @param limits - How many live requests the peer may hold
183
+ * @param link - Our price and rank for this link
102
184
  *
103
185
  * @internal
104
186
  */
105
- constructor(quic, version, hop, probe, peerSetup) {
187
+ constructor(quic, version, hop, probe, peerSetup, goaway, grant, limits = LIMITS, auth, link = { cost: Cost.link, priority: 0 }) {
106
188
  this.#quic = quic;
189
+ this.#link = link;
190
+ void quic?.closed?.then(() => this.#quicClosed.set(true), () => this.#quicClosed.set(true));
191
+ this.#announces = new Slots(limits.announces, { quic, reason: "too many announcements" });
107
192
  this.version = version;
108
193
  this.hop = hop;
109
- this.#stamp = randomHop();
110
194
  this.#probe = probe;
111
195
  this.#peerSetup = peerSetup;
196
+ this.#goaway = goaway;
197
+ this.#grant = grant;
198
+ this.#auth = auth;
199
+ if (hasRoutes(version)) {
200
+ const stream = AnnounceStream.of(quic, version);
201
+ this.#routed = new Routed({
202
+ quic,
203
+ version,
204
+ consumes: this.#consumes,
205
+ slots: this.#announces,
206
+ drained: (route) => this.#drained(route),
207
+ cost: () => this.#cost(),
208
+ priority: link.priority,
209
+ goaway,
210
+ grant,
211
+ send: (msg) => stream.send(msg),
212
+ });
213
+ }
214
+ }
215
+ // What crossing this link adds to a route's cost: our own price, else the one the peer's
216
+ // SETUP declares, else 1. A version whose announcements carry no cost charges nothing.
217
+ // Waits for the peer's SETUP only when we set no price. Mirrors `poll_link_cost` in rs/moq-net.
218
+ #cost() {
219
+ this.#linkCost ??= (async () => {
220
+ if (!hasRouteCost(this.version))
221
+ return Cost.zero;
222
+ if (this.#link.cost !== undefined)
223
+ return this.#link.cost;
224
+ const peerSetup = this.#peerSetup;
225
+ if (!peerSetup)
226
+ throw new Error("no peer SETUP to price the link");
227
+ // A transport that closes before the SETUP arrives ends the wait too, so a claim handler
228
+ // waiting on it never holds up the session's teardown.
229
+ let setup = peerSetup.peek();
230
+ while (setup === undefined) {
231
+ if (this.#quicClosed.peek())
232
+ throw new Error("session closed before the peer's SETUP");
233
+ await untilAborted(Promise.resolve(Signal.race(peerSetup, this.#quicClosed)), this.#closed.signal);
234
+ setup = peerSetup.peek();
235
+ }
236
+ return setup.cost ?? Cost.link;
237
+ })();
238
+ return this.#linkCost;
239
+ }
240
+ // Whether the peer has sent GOAWAY. Requests keep opening here until a replacement
241
+ // session's route outranks this one.
242
+ #goingAway() {
243
+ return this.#goaway?.peek() !== undefined;
244
+ }
245
+ // A route ranks below every available one once the peer has asked us to leave. A later announce on a
246
+ // draining session must not win selection, however cheap the path it advertises.
247
+ #drained(route) {
248
+ return this.#goingAway() ? { ...route, draining: true } : route;
249
+ }
250
+ // Whether our grant no longer lets us subscribe to `broadcast`.
251
+ #denied(broadcast) {
252
+ const grant = this.#grant?.peek();
253
+ return grant !== undefined && !grant.subscribe.matches(broadcast);
112
254
  }
113
255
  /**
114
- * Subscribe to broadcast announcements matching `scope`. Paths are relative
115
- * to the session, not the scope.
256
+ * Subscribe to broadcast announcements at or beneath `prefix`. Paths are relative
257
+ * to the session, not the prefix.
116
258
  *
117
259
  * Reflected announces (those whose hop chain already includes this
118
260
  * connection) are always dropped: moq-lite-06 has none to keep, and older
119
261
  * versions stay consistent with that.
120
262
  *
121
- * Hidden routes (a `.`-prefixed segment below the scope's head) are left out unless
263
+ * Hidden routes (a `.`-prefixed segment below the prefix) are left out unless
122
264
  * `options.hidden` opts in. The opt-in rides the request on lite-07+; an older peer
123
265
  * never hides anything, so the rule is also applied here.
266
+ *
267
+ * Only routes at or beneath `prefix` are reported, unless `options.covering` also asks for
268
+ * those above it. A lite-07 stream reports the best claim at each path, or each identity's
269
+ * with `options.claims`.
124
270
  */
125
- announced(scope = Path.Pattern.all(), options) {
271
+ routes(prefix = Path.empty(), options) {
272
+ // Refuse a prefix no request can carry before any reader registers for it.
273
+ Path.Prefix.parse(prefix);
274
+ Path.encode(prefix);
126
275
  const announced = new announce.Producer();
127
276
  // The wire speaks announce interest by prefix, and echoes suffixes beneath it.
128
- void this.#runAnnounced(announced, scopeHead(scope), scope, options?.hidden ?? false);
129
- return announced.consume();
277
+ const consumer = announced.consume();
278
+ // The last reader leaving ends the stream, which cancels the request.
279
+ closeUnwanted(announced);
280
+ const hidden = options?.hidden ?? false;
281
+ const covering = options?.covering ?? false;
282
+ if (this.#routed) {
283
+ // Lite-07: every reader shares the session's one Announce Stream.
284
+ this.#routed.attach(announced, { prefix, hidden, covering, claims: options?.claims ?? false });
285
+ }
286
+ else {
287
+ void this.#runAnnounced(announced, prefix, hidden);
288
+ }
289
+ return consumer;
130
290
  }
131
- async #runAnnounced(announced, prefix, scope, hidden) {
291
+ async #runAnnounced(announced, prefix, hidden) {
132
292
  console.debug(`announced: prefix=${prefix}`);
133
293
  // Lite04/05: send our own session-level Hop ID so the peer can skip announces
134
294
  // whose hop chain already passed through us. Encoding drops it on every other
135
295
  // version, where we drop the reflected announce on receipt instead. Matches the
136
296
  // Rust subscriber's `exclude_hop: self.self_origin.id` in `run_announce_prefix`.
137
- const msg = new AnnounceRequest(prefix, this.hop, hidden);
138
- const visible = (path) => scopeOverlaps(scope, path) && (hidden || !hiddenBelow(prefix, path));
297
+ const msg = new AnnounceRequest(prefix, this.hop);
298
+ // Every path the peer sends lies beneath the prefix, so only hiding and a `*`, which no
299
+ // origin accepts, filter it.
300
+ const visible = (path) => !path.includes("*") && (hidden || !hiddenBelow(prefix, path));
139
301
  // Opened outside the try so the catch can reach it: a protocol violation below has
140
302
  // to reset the stream, not just close our side of it.
141
303
  let stream;
142
304
  try {
143
- stream = await Stream.open(this.#quic, { version: this.version });
305
+ // The consumer leaving gives up the wait for a slot, so the next open takes it.
306
+ const left = new AbortController();
307
+ void race([announced.closed]).then(() => left.abort());
308
+ const opened = await Stream.tryOpen(this.#quic, { version: this.version, signal: left.signal });
309
+ // Handed a stream as the consumer left: give the slot back unused.
310
+ if (!opened || announced.closed.peek() !== undefined) {
311
+ opened?.close();
312
+ return;
313
+ }
314
+ stream = opened;
144
315
  }
145
316
  catch (err) {
146
317
  announced.close(error(err));
147
318
  return;
148
319
  }
320
+ // Each holds one of the session's announce slots, reflected and hidden ones included.
321
+ const advertised = new SlotMap(this.#announces);
322
+ // The paths this stream holds a session-minted identity for: a version before lite-07
323
+ // names none, so each advertisement stands for one stream until it ends.
324
+ const minted = new Map();
325
+ const mint = (path) => {
326
+ let identity = minted.get(path);
327
+ if (identity === undefined) {
328
+ identity = this.#minted.acquire(path);
329
+ minted.set(path, identity);
330
+ }
331
+ return identity;
332
+ };
333
+ // The peer ended the advertisement, which retires its identity.
334
+ const unmint = (path) => {
335
+ const identity = minted.get(path);
336
+ if (identity === undefined)
337
+ return;
338
+ minted.delete(path);
339
+ this.#minted.release(path, identity, true);
340
+ };
341
+ let stopDrain;
149
342
  try {
150
343
  // Send the announce interest.
151
344
  await stream.writer.u53(StreamId.Announce);
@@ -154,37 +347,61 @@ export class Subscriber {
154
347
  // It no longer stamps itself onto each hop chain, so we append it here to
155
348
  // keep the reflected-announce loop check seeing the full chain.
156
349
  let responderOrigin;
350
+ // The ANNOUNCEs still owed of the peer's initial set (lite-05+). Older versions
351
+ // mark no boundary, so they sync once the request is out, as a best effort.
352
+ let initial = 0;
353
+ let waitingSynced = hasSynced(this.version);
157
354
  if (hasAnnounceOk(this.version)) {
158
- const ok = await AnnounceOk.decode(stream.reader, this.version);
355
+ const ok = await race([AnnounceOk.decode(stream.reader, this.version), announced.closed]);
356
+ // A consumer that leaves before the peer answers ends the request now, not on the answer.
357
+ if (!(ok instanceof AnnounceOk)) {
358
+ stream.close();
359
+ return;
360
+ }
159
361
  // Keep a withheld 0: it names nobody for loop detection, but it is the
160
362
  // anonymous mark and must travel the reconstructed chain. Assigned identities
161
363
  // stay off this hop and are never forwarded.
162
364
  responderOrigin = ok.hop;
365
+ initial = ok.active;
163
366
  }
164
- const advertised = new Map();
165
367
  switch (this.version) {
166
368
  case Version.DRAFT_01:
167
369
  case Version.DRAFT_02: {
168
- // Receive ANNOUNCE_INIT first
169
- const init = await AnnounceInit.decode(stream.reader, this.version);
370
+ // Receive ANNOUNCE_INIT first. Each suffix takes an announce slot, so a set past
371
+ // what is left of the budget is refused before it is decoded.
372
+ const budget = this.#announces.available();
373
+ const init = await race([
374
+ AnnounceInit.decode(stream.reader, this.version, budget),
375
+ announced.closed,
376
+ ]);
377
+ if (!(init instanceof AnnounceInit)) {
378
+ stream.close();
379
+ return;
380
+ }
170
381
  // Process initial announcements. These are advertisements like any other, so
171
382
  // they go on record and obey the same one-per-path rule: the initial set
172
383
  // naming a path twice is the same violation as two ANNOUNCE_STARTs for it,
173
384
  // and the record is what catches either. Draft01/02 carry no hop ids and no
174
- // ANNOUNCE_OK, so this connection's stamp names the publisher.
385
+ // ANNOUNCE_OK, so nothing names the publisher.
175
386
  for (const suffix of init.suffixes) {
176
- const path = Path.join(prefix, suffix);
387
+ const path = joinAnnounced(prefix, suffix);
177
388
  if (advertised.has(path)) {
178
389
  throw new ProtocolViolation(`duplicate announce for ${path}`);
179
390
  }
180
- const route = { hops: [this.#stamp, UNKNOWN_HOP], cost: Cost.zero };
391
+ const route = this.#drained({
392
+ identity: mint(path),
393
+ epoch: 0n,
394
+ hops: [UNKNOWN_HOP],
395
+ cost: Cost.zero,
396
+ priority: this.#link.priority,
397
+ });
181
398
  const live = visible(path);
182
- const captures = scopeCaptures(scope, path);
183
- advertised.set(path, { publisher: this.#stamp, live, route, captures });
399
+ advertised.set(path, { live, route });
184
400
  if (!live)
185
401
  continue;
402
+ this.#consumes.announce(path, announced, route);
186
403
  console.debug(`announced: broadcast=${path} active=true`);
187
- announced.append({ prefix: path, captures, kind: "announced", route });
404
+ announced.append({ prefix: path, kind: "start", route });
188
405
  }
189
406
  break;
190
407
  }
@@ -192,59 +409,114 @@ export class Subscriber {
192
409
  // Draft03+: no AnnounceInit, initial state comes via Announce messages.
193
410
  break;
194
411
  }
412
+ // A draining peer usually stops announcing, so rank its routes last from the GOAWAY
413
+ // itself. Waiting for another message would leave the route primary until the
414
+ // session closed. Idempotent: a route already draining emits nothing. A GOAWAY that
415
+ // already arrived needs no listener, since `#drained()` marked every route above.
416
+ const drainAdvertised = () => {
417
+ if (announced.closed.peek() !== undefined)
418
+ return;
419
+ for (const [path, ad] of advertised) {
420
+ if (!ad.live)
421
+ continue;
422
+ const route = { ...ad.route, draining: true };
423
+ if (routesEqual(ad.route, route))
424
+ continue;
425
+ advertised.set(path, { ...ad, route });
426
+ this.#consumes.announce(path, announced, route);
427
+ announced.append({ prefix: path, kind: "update", route });
428
+ }
429
+ };
430
+ stopDrain = this.#goaway?.changed(() => drainAdvertised());
195
431
  // Lite06+: announce ids. Each received `active` implicitly assigns the next
196
- // per-stream ordinal; `endedId`/`restart` reference it, and lite-07 bases copy
197
- // from it. Tracked even for announces we skip as reflected, since the sender
432
+ // per-stream ordinal; `endedId`/`update`/`restart` reference it, and lite-07 bases
433
+ // copy from it. Tracked even for announces we skip as reflected, since the sender
198
434
  // doesn't know we skipped.
199
435
  const history = new AnnounceHistory();
200
- // Receive announce updates (for Draft03, this includes initial state)
436
+ // Only lite-07 refuses a forwarded path, and it never reaches here.
437
+ const known = (path) => {
438
+ if (path === undefined)
439
+ throw new ProtocolViolation("a refused path before lite-07");
440
+ return path;
441
+ };
442
+ // Receive announce updates (for Draft03+, this includes initial state)
201
443
  for (;;) {
444
+ if (initial === 0 && !waitingSynced)
445
+ announced.synced();
202
446
  const announce = await race([
203
447
  decodeAnnounceBroadcastMaybe(stream.reader, this.version),
204
448
  announced.closed,
205
449
  ]);
206
450
  // undefined: the stream ended. null: the consumer closed cleanly.
451
+ if (announce === undefined && (initial > 0 || waitingSynced)) {
452
+ throw new ProtocolViolation("announce stream ended inside the initial set");
453
+ }
207
454
  if (!announce)
208
455
  break;
209
456
  if (announce instanceof Error)
210
457
  throw announce;
458
+ if (announce.status === "synced") {
459
+ if (!waitingSynced)
460
+ throw new ProtocolViolation("duplicate SYNCED");
461
+ waitingSynced = false;
462
+ continue;
463
+ }
464
+ // The counted initial set is ANNOUNCEs only, so anything else cuts it short. An
465
+ // unknown message counts for nothing either way.
466
+ if (initial > 0 && announce.status !== "skipped") {
467
+ if (announce.status !== "active") {
468
+ throw new ProtocolViolation(`${announce.status} inside the initial set`);
469
+ }
470
+ initial -= 1;
471
+ }
211
472
  let path;
212
473
  let active;
213
- // Present on active/restart; ended messages never carry hops worth checking.
474
+ // Present on active/update/restart; ended messages never carry hops worth checking.
214
475
  let hops;
215
476
  let cost;
477
+ // Present on active and restart from lite-07; an update never changes them.
478
+ let identity;
479
+ let epoch;
480
+ // The advertisement now serves another identity or epoch (lite-07).
481
+ const restart = false;
216
482
  switch (announce.status) {
217
483
  case "active": {
218
- const resolved = hasAnnounceId(this.version) ? history.start(announce) : announce;
484
+ const suffix = hasAnnounceId(this.version) ? known(history.start(announce)) : announce.suffix;
219
485
  // The wire names the suffix beneath the interest prefix; the consumer
220
486
  // sees the covered path from the session root.
221
- path = Path.join(prefix, resolved.suffix);
487
+ path = joinAnnounced(prefix, suffix);
222
488
  active = true;
223
- hops = resolved.hops;
489
+ hops = announce.hops ?? [];
224
490
  cost = announce.cost;
225
491
  break;
226
492
  }
227
493
  case "ended":
228
- path = Path.join(prefix, announce.suffix);
494
+ path = joinAnnounced(prefix, announce.suffix);
229
495
  active = false;
230
496
  break;
231
497
  case "endedId":
232
498
  // Resolve and retire the id; an unknown or retired id is a protocol violation.
233
- path = Path.join(prefix, history.end(announce.id));
499
+ path = joinAnnounced(prefix, known(history.end(announce.id)));
234
500
  active = false;
235
501
  break;
236
- case "restart": {
502
+ case "update":
237
503
  // Resolve the id; it stays live (the replacement reuses it).
238
- const resolved = history.update(announce);
239
- path = Path.join(prefix, resolved.suffix);
504
+ path = joinAnnounced(prefix, history.get(announce.id));
240
505
  active = true;
241
- hops = resolved.hops;
506
+ hops = announce.hops ?? [];
242
507
  cost = announce.cost;
243
508
  break;
244
- }
245
509
  case "skipped":
246
510
  continue;
511
+ default:
512
+ // The restart and the route layer are lite-07's, on its Announce Stream.
513
+ throw new ProtocolViolation(`unexpected ${announce.status} before lite-07`);
247
514
  }
515
+ // Each suffix fits the wire limits alone, but the interest prefix can push the
516
+ // joined path past them, which the draft makes a violation too.
517
+ const error = Path.check(path);
518
+ if (error)
519
+ throw new ProtocolViolation(error);
248
520
  // One current advertisement per path per stream, decided before anything below
249
521
  // can skip this announcement. A second ANNOUNCE_START for a path the peer
250
522
  // already advertised is a violation whether or not its route would be usable
@@ -256,98 +528,126 @@ export class Subscriber {
256
528
  // idiom. lite-06 gave that its own message and older versions never had one, so
257
529
  // a duplicate means the same thing on both sides of it. Mirrors the branch the
258
530
  // Rust announce loop takes before `start_announce`.
259
- const duplicateIsRestart = restartSupported(this.version) && !hasAnnounceId(this.version);
260
- if (announce.status === "active" && !duplicateIsRestart && advertised.has(path)) {
531
+ const duplicateIsUpdate = updateSupported(this.version) && !hasAnnounceId(this.version);
532
+ if (announce.status === "active" && !duplicateIsUpdate && advertised.has(path)) {
261
533
  throw new ProtocolViolation(`duplicate announce for ${path}`);
262
534
  }
263
- // Retract the path: forget the advertisement, drop the shared consume entry so a
264
- // later announce subscribes fresh rather than cloning the dead generation's tracks,
265
- // and tell the consumer. A no-op for an advertisement never surfaced, which is
535
+ // Retract this interest's advertisement so new consumes resolve the remaining
536
+ // serving identity, and tell the consumer. A no-op for an advertisement never surfaced, which is
266
537
  // what an id retiring a skipped announce resolves to.
267
538
  const retract = () => {
268
539
  const previous = advertised.get(path);
269
540
  advertised.delete(path);
541
+ this.#consumes.withdraw(path, announced);
270
542
  if (!previous?.live)
271
543
  return;
272
- this.#consumes.evict(path);
273
544
  console.debug(`announced: broadcast=${path} active=false`);
274
545
  announced.append({
275
546
  prefix: path,
276
- captures: previous.captures,
277
- kind: "retracted",
547
+ kind: "end",
278
548
  route: previous.route,
279
549
  });
280
550
  };
551
+ if (!active) {
552
+ retract();
553
+ unmint(path);
554
+ continue;
555
+ }
556
+ // An update keeps the identity its announcement named, even through a placeholder
557
+ // below: a later update that is not reflected still names that stream. A version
558
+ // before lite-07 names none, so the session mints one per advertisement.
559
+ if (!restart) {
560
+ const previous = advertised.get(path)?.route;
561
+ identity ??= previous?.identity;
562
+ epoch ??= previous?.epoch;
563
+ }
564
+ if (identity === undefined) {
565
+ identity = mint(path);
566
+ epoch = 0n;
567
+ }
281
568
  // In Lite05+ the sender's origin arrives via AnnounceOk, not in each hop
282
569
  // list, so fold it back in before checking.
283
570
  if (hops !== undefined) {
284
571
  const full = responderOrigin !== undefined ? [...hops, responderOrigin] : hops;
285
572
  if (full.includes(this.hop)) {
286
- // A reflected restart means the peer's remaining route loops back through
573
+ // A reflected update means the peer's remaining route loops back through
287
574
  // us, so the route is gone even though the message says active. The
288
575
  // advertisement stays live: the peer still holds the path and its id still
289
576
  // resolves here.
290
577
  retract();
291
578
  advertised.set(path, {
292
- publisher: undefined,
293
579
  live: false,
294
- route: { hops: full, cost: Cost.zero },
295
- captures: undefined,
580
+ route: { identity, epoch, hops: full, cost: Cost.zero },
296
581
  });
297
582
  continue;
298
583
  }
299
584
  }
300
- if (!active) {
301
- retract();
302
- continue;
303
- }
304
- // The first hop identifies the original publisher; an empty chain means the
305
- // peer itself originated it. One that names nobody (lite-01..03, or a peer
306
- // reporting 0) gets this connection's stamp in front of its 0.
307
- const fullHops = stampHops(hops !== undefined && responderOrigin !== undefined
585
+ const fullHops = hops !== undefined && responderOrigin !== undefined
308
586
  ? [...hops, responderOrigin]
309
- : [...(hops ?? [])], this.#stamp);
587
+ : [...(hops ?? [])];
588
+ // A received empty list is the anonymous mark, not a local announcement.
589
+ if (fullHops.length === 0)
590
+ fullHops.push(UNKNOWN_HOP);
310
591
  // Appending a withheld AnnounceOk(0) onto a 32-entry list is the same
311
592
  // drop Rust's Hops::push makes: do not expose an overlong chain.
312
- if (fullHops === undefined || fullHops.length > MAX_HOPS) {
593
+ if (fullHops.length > MAX_HOPS) {
313
594
  console.debug(`announced: broadcast=${path} dropped (hop chain at MAX_HOPS)`);
314
595
  advertised.set(path, {
315
- publisher: undefined,
316
596
  live: false,
317
- route: { hops: [], cost: Cost.zero },
318
- captures: undefined,
597
+ route: { identity, epoch, hops: [], cost: Cost.zero },
319
598
  });
320
599
  continue;
321
600
  }
322
- const publisher = fullHops[0];
323
- const route = { hops: fullHops, cost: cost ?? Cost.zero };
324
- const captures = scopeCaptures(scope, path);
601
+ // What the peer advertised plus this link's price, ranked at this link's priority. The
602
+ // price may wait on the peer's SETUP, which this reader stops waiting for once closed.
603
+ const link = await race([this.#cost(), announced.closed]);
604
+ if (link instanceof Error)
605
+ throw link;
606
+ if (typeof link !== "bigint")
607
+ break;
608
+ const route = this.#drained({
609
+ identity,
610
+ epoch,
611
+ hops: fullHops,
612
+ cost: Cost.charged(cost ?? Cost.zero, link),
613
+ priority: this.#link.priority,
614
+ });
325
615
  if (!visible(path)) {
326
- advertised.set(path, { publisher, live: false, route, captures });
616
+ advertised.set(path, { live: false, route });
327
617
  continue;
328
618
  }
329
- // A second advertisement for a path we already carry is a restart: either an
619
+ // Another identity or epoch: whatever was consumed at the path may be stale, so the
620
+ // next consume subscribes fresh, while the handles already out keep theirs.
621
+ const previous = advertised.get(path);
622
+ if (restart && previous?.live) {
623
+ advertised.set(path, { live: true, route });
624
+ this.#consumes.announce(path, announced, route, true);
625
+ console.debug(`announced: broadcast=${path} restart=true identity=${identity} epoch=${epoch}`);
626
+ announced.append({ prefix: path, kind: "restart", route });
627
+ continue;
628
+ }
629
+ // A second advertisement for a path we already carry is an update: either an
330
630
  // explicit ANNOUNCE_UPDATE, or (lite-05) a duplicate ANNOUNCE. It updates the
331
631
  // route in place, so a forwarder re-prices without retracting.
332
- const previous = advertised.get(path);
333
632
  if (previous?.live) {
334
- // A different publisher took the path. Subscriptions already open drain
335
- // the old copy, but the next consume starts fresh rather than reusing the
336
- // old publisher's cached track info.
337
- if (previous.publisher !== publisher)
338
- this.#consumes.evict(path);
339
- advertised.set(path, { publisher, live: true, route, captures });
633
+ // An update preserves the advertisement's identity.
634
+ advertised.set(path, { live: true, route });
635
+ this.#consumes.announce(path, announced, route);
340
636
  console.debug(`announced: broadcast=${path} rerouted`);
341
637
  if (!routesEqual(previous.route, route)) {
342
- announced.append({ prefix: path, captures, kind: "updated", route });
638
+ announced.append({ prefix: path, kind: "update", route });
343
639
  }
344
640
  continue;
345
641
  }
346
- advertised.set(path, { publisher, live: true, route, captures });
347
- console.debug(`announced: broadcast=${path} active=true`);
348
- announced.append({ prefix: path, captures, kind: "announced", route });
642
+ advertised.set(path, { live: true, route });
643
+ this.#consumes.announce(path, announced, route);
644
+ console.debug(`announced: broadcast=${path} active=true identity=${identity}`);
645
+ announced.append({ prefix: path, kind: "start", route });
349
646
  }
350
647
  announced.close();
648
+ // Either side ending the interest ends the stream, or the peer keeps it open, still
649
+ // discovering into it and holding a stream slot.
650
+ stream.close();
351
651
  }
352
652
  catch (err) {
353
653
  const e = error(err);
@@ -360,108 +660,592 @@ export class Subscriber {
360
660
  // A violation ends the session, not just this stream, so a nonconforming peer
361
661
  // cannot repeat it on the next one. Matches `ietf::Subscriber` and the Rust
362
662
  // lite subscriber, where the announce half only ever ends the session on error.
363
- if (e instanceof ProtocolViolation) {
364
- this.#quic.close({ closeCode: PROTOCOL_VIOLATION_CODE, reason: closeReason(reason(e)) });
365
- }
663
+ closeViolation(this.#quic, e);
664
+ }
665
+ finally {
666
+ // Release only this interest's routes. Existing consumers remain pinned.
667
+ for (const path of advertised.keys())
668
+ this.#consumes.withdraw(path, announced);
669
+ advertised.clear();
670
+ // The stream closing ends none of its advertisements, which another may still carry.
671
+ for (const [path, identity] of minted)
672
+ this.#minted.release(path, identity, false);
673
+ minted.clear();
674
+ stopDrain?.();
366
675
  }
367
676
  }
677
+ /**
678
+ * Lite-07: one message the peer sent on its Announce Stream. Its routes and claims apply
679
+ * here; its own ANNOUNCE_REQUEST only has to arrive outside a DEAD's updates.
680
+ *
681
+ * @internal
682
+ */
683
+ announce(msg) {
684
+ if (!this.#routed)
685
+ throw new ProtocolViolation("Announce Stream before lite-07");
686
+ return this.#routed.receive(msg);
687
+ }
688
+ /**
689
+ * Lite-07: the peer finished its Announce Stream, so it is leaving and its routes end.
690
+ *
691
+ * @internal
692
+ */
693
+ announceFinished() {
694
+ this.#routed?.finish();
695
+ }
696
+ /**
697
+ * Lite-07: this side finished its Announce Stream, so it asks the peer for nothing more.
698
+ *
699
+ * @internal
700
+ */
701
+ announceSilenced() {
702
+ this.#routed?.silence();
703
+ }
368
704
  /**
369
705
  * Consumes a broadcast from the connection.
370
706
  *
371
- * Deduplicated per path: repeat calls for the same still-live path share one reference-counted
707
+ * Deduplicated per serving identity: repeat calls for the same path share one reference-counted
372
708
  * broadcast (and one upstream subscription). The shared broadcast closes once every caller has
373
709
  * closed its handle, so callers close normally.
374
710
  *
375
711
  * @param name - The name of the broadcast to consume
376
- * @returns A Broadcast instance
712
+ * @param pin - Consume only this identity, over its best route. A minted one names an
713
+ * announcement rather than a stream, so it pins nothing on a wire that carries no identity.
714
+ * @returns A Broadcast identity
377
715
  */
378
- consume(path) {
379
- return this.#consumes.get(path) ?? this.#consumes.insert(path, this.#createConsume(path));
380
- }
381
- #createConsume(path) {
382
- // A consumed broadcast resolves info() and fetchGroup() over the wire by reaching
383
- // back into this Subscriber (see ConsumeBroadcast below), rather than the wire
384
- // installing callbacks on the broadcast.
385
- const consumer = new ConsumeBroadcast(this, path);
716
+ consume(path, pin) {
717
+ const identity = pin !== undefined && (hasIdentity(this.version) || !Identity.isMinted(pin))
718
+ ? this.#consumes.pinned(path, pin)
719
+ : this.#consumes.identity(path);
720
+ return this.#consumes.get(path, identity) ?? this.#createConsume(path, identity);
721
+ }
722
+ #createConsume(path, identity) {
723
+ const consumed = {
724
+ identity: identity.route.identity,
725
+ id: this.#consumeNext++,
726
+ get valid() {
727
+ return identity.validity?.signal;
728
+ },
729
+ get answering() {
730
+ return identity.validity?.answering;
731
+ },
732
+ };
733
+ const consumer = new ConsumeBroadcast(this, path, consumed);
734
+ // Registered before anyone can list the broadcast, so no reader syncs without the peer.
735
+ void this.#runListing(path, consumed, wireOf(consumer).lister());
386
736
  void (async () => {
387
737
  for (;;) {
388
738
  const request = await wireOf(consumer).requested();
389
739
  if (!request)
390
740
  break;
391
- void this.#runSubscribe(path, request);
741
+ void this.#runSubscribe(path, consumed, request, consumer);
392
742
  }
393
743
  })();
394
- return consumer;
744
+ void (async () => {
745
+ for (;;) {
746
+ const request = await wireOf(consumer).requestedDatagrams();
747
+ if (!request)
748
+ return;
749
+ void this.#runDatagramRequest(path, consumed, consumer, request);
750
+ }
751
+ })();
752
+ return this.#consumes.insert(path, identity, consumer);
753
+ }
754
+ // Each request owns its setup and subscription until it ends or loses its last reader.
755
+ async #runDatagramRequest(path, consumed, consumer, request) {
756
+ const cancel = new AbortController();
757
+ const signal = AbortSignal.any([
758
+ cancel.signal,
759
+ this.#closed.signal,
760
+ ...(consumed.valid ? [consumed.valid] : []),
761
+ ]);
762
+ let producer;
763
+ let stream;
764
+ const id = this.#subscribeNext++;
765
+ const legacyKey = hasDatagrams(this.version) && !hasDatagramTracks(this.version)
766
+ ? JSON.stringify([consumed.id, request.name])
767
+ : undefined;
768
+ // A stream answer can arrive while this request waits for authorization.
769
+ if (legacyKey !== undefined)
770
+ this.#legacyRequests.set(legacyKey, request);
771
+ const unused = async () => {
772
+ while (request.priority.peek() !== undefined && request.closed.peek() === undefined)
773
+ await Signal.race(request.priority, request.closed);
774
+ // An accepted legacy producer belongs to the stream subscription, including gaps
775
+ // between datagram readers. Its priority watcher releases only their extra demand.
776
+ if (legacyKey !== undefined && this.#legacyDatagrams.has(legacyKey))
777
+ return;
778
+ if (request.priority.peek() === undefined && (!producer || hooks.closeUnusedDatagrams(producer)))
779
+ cancel.abort(new StreamError(StreamCode.Cancel));
780
+ };
781
+ void unused();
782
+ const grant = this.#grant?.subscribe(() => {
783
+ if (this.#denied(path))
784
+ cancel.abort(unauthorized(path));
785
+ });
786
+ try {
787
+ if (!hasDatagrams(this.version) ||
788
+ DatagramStream.maxDatagramSize(this.#quic) === 0 ||
789
+ !DatagramStream.canReceiveDatagrams(this.#quic))
790
+ throw new Error("transport does not support datagram tracks");
791
+ const ready = await this.#auth?.ready(path, "subscribe", {
792
+ signal,
793
+ until: () => Promise.resolve(request.closed),
794
+ });
795
+ if (ready === false)
796
+ throw new StreamError(StreamCode.Cancel);
797
+ if (this.#denied(path))
798
+ throw unauthorized(path);
799
+ signal.throwIfAborted();
800
+ if (!hasDatagramTracks(this.version)) {
801
+ await this.#legacyDatagramRequest(consumed, consumer, request, signal);
802
+ return;
803
+ }
804
+ const deadline = new Deadline();
805
+ let priority = request.priority.peek() ?? 0;
806
+ const answered = await deadline.wait(this.#exchange({ version: this.version }, async (opened) => {
807
+ stream = opened;
808
+ this.#unanswered.add(id);
809
+ await opened.writer.u53(StreamId.Datagrams);
810
+ await new Datagrams({
811
+ id,
812
+ broadcast: path,
813
+ identity: consumed.identity,
814
+ track: request.name,
815
+ priority,
816
+ }).encode(opened.writer, this.version);
817
+ const info = await DatagramsInfo.decode(opened.reader, this.version);
818
+ return info;
819
+ }, signal, deadline));
820
+ signal.throwIfAborted();
821
+ if (!stream)
822
+ throw new Error("datagram stream was not opened");
823
+ producer = request.accept(answered);
824
+ const route = { producer, timescale: answered.timescale };
825
+ this.#datagrams.set(id, route);
826
+ this.#unanswered.delete(id);
827
+ const opened = stream;
828
+ const receiving = producer;
829
+ // The only thing following DATAGRAMS_INFO is the publisher's FIN. Its last datagram may
830
+ // arrive alongside, so the datagrams already received route first.
831
+ const ended = opened.reader.done().then(async (done) => {
832
+ if (!done)
833
+ throw new ProtocolViolation("data after DATAGRAMS_INFO");
834
+ route.ended = true;
835
+ await this.#datagramsRouted(id);
836
+ receiving.finish();
837
+ });
838
+ void ended.catch(() => { });
839
+ while (producer.closed.peek() === undefined) {
840
+ const next = producer.priority.peek();
841
+ if (next === undefined && hooks.closeUnusedDatagrams(producer))
842
+ break;
843
+ if (next !== undefined && next !== priority) {
844
+ await untilAborted(new DatagramsUpdate(next).encode(opened.writer, this.version), signal);
845
+ priority = next;
846
+ // The priority may have changed again during the write, before the wait below.
847
+ continue;
848
+ }
849
+ await untilAborted(race([ended, Signal.race(producer.priority, producer.closed)]), signal);
850
+ }
851
+ const closed = producer.closed.peek();
852
+ if (closed instanceof Error)
853
+ throw closed;
854
+ stream.writer.close();
855
+ }
856
+ catch (err) {
857
+ closeViolation(this.#quic, err);
858
+ const cause = error(err);
859
+ cancel.abort(cause);
860
+ request.reject(cause);
861
+ stream?.abort(cause);
862
+ }
863
+ finally {
864
+ if (legacyKey !== undefined && this.#legacyRequests.get(legacyKey) === request)
865
+ this.#legacyRequests.delete(legacyKey);
866
+ grant?.();
867
+ this.#unanswered.delete(id);
868
+ this.#datagrams.delete(id);
869
+ cancel.abort(new StreamError(StreamCode.Cancel));
870
+ stream?.reader.stop(StreamCode.Cancel);
871
+ }
872
+ }
873
+ // Lite-05/06: the shared producer holds stream demand while any datagram reader exists.
874
+ async #legacyDatagramRequest(consumed, consumer, request, signal) {
875
+ const key = JSON.stringify([consumed.id, request.name]);
876
+ const subscriber = wireOf(consumer).subscribe(request.name, latestAt(request.priority.peek() ?? 0));
877
+ try {
878
+ await untilAborted(subscriber.info(), signal);
879
+ const shared = this.#legacyDatagrams.get(key);
880
+ if (!shared)
881
+ throw new Error("stream subscription did not bind its datagram track");
882
+ const producer = shared.producer;
883
+ // Once registered, the shared producer owns demand regardless of which kind joined first.
884
+ subscriber.close();
885
+ const closed = await untilAborted(Promise.resolve(producer.closed), signal);
886
+ if (closed instanceof Error)
887
+ throw closed;
888
+ }
889
+ finally {
890
+ subscriber.close();
891
+ }
892
+ }
893
+ // Answer listings of a consumed broadcast from the peer's TRACKS while anyone lists it, until
894
+ // the broadcast closes. Every listing of the broadcast shares one TRACKS stream.
895
+ async #runListing(broadcast, consumed, lister) {
896
+ try {
897
+ for (;;) {
898
+ if (lister.closed.peek() !== undefined || this.#closed.signal.aborted)
899
+ return;
900
+ if (!lister.wanted.peek()) {
901
+ await untilAborted(race([Signal.race(lister.wanted, lister.closed)]), this.#closed.signal).catch(() => { });
902
+ continue;
903
+ }
904
+ if (!hasTracks(this.version)) {
905
+ // An empty answer would claim the peer lists nothing.
906
+ lister.abort(new Error("track listing requires moq-lite-07 or newer"));
907
+ continue;
908
+ }
909
+ await this.#listTracks(broadcast, consumed, lister);
910
+ }
911
+ }
912
+ finally {
913
+ lister.close();
914
+ }
915
+ }
916
+ // Forward the peer's TRACKS listing of `broadcast` into `lister` until the peer ends it, it
917
+ // fails, our grant stops covering the broadcast, or nobody lists the broadcast any more.
918
+ // Returns without answering when setup was cut short, for the caller to look again.
919
+ async #listTracks(broadcast, consumed, lister) {
920
+ // The consumed identity must still be the selected one until the request is out, then
921
+ // not replaced until the peer answers: a TRACKS request without an identity lists whichever
922
+ // identity won the path when it arrived.
923
+ const valid = consumed.valid;
924
+ if (valid?.aborted) {
925
+ lister.abort(error(valid.reason));
926
+ return;
927
+ }
928
+ const setup = valid ? AbortSignal.any([this.#closed.signal, valid]) : this.#closed.signal;
929
+ // A listing is a subscribe: one opened before a token that covers it is answered would be
930
+ // refused by the peer.
931
+ const ready = await this.#auth
932
+ ?.ready(broadcast, "subscribe", {
933
+ signal: setup,
934
+ until: async () => {
935
+ while (lister.wanted.peek() && lister.closed.peek() === undefined) {
936
+ await Signal.race(lister.wanted, lister.closed);
937
+ }
938
+ },
939
+ })
940
+ .catch(() => false);
941
+ // The readers may have left while the wait settled, before the unused watch below is armed.
942
+ if (ready === false || setup.aborted || !lister.wanted.peek())
943
+ return;
944
+ // Armed before the first check and held to the end, so a shrink is never missed.
945
+ const refused = unauthorized(broadcast);
946
+ const revoked = new AbortController();
947
+ const disposeGrant = this.#grant?.subscribe(() => {
948
+ if (this.#denied(broadcast))
949
+ revoked.abort(refused);
950
+ });
951
+ if (this.#denied(broadcast)) {
952
+ disposeGrant?.();
953
+ lister.abort(refused);
954
+ return;
955
+ }
956
+ // Each listed track holds an announces slot: discovery state the peer makes us hold. Each
957
+ // kind is a namespace apart.
958
+ const listedTracks = new Set();
959
+ const listedDatagrams = new Set();
960
+ const listed = (type) => (type === "datagrams" ? listedDatagrams : listedTracks);
961
+ const unused = new AbortController();
962
+ const stop = AbortSignal.any([unused.signal, revoked.signal, this.#closed.signal]);
963
+ const disposeWanted = lister.wanted.subscribe((wanted) => {
964
+ if (!wanted)
965
+ unused.abort(new StreamError(StreamCode.Cancel, { message: "listing unused" }));
966
+ });
967
+ let stream;
968
+ try {
969
+ const cut = valid ? AbortSignal.any([stop, valid]) : stop;
970
+ stream = await Stream.tryOpen(this.#quic, { version: this.version, signal: cut });
971
+ // Gave up, perhaps handed a stream as it did: the catch below hands back any stream.
972
+ if (!stream || cut.aborted)
973
+ throw cut.reason;
974
+ await stream.writer.u53(StreamId.Tracks);
975
+ await new TracksMessage(broadcast, consumed.identity).encode(stream.writer, this.version);
976
+ let synced = false;
977
+ const answering = consumed.answering;
978
+ let unanswered = answering ? AbortSignal.any([stop, answering]) : stop;
979
+ for (;;) {
980
+ const pause = listingBudget.poll();
981
+ if (pause !== undefined)
982
+ await untilAborted(pause, stop);
983
+ const event = await untilAborted(decodeTracksEventMaybe(stream.reader, this.version), unanswered);
984
+ unanswered = stop;
985
+ if (!event) {
986
+ // The peer's broadcast ended, whether or not its retraction has arrived: end the
987
+ // listing and let go of what it listed. FIN our half too, so the stream is done.
988
+ stream.writer.close();
989
+ lister.end();
990
+ return;
991
+ }
992
+ if (event.kind === "added") {
993
+ if (listed(event.type).has(event.name))
994
+ throw new ProtocolViolation(`track listed twice: ${event.name}`);
995
+ if (!this.#announces.tryAcquire()) {
996
+ throw new SessionError(SessionCode.TooManyRequests, { reason: "too many listed tracks" });
997
+ }
998
+ listed(event.type).add(event.name);
999
+ if (event.type === "datagrams") {
1000
+ const info = { priority: event.info.priority, timescale: event.info.timescale ?? null };
1001
+ lister.add(event.name, { type: "datagrams", info });
1002
+ }
1003
+ else {
1004
+ lister.add(event.name, { type: "track", info: this.#toModelInfo(event.info) });
1005
+ }
1006
+ }
1007
+ else if (event.kind === "removed" || event.kind === "finished") {
1008
+ if (!listed(event.type).delete(event.name))
1009
+ throw new ProtocolViolation(`unlisted track removed: ${event.name}`);
1010
+ this.#announces.release();
1011
+ if (event.kind === "finished")
1012
+ lister.finish(event.name, event.type);
1013
+ else
1014
+ lister.remove(event.name, event.type);
1015
+ }
1016
+ else {
1017
+ if (synced)
1018
+ throw new ProtocolViolation("duplicate SYNCED");
1019
+ synced = true;
1020
+ // Synced when the peer is, so a track listed after it is new upstream too.
1021
+ lister.synced();
1022
+ }
1023
+ }
1024
+ }
1025
+ catch (err) {
1026
+ if (revoked.signal.aborted) {
1027
+ // Reset rather than cancel, so the peer reads a revocation instead of a routine end.
1028
+ console.debug(`tracks revoked: broadcast=${broadcast}`);
1029
+ stream?.abort(refused);
1030
+ lister.abort(refused);
1031
+ return;
1032
+ }
1033
+ if (unused.signal.aborted) {
1034
+ // Nobody lists the broadcast any more: cancel the peer's listing.
1035
+ stream?.close();
1036
+ lister.clear();
1037
+ return;
1038
+ }
1039
+ closeViolation(this.#quic, err);
1040
+ const e = await sessionCause(this.#quic, err);
1041
+ console.debug(`tracks failed: broadcast=${broadcast} error=${reason(e)}`);
1042
+ stream?.abort(e);
1043
+ lister.abort(e);
1044
+ }
1045
+ finally {
1046
+ disposeGrant?.();
1047
+ disposeWanted();
1048
+ this.#announces.release(listedTracks.size + listedDatagrams.size);
1049
+ }
395
1050
  }
396
- async #runSubscribe(broadcast, request) {
1051
+ async #runSubscribe(broadcast, consumed, request, consumer) {
397
1052
  const id = this.#subscribeNext++;
398
- const subscription = request.subscription;
399
- const initialBounds = groupBounds(subscription.groups);
400
- if (emptyRange({ startGroup: initialBounds.start, endGroup: initialBounds.end })) {
1053
+ if (wireRanges(request.subscription.ranges ?? [{}]).length === 0) {
401
1054
  request.reject(new Error(EMPTY_RANGE));
402
1055
  return;
403
1056
  }
404
- // `timescale` stays undefined until TRACK_INFO (or, on older drafts,
405
- // implicit defaults) resolves it; runGroup blocks on it before decoding.
406
- const timescale = new Signal(undefined);
407
- console.debug(`subscribe start: id=${id} broadcast=${broadcast} track=${request.name}`);
408
- const bounds = groupBounds(subscription.groups);
409
- const msg = new Subscribe({
410
- id,
411
- broadcast,
412
- track: request.name,
413
- priority: subscription.priority ?? 0,
414
- maxAge: subscription.maxAge,
415
- startGroup: subscription.groups?.start === undefined ? undefined : bounds.start,
416
- endGroup: inclusiveGroupEnd(bounds.end),
1057
+ const refused = unauthorized(broadcast);
1058
+ try {
1059
+ for (;;) {
1060
+ const ready = await this.#auth?.ready(broadcast, "subscribe", {
1061
+ signal: consumed.valid,
1062
+ until: () => unwanted(request.demand()),
1063
+ });
1064
+ if (ready !== false)
1065
+ break;
1066
+ // Demand returning before we commit is not abandonment, matching the serving loop.
1067
+ if (!isAbandoned(request.demand()))
1068
+ continue;
1069
+ request.reject(new Error("subscribe abandoned before it was authorized"));
1070
+ return;
1071
+ }
1072
+ }
1073
+ catch (err) {
1074
+ request.reject(error(err));
1075
+ return;
1076
+ }
1077
+ // Armed before the first check and held to the end, so a shrink while the
1078
+ // subscription sets up is never missed: it resets whatever reached the wire.
1079
+ const state = {
1080
+ cancel: new AbortController(),
1081
+ consumer,
1082
+ consumedId: consumed.id,
1083
+ legacyKey: JSON.stringify([consumed.id, request.name]),
1084
+ };
1085
+ const disposeGrant = this.#grant?.subscribe(() => {
1086
+ if (state.revoked || !this.#denied(broadcast))
1087
+ return;
1088
+ state.revoked = refused;
1089
+ console.debug(`subscribe revoked: id=${id} broadcast=${broadcast} track=${request.name}`);
1090
+ state.cancel.abort(refused);
1091
+ if (state.producer)
1092
+ hooks.abortTrack(state.producer, refused);
1093
+ state.stream?.abort(refused);
417
1094
  });
418
- // Open the stream under a timeout. The stream handle flows back via `state`
419
- // so the timeout path can abort it if it finishes opening after the deadline.
420
- const state = {};
421
- const setup = this.#openSubscribe(state, msg, request, id, timescale);
1095
+ try {
1096
+ if (this.#denied(broadcast)) {
1097
+ request.reject(refused);
1098
+ return;
1099
+ }
1100
+ await this.#serveSubscribe(id, broadcast, consumed, request, state);
1101
+ }
1102
+ finally {
1103
+ disposeGrant?.();
1104
+ }
1105
+ }
1106
+ async #serveSubscribe(id, broadcast, consumed, request, state) {
1107
+ const { valid } = consumed;
1108
+ const { ranges, placed } = wireHeld(request.subscription);
1109
+ const msg = this.#subscribeMessage(id, broadcast, consumed, request, rangesPolicy(ranges), ranges, placed);
1110
+ console.debug(`subscribe start: id=${id} broadcast=${broadcast} track=${request.name}`);
1111
+ // The publisher's application may hold its answer, so the setup waits for it until the
1112
+ // last subscriber leaves, the broadcast goes, or the session ends. The stream handles
1113
+ // flow back via `state` so a failed setup can close them even if they open later, and
1114
+ // `cancel` ends a setup still running, resetting its TRACK stream.
1115
+ const retire = this.#retirer(state, valid);
1116
+ valid?.addEventListener("abort", retire);
1117
+ if (valid?.aborted)
1118
+ retire();
1119
+ const deadline = new Deadline();
1120
+ const setup = this.#openSubscribe(state, consumed, msg, { ranges, placed }, request, id, deadline);
1121
+ // Subscribers and info lookups explicitly own setup, including the handoff from
1122
+ // metadata acceptance to reader attachment. Release it when the last owner leaves.
1123
+ const left = new AbortController();
1124
+ const demand = request.demand();
1125
+ let unwatch;
1126
+ const watch = () => {
1127
+ if (isAbandoned(demand)) {
1128
+ left.abort(new StreamError(StreamCode.Cancel, { message: "subscribe abandoned before it was accepted" }));
1129
+ state.cancel.abort(left.signal.reason);
1130
+ }
1131
+ else {
1132
+ unwatch = Signal.race(demand.wanted, hooks.demandReleased(demand)).changed(watch);
1133
+ }
1134
+ };
1135
+ watch();
422
1136
  let opened;
423
1137
  try {
424
- opened = await withTimeout(setup, SUBSCRIBE_SETUP_TIMEOUT_MS, `subscribe timed out after ${SUBSCRIBE_SETUP_TIMEOUT_MS}ms waiting for the first response (browser stream limit reached?)`);
1138
+ opened = await deadline.wait(untilAborted(untilAborted(setup, valid), left.signal));
425
1139
  console.debug(`subscribe ok: id=${id} broadcast=${broadcast} track=${request.name}`);
426
1140
  }
427
1141
  catch (err) {
428
- // The setup outlived its deadline waiting for the first response: a control
429
- // timeout, not content that arrived late.
430
- const e = err instanceof TimeoutError ? controlTimeout(err) : await sessionCause(this.#quic, err);
1142
+ closeViolation(this.#quic, err);
1143
+ // Local abandonment commits without yielding after the demand check. A revocation
1144
+ // says so instead.
1145
+ const e = state.revoked ?? (left.signal.aborted ? left.signal.reason : await sessionCause(this.#quic, err));
1146
+ state.cancel.abort(e);
1147
+ valid?.removeEventListener("abort", retire);
431
1148
  request.reject(e);
432
1149
  this.#subscribes.delete(id);
433
1150
  console.warn(`subscribe error: id=${id} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);
434
- // If the stream eventually opens after the timeout, abort it so we
435
- // don't leak it. Cover both branches: setup may resolve late, or it
436
- // may reject (e.g. encode/decode failure) after the stream is open.
437
- setup.then(() => state.stream?.abort(e), () => state.stream?.abort(e));
1151
+ // Close the streams open now, since a write blocked on flow control may never let
1152
+ // setup settle, and any that open later once it does. Cover both branches: setup
1153
+ // may resolve late, or it may reject (e.g. encode/decode failure) after a stream
1154
+ // is open.
1155
+ const leave = () => {
1156
+ state.stream?.abort(e);
1157
+ state.track?.close();
1158
+ };
1159
+ leave();
1160
+ setup.then(leave, leave);
438
1161
  return;
439
1162
  }
1163
+ finally {
1164
+ unwatch?.();
1165
+ }
1166
+ valid?.removeEventListener("abort", retire);
440
1167
  const { stream, entry } = opened;
1168
+ await this.#serveStream(id, broadcast, consumed, state, stream, entry, msg);
1169
+ }
1170
+ // The SUBSCRIBE of `target` (a metadata subscription for its metadata copy) asking for `ranges`,
1171
+ // its wire ranges in the model, at `policy` as a wire without a policy per range carries one, each
1172
+ // live join `placed` at a group by index starting there. Its own wire ranges wait for the track's
1173
+ // timescale when they name a time (see `#withRanges`).
1174
+ #subscribeMessage(id, broadcast, consumed, target, policy, ranges, placed = new Map()) {
1175
+ const span = wireSpan(placedAsTimes(ranges, placed));
1176
+ return new Subscribe({
1177
+ id,
1178
+ broadcast,
1179
+ identity: consumed.identity,
1180
+ track: target.name,
1181
+ priority: policy.priority,
1182
+ order: policy.order,
1183
+ maxDelay: maxAge(ranges),
1184
+ startGroup: span.start,
1185
+ endGroup: inclusiveGroupEnd(span.end),
1186
+ meta: target.meta,
1187
+ });
1188
+ }
1189
+ // Ends a subscription's setup once `signal` aborts: its streams, and the track it accepted.
1190
+ #retirer(state, signal) {
1191
+ return () => {
1192
+ state.cancel.abort(signal?.reason);
1193
+ if (state.producer)
1194
+ hooks.abortTrack(state.producer, error(signal?.reason));
1195
+ state.stream?.abort(error(signal?.reason));
1196
+ };
1197
+ }
1198
+ // Serve one SUBSCRIBE stream into its track until it ends.
1199
+ async #serveStream(id, broadcast, consumed, state, stream, entry, msg) {
1200
+ const { answering } = consumed;
441
1201
  const producer = entry.track;
1202
+ // Sent but unanswered (lite-05+; older drafts already waited for SUBSCRIBE_OK), only a
1203
+ // replacement refuses it, since that identity may be the one answering.
1204
+ const replaced = this.#retirer(state, answering);
1205
+ if (entry.unanswered && answering) {
1206
+ answering.addEventListener("abort", replaced, { signal: entry.unanswered.answered.signal });
1207
+ if (answering.aborted)
1208
+ replaced();
1209
+ }
442
1210
  try {
443
1211
  // Watch for subscription changes and send SUBSCRIBE_UPDATE. Lite01/Lite02
444
1212
  // don't carry SUBSCRIBE_UPDATE on the wire, so skip the watcher there
445
1213
  // and just wait on the stream/track like before.
446
1214
  //
447
- // On lite-05+ the publisher sends SUBSCRIBE_START/END/DROP on this stream until
448
- // its FIN; older drafts just close it. Either way group streams can still be in
449
- // flight, so the track ends only once the tail is accounted for. A reset rejects
450
- // instead, so the track ends with that error rather than a clean tail.
451
- const responses = supportsTrackStream(this.version)
452
- ? this.runResponses(stream, entry)
453
- : stream.reader.closed;
454
- const closed = responses.then(() => this.#settleTail(entry));
455
- // A reset that lands after the race below settled is moot; the race observes one before.
456
- closed.catch(() => { });
1215
+ // The publisher sends responses on this stream until its FIN. Group streams can
1216
+ // still be in flight, so the track ends only once the tail is accounted for. A reset
1217
+ // rejects instead, so the track ends with that error rather than a clean tail.
1218
+ const responses = this.#read(stream, entry);
1219
+ let tailSettled = false;
1220
+ const responsesEnded = new Once();
1221
+ const closed = responses.then(async () => {
1222
+ if (entry.feedEnded?.peek())
1223
+ return;
1224
+ await this.#settleTail(entry);
1225
+ tailSettled = true;
1226
+ }, (err) => {
1227
+ // After we acknowledge its tail, a reset ends only the original feed.
1228
+ if (entry.feedEnded?.peek() && err instanceof StreamError && !this.#quicClosed.peek())
1229
+ return;
1230
+ throw err;
1231
+ });
1232
+ void responses.then(() => responsesEnded.set(null), () => responsesEnded.set(null));
1233
+ void closed.catch((err) => {
1234
+ const violation = closeViolation(this.#quic, err);
1235
+ // The finished copy can already be serving new requests by the time this arrives.
1236
+ if (entry.feedEnded?.peek() && hooks.trackReleased(producer).peek() === undefined)
1237
+ hooks.abortTrack(producer, violation ?? error(err));
1238
+ });
457
1239
  const subscriptionUpdates = this.version === Version.DRAFT_01 || this.version === Version.DRAFT_02
458
1240
  ? undefined
459
1241
  : this.#runSubscriptionUpdates(id, broadcast, entry, msg, stream);
460
1242
  // Terminal conditions (stream end, track close, a failed subscription update) settle at most
461
1243
  // once; race them into one stable promise so the demand loop doesn't re-subscribe each pass.
462
- // Updates stop quietly at the FIN, which can land before the responses ahead of it are
463
- // decoded, so only their failure is terminal on its own.
464
- const terminal = [closed, producer.closed];
1244
+ // Updates stop quietly at the FIN or a failed write, either of which can land before the
1245
+ // responses ahead of it are decoded, so only a refused update is terminal on its own.
1246
+ const terminal = [closed, hooks.trackReleased(producer)];
1247
+ if (entry.feedEnded)
1248
+ terminal.push(entry.feedEnded);
465
1249
  if (subscriptionUpdates !== undefined)
466
1250
  terminal.push(subscriptionUpdates.then(() => closed));
467
1251
  const done = race(terminal);
@@ -469,103 +1253,436 @@ export class Subscriber {
469
1253
  // wake is level-triggered: re-check demand so a subscriber that returns before we tear
470
1254
  // down (e.g. a quickly unmuted tile) resumes on the same subscription.
471
1255
  const idle = Symbol("idle");
1256
+ const demand = producer.demand();
1257
+ let reason_;
472
1258
  for (;;) {
473
- const reason = await race([done, producer.unused().then(() => idle)]);
474
- if (reason === idle && producer.closed.peek() === undefined && producer.used.peek())
1259
+ reason_ = await race([done, unwanted(demand).then(() => idle)]);
1260
+ if (reason_ === idle && hooks.demandReleased(demand).peek() === undefined && demand.wanted.peek())
475
1261
  continue;
476
1262
  break;
477
1263
  }
478
- producer.close();
479
- stream.close();
480
- console.debug(`subscribe close: id=${id} broadcast=${broadcast} track=${request.name}`);
1264
+ tailSettled ||= entry.feedEnded?.peek() !== undefined;
1265
+ // A settled lite-05+ tail acknowledges completion with FIN, without cancelling
1266
+ // the publisher's already-finished receive half. On lite-07, a clean FIN means
1267
+ // "no further updates; keep delivering", so cancelling an unsettled subscription
1268
+ // must abort it instead.
1269
+ if (tailSettled && waitsForSubscriberFin(this.version))
1270
+ this.#fin(stream, entry);
1271
+ else if (entry.stream.kind !== "fin") {
1272
+ if (keepsSubscribeOpen(this.version))
1273
+ stream.abort(new StreamError(StreamCode.Cancel, { message: "cancel" }));
1274
+ else
1275
+ stream.close();
1276
+ }
1277
+ console.debug(`subscribe close: id=${id} broadcast=${broadcast} track=${producer.name}`);
1278
+ // Only a received SUBSCRIBE_END, or before lite-05 a FIN, declares the track's end: a
1279
+ // subscription nobody wants anymore is a released copy, not finished content.
1280
+ if (tailSettled) {
1281
+ if (entry.feedEnded?.peek() === undefined)
1282
+ entry.feedEnded?.set("ended");
1283
+ if (entry.stream.kind === "finished")
1284
+ producer.finish();
1285
+ hooks.settleTail(producer);
1286
+ entry.fills?.finishFeed();
1287
+ if (entry.feedEnded || (entry.fills && !entry.fills.isEmpty())) {
1288
+ if (entry.datagrams)
1289
+ await this.#endDatagrams(id, entry, producer);
1290
+ await this.#serveFinished(broadcast, consumed, entry, demand, responsesEnded);
1291
+ }
1292
+ }
1293
+ hooks.releaseTrack(producer);
481
1294
  }
482
1295
  catch (err) {
483
1296
  const e = await sessionCause(this.#quic, err);
484
- producer.close(e);
485
- console.warn(`subscribe error: id=${id} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);
1297
+ hooks.abortTrack(producer, e);
1298
+ console.warn(`subscribe error: id=${id} broadcast=${broadcast} track=${producer.name} error=${reason(e)}`);
486
1299
  stream.abort(e);
487
1300
  }
488
1301
  finally {
1302
+ answering?.removeEventListener("abort", replaced);
1303
+ if (entry.feedEnded?.peek())
1304
+ stream.reader.stop(StreamCode.Cancel);
1305
+ entry.tail.close();
1306
+ entry.unanswered?.held.close();
1307
+ entry.datagramDemand?.();
1308
+ if (entry.datagrams)
1309
+ await this.#endDatagrams(id, entry, producer);
489
1310
  this.#subscribes.delete(id);
490
1311
  }
491
1312
  }
492
- // Determine the track's immutable properties, accept the request (so the
493
- // application's track.Subscriber resolves and incoming groups have a producer to
494
- // write into), register it, then open the subscribe stream. `state.stream` is
495
- // populated as soon as the subscribe stream opens so the caller can clean it up
496
- // on timeout even before this promise settles.
497
- //
498
- // On lite-05+ the properties come from a TRACK stream opened first, and the
499
- // SUBSCRIBE is accepted implicitly (no SUBSCRIBE_OK). Older drafts carry no
500
- // per-track properties, so they resolve to defaults and just drain SUBSCRIBE_OK.
501
- async #openSubscribe(state, msg, request, id, timescale) {
502
- let producer;
503
- let drainOk = false;
504
- if (supportsTrackStream(this.version)) {
505
- // Fetch the immutable properties once via the TRACK stream.
506
- const info = await this.#trackInfo(msg.broadcast, msg.track);
507
- producer = request.accept(this.#toModelInfo(info));
508
- timescale.set(info.timescale);
1313
+ // A finished lite-07 copy places unresolved time starts on separate subscriptions. Keep it
1314
+ // while readers or fills still need it, without changing the original feed's ranges after FIN.
1315
+ async #serveFinished(broadcast, consumed, entry, demand, responsesEnded) {
1316
+ const requested = hooks.requested(entry.track);
1317
+ const released = hooks.trackReleased(entry.track);
1318
+ const scoped = hooks.hasScopedDrops(entry.track);
1319
+ const probes = new Map();
1320
+ const answers = new Map();
1321
+ try {
1322
+ while (released.peek() === undefined) {
1323
+ if (this.#quicClosed.peek())
1324
+ throw await closeError(this.#quic);
1325
+ const read = entry.feedEnded !== undefined && !isAbandoned(demand);
1326
+ const asks = new Set(read ? requested.asks() : []);
1327
+ const readingProbe = read && [...probes.values()].some(({ recovery }) => recovery.reading());
1328
+ if ((entry.fills?.isEmpty() ?? true) &&
1329
+ !readingProbe &&
1330
+ asks.size === 0 &&
1331
+ !(read && (scoped || responsesEnded.peek() === undefined)))
1332
+ return;
1333
+ const current = requested.peek();
1334
+ const priority = rangesPolicy(current === undefined ? [] : wireHeld(current).ranges).priority;
1335
+ let moved = false;
1336
+ let refused = false;
1337
+ for (const time of answers.keys()) {
1338
+ if (!asks.has(time))
1339
+ moved = answers.delete(time) || moved;
1340
+ }
1341
+ for (const [time, probe] of probes) {
1342
+ if (!asks.has(time) && (!read || !probe.recovery.reading())) {
1343
+ probe.recovery.cancel();
1344
+ probes.delete(time);
1345
+ continue;
1346
+ }
1347
+ const done = probe.done.peek();
1348
+ const start = probe.start.peek();
1349
+ if (asks.has(time) && !answers.has(time)) {
1350
+ if (start &&
1351
+ (start.group === undefined || start.group > time || probe.recovery.arrived() || done)) {
1352
+ answers.set(time, start.group);
1353
+ moved = true;
1354
+ }
1355
+ else if (done) {
1356
+ requested.refuseTime(time, done[0]?.refusal.error ?? new NotFound(`time ${time}`));
1357
+ refused = true;
1358
+ }
1359
+ }
1360
+ if (done)
1361
+ probes.delete(time);
1362
+ }
1363
+ // A refused reader stops requesting all its starts.
1364
+ for (const time of refused ? requested.asks() : asks) {
1365
+ if (answers.has(time) || probes.has(time))
1366
+ continue;
1367
+ if (entry.end === 0n) {
1368
+ // The exclusive end proves every time is empty, even without a SUBSCRIBE_START.
1369
+ answers.set(time, undefined);
1370
+ moved = true;
1371
+ continue;
1372
+ }
1373
+ if (time >= RESERVED) {
1374
+ requested.refuseTime(time, new RangeError("time probe exceeds the last group key"));
1375
+ refused = true;
1376
+ continue;
1377
+ }
1378
+ const start = new Once();
1379
+ const done = new Once();
1380
+ const recovery = this.#recover(broadcast, consumed, entry, { time, start }, priority);
1381
+ void recovery.done.then((refused) => done.set(refused));
1382
+ probes.set(time, { recovery, start, done });
1383
+ }
1384
+ if (moved)
1385
+ hooks.timeStarts(entry.track, answers);
1386
+ // A refusal may leave other probes without readers. Recheck before parking.
1387
+ if (refused)
1388
+ continue;
1389
+ await Signal.race(requested, released, demand.wanted, entry.fillsChanged, responsesEnded, this.#quicClosed, ...[...probes.values()].flatMap(({ start, done, recovery }) => [
1390
+ start,
1391
+ done,
1392
+ recovery.readingChanged,
1393
+ ]));
1394
+ }
509
1395
  }
510
- else {
511
- // Older drafts negotiate nothing per-track: verbatim frames, no timescale.
512
- producer = request.accept();
513
- timescale.set(0);
514
- drainOk = true;
1396
+ finally {
1397
+ for (const probe of probes.values())
1398
+ probe.recovery.cancel();
515
1399
  }
516
- // Register before opening SUBSCRIBE so a racing GROUP stream finds the entry.
517
- const entry = {
518
- track: producer,
519
- timescale,
520
- // The effective max age is the stopgap grace: the wrong clock (it bounds
521
- // presentation-time drift), but it is how long the subscriber was willing to wait
522
- // for a late group anyway. Already the smaller of the subscriber's and the track's.
523
- tail: new Tail({
524
- grace: () => {
525
- const maxAge = producer.subscription.peek()?.maxAge ?? Time.Milli.zero;
526
- return maxAge > 0 ? maxAge : TAIL_GRACE_MS;
527
- },
528
- }),
529
- requested: msg.startGroup,
530
- };
531
- this.#subscribes.set(id, entry);
532
- state.stream = await Stream.open(this.#quic, { version: this.version });
533
- await state.stream.writer.u53(StreamId.Subscribe);
534
- await msg.encode(state.stream.writer, this.version);
535
- if (drainOk) {
1400
+ }
1401
+ // Lite-05/06: end the datagrams the subscription carried as its stream track ended, once.
1402
+ async #endDatagrams(id, entry, producer) {
1403
+ const datagrams = entry.datagrams;
1404
+ if (!datagrams)
1405
+ return;
1406
+ entry.datagrams = undefined;
1407
+ // The stream track's end is its datagrams' end: those received with it route first.
1408
+ if (entry.end !== undefined && !(hooks.trackReleased(producer).peek() instanceof Error)) {
1409
+ datagrams.ended = true;
1410
+ await this.#datagramsRouted(id);
1411
+ }
1412
+ const closed = hooks.trackReleased(producer).peek();
1413
+ if (closed instanceof Error)
1414
+ hooks.abortDatagrams(datagrams.producer, closed);
1415
+ else if (entry.end !== undefined)
1416
+ datagrams.producer.finish();
1417
+ else
1418
+ datagrams.producer.close();
1419
+ this.#datagrams.delete(id);
1420
+ if (entry.legacyKey && this.#legacyDatagrams.get(entry.legacyKey) === datagrams)
1421
+ this.#legacyDatagrams.delete(entry.legacyKey);
1422
+ }
1423
+ // Open the subscribe stream and accept the request (so the application's track.Subscriber
1424
+ // resolves and incoming groups have a producer to write into) with the track's immutable
1425
+ // properties. `state.stream` is populated as soon as it opens, and `state.track` once
1426
+ // answered, so the caller can clean them up once it gives up, even before this promise settles.
1427
+ //
1428
+ // On lite-05+ the properties come from a TRACK stream, held open until the SUBSCRIBE is
1429
+ // answered, and the SUBSCRIBE goes out alongside it rather than a round trip after: it is
1430
+ // accepted implicitly (no SUBSCRIBE_OK), and needs the info only to read what it receives.
1431
+ // A time anchor counts in the track's timescale, so a SUBSCRIBE naming one waits for the
1432
+ // info, as the Rust `pipeline` does. A group stream that beats the info waits on `#pending`,
1433
+ // unread. Older drafts carry no per-track properties, so they resolve to defaults and just
1434
+ // drain SUBSCRIBE_OK.
1435
+ async #openSubscribe(state, consumed, msg, asked, request, id, deadline) {
1436
+ state.cancel.signal.throwIfAborted();
1437
+ if (!hasTrackStream(this.version)) {
1438
+ // Older drafts negotiate nothing per-track: verbatim frames with no timeline.
1439
+ const framing = { compress: false, timescale: 0, scale: undefined };
1440
+ // Nor a max age: no publisher limit, not the authored default.
1441
+ const entry = this.#register(id, msg, asked, request.accept({ maxAge: null }), framing, state);
1442
+ const stream = await this.#sendSubscribe(state, msg, deadline);
536
1443
  // The first response MUST be a SUBSCRIBE_OK (older drafts only).
537
- const resp = await decodeSubscribeResponse(state.stream.reader, this.version);
1444
+ const resp = await decodeSubscribeResponse(stream.reader, this.version);
538
1445
  if (!("ok" in resp)) {
539
1446
  throw new Error("first subscribe response must be SUBSCRIBE_OK");
540
1447
  }
1448
+ return { stream, entry };
541
1449
  }
542
- return { stream: state.stream, entry };
543
- }
544
- // Opens a TRACK stream, reads the single TRACK_INFO, and FINs. Lite-05+ only.
545
- async #trackInfo(broadcast, track) {
546
- return this.#exchange({ version: this.version }, async (stream) => {
547
- await stream.writer.u53(StreamId.Track);
548
- await new TrackMessage(broadcast, track).encode(stream.writer, this.version);
549
- const info = await TrackInfo.decode(stream.reader, this.version);
550
- // The publisher FINs after TRACK_INFO; FIN our side too.
551
- stream.close();
552
- return info;
1450
+ // The TRACK opens first, then the SUBSCRIBE, which is waiting on before it is written.
1451
+ // The answered TRACK is held at once, so a cancellation while the SUBSCRIBE still opens
1452
+ // closes it rather than waiting on an open that may never finish.
1453
+ const info = this.#trackInfo(msg.broadcast, msg, msg.track, state.cancel.signal, deadline).then((answered) => {
1454
+ state.track = answered.stream;
1455
+ // Cancelled as it was answered: the caller may already have left.
1456
+ if (state.cancel.signal.aborted)
1457
+ answered.stream.close();
1458
+ return answered;
553
1459
  });
554
- }
1460
+ let settle = () => { };
1461
+ this.#pending.set(id, new Promise((resolve) => {
1462
+ settle = resolve;
1463
+ }));
1464
+ const sending = this.#fitted(this.#withRanges(msg, asked.ranges, asked.placed)).then((msg) => this.#sendSubscribe(state, msg, deadline));
1465
+ try {
1466
+ // Either failing fails the subscription: a reset TRACK rejects the request, so the
1467
+ // origin can try another route, and the caller resets the SUBSCRIBE.
1468
+ const [answered, stream] = await Promise.all([info, sending]);
1469
+ // The setup ended as TRACK_INFO landed: the request is already rejected, so don't
1470
+ // accept it again.
1471
+ state.cancel.signal.throwIfAborted();
1472
+ const model = this.#toModelInfo(answered.info);
1473
+ const producer = request.accept(model);
1474
+ const framing = {
1475
+ compress: answered.info.compress,
1476
+ timescale: wireTimescale(this.version, answered.info.timescale) ?? 0,
1477
+ scale: model.timescale ?? undefined,
1478
+ };
1479
+ const entry = this.#register(id, msg, asked, producer, framing, state);
1480
+ // Asks upstream for what the copy's readers miss for as long as the copy lives, across every
1481
+ // subscription that feeds it. Its handler opens with the copy, so a fetch judged as soon as
1482
+ // the copy is accepted finds it.
1483
+ void this.#runFills(msg.broadcast, consumed, entry);
1484
+ entry.unanswered = { held: answered.stream, answered: new AbortController() };
1485
+ settle(entry);
1486
+ return { stream, entry };
1487
+ }
1488
+ catch (err) {
1489
+ settle(undefined);
1490
+ // Whichever exchange outlived the other is no longer wanted.
1491
+ void info.then(({ stream }) => stream.abort(error(err)), () => { });
1492
+ void sending.then((stream) => stream.abort(error(err)), () => { });
1493
+ throw err;
1494
+ }
1495
+ finally {
1496
+ this.#pending.delete(id);
1497
+ }
1498
+ }
1499
+ // `msg` asking for `ranges` on a wire that carries them, each at its own priority and order, and
1500
+ // each live join `placed` at a group by index as a Joined start there.
1501
+ #withRanges(msg, ranges, placed) {
1502
+ if (hasRanges(this.version))
1503
+ msg.ranges = toWireRanges(ranges, placed);
1504
+ return msg;
1505
+ }
1506
+ // `msg` with its lite-07 ranges widened until they fit, as the Rust `pipeline` does: the union of
1507
+ // a relay's readers' ranges need not fit one message though each reader's does.
1508
+ async #fitted(msg) {
1509
+ if (!msg.ranges || !hasRanges(this.version))
1510
+ return msg;
1511
+ const fields = await this.#subscribeFields(msg, msg);
1512
+ msg.ranges = [...Fit.fit(msg.ranges, [], [], Fit.budget(fields, 0n, msg.ranges.length)).ranges];
1513
+ return msg;
1514
+ }
1515
+ // The bytes a SUBSCRIBE like `msg` under `terms` takes besides its ranges, at the widest id,
1516
+ // measured with the smallest range, since it carries at least one. Mirrors the Rust
1517
+ // `subscribe_fields`.
1518
+ async #subscribeFields(msg, terms) {
1519
+ const widest = new Subscribe({
1520
+ ...msg,
1521
+ priority: terms.priority,
1522
+ order: terms.order,
1523
+ maxDelay: terms.maxDelay,
1524
+ id: (1n << 64n) - 1n,
1525
+ ranges: [{}],
1526
+ });
1527
+ try {
1528
+ return (await Writer.collect(this.version, (w) => widest.encode(w, this.version))).byteLength;
1529
+ }
1530
+ catch {
1531
+ // One that can't go out leaves no room, and fails as it would have.
1532
+ return Number.POSITIVE_INFINITY;
1533
+ }
1534
+ }
1535
+ // Register a subscription's accepted copy, asking for what it `asked`, so incoming groups and
1536
+ // datagrams find it.
1537
+ #register(id, msg, asked, producer, framing, state) {
1538
+ hooks.receiveTrack(producer, {
1539
+ resolvesStart: resolvesStart(this.version),
1540
+ fillsFromStart: fillsFromStart(this.version),
1541
+ });
1542
+ // A new upstream subscription: stale runs an earlier one reported were judged under other terms.
1543
+ hooks.supersedeStale(producer);
1544
+ // A wire whose ranges carry each live join answers where each starts, which alone places a
1545
+ // reader's.
1546
+ if (hasRanges(this.version))
1547
+ hooks.answersJoins(producer);
1548
+ if (!hasRanges(this.version)) {
1549
+ hooks.dropAnchors(producer);
1550
+ // A wire without ranges starts a time anchor at the first group at or after it, so its
1551
+ // readers do too, rather than at an earlier group the copy happens to hold.
1552
+ hooks.startsAtKeys(producer);
1553
+ }
1554
+ // Lite-06+ resolves where the feed starts only with SUBSCRIBE_START, so a relay serving
1555
+ // this copy holds its first group until the answer arrives.
1556
+ if (resolvesStart(this.version) && !hasRanges(this.version))
1557
+ hooks.startTrack(producer, { requested: msg.startGroup });
1558
+ // Lite-07 names every start, so the copy and its tail wait for the wire rather than a grace.
1559
+ if (hasSkip(this.version))
1560
+ hooks.proveTrack(producer);
1561
+ const live = new LiveRanges(this.version, msg.ranges ?? []);
1562
+ const entry = {
1563
+ track: producer,
1564
+ meta: msg.meta,
1565
+ staleCap: capOf(live),
1566
+ ...framing,
1567
+ // Before lite-07, the effective max delay is the stopgap grace: the wrong clock (it
1568
+ // bounds presentation-time drift), but it is how long the subscriber was willing to wait
1569
+ // for a late group anyway, and no longer than the publisher keeps one fresh.
1570
+ tail: new Tail({
1571
+ grace: () => (hasSkip(this.version) ? undefined : hooks.tailGrace(producer)),
1572
+ proven: hasSkip(this.version),
1573
+ }),
1574
+ feedEnded: hasSkip(this.version) ? new Once() : undefined,
1575
+ requested: msg.startGroup,
1576
+ floor: msg.startGroup,
1577
+ asked: [...asked.ranges],
1578
+ askedPlaced: asked.placed,
1579
+ live,
1580
+ starts: new Map(),
1581
+ joinTicks: new Map(),
1582
+ joinBudgets: new Map(),
1583
+ sent: 0,
1584
+ stream: { kind: "setup" },
1585
+ fillIds: new Set(),
1586
+ probeIds: new Set(),
1587
+ fillGroups: [],
1588
+ fillsChanged: new Signal(0),
1589
+ broadcast: msg.broadcast,
1590
+ consumedId: state.consumedId,
1591
+ };
1592
+ if (hasRanges(this.version))
1593
+ this.#declareFeed(entry);
1594
+ if (hasDatagrams(this.version) && !hasDatagramTracks(this.version) && state.consumer && state.legacyKey) {
1595
+ const info = { priority: producer.priority, timescale: framing.scale };
1596
+ const pending = this.#legacyRequests.get(state.legacyKey);
1597
+ const request = pending?.closed.peek() === undefined ? pending : undefined;
1598
+ this.#legacyRequests.delete(state.legacyKey);
1599
+ const datagrams = request
1600
+ ? request.accept(info)
1601
+ : wireOf(state.consumer).createDatagrams(producer.name, info, false);
1602
+ // Undefined while a live datagram track already holds the name: serve the stream track alone.
1603
+ if (datagrams) {
1604
+ entry.datagrams = { producer: datagrams, timescale: framing.scale };
1605
+ entry.legacyKey = state.legacyKey;
1606
+ this.#datagrams.set(id, entry.datagrams);
1607
+ this.#legacyDatagrams.set(state.legacyKey, entry.datagrams);
1608
+ let held;
1609
+ const sync = () => {
1610
+ const priority = datagrams.priority.peek();
1611
+ if (priority === undefined) {
1612
+ held?.close();
1613
+ held = undefined;
1614
+ }
1615
+ else if (held) {
1616
+ held.update(latestAt(priority));
1617
+ }
1618
+ else {
1619
+ held = producer.subscribe(latestAt(priority));
1620
+ }
1621
+ };
1622
+ const dispose = datagrams.priority.subscribe(sync);
1623
+ sync();
1624
+ entry.datagramDemand = () => {
1625
+ dispose();
1626
+ held?.close();
1627
+ };
1628
+ }
1629
+ }
1630
+ // Before any group of it reaches a reader, its publisher may judge one too old under any
1631
+ // live join it asked.
1632
+ hooks.judgeUnder(producer, narrowest(entry.live));
1633
+ this.#subscribes.set(id, entry);
1634
+ state.producer = producer;
1635
+ return entry;
1636
+ }
1637
+ // Open the subscribe stream and write the SUBSCRIBE on it.
1638
+ async #sendSubscribe(state, msg, deadline) {
1639
+ // Giving up leaves the line, so the next open takes the stream this one was waiting for.
1640
+ const signal = state.cancel.signal;
1641
+ const opening = Stream.tryOpen(this.#quic, { version: this.version, signal }).then((opened) => {
1642
+ if (!opened)
1643
+ throw signal.reason;
1644
+ return opened;
1645
+ });
1646
+ const stream = await deadline.open(opening);
1647
+ state.stream = stream;
1648
+ // Setup was given up as the open handed over its stream: the late-setup handler resets
1649
+ // the stream, so don't send a SUBSCRIBE on it first.
1650
+ signal.throwIfAborted();
1651
+ await stream.writer.u53(StreamId.Subscribe);
1652
+ await msg.encode(stream.writer, this.version);
1653
+ return stream;
1654
+ }
1655
+ // Opens a TRACK stream and reads the single TRACK_INFO. Lite-05+ only. The stream
1656
+ // stays open, as interest in the track, until the caller closes it.
1657
+ async #trackInfo(broadcast, { identity }, track, signal, deadline) {
1658
+ return this.#exchange({ version: this.version }, async (stream) => {
1659
+ await stream.writer.u53(StreamId.Track);
1660
+ await new TrackMessage(broadcast, track, identity).encode(stream.writer, this.version);
1661
+ const info = await TrackInfo.decode(stream.reader, this.version);
1662
+ return { info, stream };
1663
+ }, signal, deadline);
1664
+ }
555
1665
  // Opens a stream and runs a request/response exchange on it, resetting the stream if `run`
556
- // fails. Subscriber.close() also resets it while `run` is pending, so a peer that never
557
- // answers cannot hold it open, and a stream that opens after the close is reset at once.
558
- async #exchange(options, run) {
559
- const closed = this.#closed.signal;
1666
+ // fails. Subscriber.close() or `signal` also resets it while `run` is pending, so a peer that
1667
+ // never answers cannot hold it open, and a stream that opens after either is reset at once.
1668
+ async #exchange(options, run, signal, deadline) {
1669
+ const closed = signal ? AbortSignal.any([this.#closed.signal, signal]) : this.#closed.signal;
560
1670
  closed.throwIfAborted();
561
- const stream = await Stream.open(this.#quic, options);
1671
+ // Giving up leaves the line, so the next open takes the stream this one was waiting for.
1672
+ const opening = Stream.tryOpen(this.#quic, { ...options, signal: closed }).then((opened) => {
1673
+ if (!opened)
1674
+ throw closed.reason;
1675
+ return opened;
1676
+ });
1677
+ const stream = await deadline.open(opening);
562
1678
  const abort = () => stream.abort(error(closed.reason));
563
1679
  closed.addEventListener("abort", abort);
564
1680
  try {
565
1681
  closed.throwIfAborted();
566
- return await run(stream);
1682
+ return await untilAborted(run(stream), closed);
567
1683
  }
568
1684
  catch (err) {
1685
+ closeViolation(this.#quic, err);
569
1686
  stream.abort(error(err));
570
1687
  throw err;
571
1688
  }
@@ -576,47 +1693,93 @@ export class Subscriber {
576
1693
  // Map the wire TRACK_INFO onto the model track.Info a producer/consumer holds.
577
1694
  #toModelInfo(info) {
578
1695
  return {
579
- timescale: Time.Timescale(info.timescale),
580
- // Publisher Max Age rides on the wire, so the local retention window
1696
+ timescale: info.timescale ?? null,
1697
+ // Publisher Max Age rides on the wire, so the local media-time budget
581
1698
  // matches what the upstream advertises (relays re-serve with the same bound).
582
- maxAge: Time.Milli(info.maxAge),
1699
+ maxAge: info.maxAge === undefined ? null : Duration.millis(info.maxAge),
583
1700
  priority: info.priority,
1701
+ refresh: {
1702
+ ratio: info.refresh ?? null,
1703
+ interval: info.refreshInterval === undefined ? null : Duration.millis(info.refreshInterval),
1704
+ },
1705
+ compression: info.compress ? "deflate" : "none",
584
1706
  };
585
1707
  }
586
1708
  // Resolve a track's immutable model info via a TRACK stream (lite-05+), for the
587
- // ConsumeBroadcast backing track.Consumer.query(). On older drafts there's no TRACK
588
- // stream, so this rejects rather than fabricating defaults.
589
- async resolveTrackInfo(broadcast, track) {
590
- if (!supportsTrackStream(this.version)) {
1709
+ // ConsumeBroadcast backing track.Consumer.info(). On older drafts there's no TRACK
1710
+ // stream, so this rejects rather than fabricating defaults. The TRACK stream stays
1711
+ // open until `hold` aborts, so the publisher keeps the track for whoever asked here;
1712
+ // aborting it before TRACK_INFO resets the stream.
1713
+ async resolveTrackInfo(broadcast, track, pin = {}, hold) {
1714
+ if (!hasTrackStream(this.version)) {
591
1715
  throw new Error("track info requires moq-lite-05 or newer");
592
1716
  }
593
- return this.#toModelInfo(await this.#trackInfo(broadcast, track));
1717
+ const deadline = new Deadline();
1718
+ const { info, stream } = await deadline.wait(this.#trackInfo(broadcast, pin, track, hold, deadline));
1719
+ if (hold && !hold.aborted)
1720
+ hold.addEventListener("abort", () => stream.close(), { once: true });
1721
+ else
1722
+ stream.close();
1723
+ return this.#toModelInfo(info);
1724
+ }
1725
+ /**
1726
+ * Whether a `fetchGroup(key)` can deduplicate onto an active non-filling subscription for
1727
+ * `(broadcast, consumed, track)`: true when the active subscription hasn't accounted for `key`
1728
+ * yet (so unioning transfers at most 1 wire copy) or still caches `key` intact. False when `key`
1729
+ * was already dropped, reset, or evicted on that subscription (must use one-shot SUBSCRIBE + FIN).
1730
+ */
1731
+ canDeduplicateFetch(broadcast, consumed, track, key) {
1732
+ for (const entry of this.#subscribes.values()) {
1733
+ if (!entry.filling &&
1734
+ !entry.fillGroup &&
1735
+ // A metadata copy holds no payload a payload fetch could take.
1736
+ !entry.meta &&
1737
+ entry.broadcast === broadcast &&
1738
+ entry.consumedId === consumed.id &&
1739
+ entry.track.name === track) {
1740
+ const largest = entry.track.largest()?.group;
1741
+ if (largest !== undefined && key <= largest && !entry.tail.covers(key, key + 1n))
1742
+ return true;
1743
+ if (!entry.tail.dropped(key) && hooks.producerHoldsGroup(entry.track, key, true))
1744
+ return true;
1745
+ }
1746
+ }
1747
+ return false;
594
1748
  }
595
- // Open a FETCH stream for one group and stream its bare frames into a group, for the
596
- // ConsumeBroadcast backing track.Consumer.fetchGroup() (lite-05+).
597
- async fetchGroup(broadcast, track, sequence, options = {}) {
1749
+ // Open a one-shot bounded SUBSCRIBE + FIN for one group, for the ConsumeBroadcast backing
1750
+ // track.Consumer.fetchGroup() (lite-07).
1751
+ async fetchGroup(broadcast, track, key, options = {}, consumed = {}) {
1752
+ // On lite-05/06 a FIN unsubscribes, so the one-shot request would be cancelled at once.
1753
+ if (!hasRanges(this.version))
1754
+ throw new StreamError(StreamCode.NotSupported);
1755
+ const { identity } = consumed;
598
1756
  options.signal?.throwIfAborted();
599
- // Coalesce onto a still-open fetch of the same group so we don't open a second FETCH
600
- // stream (and re-download it); each caller reads an independent mirror.
1757
+ // Coalesce onto a still-open fetch of the same group so we don't open a second stream
1758
+ // (and re-download it); each caller reads an independent mirror.
601
1759
  //
602
1760
  // Reserve each caller's mirror before the fetch starts or is awaited: the fetch watches
603
1761
  // demand from the start, and a fast FIN cannot discard frames before these callers
604
1762
  // receive their handles. An abort closes only this caller's mirror, so the stream is
605
1763
  // cancelled once the last one leaves.
606
- const key = JSON.stringify([broadcast, track, sequence]);
607
- let entry = this.#fetches.get(key);
1764
+ // A minted identity is an object, which JSON prints as {}, so key on its text and flag.
1765
+ const pin = identity === undefined ? null : [Identity.text(identity), Identity.isMinted(identity)];
1766
+ const slot = JSON.stringify([consumed.id, broadcast, pin, track, String(key)]);
1767
+ let entry = this.#fetches.get(slot);
608
1768
  let consumer;
609
- if (entry && !entry.group.isClosed) {
1769
+ if (entry && entry.group.closed.peek() === undefined) {
610
1770
  consumer = entry.group.mirror();
611
1771
  }
612
1772
  else {
613
- const group = new netGroup.Producer(sequence);
1773
+ const group = new netGroup.Producer(key);
614
1774
  consumer = group.mirror();
615
- entry = { group, accepted: this.#runFetch(broadcast, track, sequence, options.priority ?? 0, group) };
616
- this.#fetches.set(key, entry);
1775
+ entry = {
1776
+ group,
1777
+ accepted: this.#runFetchSubscribe(broadcast, consumed, track, key, options.priority ?? 0, group),
1778
+ };
1779
+ this.#fetches.set(slot, entry);
617
1780
  void group.closed.then(() => {
618
- if (this.#fetches.get(key)?.group === group)
619
- this.#fetches.delete(key);
1781
+ if (this.#fetches.get(slot)?.group === group)
1782
+ this.#fetches.delete(slot);
620
1783
  });
621
1784
  }
622
1785
  try {
@@ -628,124 +1791,687 @@ export class Subscriber {
628
1791
  throw err;
629
1792
  }
630
1793
  }
631
- // Open the FETCH stream and pump the response into the shared group. Setup errors close the
632
- // group, evict the entry, and reject every caller waiting for acceptance. A setup every caller
633
- // has abandoned is cancelled the same way.
634
- async #runFetch(broadcast, track, sequence, priority, group) {
1794
+ // Lite-07: one-shot bounded SUBSCRIBE([Position(key, 0), Position(key + 1, 0))) + immediate
1795
+ // subscriber FIN alongside TRACK (1 RTT), delivering the incoming uni Group Stream directly
1796
+ // into `group`.
1797
+ async #runFetchSubscribe(broadcast, consumed, trackName, key, priority, group) {
1798
+ const refused = unauthorized(broadcast);
1799
+ const id = this.#subscribeNext++;
1800
+ const pending = Promise.withResolvers();
1801
+ this.#pending.set(id, pending.promise);
1802
+ const arrived = Promise.withResolvers();
1803
+ let registered = false;
1804
+ let stream;
635
1805
  try {
636
- if (!supportsTrackStream(this.version)) {
637
- throw new Error("fetch group requires moq-lite-05 or newer");
638
- }
639
- // Lite has no FETCH_OK, so a publisher that never answers would hold the setup forever.
640
- // Subscriber.close() closing the group releases every caller at any stage, and resets
641
- // the streams the setup opened.
642
- const setup = this.#fetchSetup(broadcast, track, sequence, priority, group);
643
- let accepted;
1806
+ while ((await this.#auth?.ready(broadcast, "subscribe", {
1807
+ signal: consumed.valid,
1808
+ until: () => groupUnwanted(group),
1809
+ })) === false) {
1810
+ if (group.closed.peek() === undefined && group.demand().wanted.peek())
1811
+ continue;
1812
+ throw new StreamError(StreamCode.Cancel, { message: "cancel" });
1813
+ }
1814
+ const disposeGrant = this.#grant?.subscribe(() => {
1815
+ if (this.#denied(broadcast))
1816
+ hooks.abortGroup(group, refused);
1817
+ });
1818
+ void group.closed.then(() => disposeGrant?.());
1819
+ if (this.#denied(broadcast))
1820
+ throw refused;
1821
+ const { identity, valid } = consumed;
1822
+ const cancel = new AbortController();
1823
+ void group.closed.then((err) => cancel.abort(err ?? new StreamError(StreamCode.Cancel)));
1824
+ const signal = valid ? AbortSignal.any([valid, cancel.signal]) : cancel.signal;
1825
+ const deadline = new Deadline();
1826
+ const answered = this.#trackInfo(broadcast, consumed, trackName, signal, deadline);
1827
+ answered.then(({ stream: trackStream }) => trackStream.close(), (err) => cancel.abort(error(err)));
1828
+ const ranges = [
1829
+ withPolicy({
1830
+ start: { absolute: key, frame: 0 },
1831
+ end: { absolute: key + 1n, frame: 0 },
1832
+ }, { priority, order: "ascending" }),
1833
+ ];
1834
+ const msg = new Subscribe({
1835
+ id,
1836
+ broadcast,
1837
+ identity,
1838
+ track: trackName,
1839
+ priority,
1840
+ order: "ascending",
1841
+ maxDelay: null,
1842
+ startGroup: key,
1843
+ endGroup: key,
1844
+ ranges,
1845
+ });
1846
+ const openSub = this.#exchange({ sendOrder: sendOrder({ priority }), version: this.version }, async (opened) => {
1847
+ const bytes = await Writer.collect(this.version, async (w) => {
1848
+ await w.u53(StreamId.Subscribe);
1849
+ await msg.encode(w, this.version);
1850
+ });
1851
+ await opened.writer.write(bytes);
1852
+ opened.writer.close();
1853
+ return opened;
1854
+ }, signal, deadline);
1855
+ const setup = deadline.wait(Promise.all([openSub, answered]));
1856
+ let info;
644
1857
  try {
645
- accepted = await untilAbandoned(group, setup);
1858
+ const [opened, infoRes] = await untilAbandoned(group, setup);
1859
+ stream = opened;
1860
+ info = infoRes.info;
646
1861
  }
647
1862
  catch (err) {
648
- // A setup that finishes just after the close hands back a stream nobody will read.
649
- void setup.then(({ stream }) => stream.abort(error(err)), () => void 0);
1863
+ cancel.abort(error(err));
1864
+ void openSub.then((opened) => opened.abort(error(err)), () => void 0);
650
1865
  throw err;
651
1866
  }
652
- void this.#runFetchResponse(accepted.stream, group, Time.Timescale(accepted.info.timescale));
1867
+ hooks.bindGroupCompression(group, info.compress);
1868
+ const live = new LiveRanges(this.version, ranges);
1869
+ const target = {
1870
+ producer: group,
1871
+ taken: false,
1872
+ arrived: () => arrived.resolve(),
1873
+ };
1874
+ const entry = {
1875
+ // Unused for fillGroup entries; satisfies the shared SubscribeEntry shape.
1876
+ track: undefined,
1877
+ meta: false,
1878
+ staleCap: key + 1n,
1879
+ compress: info.compress,
1880
+ timescale: wireTimescale(this.version, info.timescale) ?? 0,
1881
+ tail: new Tail({ grace: () => undefined, proven: true }),
1882
+ requested: key,
1883
+ floor: key,
1884
+ asked: [],
1885
+ askedPlaced: new Map(),
1886
+ live,
1887
+ starts: new Map(),
1888
+ joinTicks: new Map(),
1889
+ joinBudgets: new Map(),
1890
+ sent: 0,
1891
+ stream: { kind: "setup" },
1892
+ filling: "range",
1893
+ fillIds: new Set(),
1894
+ probeIds: new Set(),
1895
+ fillGroups: [],
1896
+ fillsChanged: new Signal(0),
1897
+ fillGroup: target,
1898
+ };
1899
+ this.#subscribes.set(id, entry);
1900
+ this.#pending.delete(id);
1901
+ pending.resolve(entry);
1902
+ registered = true;
1903
+ const responses = this.#readFetchSubscribe(stream, entry, key, target);
1904
+ entry.stream = { kind: "fin", responses: responses.catch(() => { }) };
1905
+ void responses.catch((err) => {
1906
+ if (!target.taken)
1907
+ arrived.reject(error(err));
1908
+ });
1909
+ // Keep reading control responses until settled; cleanup runs when both control and group settle.
1910
+ void responses
1911
+ .catch(() => { })
1912
+ .finally(() => {
1913
+ this.#subscribes.delete(id);
1914
+ entry.tail.close();
1915
+ });
1916
+ await untilAbandoned(group, arrived.promise);
653
1917
  }
654
1918
  catch (err) {
655
- group.close(error(err));
656
- throw err;
1919
+ const e = error(err);
1920
+ if (!registered) {
1921
+ this.#pending.delete(id);
1922
+ pending.resolve(undefined);
1923
+ }
1924
+ stream?.abort(e);
1925
+ hooks.abortGroup(group, e);
1926
+ throw e;
657
1927
  }
658
1928
  }
659
- // Resolve the track's timescale, then open the FETCH stream and wait for it to be accepted.
660
- // Closing the group during that wait resets the stream.
661
- async #fetchSetup(broadcast, track, sequence, priority, group) {
662
- const info = await untilClosed(group, this.#trackInfo(broadcast, track));
663
- return this.#exchange({ sendOrder: sendOrder({ priority }), version: this.version }, async (stream) => {
664
- await stream.writer.u53(StreamId.Fetch);
665
- await new FetchMessage({ broadcast, track, priority, group: sequence }).encode(stream.writer, this.version);
666
- // A byte or an empty-group FIN accepts the fetch; a reset rejects it.
667
- // done() buffers that byte so the response pump can decode it normally.
668
- await untilClosed(group, stream.reader.done());
669
- return { stream, info };
670
- });
671
- }
672
- // Read the FETCH response (bare zigzag-delta-timestamped frames) into the group, then
673
- // FIN. A stream-level failure aborts the group so its reader observes the gap.
674
- async #runFetchResponse(stream, group, timescale) {
1929
+ // Read a standalone lite-07 one-shot SUBSCRIBE's responses until publisher FIN, waiting for any
1930
+ // in-flight uni Group Stream before concluding the group was not delivered.
1931
+ async #readFetchSubscribe(stream, entry, key, target) {
1932
+ let started = false;
1933
+ let ended = false;
1934
+ let refused;
675
1935
  try {
676
- const decode = frameDecoder(timescale);
677
- // Serve until the stream FINs, the group closes, or every reader leaves. A group can
678
- // stay open indefinitely (a catalog or JSON stream), so an abandoned fetch is stopped by
679
- // demand, not by the stream ending. `unused` is watched across frames as one stable
680
- // promise; the check is level-triggered, so a coalesced fetch that arrives before we
681
- // cancel re-arms and resumes.
682
- const idle = Symbol("idle");
683
- let unused = group.unused().then(() => idle);
684
- // A decode consumes its frame whenever it lands, so one outstanding across a re-arm is
685
- // kept and awaited again rather than abandoned with its frame.
686
- let pending;
687
1936
  for (;;) {
688
- // Buffered frames are written without an await, as in a group stream.
689
- let frame = pending === undefined ? stream.reader.tryDecode(decode) : undefined;
690
- if (!frame) {
691
- pending ??= stream.reader.decodeMaybe(decode);
692
- const next = await race([pending, group.closed, unused]);
693
- if (next === idle) {
694
- if (group.isClosed)
695
- break;
696
- if (group.used.peek()) {
697
- unused = group.unused().then(() => idle);
698
- continue;
699
- }
700
- // Abandoned mid-group: the truncated group must never end clean.
701
- throw new StreamError(StreamCode.Cancel, { message: "cancel" });
1937
+ const resp = await decodeSubscribeResponseMaybe(stream.reader, this.version);
1938
+ if (!resp)
1939
+ break;
1940
+ if ("start" in resp) {
1941
+ if (started || resp.start.id !== 0n)
1942
+ throw new ProtocolViolation("unexpected fetch subscribe SUBSCRIBE_START");
1943
+ started = true;
1944
+ if (resp.start.start === undefined || resp.start.start > key) {
1945
+ entry.tail.account(key, key + 1n);
1946
+ refused ??= new NotFound(`group ${key}`);
702
1947
  }
703
- pending = undefined;
704
- if (!next || next instanceof Error)
705
- break;
706
- frame = next;
707
1948
  }
708
- group.writeFrame(frame);
1949
+ else if ("drop" in resp || "skip" in resp || "old" in resp) {
1950
+ const { start, end } = "drop" in resp ? resp.drop : "skip" in resp ? resp.skip : resp.old;
1951
+ entry.tail.account(start, end);
1952
+ if (key >= start && key < end) {
1953
+ // A lite-07 drop or skip is not found here; a stale verdict, as every drop before
1954
+ // lite-07 reads, is old.
1955
+ const stale = "old" in resp || ("drop" in resp && !hasSkip(this.version));
1956
+ refused ??= stale ? new StreamError(StreamCode.Old) : new NotFound(`group ${key}`);
1957
+ // The publisher gave up the group: a stream it opened ends with this reason,
1958
+ // even where the browser lost its reset. One received whole stays whole.
1959
+ target.dropped ??= refused;
1960
+ if (target.taken)
1961
+ hooks.abortGroup(target.producer, refused);
1962
+ }
1963
+ }
1964
+ else if ("end" in resp) {
1965
+ if (ended)
1966
+ throw new ProtocolViolation("duplicate SUBSCRIBE_END");
1967
+ ended = true;
1968
+ if (resp.end.group <= key) {
1969
+ entry.tail.account(key, key + 1n);
1970
+ refused ??= new NotFound(`group ${key}`);
1971
+ }
1972
+ }
1973
+ else {
1974
+ throw new ProtocolViolation("unexpected fetch subscribe response");
1975
+ }
709
1976
  }
710
- group.close();
711
- stream.close();
1977
+ // Publisher FIN'd cleanly; wait for the uni Group Stream if not yet arrived or still reading.
1978
+ // Lite-07 names every start with no grace timer, but abandoning the fetch or closing the
1979
+ // session ends the wait so the subscription entry always cleans up.
1980
+ const stop = new Once();
1981
+ const cancel = () => {
1982
+ if (stop.peek() === undefined)
1983
+ stop.set(null);
1984
+ };
1985
+ const unsubSession = this.#quicClosed.subscribe((closed) => {
1986
+ if (closed)
1987
+ cancel();
1988
+ });
1989
+ if (this.#quicClosed.peek())
1990
+ cancel();
1991
+ void target.producer.closed.then(cancel, cancel);
1992
+ try {
1993
+ if (!target.taken && refused === undefined) {
1994
+ const covered = () => target.taken || entry.tail.covers(key, key + 1n);
1995
+ await entry.tail.settle(covered, stop);
1996
+ }
1997
+ if (entry.tail.reading) {
1998
+ await entry.tail.settle(() => true, stop);
1999
+ }
2000
+ }
2001
+ finally {
2002
+ unsubSession();
2003
+ cancel();
2004
+ }
2005
+ if (!target.taken) {
2006
+ throw refused ?? new NotFound(`group ${key}`);
2007
+ }
2008
+ if (target.lost)
2009
+ hooks.abortGroup(target.producer, refused ?? target.lost);
712
2010
  }
713
2011
  catch (err) {
714
- const e = error(err);
715
- group.close(e);
2012
+ closeViolation(this.#quic, err);
2013
+ const e = await sessionCause(this.#quic, err);
716
2014
  stream.abort(e);
2015
+ if (target.taken)
2016
+ hooks.abortGroup(target.producer, e);
2017
+ throw e;
2018
+ }
2019
+ }
2020
+ // Serve the received copy's misses as its request handler, until the copy closes. Each is asked
2021
+ // through a subscription (see `RangeFills`): on lite-07 the copy's own, and before it one of its
2022
+ // own per run, as the Rust serve loop's `range_fills` does.
2023
+ async #runFills(broadcast, consumed, entry) {
2024
+ const requests = entry.track.requests();
2025
+ const fills = new RangeFills(entry.track, this.version, (groups, priority) => this.#recover(broadcast, consumed, entry, groups, priority));
2026
+ entry.fills = fills;
2027
+ const driving = this.#driveFills(entry, fills);
2028
+ try {
2029
+ for (let fill = await requests.requestedFill(); fill; fill = await requests.requestedFill())
2030
+ fills.push(fill);
2031
+ }
2032
+ finally {
2033
+ requests.close();
2034
+ fills.close();
2035
+ await driving;
2036
+ }
2037
+ }
2038
+ // Settle `fills` as their inputs change, until the copy closes, asking what they owe through
2039
+ // `entry`'s subscription. Mirrors the Rust serve loop's `RangeFills::poll`.
2040
+ async #driveFills(entry, fills) {
2041
+ const demand = entry.track.demand();
2042
+ while (!fills.closed) {
2043
+ // A stream still arriving on a recovery is kept only for someone reading it. The
2044
+ // finished copy can release its request handler when the last recovery ends.
2045
+ const recovering = fills.recovering;
2046
+ if (fills.poll(entry.tail, !isAbandoned(demand)) || fills.recovering !== recovering)
2047
+ entry.fillsChanged.update((revision) => revision + 1);
2048
+ await fills.changed(entry.tail, demand);
2049
+ }
2050
+ entry.fillsChanged.update((revision) => revision + 1);
2051
+ }
2052
+ // Ask `asked` of `copy` on a SUBSCRIBE of their own with no max delay, as the Rust `Recovery`
2053
+ // does: on lite-07 `copy`'s subscription dropped them as stale, or delivered them before and they
2054
+ // were since evicted, so it never sends them again, and before lite-07 every run is asked this
2055
+ // way. Its groups land in the copy as a subscription's do. It FINs once every group is accounted
2056
+ // for and read, and is over at the publisher's FIN in reply, refusing whatever it did not deliver.
2057
+ #recover(broadcast, consumed, copy, asked, priority) {
2058
+ const producer = copy.track;
2059
+ const id = this.#subscribeNext++;
2060
+ // Narrowed in place once the first group before lite-07 settles how far it reaches.
2061
+ const groups = "time" in asked ? { start: asked.time, end: asked.time + 1n } : { ...asked };
2062
+ // Before lite-07 the subscription proves only the keys below its start, so the range stays open
2063
+ // until the first group that arrives caps it: only upstream knows which group it still holds
2064
+ // past the run, and a relay's start may be its floor, which names no group.
2065
+ const oneStart = !hasGroupEnd(this.version);
2066
+ const oneShot = keepsSubscribeOpen(this.version);
2067
+ const policy = { priority, order: "ascending" };
2068
+ const ranges = [span(groups.start, oneStart ? undefined : groups.end) ?? EMPTY];
2069
+ // A metadata copy's fill asks for headers alone too.
2070
+ const target = { name: producer.name, meta: copy.meta };
2071
+ const msg = this.#withRanges(this.#subscribeMessage(id, broadcast, consumed, target, policy, ranges), ranges);
2072
+ // Lite-07 recovery asks for exact group bounds [Position(start, 0), Position(end, 0))
2073
+ // rather than time-containment ranges.
2074
+ if (hasRanges(this.version)) {
2075
+ msg.ranges = [
2076
+ withPolicy("time" in asked
2077
+ ? probe(asked.time)
2078
+ : {
2079
+ start: { absolute: groups.start, frame: 0 },
2080
+ end: { absolute: groups.end, frame: 0 },
2081
+ }, msg),
2082
+ ];
2083
+ }
2084
+ const live = new LiveRanges(this.version, msg.ranges ?? []);
2085
+ const entry = {
2086
+ track: producer,
2087
+ meta: copy.meta,
2088
+ staleCap: capOf(live),
2089
+ compress: copy.compress,
2090
+ timescale: copy.timescale,
2091
+ tail: new Tail({
2092
+ grace: () => (hasSkip(this.version) ? undefined : hooks.tailGrace(producer)),
2093
+ proven: hasSkip(this.version),
2094
+ }),
2095
+ requested: msg.startGroup,
2096
+ floor: msg.startGroup,
2097
+ asked: ranges,
2098
+ askedPlaced: new Map(),
2099
+ live,
2100
+ starts: new Map(),
2101
+ joinTicks: new Map(),
2102
+ joinBudgets: new Map(),
2103
+ sent: 0,
2104
+ // Its responses are read here, which owns this stream's end.
2105
+ stream: { kind: "setup" },
2106
+ filling: "time" in asked ? "probe" : "range",
2107
+ feedEnded: "time" in asked ? new Once() : undefined,
2108
+ fillIds: new Set(),
2109
+ probeIds: new Set(),
2110
+ fillGroups: [],
2111
+ fillsChanged: new Signal(0),
2112
+ };
2113
+ const left = new AbortController();
2114
+ const signal = consumed.valid ? AbortSignal.any([consumed.valid, left.signal]) : left.signal;
2115
+ const leaving = new Promise((resolve) => left.signal.addEventListener("abort", () => resolve(), { once: true }));
2116
+ let refused = [];
2117
+ // Those the fills have yet to take: each refusal is handed over once.
2118
+ let fresh = [];
2119
+ // TEMPORARY MIGRATION, delete at the next version cut with `Stall`, once no relay of the
2120
+ // previous release is left. That relay starts the recovery at its floor, sends the next group it
2121
+ // holds, and never accounts for the keys between: it read a SUBSCRIBE asking no max delay as a
2122
+ // 285,000-year grace, so it never asks its own upstream. Once the `Stall` grace passes with no
2123
+ // progress, what is still owed is refused for now: asked a key at a time instead, a sparse span
2124
+ // would cost a request per key.
2125
+ let stall;
2126
+ const changed = new Signal(0);
2127
+ // What the publisher gives up of the groups, accounted for in the tail. The latest verdict on a
2128
+ // group replaces any earlier one, so a peer repeating its drops grows nothing.
2129
+ const giveUp = (start, end, refusal) => {
2130
+ stall?.restart();
2131
+ entry.tail.account(start, end);
2132
+ refused = refuseRun(refused, max(start, groups.start), min(end, groups.end), refusal);
2133
+ fresh = refuseRun(fresh, max(start, groups.start), min(end, groups.end), refusal);
2134
+ changed.update((revision) => revision + 1);
2135
+ };
2136
+ this.#subscribes.set(id, entry);
2137
+ const done = (async () => {
2138
+ let failed = new StreamError(StreamCode.Cancel, { message: "recovery ended" });
2139
+ let stream;
2140
+ try {
2141
+ while ((await this.#auth?.ready(broadcast, "subscribe", { signal, until: () => leaving })) === false) {
2142
+ if (left.signal.aborted)
2143
+ return fresh;
2144
+ }
2145
+ if (this.#denied(broadcast))
2146
+ throw unauthorized(broadcast);
2147
+ const opened = await this.#exchange({ sendOrder: sendOrder({ priority }), version: this.version }, async (stream) => {
2148
+ const bytes = await Writer.collect(this.version, async (w) => {
2149
+ await w.u53(StreamId.Subscribe);
2150
+ await msg.encode(w, this.version);
2151
+ });
2152
+ await stream.writer.write(bytes);
2153
+ // Lite-07 one-shot SUBSCRIBE + immediate FIN (1 RTT).
2154
+ if (oneShot)
2155
+ stream.writer.close();
2156
+ return stream;
2157
+ }, signal, new Deadline());
2158
+ stream = opened;
2159
+ let fin = oneShot;
2160
+ // The update capping the open range at the first group that arrives, which goes out before
2161
+ // our FIN.
2162
+ let capping = Promise.resolve();
2163
+ let capped = !oneStart;
2164
+ let started = false;
2165
+ const cap = () => {
2166
+ capped = true;
2167
+ const update = new SubscribeUpdate({
2168
+ priority: msg.priority,
2169
+ order: msg.order,
2170
+ maxDelay: msg.maxDelay,
2171
+ startGroup: msg.startGroup,
2172
+ endGroup: inclusiveGroupEnd(groups.end),
2173
+ });
2174
+ // A failed write means the publisher stopped reading: its responses decide the end.
2175
+ capping = Writer.collect(this.version, (w) => update.encode(w, this.version))
2176
+ .then((encoded) => opened.writer.write(encoded))
2177
+ .catch(() => undefined);
2178
+ };
2179
+ // Only a group that arrives proves one, so once started the range stops past the first;
2180
+ // what lies between is named by the publisher's drops, or given up with the grace.
2181
+ const capAtFirst = () => {
2182
+ const first = entry.tail.first;
2183
+ if (capped || !started || first === undefined || first < groups.start)
2184
+ return;
2185
+ if (first + 1n < groups.end)
2186
+ groups.end = first + 1n;
2187
+ cap();
2188
+ // TEMPORARY MIGRATION, see `stall`.
2189
+ if (!entry.tail.covers(groups.start, groups.end)) {
2190
+ stall?.close();
2191
+ stall = new Stall(entry.tail);
2192
+ }
2193
+ };
2194
+ const responses = this.#recoveryResponses(opened, entry, groups, (group) => {
2195
+ if ("time" in asked) {
2196
+ if (group !== undefined && group < asked.time) {
2197
+ // The time is inside this group, whose start is the only key owed.
2198
+ groups.start = group;
2199
+ groups.end = group + 1n;
2200
+ }
2201
+ asked.start.set({ group });
2202
+ }
2203
+ const from = group ?? groups.end;
2204
+ started = true;
2205
+ // Starting past the run answers all of it, so nothing more is asked.
2206
+ if (!capped && from >= groups.end)
2207
+ cap();
2208
+ capAtFirst();
2209
+ }, giveUp, () => fin);
2210
+ // FIN once every group is accounted for and read, as a subscriber does once its tail
2211
+ // settles, and the publisher FINs in reply.
2212
+ let ended = false;
2213
+ const over = responses.then(() => {
2214
+ ended = true;
2215
+ }, () => {
2216
+ ended = true;
2217
+ });
2218
+ // Ends a settle still waiting once this loop leaves it.
2219
+ const stopped = new Once();
2220
+ const covered = () => entry.tail.covers(groups.start, groups.end);
2221
+ try {
2222
+ while (!oneShot && !ended && !left.signal.aborted) {
2223
+ capAtFirst();
2224
+ // TEMPORARY MIGRATION, see `stall`: what is still owed once the grace passed with no
2225
+ // progress is refused for now, as this route cannot account for it.
2226
+ if (stall?.poll(entry.tail) && !covered()) {
2227
+ failed = new StreamError(StreamCode.Unroutable, { message: "recovery stalled" });
2228
+ left.abort();
2229
+ break;
2230
+ }
2231
+ if (covered()) {
2232
+ await race([entry.tail.settle(covered, stopped), over, leaving]);
2233
+ if (ended || left.signal.aborted)
2234
+ break;
2235
+ // The cap goes out before our FIN; a cancel, which resets a write still blocked, or
2236
+ // the publisher's end stops the wait.
2237
+ await race([capping, over, leaving]);
2238
+ if (ended || left.signal.aborted)
2239
+ break;
2240
+ fin = true;
2241
+ opened.writer.close();
2242
+ break;
2243
+ }
2244
+ await race([
2245
+ Signal.race(entry.tail.changed),
2246
+ over,
2247
+ leaving,
2248
+ ...(stall === undefined ? [] : [stall.wake]),
2249
+ ]);
2250
+ }
2251
+ }
2252
+ finally {
2253
+ stopped.set(null);
2254
+ }
2255
+ // After our FIN, a cancel still stops the wait for the publisher's.
2256
+ if (!ended)
2257
+ await race([over, leaving]);
2258
+ // Cancelled: nothing more is read, and our own reset ends the reads above.
2259
+ if (!ended) {
2260
+ opened.abort(failed);
2261
+ await over;
2262
+ }
2263
+ else {
2264
+ await responses;
2265
+ // The publisher FINs once done (unprompted before lite-07, or in reply to our
2266
+ // one-shot FIN on lite-07), before every uni Group Stream it opened may have
2267
+ // landed: wait for those before refusing what is left, at most the grace before
2268
+ // lite-07, whose tail has none, and a stream silent that long is given up on. A proven
2269
+ // tail waits only for what lies above the runs it forgot: below them it lost proof, so
2270
+ // that part is refused for the fill to ask again.
2271
+ const lost = () => entry.tail.lost([groups]);
2272
+ if (!covered() || entry.tail.reading) {
2273
+ const drained = new Once();
2274
+ try {
2275
+ const answered = () => entry.tail.answered(groups.start, groups.end);
2276
+ await race([entry.tail.drain(answered, drained, GRACE), leaving]);
2277
+ }
2278
+ finally {
2279
+ drained.set(null);
2280
+ }
2281
+ }
2282
+ if (lost())
2283
+ failed = new StreamError(StreamCode.Unroutable, {
2284
+ message: "recovery tail forgot runs it still owes",
2285
+ });
2286
+ opened.close();
2287
+ }
2288
+ }
2289
+ catch (err) {
2290
+ closeViolation(this.#quic, err);
2291
+ failed = error(err);
2292
+ // The publisher reset its side, or reading failed: give back our side too.
2293
+ stream?.abort(failed);
2294
+ }
2295
+ finally {
2296
+ stall?.close();
2297
+ left.abort();
2298
+ entry.feedEnded?.set("ended");
2299
+ this.#subscribes.delete(id);
2300
+ entry.tail.close();
2301
+ }
2302
+ // What nothing accounted for is refused, as nothing more arrives on it.
2303
+ let unanswered = [{ ...groups }];
2304
+ for (const run of [...entry.tail.accounted(groups.start, groups.end), ...refused])
2305
+ unanswered = removeRun(unanswered, run.start, run.end);
2306
+ for (const gap of unanswered)
2307
+ fresh.push({ ...gap, refusal: passing(failed) });
2308
+ // Only what was not handed over while it was out.
2309
+ return fresh;
2310
+ })();
2311
+ const takeRefused = () => {
2312
+ const taken = fresh;
2313
+ fresh = [];
2314
+ return taken;
2315
+ };
2316
+ return {
2317
+ groups: () => groups,
2318
+ arrived: () => entry.tail.first !== undefined,
2319
+ done,
2320
+ takeRefused,
2321
+ changed,
2322
+ readingChanged: entry.tail.changed,
2323
+ reading: () => entry.tail.reading,
2324
+ cancel: () => left.abort(),
2325
+ };
2326
+ }
2327
+ // Read a recovery's responses to the publisher's FIN, giving up what it names it will not
2328
+ // deliver. `fin` says whether our FIN went out, which the publisher's answers, and `onStart`
2329
+ // hears where SUBSCRIBE_START says delivery starts.
2330
+ async #recoveryResponses(stream, entry, groups, onStart, giveUp, fin) {
2331
+ let started = false;
2332
+ let finished = false;
2333
+ // Where the SUBSCRIBE_START's answer for the groups below its start ends.
2334
+ let answered;
2335
+ for (;;) {
2336
+ const resp = await decodeSubscribeResponseMaybe(stream.reader, this.version);
2337
+ if (!resp) {
2338
+ // The publisher FINs in reply to ours, or once it finished the track.
2339
+ if (fin() || finished)
2340
+ return;
2341
+ throw new ProtocolViolation("recovery subscribe ended without SUBSCRIBE_END");
2342
+ }
2343
+ if ("start" in resp) {
2344
+ // One start, for its one range.
2345
+ if (started || resp.start.id !== 0n)
2346
+ throw new ProtocolViolation("unexpected recovery SUBSCRIBE_START");
2347
+ started = true;
2348
+ // Below its start the publisher, asked with no max delay, lacks them.
2349
+ const from = resp.start.start ?? groups.end;
2350
+ giveUp(groups.start, max(groups.start, min(from, groups.end)), passing(new NotFound(`group ${groups.start}`)));
2351
+ onStart(resp.start.start);
2352
+ // After `onStart`, which narrows a time probe's groups to the group it starts.
2353
+ answered = max(groups.start, min(from, groups.end));
2354
+ }
2355
+ else if ("skip" in resp) {
2356
+ // Never produced: final, as the subscription feeding the copy records it.
2357
+ const { start, end } = resp.skip;
2358
+ entry.tail.account(start, end);
2359
+ hooks.skipTrackGroups(entry.track, start, end);
2360
+ }
2361
+ else if ("drop" in resp || "old" in resp) {
2362
+ const { start, end } = "drop" in resp ? resp.drop : resp.old;
2363
+ // Before lite-07 a drop only ever named staleness.
2364
+ const stale = "old" in resp || !hasSkip(this.version);
2365
+ const cause = stale ? new StreamError(StreamCode.Old) : new NotFound(`group ${start}`);
2366
+ this.#dropped(entry, start, end);
2367
+ // Final on this subscription, so a stream it overtook is told from one whose gap the grace
2368
+ // gave up on. It says nothing of whether the groups exist, so the fills owing them are
2369
+ // refused for now rather than answered. Below its start the SUBSCRIBE_START already
2370
+ // answered them, which a publisher naming them again does not change.
2371
+ entry.tail.drop(start, end);
2372
+ giveUp(max(start, answered ?? start), end, passing(cause));
2373
+ }
2374
+ else if ("end" in resp) {
2375
+ if (finished)
2376
+ throw new ProtocolViolation("duplicate SUBSCRIBE_END");
2377
+ finished = true;
2378
+ // Nothing at or past the track's end will be produced. Lite-05 specified an inclusive
2379
+ // end, which @moq/net 0.1.3 to 0.1.9 sent, so its end group may still be in flight: the
2380
+ // tail settles it instead.
2381
+ const end = max(this.version === Version.DRAFT_05 ? resp.end.group + 1n : resp.end.group, groups.start);
2382
+ giveUp(end, groups.end, dropped(new NotFound(`group ${end}`)));
2383
+ }
2384
+ else {
2385
+ throw new ProtocolViolation("unexpected recovery subscribe response");
2386
+ }
717
2387
  }
718
2388
  }
719
- // Reads SUBSCRIBE_START/END/DROP on the subscribe stream until FIN (lite-05+), recording
720
- // the range the tail is accounted against. SUBSCRIBE_END declares the track's end right
721
- // away, so a consumer learns it before the last groups arrive. The publisher must declare
722
- // the end before FIN unless we cancelled locally; resets and malformed responses reject.
2389
+ // Start reading the subscribe stream's responses; see `runResponses`.
2390
+ #read(stream, entry) {
2391
+ const responses = this.runResponses(stream, entry);
2392
+ entry.stream = { kind: "reading", responses: responses.catch(() => { }) };
2393
+ return responses;
2394
+ }
2395
+ // Reads the subscribe stream's responses until FIN, recording the range the tail is
2396
+ // accounted against: SUBSCRIBE_START/END/DROP on lite-05+, and any SUBSCRIBE_DROP after the
2397
+ // OK before then, where the FIN itself ends the track. Reading to the FIN, rather than
2398
+ // awaiting it, matters: a pull-driven transport stream closes only on a read.
2399
+ // SUBSCRIBE_END declares the track's end right away, so a consumer learns it before the
2400
+ // last groups arrive. The publisher must declare the end before FIN unless we cancelled
2401
+ // locally; resets and malformed responses reject.
723
2402
  async runResponses(stream, entry) {
2403
+ let observed;
724
2404
  for (;;) {
725
2405
  const resp = await decodeSubscribeResponseMaybe(stream.reader, this.version);
2406
+ // The publisher answered, so its demand stands on the subscription from here.
2407
+ if (entry.unanswered) {
2408
+ entry.unanswered.held.close();
2409
+ entry.unanswered.answered.abort();
2410
+ entry.unanswered = undefined;
2411
+ }
726
2412
  if (!resp) {
727
- if (entry.end === undefined && entry.track.closed.peek() === undefined)
2413
+ // Before lite-05 the FIN is the track's only end.
2414
+ if (!hasTrackStream(this.version)) {
2415
+ // Our side never FINs there, so the stream is still being read.
2416
+ if (entry.stream.kind === "reading")
2417
+ entry.stream = { kind: "finished", responses: entry.stream.responses };
2418
+ return;
2419
+ }
2420
+ if (entry.end === undefined && hooks.trackReleased(entry.track).peek() === undefined)
728
2421
  throw new ProtocolViolation("subscribe stream ended without SUBSCRIBE_END");
729
2422
  return;
730
2423
  }
2424
+ // Once its tail is accounted for, this feed no longer owns the copy's placement.
2425
+ if (entry.feedEnded?.peek())
2426
+ continue;
2427
+ if ("ok" in resp)
2428
+ throw new ProtocolViolation("duplicate SUBSCRIBE_OK");
731
2429
  if ("start" in resp) {
732
- entry.start = resp.start.group;
733
- // The groups the SUBSCRIBE asked for below it are not waited for, whatever the
734
- // demand asks later. One that still arrives is delivered.
735
- if (entry.requested !== undefined)
736
- entry.tail.account(entry.requested, entry.start);
2430
+ if (hasRanges(this.version)) {
2431
+ this.#started(entry, resp.start);
2432
+ const { id, largest } = resp.start;
2433
+ if (typeof largest === "object" && entry.live.get(id)) {
2434
+ const group = largest.position.group;
2435
+ observed ??= new Sorted((key) => key, (a, b) => (a < b ? -1 : a > b ? 1 : 0));
2436
+ if (observed.floor(group) !== group)
2437
+ observed.insert(group);
2438
+ }
2439
+ // The rest of a burst already here is recorded before applying it once.
2440
+ if (!startBuffered(stream.reader, this.version)) {
2441
+ this.#applyStarts(entry, observed);
2442
+ observed = undefined;
2443
+ }
2444
+ }
2445
+ else {
2446
+ // Before lite-07 the one start answers the subscription, and says the feed is live.
2447
+ if (entry.start !== undefined)
2448
+ throw new ProtocolViolation("duplicate SUBSCRIBE_START");
2449
+ const start = resp.start.start;
2450
+ entry.start = start ?? null;
2451
+ // A tail waits for SUBSCRIBE_START to say where delivery starts.
2452
+ entry.tail.touch();
2453
+ hooks.startTrack(entry.track, {
2454
+ start: entry.start,
2455
+ requested: entry.requested,
2456
+ restated: entry.restated,
2457
+ });
2458
+ // The groups the SUBSCRIBE asked for below it are not waited for, whatever the
2459
+ // demand asks later. One that still arrives is delivered.
2460
+ if (entry.requested !== undefined && start !== undefined)
2461
+ entry.tail.account(entry.requested, start);
2462
+ }
737
2463
  }
738
2464
  else if ("end" in resp) {
739
2465
  if (entry.end !== undefined)
740
2466
  throw new ProtocolViolation("duplicate SUBSCRIBE_END");
741
2467
  entry.end = resp.end.group;
742
- if (hasStreamCount(this.version))
743
- entry.streams = resp.end.streams;
744
2468
  // A local close can win the race with the response; there is nothing left to end.
745
- if (entry.track.closed.peek() !== undefined)
2469
+ if (hooks.trackReleased(entry.track).peek() !== undefined)
746
2470
  continue;
747
2471
  try {
748
- entry.track.finishAt(entry.end);
2472
+ // Lower groups may still be on the wire behind a higher one, so readers hold
2473
+ // at a hole below the end until the tail settles.
2474
+ hooks.endTrack(entry.track, { group: entry.end, frame: 0 });
749
2475
  }
750
2476
  catch (err) {
751
2477
  // lite-05 specified an inclusive end, and @moq/net 0.1.3 to 0.1.9 sent one, so
@@ -756,44 +2482,227 @@ export class Subscriber {
756
2482
  }
757
2483
  console.warn(`invalid SUBSCRIBE_END: ${reason(error(err))}`);
758
2484
  }
2485
+ // Lite-07 keeps the stream open past SUBSCRIBE_END: FIN once the tail settles,
2486
+ // and the publisher's FIN in reply ends this loop.
2487
+ if (keepsSubscribeOpen(this.version))
2488
+ void this.#finishTail(stream, entry).catch(() => { });
2489
+ }
2490
+ else if ("skip" in resp) {
2491
+ this.#skipped(entry, resp.skip.start, resp.skip.end);
2492
+ }
2493
+ else if ("drop" in resp || "old" in resp) {
2494
+ const { start, end } = "drop" in resp ? resp.drop : resp.old;
2495
+ // The publisher will never send these groups on this subscription, so they are accounted
2496
+ // for without a stream. Lite-07 tells a stream a drop overtook from one whose gap the grace
2497
+ // gave up on.
2498
+ if (hasSkip(this.version))
2499
+ entry.tail.drop(start, end);
2500
+ else
2501
+ entry.tail.account(start, end);
2502
+ this.#dropped(entry, start, end);
2503
+ let refusal;
2504
+ if ("old" in resp) {
2505
+ // Stale, recorded under the max age it names it judged under: a reader wider than that
2506
+ // does not settle on it, and asks for the group with a request of its own. A group a
2507
+ // fill asked for is recovered on its own, so the copy does not record it given up
2508
+ // meanwhile. Mirrors the Rust `ServeLoop::apply_response`.
2509
+ const hole = staleHole(resp.old.maxAge, entry.staleCap);
2510
+ for (const given of runGaps(entry.fillGroups, start, end))
2511
+ hooks.dropTrackGroups(entry.track, given.start, given.end, hole);
2512
+ refusal = stale(new StreamError(StreamCode.Old));
2513
+ }
2514
+ else if (!hasSkip(this.version)) {
2515
+ // Before lite-07 a drop carries no code and only ever names staleness, judged under no
2516
+ // budget this side can see: superseded, as it always read. A group a fill still owes
2517
+ // is left to the fill's recovery, which asks with no max delay: the publisher answers
2518
+ // both, and which lands first must not decide what the reader gets. Mirrors the Rust
2519
+ // `ServeLoop::apply_response`.
2520
+ // Before lite-05 nothing recovers a fill, so the drop is recorded for it too.
2521
+ const owed = hasTrackStream(this.version) ? hooks.fillsOwe(entry.track, start, end) : [];
2522
+ for (const given of runGaps(owed, start, end))
2523
+ hooks.dropTrackGroups(entry.track, given.start, given.end, { reason: "old" });
2524
+ refusal = stale(new StreamError(StreamCode.Old));
2525
+ }
2526
+ else {
2527
+ // A lite-07 drop is this subscription's alone, which says nothing of whether the groups
2528
+ // exist: a copy of one still arriving on it is given up for now, and a reader that still
2529
+ // wants one asks a fill, which another request or route may answer.
2530
+ hooks.loseTrackGroups(entry.track, start, end);
2531
+ refusal = scoped(new NotFound(`group ${start}`));
2532
+ }
2533
+ entry.fills?.refuse(start, end, refusal);
2534
+ }
2535
+ }
2536
+ }
2537
+ // Lite-07: record where one range starts, from its SUBSCRIBE_START, along with what the publisher
2538
+ // knows of the live edge, which `#applyStarts` then applies. A range following the live edge is
2539
+ // answered with where the edge is. Mirrors the Rust `ServeLoop::record_start`.
2540
+ #started(entry, msg) {
2541
+ const { id, start, largest } = msg;
2542
+ const range = entry.live.get(id);
2543
+ const follows = range !== undefined && (range.start?.live !== undefined || range.end === undefined);
2544
+ if (!entry.live.assigned(id) || entry.starts.has(id) || (largest === "unknown" && follows))
2545
+ throw new ProtocolViolation(`unexpected SUBSCRIBE_START: ${id}`);
2546
+ // Recorded whole, so a relay answers its own readers that the group ended.
2547
+ if (typeof largest === "object")
2548
+ hooks.reportedLargest(entry.track, largest.position, largest.ended);
2549
+ if (largest !== "unknown")
2550
+ hooks.answerEdge(entry.track);
2551
+ // One retired since is owed nothing.
2552
+ if (range) {
2553
+ entry.starts.set(id, start);
2554
+ // A fill's range starting past where it asked skips groups it will not deliver.
2555
+ const asked = entry.fillIds.has(id) ? fillRun(range) : undefined;
2556
+ if (asked) {
2557
+ const skipped = max(asked.start, min(start ?? asked.end, asked.end));
2558
+ // The tail uses each range's own START. Another range can still owe this prefix.
2559
+ entry.fills?.skip(asked, asked.start, skipped);
2560
+ }
2561
+ }
2562
+ }
2563
+ // Apply the lite-07 SUBSCRIBE_STARTs `#started` recorded to what every range shares: where the
2564
+ // feed starts, the tail, and the starts the copy's readers resolve against. Once per burst, since
2565
+ // each pass walks every range, so one per START would cost the square of the ranges. Mirrors the
2566
+ // Rust `ServeLoop::apply_starts`.
2567
+ #applyStarts(entry, observed) {
2568
+ // The lowest start any range reported is the first group served; none leaves nothing owed.
2569
+ let lowest = null;
2570
+ for (const at of entry.starts.values())
2571
+ if (at !== undefined && (lowest === null || at < lowest))
2572
+ lowest = at;
2573
+ entry.start = lowest;
2574
+ // The tail judges what is owed again.
2575
+ entry.tail.touch();
2576
+ this.#reportStarts(entry);
2577
+ this.#declareFeed(entry, observed);
2578
+ }
2579
+ // The publisher never produced `[start, end)`, as a SUBSCRIBE_SKIP says, so nothing is
2580
+ // waited for and no reader ends. A skip replaces any drop of the same groups; a reader a drop
2581
+ // already ended stays ended.
2582
+ #skipped(entry, start, end) {
2583
+ entry.tail.account(start, end);
2584
+ // A fill owing them is answered: the source never had them.
2585
+ entry.fills?.refuse(start, end, passing(new NotFound(`group ${start}`)));
2586
+ // A group that arrived was produced after all, so the skip contradicts it: it keeps the
2587
+ // group, and the session goes on, since the draft requires no more.
2588
+ const [cached] = hooks.skipTrackGroups(entry.track, start, end);
2589
+ if (cached) {
2590
+ console.warn(`protocol error: SUBSCRIBE_SKIP skips [${start}, ${end}), which holds group ${cached.start}, which arrived; keeping it`);
2591
+ }
2592
+ }
2593
+ // Settle a lite-07 tail past SUBSCRIBE_END, then FIN. An update sent meanwhile asks for more,
2594
+ // which waits a fresh grace rather than one that may have passed while a stream was read.
2595
+ async #finishTail(stream, entry) {
2596
+ for (;;) {
2597
+ const sent = entry.sent;
2598
+ try {
2599
+ await this.#settleTail(entry);
759
2600
  }
760
- else if ("drop" in resp) {
761
- entry.tail.account(resp.drop.start, resp.drop.end + 1);
2601
+ catch (err) {
2602
+ // The tail lost its proof: this route cannot prove the track's end, so the track ends
2603
+ // with the error for another to resume, as the Rust subscriber gives it back.
2604
+ const e = error(err);
2605
+ hooks.abortTrack(entry.track, e);
2606
+ stream.abort(e);
2607
+ return;
762
2608
  }
2609
+ if (hooks.trackReleased(entry.track).peek() !== undefined)
2610
+ return;
2611
+ if (entry.sent !== sent || !this.#covered(entry))
2612
+ continue;
2613
+ // The copy's own tail settles with the subscription's, which its readers wait on, whatever
2614
+ // fill is still out.
2615
+ if (entry.stream.kind !== "reading")
2616
+ return;
2617
+ this.#fin(stream, entry);
2618
+ hooks.settleTail(entry.track);
2619
+ entry.fills?.finishFeed();
2620
+ entry.feedEnded?.set("ended");
2621
+ return;
763
2622
  }
764
2623
  }
2624
+ // FIN our side once, acknowledging a settled tail without cancelling the publisher's half.
2625
+ #fin(stream, entry) {
2626
+ if (entry.stream.kind !== "reading")
2627
+ return;
2628
+ entry.stream = { kind: "fin", responses: entry.stream.responses };
2629
+ stream.writer.close();
2630
+ }
765
2631
  // Wait for the group streams the publisher still owes once it has ended the subscription.
766
2632
  //
767
- // lite-07 counts streams, so skipped sequences owe nothing. Older drafts account for
768
- // the range using received headers and SUBSCRIBE_DROP. A counted stream reset before
769
- // its header leaves no trace, so the grace still bounds that wait. Streams whose
770
- // headers arrived keep reading until their own FIN or reset.
771
- #settleTail(entry) {
2633
+ // Received headers and SUBSCRIBE_DROP account for the range. An unaccounted
2634
+ // key, such as a lost datagram, still waits out the grace. Streams whose
2635
+ // headers arrived keep reading until their own FIN or reset, or, with a grace, until they go
2636
+ // quiet for it: a browser can lose a stream's reset.
2637
+ //
2638
+ // A lite-07 tail that forgot runs it still owes can never settle, so it throws
2639
+ // {@link StreamCode.Unroutable} instead.
2640
+ async #settleTail(entry) {
772
2641
  const { tail, track } = entry;
773
- const complete = () => {
774
- if (entry.streams !== undefined)
775
- return tail.streams >= entry.streams;
776
- // Without SUBSCRIBE_END (older drafts) nothing says which groups are owed.
777
- if (entry.end === undefined)
778
- return false;
779
- // Without SUBSCRIBE_START the publisher served no group at all.
780
- if (entry.start === undefined)
781
- return true;
782
- // Owed from the floor the demand last asked for, which an update can move either
783
- // way, or where SUBSCRIBE_START resolved a live-edge one. The groups the SUBSCRIBE
784
- // asked for below its SUBSCRIBE_START were accounted for when it arrived.
785
- const groups = track.subscription.peek()?.groups;
786
- const bounds = groupBounds(groups ?? {});
787
- const start = groups?.start === undefined ? entry.start : bounds.start;
788
- const end = bounds.end === undefined ? entry.end : Math.min(entry.end, bounds.end);
789
- return tail.covers(start, end);
790
- };
791
- return tail.settle(complete, track.closed);
2642
+ await tail.drain(() => this.#covered(entry) || this.#lost(entry), hooks.trackReleased(track));
2643
+ if (this.#lost(entry)) {
2644
+ throw new StreamError(StreamCode.Unroutable, { message: "subscription tail forgot runs it still owes" });
2645
+ }
2646
+ }
2647
+ // Whether a lite-07 tail lost the proof for what it is owed (see `Tail.lost`).
2648
+ #lost(entry) {
2649
+ const owed = hasRanges(this.version) ? this.#owed(entry) : undefined;
2650
+ return owed !== undefined && entry.tail.lost(owed);
2651
+ }
2652
+ // The groups a lite-07 subscription the publisher ended is owed, or undefined while nothing
2653
+ // says yet. Lite-07 answers each range with its own SUBSCRIBE_START, even once the track ended,
2654
+ // unless nothing was asked below the end. Each range the publisher holds is then owed from the
2655
+ // start its SUBSCRIBE_START named, which accounts for a skipped prefix and resolves a live join
2656
+ // or a time start; one whose SUBSCRIBE_START is still on its way owes what nothing says yet.
2657
+ #owed(entry) {
2658
+ if (entry.end === undefined)
2659
+ return undefined;
2660
+ const held = wireHeld(hooks.requested(entry.track).peek() ?? {});
2661
+ const ranges = placedAsTimes(held.ranges, held.placed);
2662
+ const end = min(entry.end, wireSpan(ranges).end ?? entry.end);
2663
+ if (entry.start === undefined)
2664
+ return end > (rangesStart(ranges) ?? 0n) ? undefined : [];
2665
+ const owed = [];
2666
+ for (const [id, range] of entry.live.entries()) {
2667
+ if (!entry.starts.has(id))
2668
+ return undefined;
2669
+ const at = entry.starts.get(id);
2670
+ if (at === undefined)
2671
+ continue;
2672
+ const model = requestedRange(range);
2673
+ owed.push({ ...model, start: at });
2674
+ }
2675
+ // Each starts at the group its publisher reported starting it at.
2676
+ return new Window(owed, entry.track.largest()?.group, AT_KEYS).runs(0n, end);
2677
+ }
2678
+ // Whether the groups received and dropped account for every group the demand is owed once
2679
+ // the publisher ended the subscription.
2680
+ #covered(entry) {
2681
+ // Without SUBSCRIBE_END (older drafts) nothing says which groups are owed.
2682
+ if (entry.end === undefined)
2683
+ return false;
2684
+ const held = wireHeld(hooks.requested(entry.track).peek() ?? {});
2685
+ const ranges = placedAsTimes(held.ranges, held.placed);
2686
+ const end = min(entry.end, wireSpan(ranges).end ?? entry.end);
2687
+ const floor = rangesStart(ranges);
2688
+ if (hasRanges(this.version)) {
2689
+ return this.#owed(entry)?.every((run) => entry.tail.covers(run.start, run.end)) ?? false;
2690
+ }
2691
+ // Without SUBSCRIBE_START the publisher served no group at all. Otherwise each group is owed
2692
+ // from the floor the demand last asked for, or where SUBSCRIBE_START resolved a live-edge one,
2693
+ // but never below that START: nothing answers an update, and the publisher applies none once it
2694
+ // has sent its FIN, so a floor an update lowered may never have reached it. The groups the
2695
+ // SUBSCRIBE asked for below its SUBSCRIBE_START were accounted for when it arrived.
2696
+ if (entry.start === undefined || entry.start === null)
2697
+ return true;
2698
+ const window = new Window(ranges, entry.track.largest()?.group);
2699
+ const from = max(floor ?? entry.start, entry.start);
2700
+ return window.runs(from, end).every((run) => entry.tail.covers(run.start, run.end));
792
2701
  }
793
2702
  /**
794
2703
  * Send SUBSCRIBE_UPDATE messages whenever the track's aggregate subscription changes.
795
2704
  *
796
- * Resolves cleanly when the stream or track closes, so the caller can include
2705
+ * Resolves cleanly when the stream or track closes, or a write fails, so the caller can include
797
2706
  * this in a race without leaving a dangling pending write that would
798
2707
  * become an unhandled rejection if the user calls update after close.
799
2708
  *
@@ -803,58 +2712,368 @@ export class Subscriber {
803
2712
  */
804
2713
  async #runSubscriptionUpdates(id, broadcast, entry, msg, stream) {
805
2714
  const track = entry.track;
806
- const stopped = race([track.closed, stream.reader.closed]).then(() => null);
807
- let lastSent = {
2715
+ // A reset stops updates too; the responses decide how the track ends.
2716
+ const stopped = race([
2717
+ hooks.trackReleased(track),
2718
+ stream.reader.closed,
2719
+ ...(entry.feedEnded ? [entry.feedEnded] : []),
2720
+ ]).then(() => null, () => null);
2721
+ let lastSent = { ranges: entry.asked };
2722
+ if (entry.askedPlaced.size > 0)
2723
+ lastSent.placed = entry.askedPlaced;
2724
+ // The wanted group is subscription state: an update announces each new one past our
2725
+ // largest, and every later update restates it. Requests asking for the same group
2726
+ // coalesce into that one update.
2727
+ let sentWanted;
2728
+ // What the fills asked with the last update, and the priority it carried.
2729
+ let sentFills = [];
2730
+ let sentFillOrder;
2731
+ let sentPriority = msg.priority;
2732
+ // The time starts and live joins the readers waited on as the last update went out.
2733
+ let sentAsks = [];
2734
+ let sentJoins = [];
2735
+ // The terms the publisher last heard; an update restating them tells it nothing, as when a
2736
+ // join's tick moves while its probe is still unanswered.
2737
+ let live = new SubscribeUpdate({
808
2738
  priority: msg.priority,
809
- maxAge: Time.Milli(msg.maxAge),
810
- groups: {
811
- start: msg.startGroup === undefined ? undefined : { included: msg.startGroup },
812
- end: msg.endGroup === undefined ? undefined : { excluded: exclusiveGroupEnd(msg.endGroup) ?? 0 },
813
- },
814
- };
815
- for (;;) {
816
- const current = track.subscription.peek();
817
- if (current === undefined || this.#sameSubscription(current, lastSent)) {
818
- // Nothing new to send; wait for a change or termination.
819
- const next = await race([track.subscription.changed(), stopped]);
2739
+ order: msg.order,
2740
+ maxDelay: msg.maxDelay,
2741
+ startGroup: msg.startGroup,
2742
+ endGroup: msg.endGroup,
2743
+ startFrame: msg.startFrame,
2744
+ endFrame: msg.endFrame,
2745
+ });
2746
+ const asked = hooks.demandAsked(track.demand());
2747
+ const edge = hooks.producerLargest(track);
2748
+ while (entry.stream.kind === "reading") {
2749
+ const largest = edge.peek()?.group;
2750
+ const wanted = asked.peek();
2751
+ const refresh = hasRefresh(this.version) &&
2752
+ largest !== undefined &&
2753
+ wanted !== undefined &&
2754
+ wanted > largest &&
2755
+ wanted !== sentWanted
2756
+ ? wanted
2757
+ : undefined;
2758
+ const current = hooks.requested(track).peek();
2759
+ // Lite-07 asks upstream to place each time start and live join the readers wait on.
2760
+ const asks = hasRanges(this.version) ? hooks.requested(track).asks() : [];
2761
+ const joins = hasRanges(this.version) ? hooks.requested(track).joins() : [];
2762
+ // Lite-07 asks the held fills' groups through the same subscription, each at the fills' own
2763
+ // priority and order; a wire before it carries one policy, the demand's or the more urgent
2764
+ // fills'.
2765
+ const fills = entry.fills?.ask;
2766
+ const fillGroups = fills?.groups ?? [];
2767
+ const demandPolicy = rangesPolicy(current === undefined ? [] : wireHeld(current).ranges);
2768
+ const priority = Math.max(demandPolicy.priority, fills?.priority ?? -128);
2769
+ if (current === undefined ||
2770
+ (refresh === undefined &&
2771
+ priority === sentPriority &&
2772
+ sameList(fillGroups, sentFills, sameRun) &&
2773
+ (fillGroups.length === 0 || fills?.order === sentFillOrder) &&
2774
+ sameList(asks, sentAsks) &&
2775
+ sameList(joins, sentJoins, sameJoin) &&
2776
+ this.#sameSubscription(current, lastSent))) {
2777
+ // Each wake releases the quiet signals too, including when termination wins.
2778
+ const next = await race([
2779
+ Signal.race(hooks.requested(track), asked, edge, entry.fillsChanged),
2780
+ stopped,
2781
+ ]);
820
2782
  if (next === null)
821
2783
  return;
822
2784
  continue;
823
2785
  }
824
2786
  // Demand collapsing to nothing is refused the same way an initial empty
825
2787
  // request is: the error closes the track, so every local subscriber sees it.
826
- const bounds = groupBounds(current.groups);
827
- if (emptyRange({ startGroup: bounds.start, endGroup: bounds.end }))
2788
+ const { ranges, placed } = wireHeld(current);
2789
+ if (ranges.length === 0)
828
2790
  throw new Error(EMPTY_RANGE);
829
- // A lowered floor owes groups nobody asked for until now.
830
- if (current.groups?.start !== undefined) {
831
- const floor = lastSent.groups?.start === undefined ? entry.start : groupBounds(lastSent.groups).start;
832
- entry.tail.demand(bounds.start, floor ?? Number.POSITIVE_INFINITY);
2791
+ // A wire before lite-07 narrows a placed join to a start at its group.
2792
+ const times = placedAsTimes(ranges, placed);
2793
+ const span = wireSpan(times);
2794
+ // Changed ranges owe groups nobody asked for until now: below a lowered floor, or
2795
+ // between ranges a widening joins while keeping the floor. Each gap they reach waits
2796
+ // a fresh grace, which only delays giving up on one still owed.
2797
+ const start = rangesStart(times);
2798
+ const last = wireHeld(lastSent);
2799
+ if (!sameRanges(ranges, last.ranges) || !samePlaced(placed, last.placed))
2800
+ entry.tail.demand(start ?? entry.start ?? 0n, UNBOUNDED);
2801
+ // Lite-07 edits the live ranges: a range already live keeps its Range ID, and where it
2802
+ // started. The retired ones owe nothing more.
2803
+ let edit;
2804
+ if (hasRanges(this.version)) {
2805
+ // The demand's ranges and the fills' groups, widened together until they fit. The fills
2806
+ // keep their exact ask, so what they ask next is compared with that, not the wire.
2807
+ const demanded = toWireRanges(ranges, placed);
2808
+ const fields = await this.#subscribeFields(msg, {
2809
+ priority,
2810
+ order: demandPolicy.order,
2811
+ maxDelay: maxAge(ranges),
2812
+ });
2813
+ if (entry.stream.kind !== "reading")
2814
+ return;
2815
+ const budget = Fit.budget(fields, entry.live.next(), demanded.length + asks.length + joins.length + fillGroups.length);
2816
+ const fitted = Fit.fit(demanded, fillGroups, entry.fills?.avoid() ?? [], budget);
2817
+ // A fill's range starting past its run speaks only while that run is asked whole.
2818
+ entry.fills?.retireSkipped(fitted.fills);
2819
+ // Each fill's range is its own, at the fills' priority and order, so the demand's ranges
2820
+ // keep theirs. Mirrors the Rust `FillAsk::wire`.
2821
+ const fillPolicy = { priority: fills?.priority ?? 0, order: fills?.order ?? "ascending" };
2822
+ const fillRanges = fitted.fills.map((run) => withPolicy({ start: { absolute: run.start }, end: { absolute: run.end } }, fillPolicy));
2823
+ // The probes the readers' asks and joins need, as many as fit beside the rest: those left
2824
+ // out go once an answer lets the readers waiting on others go.
2825
+ const wanted = wantedProbes(entry, asks, joins, fitted.ranges);
2826
+ // A probe asks on behalf of the demand's readers, at what the demand asks as a whole.
2827
+ const asked = wanted.probes.map((probe) => withPolicy(probe, demandPolicy));
2828
+ const probed = Fit.fitAfter(budget, [...fitted.ranges, ...fillRanges], asked);
2829
+ // A live probe asked afresh is retired and added again, which the publisher answers anew.
2830
+ const renew = fittedReasks(wanted.reasked, entry.live, probed);
2831
+ // The demand's ranges, then the probes, then the fills'.
2832
+ const kindOf = (id) => entry.fillIds.has(id) ? "fill" : entry.probeIds.has(id) ? "probe" : "demand";
2833
+ // Before a retune moves it: the publisher may answer under the max asked until then.
2834
+ for (const [id, range] of entry.live.entries()) {
2835
+ const live = range.start?.live;
2836
+ const joined = range.start?.joined;
2837
+ // Every max a placed join was ever asked under, answered or not: a retune keeps its
2838
+ // answer, which proves history only if none was finite.
2839
+ const recorded = live !== undefined ? !entry.joinTicks.has(id) : joined !== undefined;
2840
+ if (!recorded)
2841
+ continue;
2842
+ const max = (live ?? joined)?.max ?? null;
2843
+ entry.joinBudgets.set(id, Math.min(entry.joinBudgets.get(id) ?? NO_MAX_DELAY, wireBudget(max)));
2844
+ }
2845
+ const edited = entry.live.edit([...fitted.ranges, ...probed, ...fillRanges], { probes: probed.length, fills: fillRanges.length, kindOf }, renew);
2846
+ edit = edited;
2847
+ for (const id of entry.starts.keys())
2848
+ if (!entry.live.get(id))
2849
+ entry.starts.delete(id);
2850
+ for (const id of entry.joinTicks.keys())
2851
+ if (!entry.live.get(id))
2852
+ entry.joinTicks.delete(id);
2853
+ for (const id of entry.joinBudgets.keys())
2854
+ if (!entry.live.get(id))
2855
+ entry.joinBudgets.delete(id);
2856
+ // Before the update reaches the wire, as the SUBSCRIBE did.
2857
+ hooks.judgeUnder(entry.track, narrowest(entry.live));
2858
+ if (capOf(entry.live) !== entry.staleCap)
2859
+ entry.staleCap = undefined;
2860
+ for (const id of entry.fillIds)
2861
+ if (!entry.live.get(id))
2862
+ entry.fillIds.delete(id);
2863
+ for (const id of edited.fillIds)
2864
+ entry.fillIds.add(id);
2865
+ for (const id of entry.probeIds)
2866
+ if (!entry.live.get(id))
2867
+ entry.probeIds.delete(id);
2868
+ for (const id of edited.probeIds)
2869
+ entry.probeIds.add(id);
2870
+ // The groups a fill newly asks for wait a fresh grace too.
2871
+ for (const run of fitted.fills)
2872
+ for (const gap of runGaps(entry.fillGroups, run.start, run.end))
2873
+ entry.tail.demand(gap.start, gap.end);
2874
+ entry.fillGroups = fitted.fills;
2875
+ entry.floor = span.start;
2876
+ // Pending while a range the update adds awaits SUBSCRIBE_START, if it may start lower.
2877
+ this.#reportStarts(entry);
2878
+ this.#declareFeed(entry);
2879
+ }
2880
+ else {
2881
+ const before = wireSpan(placedAsTimes(last.ranges, last.placed));
2882
+ // An update gets no fresh SUBSCRIBE_START, so the floor follows the requested start in
2883
+ // both directions: one that moves back keeps the floor asked, not the stale START.
2884
+ if (span.start !== before.start)
2885
+ hooks.startTrack(entry.track, { start: null, requested: span.start });
2886
+ else if (resolvesStart(this.version) &&
2887
+ span.start === undefined &&
2888
+ (span.end !== before.end || maxAge(ranges) !== maxAge(last.ranges))) {
2889
+ // A join with no start is placed afresh within the new max age or end, which may reach
2890
+ // below the START: a reader's join may too, while fills still wait on the re-offer.
2891
+ entry.restated = true;
2892
+ hooks.restateTrack(entry.track);
2893
+ }
833
2894
  }
834
2895
  // Round-trip the other Subscribe parameters so the publisher doesn't
835
- // interpret SUBSCRIBE_UPDATE as a reset of ordered/maxAge/etc.
2896
+ // interpret SUBSCRIBE_UPDATE as a reset of ordered/delay/etc.
836
2897
  const update = new SubscribeUpdate({
837
- priority: current.priority ?? 0,
838
- maxAge: current.maxAge,
839
- startGroup: current.groups?.start === undefined ? undefined : bounds.start,
840
- endGroup: inclusiveGroupEnd(bounds.end),
2898
+ wantedGroup: refresh ?? sentWanted,
2899
+ priority,
2900
+ order: demandPolicy.order,
2901
+ maxDelay: maxAge(ranges),
2902
+ startGroup: span.start,
2903
+ endGroup: inclusiveGroupEnd(span.end),
2904
+ ranges: edit?.add,
2905
+ remove: edit?.remove,
2906
+ retune: edit?.retune,
841
2907
  });
842
- await update.encode(stream.writer, this.version);
2908
+ // Encoded apart from the write, so a bound the wire can't carry still fails the track.
2909
+ const encoded = await Writer.collect(this.version, (w) => update.encode(w, this.version));
2910
+ if (entry.stream.kind !== "reading")
2911
+ return;
2912
+ if (!restates(this.version, update, live)) {
2913
+ // A failed write means the publisher stopped reading, as it does once it finishes the
2914
+ // track. The responses decide how the track ends, cleanly at the FIN or with a reset's error.
2915
+ try {
2916
+ await stream.writer.write(encoded);
2917
+ }
2918
+ catch {
2919
+ return;
2920
+ }
2921
+ entry.sent += 1;
2922
+ // A tail settling past SUBSCRIBE_END re-judges what the update now asks for.
2923
+ entry.tail.touch();
2924
+ console.debug(`subscribe update: id=${id} broadcast=${broadcast} track=${track.name}`);
2925
+ }
2926
+ live = update;
2927
+ if (refresh !== undefined)
2928
+ sentWanted = refresh;
843
2929
  lastSent = { ...current };
844
- console.debug(`subscribe update: id=${id} broadcast=${broadcast} track=${track.name}`);
2930
+ sentFills = fillGroups;
2931
+ sentFillOrder = fills?.order;
2932
+ sentPriority = priority;
2933
+ sentAsks = asks;
2934
+ sentJoins = joins;
2935
+ }
2936
+ }
2937
+ #reportStarts(entry) {
2938
+ // Where the publisher started each live range asked from a group's start, a placed join's
2939
+ // with no max age, or from the oldest group as time 0, which a reader's time start there resolves to when the copy can't place it
2940
+ // among its groups; and one asked as a live join, whose answer alone places that join for the
2941
+ // copy's readers within the max it was asked under. Mirrors the Rust `SubStream::report_starts`.
2942
+ const times = [];
2943
+ for (const id of entry.live.ids()) {
2944
+ const range = entry.live.get(id);
2945
+ if (range === undefined || !entry.starts.has(id))
2946
+ continue;
2947
+ // Undefined for a range with no group to deliver.
2948
+ const at = entry.starts.get(id);
2949
+ if (range.start?.live !== undefined) {
2950
+ // Recorded once, as it arrives: a reader that began waiting since takes only a newer answer.
2951
+ if (!entry.joinTicks.has(id)) {
2952
+ const { min, max } = range.start.live;
2953
+ const budget = Math.min(entry.joinBudgets.get(id) ?? NO_MAX_DELAY, wireBudget(max));
2954
+ // Kept with it, so a retune wider after it lands still finds the answer narrower.
2955
+ entry.joinBudgets.set(id, budget);
2956
+ entry.joinTicks.set(id, hooks.answerJoin(entry.track, min, through(range.end), at, budget));
2957
+ }
2958
+ continue;
2959
+ }
2960
+ // A max age, now or under a retune since, may start a placed join past groups the publisher
2961
+ // still holds, as stale for it alone, so its answer proves nothing of history. Its readers
2962
+ // are placed already.
2963
+ const joined = range.start?.joined;
2964
+ if (joined !== undefined &&
2965
+ Math.min(entry.joinBudgets.get(id) ?? NO_MAX_DELAY, wireBudget(joined.max)) < NO_MAX_DELAY)
2966
+ continue;
2967
+ // An exact-group Position start is not a time-containment query.
2968
+ if (range.start?.absolute !== undefined)
2969
+ continue;
2970
+ const asked = range.start?.time ?? joined?.absolute ?? 0n;
2971
+ // One with no group to deliver says nothing of its time unless it reaches it.
2972
+ if (at !== undefined || reaches(range.end, asked))
2973
+ times.push([asked, at]);
2974
+ }
2975
+ hooks.timeStarts(entry.track, times);
2976
+ const live = new Set(entry.live.ranges().map(wireJoin));
2977
+ hooks.retainJoins(entry.track, (min, end) => live.has(joinKey(min, end)));
2978
+ }
2979
+ // Declare where a lite-07 feed starts: the lowest start the live ranges report, or the
2980
+ // requested floor, pending, while SUBSCRIBE_START or a range's SUBSCRIBE_START has yet to
2981
+ // say where one starts. Mirrors the Rust `SubStream::declare`.
2982
+ #declareFeed(entry, observed) {
2983
+ let start = null;
2984
+ let pending = entry.start === undefined;
2985
+ // Only the demand's ranges say where the live feed starts, not a fill's or a probe.
2986
+ const feeding = [...entry.live.ids()].filter((id) => !entry.fillIds.has(id) && !entry.probeIds.has(id));
2987
+ for (const id of feeding) {
2988
+ if (!entry.starts.has(id))
2989
+ continue;
2990
+ const at = entry.starts.get(id);
2991
+ // A range with no group there serves nothing to start from.
2992
+ if (at !== undefined && (start === null || at < start))
2993
+ start = at;
845
2994
  }
2995
+ // One still unanswered leaves the start standing once the feed started only while it can't
2996
+ // start below it.
2997
+ const lowest = start;
2998
+ const lower = (id) => {
2999
+ const range = entry.live.get(id);
3000
+ return lowest === null || range === undefined || !startsPast(range, lowest);
3001
+ };
3002
+ if (feeding.some((id) => !entry.starts.has(id) && lower(id)))
3003
+ pending = true;
3004
+ const runs = [];
3005
+ const latest = entry.track.largest()?.group;
3006
+ let timeFloors;
3007
+ for (const id of feeding) {
3008
+ const range = entry.live.get(id);
3009
+ if (!range)
3010
+ continue;
3011
+ const at = entry.starts.get(id);
3012
+ if (at === undefined && entry.starts.has(id))
3013
+ continue;
3014
+ const time = range.start?.time;
3015
+ let intervening;
3016
+ if (at === undefined && time !== undefined) {
3017
+ // A known group at or before the anchor excludes earlier groups even after the live edge passes it.
3018
+ intervening = entry.timeFloors?.get(id);
3019
+ const reported = latest !== undefined && latest <= time ? latest : observed?.floor(time);
3020
+ if (reported !== undefined)
3021
+ intervening = max(intervening ?? 0n, reported);
3022
+ if (intervening !== undefined) {
3023
+ timeFloors ??= new Map();
3024
+ timeFloors.set(id, intervening);
3025
+ }
3026
+ }
3027
+ const asked = range.start?.absolute ?? range.start?.joined?.absolute ?? intervening ?? 0n;
3028
+ const from = at ?? asked;
3029
+ const end = range.end === undefined ? UNBOUNDED : (through(range.end) ?? -1n) + 1n;
3030
+ if (from < end)
3031
+ runs.push({ start: from, end });
3032
+ }
3033
+ entry.timeFloors = timeFloors;
3034
+ runs.sort((a, b) => (a.start < b.start ? -1 : a.start > b.start ? 1 : 0));
3035
+ const feed = [];
3036
+ for (const run of runs)
3037
+ insertRun(feed, run.start, run.end);
3038
+ const next = { start: pending ? undefined : start, requested: entry.floor, feed };
3039
+ const last = entry.declared;
3040
+ if (last &&
3041
+ last.start === next.start &&
3042
+ last.requested === next.requested &&
3043
+ sameList(last.feed, feed, sameRun))
3044
+ return;
3045
+ entry.declared = next;
3046
+ hooks.startTrack(entry.track, next);
846
3047
  }
847
3048
  #sameSubscription(a, b) {
848
- const ag = groupBounds(a.groups);
849
- const bg = groupBounds(b.groups);
850
- // `groupBounds` reads an omitted start as 0. A pre-06 wire tells them apart: omitted
851
- // joins at the publisher's start, and 0 is group 0. Lite-06 encodes both as 0.
852
- const sameStart = resolvesStart(this.version) || (a.groups?.start === undefined) === (b.groups?.start === undefined);
853
- return ((a.priority ?? 0) === (b.priority ?? 0) &&
854
- (a.maxAge ?? 0) === (b.maxAge ?? 0) &&
855
- sameStart &&
856
- ag.start === bg.start &&
857
- ag.end === bg.end);
3049
+ const aw = wireHeld(a);
3050
+ const bw = wireHeld(b);
3051
+ const ar = aw.ranges;
3052
+ const br = bw.ranges;
3053
+ let rangesEqual;
3054
+ if (hasRanges(this.version))
3055
+ rangesEqual = sameRanges(ar, br) && samePlaced(aw.placed, bw.placed);
3056
+ else {
3057
+ // A placed join goes out as a start at its group.
3058
+ const as = wireSpan(placedAsTimes(ar, aw.placed));
3059
+ const bs = wireSpan(placedAsTimes(br, bw.placed));
3060
+ // A lite-06 `Group Start` of 0 is no floor, so the two spell the same; a pre-06 wire tells
3061
+ // them apart: omitted joins at the publisher's start, and 0 is group 0.
3062
+ const start = resolvesStart(this.version)
3063
+ ? (span) => span.start ?? 0n
3064
+ : (span) => span.start;
3065
+ rangesEqual = start(as) === start(bs) && as.end === bs.end;
3066
+ }
3067
+ // Lite-07 carries a policy per range, which the ranges compare; before it one for the whole
3068
+ // subscription, and a wire without `Group Order` cannot carry a change to the order.
3069
+ const pa = rangesPolicy(ar);
3070
+ const pb = rangesPolicy(br);
3071
+ const sameOrder = hasRanges(this.version) || !hasOrder(this.version) || pa.order === pb.order;
3072
+ const samePriority = hasRanges(this.version) || pa.priority === pb.priority;
3073
+ // A wire before lite-07 carries one max age for the whole subscription; lite-07 one per live
3074
+ // join, which the ranges compare.
3075
+ const sameMax = hasRanges(this.version) || maxAge(ar) === maxAge(br);
3076
+ return samePriority && sameOrder && sameMax && rangesEqual;
858
3077
  }
859
3078
  /**
860
3079
  * Handles a group message.
@@ -864,55 +3083,183 @@ export class Subscriber {
864
3083
  * @internal
865
3084
  */
866
3085
  async runGroup(group, stream) {
867
- const entry = this.#subscribes.get(group.subscribe);
3086
+ // One that beats its subscription's TRACK_INFO waits for it unread, which flow control
3087
+ // bounds. Waiters resume in the order they arrived.
3088
+ const entry = this.#subscribes.get(group.subscribe) ?? (await this.#pending.get(group.subscribe));
868
3089
  if (!entry) {
869
3090
  if (group.subscribe >= this.#subscribeNext) {
870
3091
  throw new Error(`unknown subscription: id=${group.subscribe}`);
871
3092
  }
872
3093
  return;
873
3094
  }
874
- // This reader cannot preserve a partial group's frame indices, so refuse it before
875
- // publishing anything that would number its first received frame as zero.
876
- if (group.frameStart !== 0) {
877
- throw new ProtocolViolation(`group ${group.sequence} starts at frame ${group.frameStart}`);
3095
+ if (entry.fillGroup) {
3096
+ const target = entry.fillGroup;
3097
+ if (group.key !== target.producer.start || target.taken || target.dropped) {
3098
+ stream.stop(StreamCode.Cancel);
3099
+ return;
3100
+ }
3101
+ target.taken = true;
3102
+ target.arrived();
3103
+ const counted = entry.tail.open(group.key);
3104
+ try {
3105
+ const format = {
3106
+ scale: entry.timescale,
3107
+ compress: entry.compress,
3108
+ lengthFirst: hasLengthFirst(this.version),
3109
+ frameStart: group.frameStart,
3110
+ };
3111
+ const end = await untilAbandoned(target.producer, readFrames(stream, target.producer, format));
3112
+ if (end === undefined)
3113
+ target.producer.finish();
3114
+ else
3115
+ target.producer.finishAt(end);
3116
+ stream.stop(StreamCode.Cancel);
3117
+ }
3118
+ catch (err) {
3119
+ if (err instanceof ProtocolViolation) {
3120
+ hooks.abortGroup(target.producer, err);
3121
+ throw err;
3122
+ }
3123
+ const e = await sessionCause(this.#quic, err);
3124
+ // A failure with no code waits for the subscription's end to say why.
3125
+ if (e instanceof StreamError || e instanceof SessionError)
3126
+ hooks.abortGroup(target.producer, e);
3127
+ else
3128
+ target.lost = e;
3129
+ stream.stop(e);
3130
+ }
3131
+ finally {
3132
+ counted.done();
3133
+ }
3134
+ return;
3135
+ }
3136
+ const { track, timescale, tail, feedEnded } = entry;
3137
+ if (feedEnded?.peek()) {
3138
+ stream.stop(StreamCode.Cancel);
3139
+ return;
878
3140
  }
879
- const { track, timescale, tail } = entry;
880
- const producer = new netGroup.Producer(group.sequence);
881
- const read = tail.open(group.sequence);
3141
+ const feed = feedEnded ? [feedEnded] : [];
3142
+ // Lite-07: a drop that overtook the header, rather than a gap the grace gave up on.
3143
+ const overtaken = hasSkip(this.version) && tail.dropped(group.key);
3144
+ let producer;
3145
+ let arriving;
3146
+ const counted = tail.open(group.key, () => stream.last);
882
3147
  try {
883
3148
  // The publisher contradicted its own end, which no later group can repair. lite-05
884
3149
  // specified an inclusive end, so its last group lands on it: the write below drops
885
3150
  // only that group there.
886
- if (entry.end !== undefined && group.sequence >= entry.end && this.version !== Version.DRAFT_05) {
887
- const violation = new ProtocolViolation(`group ${group.sequence} is at or past the declared end ${entry.end}`);
888
- track.close(violation);
3151
+ if (entry.end !== undefined && group.key >= entry.end && this.version !== Version.DRAFT_05) {
3152
+ const violation = new ProtocolViolation(`group ${group.key} is at or past the declared end ${entry.end}`);
3153
+ hooks.abortTrack(track, violation);
889
3154
  throw violation;
890
3155
  }
891
- track.writeGroup(producer);
892
- // Block until the timescale is known; the group's stream can arrive before
893
- // TRACK_INFO (or implicit defaults) resolves it on the subscribe stream.
894
- let scale = timescale.peek();
895
- while (scale === undefined) {
896
- if (track.closed.peek() !== undefined) {
897
- // Subscription ended before the scale resolved; nothing to decode.
898
- producer.close();
899
- stream.stop(new StreamError(StreamCode.Cancel, { message: "cancel" }));
900
- return;
3156
+ // Registered before any duplicate wait below, so a drop that lands during it finds the read.
3157
+ if (hasSkip(this.version)) {
3158
+ entry.reading ??= new Map();
3159
+ entry.reading.set(counted, group.key);
3160
+ }
3161
+ // A duplicate of a copy still arriving, such as one another subscription sharing the copy
3162
+ // delivers, waits unread, which flow control bounds. Created once that copy ends, it is
3163
+ // refused as a duplicate if the copy finished and takes the group if it failed,
3164
+ // continuing the reads of that copy, which wait while it is held. Its own reset ends the
3165
+ // wait; a clean end leaves it on the copy alone. Parked meanwhile: that copy's stream holds
3166
+ // the end of whatever carries it, so a stall there never holds this subscription's.
3167
+ for (;;) {
3168
+ // Kept held past a failure until this copy takes the group, below.
3169
+ const next = hooks.arrivingGroup(track, group.key);
3170
+ if (next === undefined)
3171
+ break;
3172
+ arriving?.release();
3173
+ arriving = next;
3174
+ counted.park();
3175
+ const settled = arriving.settled;
3176
+ // Only a failure of this stream ends the wait; its clean end, as the cancel after a reset
3177
+ // is, waits on nothing new, so nothing stays on the copy past this race. The reset is
3178
+ // decoded as `stream.closed` decodes it.
3179
+ const failed = stream.closed.then(() => new Promise(() => { }));
3180
+ const end = await raceAborted([settled, failed, ...feed], stream.resetSignal, fromTransport);
3181
+ if (end === "ended")
3182
+ throw new StreamError(StreamCode.Cancel);
3183
+ }
3184
+ counted.resume();
3185
+ // The drop already named this stream's group on the wire, so the stream holds no end, even
3186
+ // once it takes the group from a copy that failed: its reset, which a browser can lose, may
3187
+ // be all that is left of it. It reads on until its own end or the feed closes.
3188
+ if (overtaken)
3189
+ counted.done();
3190
+ producer ??= hooks.receiveGroup(track, {
3191
+ start: group.key,
3192
+ offset: group.frameStart,
3193
+ fill: entry.filling !== undefined,
3194
+ });
3195
+ // Before lite-07 no answer says where the live feed is, so its first group does, once the
3196
+ // copy holds it. Mirrors the Rust `Producer::edge_from_groups`.
3197
+ if (!hasRanges(this.version) && !entry.filling)
3198
+ hooks.answerEdge(track);
3199
+ // Released once this copy took the group, so the failed copy's readers find it.
3200
+ arriving?.release();
3201
+ const format = {
3202
+ scale: timescale,
3203
+ compress: entry.compress,
3204
+ lengthFirst: hasLengthFirst(this.version),
3205
+ frameStart: group.frameStart,
3206
+ };
3207
+ const frames = readFrames(stream, producer, format);
3208
+ // A stream the subscription's end gave up on, as one whose reset the browser lost, fails like
3209
+ // a reset, so the reader may fetch what it still wants.
3210
+ const quiet = counted.stalled.then(() => {
3211
+ console.debug(`group stream stalled: group=${group.key} track=${track.name}`);
3212
+ throw new StreamError(StreamCode.DeliveryTimeout, { message: "stalled" });
3213
+ });
3214
+ const end = await race([
3215
+ entry.filling === "range" ? untilAbandoned(producer, frames) : frames,
3216
+ quiet,
3217
+ ...feed,
3218
+ ]);
3219
+ if (end === "ended")
3220
+ throw new StreamError(StreamCode.Cancel);
3221
+ // Whole at a GROUP_END's end, else without one: every frame sent arrived.
3222
+ if (end === undefined)
3223
+ producer.finish();
3224
+ else {
3225
+ producer.finishAt(end);
3226
+ // No other group starts inside the span, which the tail counts as it counts the
3227
+ // group, and the track records skipped, as its own publisher's append did.
3228
+ if (end > group.key + 1n) {
3229
+ tail.account(group.key + 1n, end);
3230
+ hooks.skipTrackGroups(track, group.key + 1n, end);
901
3231
  }
902
- await Signal.race(timescale, track.closed);
903
- scale = timescale.peek();
904
3232
  }
905
- await readFrames(stream, producer, scale);
906
- producer.close();
907
- stream.stop(new StreamError(StreamCode.Cancel, { message: "cancel" }));
3233
+ stream.stop(StreamCode.Cancel);
908
3234
  }
909
3235
  catch (err) {
3236
+ // A violation ends the session, which the connection does once it escapes; anything
3237
+ // else ends only this group.
3238
+ if (err instanceof ProtocolViolation) {
3239
+ if (producer)
3240
+ hooks.abortGroup(producer, err);
3241
+ throw err;
3242
+ }
910
3243
  const e = await sessionCause(this.#quic, err);
911
- producer.close(e);
3244
+ if (producer)
3245
+ hooks.abortGroup(producer, e);
912
3246
  stream.stop(e);
913
3247
  }
914
3248
  finally {
915
- read();
3249
+ arriving?.release();
3250
+ entry.reading?.delete(counted);
3251
+ counted.done();
3252
+ }
3253
+ }
3254
+ // A SUBSCRIBE_DROP named `[start, end)`: a stream still reading a group it names holds the
3255
+ // subscription's end no longer, since the drop accounts for the group and a browser can lose
3256
+ // that stream's reset. A final drop ends the read through the track, which aborts the group. A
3257
+ // stale one leaves it reading until its own end or this feed closes, which cuts a group still
3258
+ // arriving: lite-07 waits out no timer for a group the publisher already gave up.
3259
+ #dropped(entry, start, end) {
3260
+ for (const [counted, key] of entry.reading ?? []) {
3261
+ if (key >= start && key < end)
3262
+ counted.done();
916
3263
  }
917
3264
  }
918
3265
  /**
@@ -936,6 +3283,12 @@ export class Subscriber {
936
3283
  try {
937
3284
  try {
938
3285
  for (;;) {
3286
+ const yielded = datagramBudget.poll();
3287
+ if (yielded !== undefined) {
3288
+ this.#receiveYield = yielded;
3289
+ await yielded;
3290
+ this.#receiveYield = undefined;
3291
+ }
939
3292
  const { value, done } = await reader.read();
940
3293
  if (done)
941
3294
  break;
@@ -963,22 +3316,96 @@ export class Subscriber {
963
3316
  }
964
3317
  }
965
3318
  }
966
- // Decode one datagram body and hand it to the matching subscription's producer. Drops the
967
- // datagram (best-effort) if the subscription is unknown/closed or its timescale isn't resolved.
3319
+ // Decode one datagram body and hand it to the datagram track it was sent for. A publisher
3320
+ // sends a track's first datagram right behind its answer, which the transport may hand over
3321
+ // first: one for a subscription still awaiting its answer is held a host task, so an answer
3322
+ // already received decodes before it, while other tracks' datagrams go on. One that still
3323
+ // finds no track is dropped and counted.
968
3324
  async #routeDatagram(payload) {
3325
+ if (payload.byteLength > DatagramMessage.MAX_SIZE)
3326
+ return;
3327
+ let unrouted = await this.#deliverDatagram(payload, true);
3328
+ if (unrouted === undefined)
3329
+ return;
3330
+ // Its track may have registered while the decode awaited.
3331
+ if (!this.#isHeld(unrouted) && this.#datagrams.has(unrouted))
3332
+ unrouted = await this.#deliverDatagram(payload, true);
3333
+ if (unrouted === undefined)
3334
+ return;
3335
+ const awaiting = this.#isHeld(unrouted) || this.#unanswered.has(unrouted) || this.#pending.has(unrouted);
3336
+ if (awaiting && this.#held.length < HELD_DATAGRAMS) {
3337
+ this.#held.push({ subscribe: unrouted, payload });
3338
+ this.#heldRouted ??= this.#routeHeld();
3339
+ return;
3340
+ }
3341
+ this.#dropUnrouted(unrouted);
3342
+ }
3343
+ // Wait for the datagrams received for `subscribe` so far to route: a host task, then until the
3344
+ // receive loop reads the transport's queue empty rather than yielding to its budget, and those
3345
+ // held for its answer. A peer keeping the queue full delays the end, holding nothing more.
3346
+ async #datagramsRouted(subscribe) {
3347
+ await yieldNow();
3348
+ for (;;) {
3349
+ const receiveYield = this.#receiveYield;
3350
+ if (receiveYield !== undefined) {
3351
+ await receiveYield;
3352
+ // The loop reads on in microtasks, until the queue empties or its next yield.
3353
+ await yieldNow();
3354
+ }
3355
+ else if (this.#isHeld(subscribe)) {
3356
+ // A held datagram keeps its routing pass running.
3357
+ await this.#heldRouted;
3358
+ }
3359
+ else
3360
+ return;
3361
+ }
3362
+ }
3363
+ // Whether a datagram for `subscribe` is held, which later ones wait behind to keep its order.
3364
+ #isHeld(subscribe) {
3365
+ return this.#held.some((held) => held.subscribe === subscribe);
3366
+ }
3367
+ // A host task later, route the datagrams held until now, then any held meanwhile.
3368
+ async #routeHeld() {
3369
+ await yieldNow();
3370
+ for (let count = this.#held.length; count > 0; count--) {
3371
+ const [{ payload }] = this.#held;
3372
+ try {
3373
+ const unrouted = await this.#deliverDatagram(payload, false);
3374
+ if (unrouted !== undefined)
3375
+ this.#dropUnrouted(unrouted);
3376
+ }
3377
+ catch (err) {
3378
+ console.debug(`dropping datagram: ${reason(err)}`);
3379
+ }
3380
+ this.#held.shift();
3381
+ }
3382
+ this.#heldRouted = this.#held.length > 0 ? this.#routeHeld() : undefined;
3383
+ }
3384
+ #dropUnrouted(subscribe) {
3385
+ this.datagramsUnrouted++;
3386
+ console.debug(`dropping datagram for a subscription with no datagram track: id=${subscribe}`);
3387
+ }
3388
+ // Deliver one datagram body, returning its Subscribe ID if that subscription has no datagram
3389
+ // track, or, `behindHeld`, has a datagram held.
3390
+ async #deliverDatagram(payload, behindHeld) {
969
3391
  const dg = await DatagramMessage.decode(payload, this.version);
970
- const entry = this.#subscribes.get(dg.subscribe);
3392
+ const entry = this.#datagrams.get(dg.subscribe);
971
3393
  if (!entry)
972
- return; // Unknown or already-closed subscription.
973
- // Datagrams are lite-05+, which always negotiates a timescale; if it hasn't resolved
974
- // yet (the datagram raced ahead of TRACK_INFO), drop rather than guess.
975
- const scale = entry.timescale.peek();
976
- if (!scale)
977
- return;
978
- const timestamp = new Time.Timestamp(dg.timestamp, Time.Timescale(scale));
979
- // A datagram's sequence is never owed a stream, so it never holds the tail open.
980
- entry.tail.account(dg.sequence, dg.sequence + 1);
981
- entry.track.insertDatagram(dg.sequence, timestamp, dg.payload);
3394
+ return dg.subscribe;
3395
+ if (behindHeld && this.#isHeld(dg.subscribe))
3396
+ return dg.subscribe;
3397
+ // A scale-less datagram's timestamp is bare, which the track checks is its key.
3398
+ // A lite-05/06 datagram's wire timestamp is dropped, so its sequence stands in as the key.
3399
+ const timestamp = entry.timescale === undefined
3400
+ ? Time.Timestamp.unscaled(dg.sequence ?? dg.timestamp)
3401
+ : new Time.Timestamp(toNumber(dg.timestamp), entry.timescale);
3402
+ const datagram = { timestamp, payload: dg.payload };
3403
+ // Lite-05/06 name a sequence, which a hop to a peer of those versions sends again.
3404
+ if (dg.sequence === undefined)
3405
+ entry.producer.write(datagram);
3406
+ else
3407
+ hooks.writeDatagramWire(entry.producer, datagram, dg.sequence);
3408
+ return undefined;
982
3409
  }
983
3410
  /**
984
3411
  * Opens a PROBE bidi stream to receive bandwidth estimates from the publisher.
@@ -993,80 +3420,165 @@ export class Subscriber {
993
3420
  */
994
3421
  // Await the peer's advertised probe level, blocking until its SETUP arrives. The peer
995
3422
  // MUST send exactly one SETUP, so this resolves once that stream is read.
996
- async #peerProbeLevel(peerSetup) {
3423
+ async #peerProbeLevel(peerSetup, scope) {
997
3424
  let setup = peerSetup.peek();
998
3425
  while (setup === undefined) {
999
- setup = await peerSetup.changed();
3426
+ setup = await scope.race([Signal.race(peerSetup)]);
3427
+ if (setup === undefined)
3428
+ return;
1000
3429
  }
1001
3430
  return setup.probe;
1002
3431
  }
1003
- async runProbe() {
3432
+ async runProbe(signal, target) {
1004
3433
  if (!this.#probe)
1005
3434
  return;
1006
3435
  if (this.version === Version.DRAFT_01 || this.version === Version.DRAFT_02)
1007
3436
  return;
1008
- // Lite-05+ gates the PROBE stream on the peer advertising Probe >= Report in its
1009
- // SETUP. Wait for the SETUP, then bail if the peer can't report bitrate. Older
1010
- // drafts have no SETUP, so they keep probing unconditionally.
1011
- if (this.#peerSetup) {
1012
- const probe = await this.#peerProbeLevel(this.#peerSetup);
1013
- if (probe < ProbeLevel.Report)
1014
- return;
1015
- }
1016
- // Probe is best-effort: any failure (stream reset by peer, missing peer support,
1017
- // transport hiccup) MUST NOT tear down the connection. On error, drop the
1018
- // estimates so consumers know they're stale.
3437
+ const scope = new Effect();
3438
+ const abort = signal ? AbortSignal.any([signal, this.#closed.signal]) : this.#closed.signal;
3439
+ const stop = () => scope.close();
3440
+ abort.addEventListener("abort", stop, { once: true });
3441
+ if (abort.aborted)
3442
+ stop();
3443
+ // Probe is best-effort: transport failures stay per-stream, but malformed control
3444
+ // input ends the session. Drop the estimates so consumers know they're stale.
1019
3445
  try {
1020
- const stream = await Stream.open(this.#quic, { version: this.version });
1021
- await stream.writer.u53(StreamId.Probe);
3446
+ // Lite-05+ gates PROBE on the peer advertising Probe >= Report in its SETUP.
3447
+ // Only a peer that probes up to a target is sent one; a Report-level peer ignores it.
3448
+ let increase = false;
3449
+ if (hasSetupStream(this.version) && this.#peerSetup) {
3450
+ const level = await this.#peerProbeLevel(this.#peerSetup, scope);
3451
+ if (level === undefined || level < ProbeLevel.Report)
3452
+ return;
3453
+ increase = level >= ProbeLevel.Increase;
3454
+ }
3455
+ if (this.#goingAway() || abort.aborted)
3456
+ return;
3457
+ const stream = await Stream.tryOpen(this.#quic, { version: this.version, signal: abort });
3458
+ if (!stream)
3459
+ return;
3460
+ if (abort.aborted) {
3461
+ // Handed a stream as it gave up: give the slot back unused.
3462
+ stream.close();
3463
+ return;
3464
+ }
3465
+ scope.cleanup(() => stream.close());
3466
+ await scope.race([stream.writer.u53(StreamId.Probe)]);
3467
+ if (target && increase)
3468
+ this.#sendTarget(stream, target, scope);
1022
3469
  for (;;) {
1023
- const probe = await Probe.decodeMaybe(stream.reader, this.version);
3470
+ const probe = await scope.race([Probe.decodeMaybe(stream.reader, this.version)]);
1024
3471
  if (!probe)
1025
3472
  break;
1026
- // lite-03 carries no RTT field, so an absent value there means "not
1027
- // carried" and the last reading stands. From lite-04 the field is
1028
- // always present and 0 explicitly means unknown, so undefined is the
1029
- // peer retracting a value we would otherwise hold forever.
3473
+ // Lite-03 carries no RTT; newer drafts retract it with a zero.
1030
3474
  const prev = this.#probe.peek();
1031
- const rtt = probe.rtt !== undefined ? Time.Milli(probe.rtt) : undefined;
3475
+ const rtt = probe.rtt !== undefined ? Duration.millis(probe.rtt) : undefined;
1032
3476
  this.#probe.set({
1033
- // `undefined` is the peer reporting "unknown", not an estimate of
1034
- // zero; letting it through would become a real 0 bps ABR target.
3477
+ // `undefined` is the peer reporting "unknown"; a 0 would become a real ABR target.
1035
3478
  estimatedRecvRate: probe.bitrate,
1036
3479
  rtt: hasProbeRtt(this.version) ? rtt : (rtt ?? prev.rtt),
1037
3480
  });
1038
3481
  }
1039
3482
  }
1040
3483
  catch (err) {
3484
+ closeViolation(this.#quic, err);
1041
3485
  if (!this.#closed.signal.aborted) {
1042
3486
  console.warn("probe stream error", err);
1043
3487
  }
1044
3488
  }
1045
3489
  finally {
3490
+ scope.close();
3491
+ abort.removeEventListener("abort", stop);
1046
3492
  this.#probe.set({});
1047
3493
  }
1048
3494
  }
3495
+ // Send `target` on the PROBE stream whenever it changes, in order, while `scope` lives.
3496
+ // Nothing is sent while it is zero, until it retracts a target already sent. One write is
3497
+ // in flight at a time, and the next sends the latest target, so a peer that stops reading
3498
+ // holds one target however often it changes.
3499
+ #sendTarget(stream, target, scope) {
3500
+ let sent = 0;
3501
+ let writing = false;
3502
+ const write = async () => {
3503
+ writing = true;
3504
+ try {
3505
+ for (;;) {
3506
+ // The wire carries whole bits per second.
3507
+ const next = Math.floor(target.peek());
3508
+ if (next === sent)
3509
+ return;
3510
+ sent = next;
3511
+ // Zero reads as unknown on the wire, which retracts the last target.
3512
+ await new Probe({ bitrate: next > 0 ? next : undefined }).encode(stream.writer, this.version);
3513
+ }
3514
+ }
3515
+ catch {
3516
+ // The writer and reader are independent, so a failed write does not end the
3517
+ // reads: end the probe here, which also closes the stream.
3518
+ scope.close();
3519
+ }
3520
+ finally {
3521
+ writing = false;
3522
+ }
3523
+ };
3524
+ scope.run((effect) => {
3525
+ effect.get(target);
3526
+ if (!writing)
3527
+ void write();
3528
+ });
3529
+ // A close queues behind a write the peer is not reading, which would hold the stream
3530
+ // open past the probe; a reset rejects that write and frees the stream.
3531
+ scope.cleanup(() => {
3532
+ if (writing)
3533
+ stream.abort(new StreamError(StreamCode.Cancel, { message: "probe ended" }));
3534
+ });
3535
+ }
1049
3536
  /**
1050
- * Ends every subscribed track: cleanly for a deliberate close, or with `err` when the
1051
- * session died, since those tracks were cut off rather than ended.
3537
+ * Wait until every subscribe stream's responses are read to its FIN or reset. Bounded only
3538
+ * once the transport is closed, so that its reads end.
3539
+ *
3540
+ * @internal
1052
3541
  */
1053
- close(err) {
1054
- // A fetch or setup exchange cut off by the session is incomplete even on a deliberate
1055
- // close, so it always ends with an error.
1056
- const cut = err ?? new StreamError(StreamCode.SessionClosed, { message: "session closed" });
1057
- this.#closed.abort(cut);
1058
- for (const { track } of this.#subscribes.values()) {
1059
- track.close(err);
3542
+ async drain() {
3543
+ await Promise.all(Array.from(this.#subscribes.values(), (entry) => entry.stream.kind !== "setup" && entry.stream.responses));
3544
+ }
3545
+ /**
3546
+ * Ends every subscribed track, fetch, and setup exchange with `err`, the session's end, which
3547
+ * defaults to a clean close: they were cut off rather than ended. A track whose publisher
3548
+ * already ended it finishes instead, datagram tracks included.
3549
+ */
3550
+ close(err = new SessionError(SessionCode.Cancel)) {
3551
+ this.#closed.abort(err);
3552
+ this.#routed?.close(err);
3553
+ for (const { track, stream, end, datagrams, fillGroup } of this.#subscribes.values()) {
3554
+ if (fillGroup) {
3555
+ hooks.abortGroup(fillGroup.producer, err);
3556
+ continue;
3557
+ }
3558
+ if (stream.kind === "finished")
3559
+ track.finish();
3560
+ hooks.abortTrack(track, err);
3561
+ // Lite-05/06: the stream track's end is its datagrams' end. An abort after the declared
3562
+ // end settled ends it cleanly, even while the FIN that would finalize it is in flight.
3563
+ if (datagrams && end !== undefined && hooks.trackReleased(track).peek() === null)
3564
+ datagrams.ended = true;
1060
3565
  }
1061
3566
  this.#subscribes.clear();
3567
+ for (const { producer, ended } of this.#datagrams.values()) {
3568
+ if (ended)
3569
+ producer.finish();
3570
+ hooks.abortDatagrams(producer, err);
3571
+ }
3572
+ this.#datagrams.clear();
3573
+ this.#legacyDatagrams.clear();
1062
3574
  // This also releases callers still awaiting acceptance.
1063
3575
  for (const { group } of this.#fetches.values()) {
1064
- group.close(cut);
3576
+ hooks.abortGroup(group, err);
1065
3577
  }
1066
3578
  }
1067
3579
  }
1068
3580
  // Settles with `step`, or rejects with the group's error once it closes first. A publisher
1069
- // may never answer a FETCH, so Subscriber.close() closing the group is what releases it.
3581
+ // may never answer a fetch, so Subscriber.close() closing the group is what releases it.
1070
3582
  async function untilClosed(group, step) {
1071
3583
  const value = await race([step, group.closed]);
1072
3584
  const closed = group.closed.peek();
@@ -1074,40 +3586,303 @@ async function untilClosed(group, step) {
1074
3586
  throw closed ?? new Error("fetch closed before it was accepted");
1075
3587
  return value;
1076
3588
  }
3589
+ // Resolve once no reader wants `group`, or it closed.
3590
+ async function groupUnwanted(group) {
3591
+ const demand = group.demand();
3592
+ while (demand.wanted.peek() && demand.closed.peek() === undefined) {
3593
+ await Signal.race(demand.wanted, demand.closed);
3594
+ }
3595
+ }
1077
3596
  // Like untilClosed, but also cancels once every reader has left. Demand is level-triggered, so a
1078
3597
  // caller that coalesces onto the group before the check re-arms it.
1079
3598
  async function untilAbandoned(group, step) {
1080
3599
  const idle = Symbol("idle");
1081
3600
  for (;;) {
1082
- const value = await untilClosed(group, race([step, group.unused().then(() => idle)]));
3601
+ const value = await untilClosed(group, race([step, groupUnwanted(group).then(() => idle)]));
1083
3602
  if (value !== idle)
1084
3603
  return value;
1085
- if (!group.used.peek())
1086
- throw new StreamError(StreamCode.Cancel, { message: "cancel" });
3604
+ if (!group.demand().wanted.peek()) {
3605
+ // Close here rather than where the error lands, so no fetch coalesces onto the group
3606
+ // in between only to fail with it.
3607
+ const err = new StreamError(StreamCode.Cancel, { message: "cancel" });
3608
+ hooks.abortGroup(group, err);
3609
+ throw err;
3610
+ }
1087
3611
  }
1088
3612
  }
1089
3613
  /**
1090
- * A broadcast consumed from a lite session. It resolves `track.Consumer.query()` and
1091
- * `.fetchGroup()` over the wire (lite-05+ TRACK / FETCH streams) by reaching into the
1092
- * {@link Subscriber} it was opened from, the way the Rust `BroadcastConsumer` holds its
1093
- * session. Live subscribes still flow through the inherited requested() queue.
3614
+ * A broadcast consumed from a lite session. It resolves `track.Consumer.info()` from a copy it
3615
+ * holds, else over the wire, and `.fetchGroup()` over the wire (lite-05+), by reaching into the
3616
+ * {@link Subscriber} it was opened from, the way the Rust `BroadcastConsumer` holds its session.
3617
+ * Live subscribes still flow through the inherited requested() queue.
1094
3618
  */
1095
3619
  class ConsumeBroadcast extends broadcast.Consumer {
1096
3620
  #subscriber;
1097
3621
  #path;
1098
- constructor(subscriber, path, state) {
3622
+ #consumed;
3623
+ constructor(subscriber, path, consumed, state) {
1099
3624
  super(state);
3625
+ // A metadata reader gets a copy of its own, filled by a metadata subscription.
3626
+ if (hasMeta(subscriber.version))
3627
+ hooks.serveMeta(this);
3628
+ const baseFetchGroup = wireOf(this).fetchGroup;
1100
3629
  overrideBroadcastWire(this, {
1101
- resolveTrackInfo: (name) => subscriber.resolveTrackInfo(path, name),
1102
- fetchGroup: (name, sequence, options) => subscriber.fetchGroup(path, name, sequence, options),
3630
+ // Only lite-07 keeps a name's stream and datagram tracks apart.
3631
+ distinguishesKinds: hasDatagramTracks(subscriber.version),
3632
+ resolveTrackInfo: async (name, hold) => {
3633
+ hold?.throwIfAborted();
3634
+ // A copy already accepted holds the identity's immutable info, so it answers without
3635
+ // waiting on its upstream, as the Rust broadcast answers from the track it holds. The
3636
+ // lookup holds that copy, and so its upstream subscription, until `hold` aborts.
3637
+ const held = hooks.resolveHeld(this, name, hold);
3638
+ if (held !== undefined)
3639
+ return held;
3640
+ if (!consumed.valid)
3641
+ return subscriber.resolveTrackInfo(path, name, consumed, hold);
3642
+ // Retirement cancels setup, but a one-shot query still releases its TRACK
3643
+ // as soon as it answers instead of holding it for the broadcast's lifetime.
3644
+ const query = new AbortController();
3645
+ const signal = AbortSignal.any([consumed.valid, hold ?? query.signal]);
3646
+ try {
3647
+ return await subscriber.resolveTrackInfo(path, name, consumed, signal);
3648
+ }
3649
+ finally {
3650
+ if (!hold)
3651
+ query.abort();
3652
+ }
3653
+ },
3654
+ // On lite-07, fetchGroup deduplicates onto an active SUBSCRIBE when it covers or caches
3655
+ // `key`, else opens a one-shot bounded SUBSCRIBE + FIN. On lite-05/06 it reads a copy, whose
3656
+ // fill asks a missing group on a SUBSCRIBE of its own. Older drafts have no fill to ask.
3657
+ fetchGroup: hasRanges(subscriber.version)
3658
+ ? (name, key, options) => {
3659
+ if (baseFetchGroup && subscriber.canDeduplicateFetch(path, consumed, name, key)) {
3660
+ return baseFetchGroup(name, key, options);
3661
+ }
3662
+ return subscriber.fetchGroup(path, name, key, options, consumed);
3663
+ }
3664
+ : hasTrackStream(subscriber.version)
3665
+ ? baseFetchGroup
3666
+ : undefined,
1103
3667
  });
1104
3668
  this.#subscriber = subscriber;
1105
3669
  this.#path = path;
3670
+ this.#consumed = consumed;
1106
3671
  }
1107
3672
  // Preserve the subclass (and its wire-backed info/fetchGroup) when the consume cache shares
1108
3673
  // this broadcast across callers.
1109
3674
  clone() {
1110
- return new ConsumeBroadcast(this.#subscriber, this.#path, this.shareState());
3675
+ return new ConsumeBroadcast(this.#subscriber, this.#path, this.#consumed, this.shareState());
3676
+ }
3677
+ }
3678
+ /**
3679
+ * The probes to ask for `asks` and `joins` beside the demand's `ranges` (see `probes` and
3680
+ * `joinProbes`), and the live probes to ask afresh. A time start's and a join's in turn, then
3681
+ * whichever kind is left, so a flood of either leaves the other its share of what fits. Mirrors the
3682
+ * Rust `wanted_probes`.
3683
+ *
3684
+ * @internal
3685
+ */
3686
+ export function wantedProbes(entry, asks, joins, ranges) {
3687
+ const times = probes(asks, ranges);
3688
+ const joined = joinProbes(entry, joins, ranges);
3689
+ const wanted = [];
3690
+ for (let i = 0; i < Math.max(times.length, joined.probes.length); i++) {
3691
+ if (i < times.length)
3692
+ wanted.push(times[i]);
3693
+ if (i < joined.probes.length)
3694
+ wanted.push(joined.probes[i]);
3695
+ }
3696
+ return { probes: wanted, reasked: joined.reasked };
3697
+ }
3698
+ // The probes to ask for `asks`, each a time start the copy's readers wait on, beside the demand's
3699
+ // `ranges`: a demand range from the same time answers it already. Mirrors the Rust `probes`.
3700
+ function probes(asks, ranges) {
3701
+ if (asks.length === 0)
3702
+ return [];
3703
+ const answered = new Set();
3704
+ for (const { start } of ranges) {
3705
+ const time = start?.time;
3706
+ if (time !== undefined)
3707
+ answered.add(time);
3708
+ }
3709
+ return asks.filter((time) => !answered.has(time)).map(probe);
3710
+ }
3711
+ // The probes to ask for `joins`, each a live join the copy's readers wait on, beside the demand's
3712
+ // `ranges`, and the live probes to ask afresh: one answered before a reader began waiting.
3713
+ //
3714
+ // A live range asking the join answers it when it is still unanswered under a max as wide as the
3715
+ // waiting readers', or was answered after every waiting reader began under one. The max asked
3716
+ // may have bounded the answering relay's copy. A demand range added by this edit also qualifies
3717
+ // because its answer comes after the edit. A probe stays until its readers stop waiting, so its
3718
+ // answer outlives their placing, and asks the widest max they wait with, retuned in place as that
3719
+ // moves. Mirrors the Rust `join_probes`.
3720
+ /** @internal */
3721
+ export function joinProbes(entry, joins, ranges) {
3722
+ const out = [];
3723
+ const reasked = [];
3724
+ for (const join of joins) {
3725
+ const key = joinKey(join.min, join.end);
3726
+ const answers = (id) => {
3727
+ const asked = entry.joinBudgets.get(id) ?? NO_MAX_DELAY;
3728
+ const live = entry.live.get(id)?.start?.live;
3729
+ const now = live === undefined ? 0 : wireBudget(live.max);
3730
+ // The publisher may answer under the max asked before a retune since.
3731
+ const wide = Math.min(asked, now) >= join.budget;
3732
+ const tick = entry.joinTicks.get(id);
3733
+ if (tick === undefined)
3734
+ return !entry.starts.has(id) && wide;
3735
+ return tick > join.since && wide;
3736
+ };
3737
+ // Each live range asking the join, with whether it is a probe.
3738
+ const live = [];
3739
+ for (const [id, held] of entry.live.entries())
3740
+ if (!entry.fillIds.has(id) && wireJoin(held) === key)
3741
+ live.push([id, entry.probeIds.has(id)]);
3742
+ // A demand range answers only while this edit keeps it: one the going-out ranges no longer
3743
+ // ask, hidden by a wider range or collapsed into another, is retired with its answer.
3744
+ const kept = ranges.some((held) => wireJoin(held) === key);
3745
+ const demandAnswers = kept && live.some(([id, probe]) => !probe && answers(id));
3746
+ const added = kept && !live.some(([, probe]) => !probe);
3747
+ if (demandAnswers || added)
3748
+ continue;
3749
+ const probing = live.filter(([, probe]) => probe).map(([id]) => id);
3750
+ if (!probing.some(answers))
3751
+ reasked.push(...probing);
3752
+ out.push(joinProbe(join));
3753
+ }
3754
+ return { probes: out, reasked };
3755
+ }
3756
+ // The range a copy asks its upstream to place the live join `join` with: the join itself, under the
3757
+ // widest max its readers wait with, so readers waiting on it share it, as a demand range asking it
3758
+ // goes out (see `toWireRanges`). Mirrors the Rust `join_probe`.
3759
+ function joinProbe(join) {
3760
+ const live = { min: join.min, max: join.budget < NO_MAX_DELAY ? join.budget : null };
3761
+ return join.end === undefined ? { start: { live } } : { start: { live }, end: { time: join.end } };
3762
+ }
3763
+ /**
3764
+ * The live probes in `reasked` whose join a fresh probe among `probes` still asks, so each is
3765
+ * retired and asked afresh; the rest stay, as no probe that fit replaces them. Matched by the join
3766
+ * each asks, not the whole range: the fresh probe asks the max its readers now wait with, which may
3767
+ * differ from the one the live probe was answered under. Mirrors the Rust `fitted_reasks`.
3768
+ *
3769
+ * @internal
3770
+ */
3771
+ export function fittedReasks(reasked, live, probes) {
3772
+ const kept = new Set(probes.map(wireJoin).filter((join) => join !== undefined));
3773
+ const renew = new Set();
3774
+ for (const id of reasked) {
3775
+ const range = live.get(id);
3776
+ const join = range === undefined ? undefined : wireJoin(range);
3777
+ if (join !== undefined && kept.has(join))
3778
+ renew.add(id);
3779
+ }
3780
+ return renew;
3781
+ }
3782
+ // The narrowest max in milliseconds among the live joins of `live`, {@link NO_MAX_DELAY} for none:
3783
+ // the budget an upstream may judge a group too old under, which a stream reset as too old names
3784
+ // nowhere. Mirrors the Rust `narrowest`.
3785
+ function narrowest(live) {
3786
+ let narrowest = NO_MAX_DELAY;
3787
+ for (const range of live.ranges()) {
3788
+ const max = range.start?.live?.max ?? range.start?.joined?.max;
3789
+ if (max !== undefined)
3790
+ narrowest = Math.min(narrowest, wireBudget(max));
1111
3791
  }
3792
+ return narrowest;
3793
+ }
3794
+ // A wire live start's max in milliseconds as a budget: {@link NO_MAX_DELAY} for none.
3795
+ function wireBudget(max) {
3796
+ return max ?? NO_MAX_DELAY;
3797
+ }
3798
+ // The live join `min` milliseconds behind the live edge (null for no lag limit) through the time
3799
+ // `end`, as one key.
3800
+ function joinKey(min, end) {
3801
+ return `${min}:${end ?? ""}`;
3802
+ }
3803
+ // The live join a wire range asks, as its lag and inclusive end (see `through`), undefined for one
3804
+ // that isn't a live join: where it lands doesn't depend on its max. Mirrors the Rust `wire_join`.
3805
+ function wireJoin(range) {
3806
+ const live = range.start?.live;
3807
+ return live === undefined ? undefined : joinKey(live.min, through(range.end));
3808
+ }
3809
+ // The exclusive group end past every range among `live`, undefined when one follows the live edge
3810
+ // or `live` holds none: the cap a stale drop is judged within. Mirrors the Rust `cap_of`.
3811
+ function capOf(live) {
3812
+ let cap;
3813
+ for (const range of live.ranges()) {
3814
+ if (range.end === undefined)
3815
+ return undefined;
3816
+ const last = through(range.end);
3817
+ // A range ending before the first group reaches none.
3818
+ cap = max(cap ?? 0n, last === undefined ? 0n : last + 1n);
3819
+ }
3820
+ return cap;
3821
+ }
3822
+ // The one `Subscriber Max Age` a wire before lite-07 carries for `ranges`, in milliseconds: `null`
3823
+ // (no limit) while a history range is asked for, and otherwise the largest live join's max.
3824
+ // Mirrors the Rust `Subscription::max_age`.
3825
+ function maxAge(ranges) {
3826
+ const budget = widest(ranges);
3827
+ return budget < NO_MAX_DELAY ? budget : null;
3828
+ }
3829
+ // Whether `update` restates `live`, the terms the publisher last heard: the same terms, and on
3830
+ // lite-07 no range edited, or before it the same span. Mirrors the Rust `begin_subscription`.
3831
+ function restates(version, update, live) {
3832
+ const terms = update.wantedGroup === live.wantedGroup &&
3833
+ update.priority === live.priority &&
3834
+ update.order === live.order &&
3835
+ update.maxDelay === live.maxDelay;
3836
+ if (!terms)
3837
+ return false;
3838
+ if (hasRanges(version))
3839
+ return update.ranges?.length === 0 && !update.remove?.length && !update.retune?.length;
3840
+ return (update.startGroup === live.startGroup &&
3841
+ update.endGroup === live.endGroup &&
3842
+ update.startFrame === live.startFrame &&
3843
+ update.endFrame === live.endFrame);
3844
+ }
3845
+ // The range a copy asks its upstream to place time start `time` with: the group containing it
3846
+ // alone, so it delivers nothing another range does not, and readers starting there share it.
3847
+ // Mirrors the Rust `probe`.
3848
+ function probe(time) {
3849
+ return { start: { time }, end: { time } };
3850
+ }
3851
+ // Whether the live range `range`, once answered, starts at or past group `start`, which the live feed
3852
+ // already serves: from a time at or past it, as the group containing that time is, from a join placed
3853
+ // there, or at the latest group, which no group the feed serves is past. Mirrors the Rust `starts_past`.
3854
+ function startsPast(range, start) {
3855
+ const from = range.start;
3856
+ if (from?.time !== undefined)
3857
+ return from.time >= start;
3858
+ if (from?.absolute !== undefined)
3859
+ return from.absolute >= start;
3860
+ if (from?.joined !== undefined)
3861
+ return from.joined.absolute >= start;
3862
+ return from?.live?.min === 0;
3863
+ }
3864
+ // Whether a lite-07 range with no group to deliver says its publisher held none at or before its
3865
+ // reach: only one whose end takes in the group containing its time, which a range that ends before
3866
+ // its time may not, and an open one always does. Mirrors the Rust `SubStream::report_starts`.
3867
+ function reaches(end, asked) {
3868
+ if (end === undefined)
3869
+ return true;
3870
+ if (end.time !== undefined)
3871
+ return end.time >= asked;
3872
+ if (end.absolute !== undefined)
3873
+ return end.absolute > asked;
3874
+ return false;
3875
+ }
3876
+ // The last time a lite-07 range ending at `end` reaches, as its own inclusive time, undefined while
3877
+ // it follows the live edge: an exclusive group end stops at the time before it. Mirrors the Rust
3878
+ // `through`.
3879
+ function through(end) {
3880
+ if (end?.time !== undefined)
3881
+ return end.time;
3882
+ if (end?.absolute === undefined)
3883
+ return undefined;
3884
+ if (end.frame)
3885
+ return end.absolute;
3886
+ return end.absolute > 0n ? end.absolute - 1n : undefined;
1112
3887
  }
1113
3888
  //# sourceMappingURL=subscriber.js.map