@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,45 +1,100 @@
1
- import { race, Signal } from "@moq/signals";
1
+ import { Duration, yieldNow } from "@moq/clock";
2
+ import { 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 { closeError, controlTimeout, error, ProtocolViolation, reason, SessionCode, StreamCode, StreamError, sessionCause, } from "../error.js";
6
- import * as netGroup from "../group.js";
7
- import { Cost, randomHop, routesEqual, stampHops, UNKNOWN_HOP } from "../hop.js";
8
- import { hiddenBelow, hooks, scopeCaptures, scopeHead, scopeOverlaps } from "../internal.js";
6
+ import * as DatagramStream from "../datagram_stream.js";
7
+ import { closeError, closeReason, error, NotFound, ProtocolViolation, reason, SessionCode, StreamCode, Stream as StreamError, sessionCause, TimestampMismatch, unauthorized, } from "../error.js";
8
+ import { fillChanged, wantedRuns } from "../fill.js";
9
+ import { Cost, routesEqual, UNKNOWN_HOP } from "../hop.js";
10
+ import { dropHole, finalKey, hiddenBelow, hooks } from "../internal.js";
11
+ import * as Mint from "../mint.js";
9
12
  import * as Path from "../path.js";
10
- import { UnexpectedEnd } from "../stream.js";
13
+ import { receiveFrame, skipPayload } from "../payload.js";
14
+ import { Reader } from "../stream.js";
11
15
  import { Tail } from "../tail.js";
12
- import { Timestamp } from "../time.js";
13
- import { TimeoutError, withTimeout } from "../util/timeout.js";
14
- import { overrideBroadcastWire, wireOf } from "../wire.js";
16
+ import { untilAborted } from "../util/abort.js";
17
+ import { closeUnwanted } from "../util/announce.js";
18
+ import { Deadline } from "../util/deadline.js";
19
+ import { abandoned as demandAbandoned, isAbandoned, unwanted } from "../util/demand.js";
20
+ import { min } from "../util/key.js";
21
+ import { LIMITS, SlotMap, Slots } from "../util/limits.js";
22
+ import { Budget } from "../util/yield.js";
23
+ import { bounded, latestAt, placedAsTimes, rangesPolicy, wireHeld, wireSpan } from "../window.js";
24
+ import { wireOf } from "../wire.js";
15
25
  import { DuplicateTrackAlias, RetiredTrackAlias, TrackAliases } from "./aliases.js";
16
26
  import * as Cluster from "./cluster.js";
17
- import { requestReason, toRequestCode } from "./error.js";
18
- import { Frame, hasFirstObjectBit } from "./object.js";
19
- import { fromWire, toWire } from "./priority.js";
20
- import { PublishDone, PublishError, publishDoneClean } from "./publish.js";
21
- import { PublishNamespaceDone, PublishNamespaceError, PublishNamespaceOk, PublishNamespaceUpdate, } from "./publish_namespace.js";
27
+ import { ObjectDatagram } from "./datagram.js";
28
+ import { requestReason, SubscribeRefused } from "./error.js";
29
+ import { Fetch, FetchHeader, FetchOk } from "./fetch.js";
30
+ import { isDraft20 } from "./filter.js";
31
+ import { Join } from "./join.js";
32
+ import * as Message from "./message.js";
33
+ import * as Namespace from "./namespace.js";
34
+ import { decodeFetchObject, decodeObjectProperties, EndOfTrackProperties, Frame, ObjectIdGap, objectDeltaBias, objectTime, statusDefined, } from "./object.js";
35
+ import { Parameters } from "./parameters.js";
36
+ import { DEFAULT_WIRE, fromWire, toWire } from "./priority.js";
37
+ import { PublishDone, PublishDoneStatus, publishDoneClean } from "./publish.js";
38
+ import { PublishNamespaceUpdate } from "./publish_namespace.js";
39
+ import { RangeFetch } from "./range.js";
22
40
  import { RequestError, RequestOk } from "./request.js";
23
- import { joinFilter, Subscribe, SubscribeError, SubscribeOk, Unsubscribe } from "./subscribe.js";
24
- import { PublishBlocked, SubscribeNamespace, SubscribeNamespaceEntry, SubscribeNamespaceEntryDone, SubscribeNamespaceLegacy, SubscribeNamespaceOk, UnsubscribeNamespace, } from "./subscribe_namespace.js";
25
- import { Version } from "./version.js";
26
- // Bound on how long stream-open plus SUBSCRIBE_OK may take. Browsers cap
27
- // concurrent QUIC streams (Chrome ~100); past the cap openBi() silently
28
- // blocks. The timeout turns that into a clear error.
29
- const SUBSCRIBE_OK_TIMEOUT_MS = 10_000;
30
- /** Whether a reader with `filter` sees an announcement at `path`. */
41
+ import { malformed, RequestStream, refuseReserved, refuseUpdate } from "./request_stream.js";
42
+ import { joinFilter, Subscribe, SubscribeOk, SubscribeUpdate } from "./subscribe.js";
43
+ import { SubscribeNamespace, SubscribeNamespaceEntry, SubscribeNamespaceEntryDone } from "./subscribe_namespace.js";
44
+ import { MalformedAuthToken } from "./token.js";
45
+ import { TrackStatusOk, TrackStatusRequest } from "./track.js";
46
+ import { isDraft23 } from "./version.js";
47
+ /** A fetch stream the head cannot be stitched from, which costs only that head. */
48
+ class JoinUnsupported extends Error {
49
+ constructor(message) {
50
+ super(message);
51
+ this.name = "JoinUnsupported";
52
+ }
53
+ }
54
+ /** Whether a reader with `filter` sees an announcement at `path`; never one holding a `*`, which no origin accepts. */
31
55
  function sees(filter, path) {
32
- return scopeOverlaps(filter.scope, path) && (filter.hidden || !hiddenBelow(filter.prefix, path));
56
+ return ((Path.hasPrefix(filter.prefix, path) || (filter.covering && Path.hasPrefix(path, filter.prefix))) &&
57
+ !path.includes("*") &&
58
+ (filter.hidden || !hiddenBelow(filter.prefix, path)));
59
+ }
60
+ /**
61
+ * The group a SUBSCRIBE asks from, undefined for a live join. A range from the oldest group is
62
+ * history, so it asks from group 0 and the publisher delivers the backlog it holds: a wire without
63
+ * ranges can't name the oldest any other way. Mirrors the Rust `wire_start`.
64
+ */
65
+ function wireStart(ranges) {
66
+ // Only a time start can be empty, so every range from the oldest group delivers something.
67
+ if (ranges.some((range) => range.start === undefined))
68
+ return 0n;
69
+ return wireSpan(ranges).start;
70
+ }
71
+ /**
72
+ * Skip the `gap` keys just below the group at `key`, as an object's Prior Group ID Gap says
73
+ * none of them will ever exist, through the path a lite SUBSCRIBE_SKIP takes. Best effort: a
74
+ * publisher that sends none leaves those keys to arrive or be given up.
75
+ */
76
+ function skipPrior(track, key, gap) {
77
+ if (gap > key) {
78
+ throw new StreamError(StreamCode.MalformedTrack, {
79
+ message: `Prior Group ID Gap ${gap} reaches below group 0 from group ${key}`,
80
+ });
81
+ }
82
+ // A group that arrived was produced after all: it keeps the group, and the session goes on.
83
+ const [cached] = hooks.skipTrackGroups(track, key - gap, key);
84
+ if (cached) {
85
+ console.warn(`protocol error: a Prior Group ID Gap of ${gap} at group ${key} covers group ${cached.start}, which arrived; keeping it`);
86
+ }
33
87
  }
34
88
  /**
35
89
  * Handles subscribing to broadcasts using moq-transport protocol.
36
- * Uses the stream-per-request pattern (real bidi streams for v17, virtual for v14-v16).
90
+ * Each request rides its own bidi stream.
37
91
  *
38
92
  * @internal
39
93
  */
40
94
  export class Subscriber {
95
+ #streamSources = new WeakMap();
96
+ #datagramRequests = new WeakMap();
41
97
  #session;
42
- #localClose = false;
43
98
  // The transport, so a request cut off by the session's close ends with the session's
44
99
  // error. Optional for tests that drive a bare session.
45
100
  #quic;
@@ -49,45 +104,90 @@ export class Subscriber {
49
104
  #cluster;
50
105
  // Publisher-chosen aliases used by incoming group streams.
51
106
  #aliases = new TrackAliases();
52
- // Units for each track's object Timestamps, from the TIMESCALE Track Property in
53
- // SUBSCRIBE_OK. A track missing from this map declared no timeline, so the publisher
54
- // opted out of timestamps and its frames are stamped on arrival instead.
55
- #timescales = new Map();
107
+ #receiveYield;
108
+ // Each track's ID_TIMESCALE Track Property from SUBSCRIBE_OK, the units of its Group IDs and
109
+ // Object IDs. A track missing from this map declared no timeline.
110
+ #timing = new Map();
111
+ // The requests a fetch stream may answer, mapped to the subscription whose head it brings:
112
+ // a draft-18 joining FETCH's own request ID, or a draft-22 SUBSCRIBE's, whose fill can
113
+ // overtake SUBSCRIBE_OK and so waits on it. A fetch stream needs no track alias.
114
+ #fetches = new Map();
115
+ #ranges = new Map();
116
+ #joins = new WeakMap();
56
117
  // Dedup consumed broadcasts per path: repeat consume() calls share one subscription.
57
118
  #consumes = new BroadcastCache();
58
- // A random Hop ID of this connection's own, written as the first hop of any path that
59
- // names no publisher, so a publisher that reconnects reads as a new one.
60
- #stamp = randomHop();
61
- // Paths with a legacy PUBLISH_NAMESPACE request in flight, reserved synchronously.
62
- // The count below is only taken once the OK is written, and two requests that both
63
- // got past the duplicate check before either attached would both take one.
64
- #legacyRequests = new Set();
65
- // Every announced path, counted by how many live advertisements reference it.
119
+ // Every announced path, with the live advertisements that reference it.
66
120
  //
67
121
  // A peer may advertise one namespace twice on a session: an unsolicited
68
122
  // PUBLISH_NAMESPACE and an inline NAMESPACE answering our own SUBSCRIBE_NAMESPACE are
69
123
  // two messages about one source, which the MoQ Solicit draft requires us to tolerate.
70
- // Counting them is what keeps the second from duplicating the announce and the first
71
- // to end from retracting what the other still holds.
124
+ // Tracking each is what keeps the second from duplicating the announce and the first
125
+ // to end from retracting what the other still holds. A publisher replacing its identity
126
+ // withdraws one advertisement and makes another, on separate streams that
127
+ // can arrive in either order, so the newest stands until it goes and an update to an
128
+ // older one changes nothing. Each live wire advertisement holds an announce slot,
129
+ // even while its route loops back through us and is absent from this derived map.
72
130
  #announced = new Map();
73
- // Any consumers that want each new announcement, keyed by their local filter.
131
+ #announceSlots;
132
+ // Names each advertisement the peer makes, so a later update or withdrawal finds its own.
133
+ #nextAdvert = 0;
134
+ // Any consumers that want each new announcement, keyed by their local filter, until
135
+ // their request is off the wire.
74
136
  #announcedConsumers = new Map();
75
137
  // Whether the peer understands the HIDDEN parameter (MoQ Hidden).
76
138
  #hidden;
77
- /** Marks this subscriber's deliberate local session close. @internal */
78
- close() {
79
- this.#localClose = true;
80
- }
139
+ // Whether a SUBSCRIBE_NAMESPACE's REQUEST_OK counts the NAMESPACEs that follow it (MoQ Active Count).
140
+ #activeCount;
141
+ // Settles when the peer sends GOAWAY, ranking this session's routes last.
142
+ #goaway;
143
+ // Our grant: a subscription it stops covering is cancelled. Undefined until
144
+ // the peer answers, which allows everything.
145
+ #grant;
146
+ #auth;
147
+ // What crossing this link costs and how it ranks, carried by every route through it.
148
+ #link;
81
149
  /**
82
150
  * Creates a new Subscriber instance.
83
151
  *
84
152
  * @internal
85
153
  */
86
- constructor({ session, quic, cluster, hidden = false, }) {
154
+ constructor({ session, quic, cluster, hidden = false, activeCount = false, goaway, grant, auth, limits = LIMITS, link = { cost: Cost.zero, priority: 0 }, }) {
87
155
  this.#session = session;
156
+ this.#link = link;
88
157
  this.#quic = quic;
158
+ this.#announceSlots = new Slots(limits.announces, { quic, reason: "too many announcements" });
89
159
  this.#cluster = cluster;
90
160
  this.#hidden = hidden;
161
+ this.#activeCount = activeCount;
162
+ this.#goaway = goaway;
163
+ this.#grant = grant;
164
+ this.#auth = auth;
165
+ // A draining peer usually stops publishing namespaces, so rank its routes last from the
166
+ // signal itself. Waiting for another message would leave the route primary until close.
167
+ void goaway?.then(() => this.#drainAnnounced());
168
+ }
169
+ // Whether the peer has sent GOAWAY. Requests keep opening here until a replacement
170
+ // session's route outranks this one, deliberately past draft-22 section 9.2's SHOULD
171
+ // NOT: refusing them would fail requests that land before the replacement is up.
172
+ #goingAway() {
173
+ return this.#goaway?.peek() !== undefined;
174
+ }
175
+ // A route ranks below every available one, at its real cost, once the peer has asked us to leave.
176
+ #drained(route) {
177
+ if (!this.#goingAway() || route.draining)
178
+ return route;
179
+ return { ...route, draining: true };
180
+ }
181
+ // Rank every live advertisement last. Idempotent, since the signal stays set.
182
+ #drainAnnounced() {
183
+ for (const [path, info] of this.#announced) {
184
+ this.#settleAnnounce(path, info);
185
+ }
186
+ }
187
+ // Whether our grant no longer lets us subscribe to `broadcast`. No grant yet allows it.
188
+ #denied(broadcast) {
189
+ const grant = this.#grant?.peek();
190
+ return grant !== undefined && !grant.subscribe.matches(broadcast);
91
191
  }
92
192
  /**
93
193
  * Whether an advertisement is ours coming back: its hop path already ran through us, so
@@ -101,220 +201,344 @@ export class Subscriber {
101
201
  return advert !== undefined && this.#cluster !== undefined && Cluster.loops(advert, this.#cluster.self);
102
202
  }
103
203
  /**
104
- * The route an advertisement carries; one without a path is free. A path that names no
105
- * publisher, or none at all, gets this connection's stamp in front of a 0.
204
+ * The route an advertisement carries, before it is minted an identity: its path, or the
205
+ * anonymous mark, at its cost plus this link's, ranked at this link's priority.
106
206
  */
107
- #route(advert) {
108
- if (advert === undefined)
109
- return { hops: [this.#stamp, UNKNOWN_HOP], cost: Cost.zero };
110
- // A full chain, or a stamp colliding with an entry (a 1-in-2^53 draw), keeps the
111
- // path as sent.
112
- const hops = stampHops(advert.hops, this.#stamp) ?? [...advert.hops];
113
- return { hops, cost: { warm: advert.cost, cold: advert.cost } };
207
+ #route({ cluster }) {
208
+ const { hops, cost } = cluster ?? { hops: [UNKNOWN_HOP], cost: Cost.zero };
209
+ return { hops: [...hops], cost: Cost.charged(cost, this.#link.cost), priority: this.#link.priority };
114
210
  }
115
211
  /**
116
- * Gets an announced reader matching `scope`. Paths are relative to the session,
117
- * not the scope.
212
+ * Gets an announced reader for the routes at or beneath `prefix`. Paths are relative to
213
+ * the session, not the prefix.
118
214
  *
119
215
  * The peer is asked with SUBSCRIBE_NAMESPACE regardless of what it declared, and an
120
216
  * unsolicited PUBLISH_NAMESPACE lands here too, so a peer that only tells and one
121
217
  * that only answers are both discovered.
122
218
  *
123
- * Hidden routes (a `.`-prefixed segment below the scope's head) are left out unless
219
+ * Hidden routes (a `.`-prefixed segment below the prefix) are left out unless
124
220
  * `options.hidden` opts in. The opt-in rides the SUBSCRIBE_NAMESPACE when the peer
125
221
  * understands it (MoQ Hidden); the rule is also applied here, since an unsolicited
126
222
  * PUBLISH_NAMESPACE or a peer that never heard of it hides nothing.
223
+ *
224
+ * Only routes at or beneath `prefix` are reported, unless `options.covering` also asks for
225
+ * those above it.
226
+ *
227
+ * The request goes out once every overlapping request already closed here is off the
228
+ * wire, so a peer that refuses overlapping requests never sees this one beside them.
127
229
  */
128
- announced(scope = Path.Pattern.all(), options) {
129
- // The wire speaks announce interest by prefix.
130
- const prefix = scopeHead(scope);
131
- const filter = { scope, prefix, hidden: options?.hidden ?? false };
230
+ routes(prefix = Path.empty(), options) {
231
+ // Refuse a prefix no request can carry before any reader registers for it.
232
+ Path.Prefix.parse(prefix);
233
+ Path.encode(prefix);
234
+ const filter = {
235
+ prefix,
236
+ hidden: options?.hidden ?? false,
237
+ covering: options?.covering ?? false,
238
+ };
239
+ // The overlapping requests on their way out, such as the narrower ones an exclusive
240
+ // discovery just closed for this one. Those still open overlap it only where the
241
+ // caller holds both on purpose. One whose last reader just closed is leaving even
242
+ // before its producer closes.
243
+ const blockers = [];
244
+ for (const [other, { prefix: asked, gone }] of this.#announcedConsumers) {
245
+ if (gone === undefined || (other.wanted.peek() && other.closed.peek() === undefined))
246
+ continue;
247
+ if (Path.hasPrefix(asked, prefix) || Path.hasPrefix(prefix, asked))
248
+ blockers.push(gone);
249
+ }
132
250
  const announced = new announce.Producer();
133
251
  for (const [active, info] of this.#announced) {
134
252
  if (!sees(filter, active))
135
253
  continue;
136
254
  announced.append({
137
255
  prefix: active,
138
- captures: scopeCaptures(scope, active),
139
- kind: "announced",
256
+ kind: "start",
140
257
  route: info.route,
141
258
  });
142
259
  }
143
260
  this.#announcedConsumers.set(announced, filter);
144
- void this.#runAnnounced(announced, prefix, filter.hidden && this.#hidden).finally(() => {
261
+ const consumer = announced.consume();
262
+ // The last reader leaving ends the stream, which cancels the request.
263
+ closeUnwanted(announced);
264
+ filter.gone = this.#runAnnounced(announced, prefix, filter.hidden && this.#hidden, blockers).finally(() => {
145
265
  this.#announcedConsumers.delete(announced);
146
266
  announced.close();
147
267
  });
148
- return announced.consume();
268
+ return consumer;
149
269
  }
150
270
  /**
151
- * Record one more advertisement for a path, telling consumers only when it is the
152
- * first. A second one is the same namespace said twice, not news.
271
+ * Record one more advertisement for a path, returning the id that names it. Consumers
272
+ * hear `start` for the first; a later one stands as the newest (see `#settleAnnounce`).
153
273
  */
154
274
  #attachAnnounce(path, route) {
275
+ const id = this.#nextAdvert++;
155
276
  const existing = this.#announced.get(path);
156
277
  if (existing) {
157
- existing.count += 1;
158
- return;
278
+ existing.adverts.push({ id, route });
279
+ this.#settleAnnounce(path, existing);
280
+ return id;
159
281
  }
160
- this.#announced.set(path, { count: 1, route });
282
+ // moq-transport carries no identity, so each namespace the peer advertises anew is a
283
+ // stream of its own, even one it advertised before on this session.
284
+ route = this.#drained({ ...route, identity: Mint.fresh(), epoch: 0n });
285
+ const entry = { adverts: [{ id, route }], route };
286
+ this.#announced.set(path, entry);
287
+ this.#consumes.announce(path, entry, route);
161
288
  console.debug(`announced: broadcast=${path} active=true`);
162
289
  for (const [consumer, filter] of this.#announcedConsumers) {
163
- if (!sees(filter, path))
290
+ // A consumer that closed stays registered until its request is off the wire.
291
+ if (!sees(filter, path) || consumer.closed.peek() !== undefined)
164
292
  continue;
165
- const scope = filter.scope;
166
- consumer.append({ prefix: path, captures: scopeCaptures(scope, path), kind: "announced", route });
293
+ consumer.append({ prefix: path, kind: "start", route });
167
294
  }
295
+ return id;
296
+ }
297
+ /** Replace the route of advertisement `id`, which moves the path only while it is the newest. */
298
+ #updateAnnounce(path, id, route) {
299
+ const existing = this.#announced.get(path);
300
+ const advert = existing?.adverts.find((advert) => advert.id === id);
301
+ if (existing === undefined || advert === undefined)
302
+ return;
303
+ advert.route = route;
304
+ this.#settleAnnounce(path, existing);
168
305
  }
169
306
  /**
170
- * Replace the stored route for a path that is already announced. A no-op when the
171
- * hops and cost did not change; otherwise consumers hear `updated` so a forwarder
172
- * can reprice without retracting.
173
- *
174
- * A new first hop is a new publisher: holders keep their broadcast to drain, but the
175
- * next consume starts fresh rather than reusing the old publisher's cached track info.
307
+ * Route a path by its newest live advertisement. A no-op when that changed nothing.
308
+ * Otherwise consumers hear `update` for new hops or cost, so a forwarder can reprice
309
+ * without retracting, and the shared consume stays.
176
310
  */
177
- #updateAnnounce(path, route) {
178
- const existing = this.#announced.get(path);
179
- if (existing === undefined || routesEqual(existing.route, route))
311
+ #settleAnnounce(path, existing) {
312
+ const newest = existing.adverts.at(-1);
313
+ if (newest === undefined)
314
+ return;
315
+ // Every advertisement of a path the peer holds is the stream its first one named.
316
+ const { identity, epoch } = existing.route;
317
+ const route = this.#drained({ ...newest.route, identity, epoch });
318
+ if (routesEqual(existing.route, route))
180
319
  return;
181
- if (existing.route.hops[0] !== route.hops[0])
182
- this.#consumes.evict(path);
183
320
  existing.route = route;
321
+ this.#consumes.announce(path, existing, route, false);
184
322
  console.debug(`announced: broadcast=${path} rerouted`);
185
323
  for (const [consumer, filter] of this.#announcedConsumers) {
186
- if (!sees(filter, path))
324
+ // A consumer that closed stays registered until its request is off the wire.
325
+ if (!sees(filter, path) || consumer.closed.peek() !== undefined)
187
326
  continue;
188
- const scope = filter.scope;
189
- consumer.append({ prefix: path, captures: scopeCaptures(scope, path), kind: "updated", route });
327
+ consumer.append({ prefix: path, kind: "update", route });
190
328
  }
191
329
  }
192
330
  /**
193
- * Drop one advertisement for a path, retracting it only once the last one goes.
331
+ * Drop advertisement `id` for a path, retracting it only once the last one goes.
194
332
  */
195
- #detachAnnounce(path) {
333
+ #detachAnnounce(path, id, ended) {
196
334
  const existing = this.#announced.get(path);
197
- if (existing === undefined)
335
+ const index = existing?.adverts.findIndex((advert) => advert.id === id) ?? -1;
336
+ if (existing === undefined || index === -1)
198
337
  return;
199
- if (existing.count > 1) {
200
- existing.count -= 1;
338
+ existing.adverts.splice(index, 1);
339
+ if (existing.adverts.length > 0) {
340
+ // The newest went while an older one stands: that one is what remains.
341
+ this.#settleAnnounce(path, existing);
201
342
  return;
202
343
  }
203
344
  this.#announced.delete(path);
204
345
  // The path is gone, so stop sharing its broadcast: a holder outliving the publisher
205
346
  // would otherwise hand the dead generation to whoever consumes the path next.
206
- this.#consumes.evict(path);
347
+ this.#consumes.withdraw(path, existing);
207
348
  console.debug(`announced: broadcast=${path} active=false`);
208
349
  for (const [consumer, filter] of this.#announcedConsumers) {
209
- if (!sees(filter, path))
350
+ // A consumer that closed stays registered until its request is off the wire.
351
+ if (!sees(filter, path) || consumer.closed.peek() !== undefined)
210
352
  continue;
211
- const scope = filter.scope;
212
- try {
213
- consumer.append({
214
- prefix: path,
215
- captures: scopeCaptures(scope, path),
216
- kind: "retracted",
217
- route: existing.route,
218
- });
219
- }
220
- catch {
221
- // Consumer already closed, will be cleaned up
222
- }
353
+ // Only the peer's withdrawal ends the route; losing its stream or path lets it go.
354
+ consumer.append({
355
+ prefix: path,
356
+ kind: ended ? "end" : "offline",
357
+ route: existing.route,
358
+ });
223
359
  }
224
360
  }
225
- async #runAnnounced(announced, prefix, hidden) {
361
+ // Close with this code before the session's own close, which would send a clean one, as
362
+ // the connection does for its own violations.
363
+ #fail(code, reason) {
364
+ try {
365
+ this.#quic?.close({ closeCode: code, reason: closeReason(reason) });
366
+ }
367
+ catch {
368
+ // Already closed.
369
+ }
370
+ this.#session.close();
371
+ }
372
+ async #runAnnounced(announced, prefix, hidden, blockers) {
226
373
  const version = this.#session.version;
227
- // Suffixes live on this stream, so a repeat is recognized as an update to the
228
- // advertisement rather than a second one, which would leak the count.
229
- const live = new Set();
230
- // Set once the teardown below has given back everything this stream held. The read
231
- // loop is not awaited when the local consumer closes first, and closing the stream
232
- // cancels the transport without discarding what the reader already buffered, so a
233
- // fully buffered entry can still decode afterwards. Attaching one then would take a
234
- // reference nobody is left to release, pinning the path for the session.
374
+ // Suffixes live on this stream, with the advertisement each holds,
375
+ // so a repeat is recognized as an update to it rather than a second one, which would leak.
376
+ // An advertisement stays live on the wire until its NAMESPACE_DONE, even while its
377
+ // route is detached (`id` unset) for looping back through us.
378
+ const live = new SlotMap(this.#announceSlots);
379
+ // Set once `release` has given back everything this stream held. The read loop is not
380
+ // awaited when the local consumer closes first, and the stream keeps delivering what
381
+ // the peer sends until it ends its half, so an entry can still decode afterwards.
382
+ // Attaching one then would take a reference nobody is left to release, pinning the
383
+ // path for the session.
235
384
  let released = false;
236
- // v14/v15: SubscribeNamespace on control stream (via adapter virtual stream)
237
- // v16+: SubscribeNamespace on its own real bidi stream
238
- const requestId = await this.#session.nextRequestId();
385
+ // The stream owns every advertisement it carried, so give them back however it ends:
386
+ // as the request starts leaving, a decode error, or the peer resetting it. Closing the
387
+ // stream withdraws nothing, which NAMESPACE_DONE is for, so they go offline. Without
388
+ // this each namespace keeps its count and the source never detaches, which would pin
389
+ // the path for the session even after the other source withdrew.
390
+ const release = () => {
391
+ released = true;
392
+ for (const [path, held] of live) {
393
+ if (held.id !== undefined)
394
+ this.#detachAnnounce(path, held.id, false);
395
+ }
396
+ live.clear();
397
+ };
398
+ // A peer that refuses overlapping requests would refuse this one while it still holds
399
+ // a request this overlaps, so wait for those to leave the wire. A consumer that leaves
400
+ // meanwhile sends nothing.
401
+ if (blockers.length > 0) {
402
+ await race([Promise.allSettled(blockers), announced.closed]);
403
+ if (announced.closed.peek() !== undefined)
404
+ return;
405
+ }
406
+ // A consumer that leaves while waiting on request-ID credit takes no ID, so a granted one
407
+ // never opens a request nobody wants.
408
+ const left = new AbortController();
409
+ void announced.closed.then(() => left.abort());
410
+ let requestId;
411
+ try {
412
+ requestId = await this.#session.nextRequestId(left.signal);
413
+ }
414
+ catch (err) {
415
+ if (left.signal.aborted)
416
+ return;
417
+ throw err;
418
+ }
239
419
  if (requestId === undefined)
240
420
  return;
241
421
  try {
242
- // v16: use a real bidi stream (not virtual control stream)
243
- const stream = version === Version.DRAFT_16 && this.#session.openNativeBi
244
- ? await this.#session.openNativeBi()
245
- : await this.#session.openBi();
246
- try {
247
- // Draft-18+ uses SUBSCRIBE_NAMESPACE (0x50); earlier drafts use the
248
- // legacy 0x11 message with a Subscribe Options field.
249
- if (version === Version.DRAFT_14 ||
250
- version === Version.DRAFT_15 ||
251
- version === Version.DRAFT_16 ||
252
- version === Version.DRAFT_17) {
253
- await stream.writer.u53(SubscribeNamespaceLegacy.id);
254
- await new SubscribeNamespaceLegacy({ namespace: prefix, requestId, hidden }).encode(stream.writer, version);
255
- }
256
- else {
257
- await stream.writer.u53(SubscribeNamespace.id);
258
- await new SubscribeNamespace({ namespace: prefix, requestId, hidden }).encode(stream.writer, version);
259
- }
422
+ const deadline = new Deadline();
423
+ const request = await deadline.wait(RequestStream.open(this.#session, deadline, { quic: this.#quic }));
424
+ const run = async () => {
425
+ const msg = new SubscribeNamespace({ namespace: prefix, requestId, hidden });
426
+ await Message.write(request.writer, SubscribeNamespace.id, msg, version);
260
427
  console.debug(`subscribe_namespace written: requestId=${requestId}`);
261
- // Read response
262
- const respTypeId = await stream.reader.u53();
263
- if (respTypeId === RequestOk.id) {
264
- await RequestOk.decode(stream.reader, version);
265
- }
266
- else if (respTypeId === SubscribeNamespaceOk.id) {
267
- // v14: SubscribeNamespaceOk
268
- const size = await stream.reader.u16();
269
- await stream.reader.read(size);
270
- }
271
- else {
272
- throw new Error(`SubscribeNamespace rejected: typeId=0x${respTypeId.toString(16)}`);
428
+ // End the request, settling once it is off the wire. `reading` is whatever reads
429
+ // the stream now, which has to finish before anything else may.
430
+ const end = async (reading) => {
431
+ release();
432
+ // A request on another stream can overtake the cancel, so this one is off the
433
+ // wire only once the peer ends its half. What it sends meanwhile is dropped.
434
+ request.cancel();
435
+ await reading.catch(() => undefined);
436
+ try {
437
+ while ((await request.next()) !== undefined) { }
438
+ }
439
+ catch {
440
+ // Reset, or the session ended.
441
+ }
442
+ request.close();
443
+ };
444
+ // Resolves to how many NAMESPACEs make up the initial set (MoQ Active Count).
445
+ const response = (async () => {
446
+ const framed = await request.next();
447
+ if (framed === undefined)
448
+ throw new Error("namespace stream ended before its response");
449
+ if (framed.type === RequestOk.id) {
450
+ const ok = await RequestOk.decode(framed.reader, version);
451
+ // A count the negotiation did not promise, or a missing one it did, is
452
+ // the peer breaking the extension. Without it, the answer is the best
453
+ // boundary there is.
454
+ const count = ok.parameters.activeCount;
455
+ if (this.#activeCount !== (count !== undefined)) {
456
+ throw new ProtocolViolation("ACTIVE_COUNT does not match the negotiation");
457
+ }
458
+ return count ?? 0;
459
+ }
460
+ // A well-formed refusal already ended the request, so end ours cleanly before
461
+ // failing it. Anything else leaves the stream for the reset.
462
+ if (framed.type === RequestError.id) {
463
+ await RequestError.decode(framed.reader, version);
464
+ request.close();
465
+ }
466
+ throw new Error(`SubscribeNamespace rejected: typeId=0x${framed.type.toString(16)}`);
467
+ })();
468
+ // A consumer that leaves before the peer answers ends the request now, not on the answer.
469
+ const answered = await race([response, announced.closed.then(() => undefined)]);
470
+ if (answered === undefined) {
471
+ await end(response);
472
+ return;
273
473
  }
474
+ let initial = answered;
274
475
  // Loop reading Namespace/NamespaceDone entries
275
476
  const readLoop = (async () => {
276
477
  for (;;) {
277
- const done = await stream.reader.done();
278
- if (done)
478
+ if (initial === 0)
479
+ announced.synced();
480
+ const framed = await request.next();
481
+ // Ending: `end` drains the rest.
482
+ if (released)
279
483
  break;
280
- const msgType = await stream.reader.u53();
484
+ if (framed === undefined) {
485
+ if (initial > 0)
486
+ throw new ProtocolViolation("namespace stream ended inside the initial set");
487
+ break;
488
+ }
489
+ const msgType = framed.type;
490
+ // The counted initial set is NAMESPACEs only, so anything else cuts it short.
491
+ if (initial > 0 && msgType !== SubscribeNamespaceEntry.id) {
492
+ throw new ProtocolViolation(`message 0x${msgType.toString(16)} inside the initial set`);
493
+ }
281
494
  if (msgType === SubscribeNamespaceEntry.id) {
282
- const entry = await SubscribeNamespaceEntry.decode(stream.reader, version, Cluster.negotiated(this.#cluster));
495
+ const entry = await SubscribeNamespaceEntry.decode(framed.reader, version, {
496
+ cluster: Cluster.negotiated(this.#cluster),
497
+ });
498
+ // Counted even when discarded below.
499
+ if (initial > 0)
500
+ initial -= 1;
283
501
  if (released)
284
502
  break;
285
- const path = Path.join(prefix, entry.suffix);
503
+ const path = Path.tryJoin(prefix, entry.suffix);
504
+ if (path === undefined)
505
+ throw new ProtocolViolation("announced namespace exceeds the path limits");
506
+ const params = entry.params ?? {};
507
+ const held = live.get(path);
508
+ // The wire still holds a reflected advertisement until DONE, so charge
509
+ // it before deciding whether its route can be used. Repeats keep the slot.
510
+ if (held === undefined)
511
+ live.set(path, {});
286
512
  // A repeat updates the advertisement in place, so one that now
287
513
  // loops back through us has taken a route we can't subscribe
288
514
  // over: the path is gone even though the message says active.
289
- if (this.#reflected(entry.cluster)) {
515
+ if (this.#reflected(params.cluster)) {
290
516
  console.debug(`dropping reflected namespace: broadcast=${path}`);
291
- if (live.delete(path))
292
- this.#detachAnnounce(path);
517
+ if (held?.id !== undefined)
518
+ this.#detachAnnounce(path, held.id, false);
519
+ live.set(path, {});
293
520
  continue;
294
521
  }
295
- // A repeat replaces the advertisement in place: HOP_PATH / ROUTE_COST
296
- // can change without a NAMESPACE_DONE. Only the first is a new path.
297
- const route = this.#route(entry.cluster);
298
- if (live.has(path)) {
299
- this.#updateAnnounce(path, route);
522
+ // A repeat updates HOP_PATH and ROUTE_COST in place. Only the first is a new path.
523
+ const route = this.#route(params);
524
+ if (held?.id !== undefined) {
525
+ this.#updateAnnounce(path, held.id, route);
300
526
  }
301
527
  else {
302
- live.add(path);
303
- this.#attachAnnounce(path, route);
528
+ live.set(path, { id: this.#attachAnnounce(path, route) });
304
529
  }
305
530
  }
306
531
  else if (msgType === SubscribeNamespaceEntryDone.id) {
307
- const entry = await SubscribeNamespaceEntryDone.decode(stream.reader, version);
532
+ const entry = await SubscribeNamespaceEntryDone.decode(framed.reader, version);
308
533
  if (released)
309
534
  break;
310
- const path = Path.join(prefix, entry.suffix);
311
- if (live.delete(path)) {
312
- this.#detachAnnounce(path);
313
- }
314
- }
315
- else if (msgType === PublishBlocked.id && version === Version.DRAFT_17) {
316
- const blocked = await PublishBlocked.decode(stream.reader, version);
317
- console.debug(`publish_blocked: suffix=${blocked.suffix} track=${blocked.trackName}`);
535
+ const path = Path.tryJoin(prefix, entry.suffix);
536
+ if (path === undefined)
537
+ throw new ProtocolViolation("announced namespace exceeds the path limits");
538
+ const held = live.get(path);
539
+ live.delete(path);
540
+ if (held?.id !== undefined)
541
+ this.#detachAnnounce(path, held.id, true);
318
542
  }
319
543
  else {
320
544
  throw new Error(`unexpected message on subscribe_namespace stream: 0x${msgType.toString(16)}`);
@@ -323,42 +547,21 @@ export class Subscriber {
323
547
  })();
324
548
  // The race below can end through the consumer's close while a message that
325
549
  // already arrived is still decoding, which leaves the loop with nothing
326
- // awaiting it: a violation decoded after that would land nowhere, and its
327
- // rejection would go unhandled. Idempotent with the catch below, which is
328
- // what runs when the loop is the one that ends the race.
329
- readLoop.catch((err) => {
330
- if (err instanceof ProtocolViolation)
331
- this.#session.close();
332
- });
550
+ // awaiting it: a violation decoded after that still closes the session.
551
+ // An advertisement is decoded here rather than in the session dispatch, so
552
+ // this is the only place a malformed one surfaces, and the cluster draft
553
+ // requires closing the session over it: the peer would just repeat it on the
554
+ // next SUBSCRIBE_NAMESPACE.
555
+ readLoop.catch((err) => request.abort(err));
333
556
  // Wait for either the read loop or the announced to close
334
557
  await race([readLoop, announced.closed]);
335
- // For v14/v15: send UnsubscribeNamespace before closing
336
- if (version === Version.DRAFT_14 || version === Version.DRAFT_15) {
337
- try {
338
- await stream.writer.u53(UnsubscribeNamespace.id);
339
- const unsub = new UnsubscribeNamespace({ requestId });
340
- await unsub.encode(stream.writer, version);
341
- }
342
- catch {
343
- // Stream might already be closed
344
- }
345
- }
346
- stream.close();
347
- }
348
- catch (err) {
349
- stream.abort(error(err));
350
- throw err;
351
- }
558
+ await end(readLoop);
559
+ };
560
+ await request.serve(run());
352
561
  }
353
562
  catch (err) {
354
563
  const e = error(err);
355
564
  console.warn(`subscribe_namespace error: ${reason(e)}`);
356
- // An advertisement is decoded here rather than in the session dispatch, so this
357
- // is the only place a malformed one surfaces. The cluster draft requires closing
358
- // the session over those, and the stream alone is not enough: the peer would
359
- // just repeat it on the next SUBSCRIBE_NAMESPACE.
360
- if (e instanceof ProtocolViolation)
361
- this.#session.close();
362
565
  // Abort the stream rather than letting the caller's `finally` close it cleanly.
363
566
  // A rejected namespace subscription is a failure, and a consumer that can't tell
364
567
  // it from "nothing is published under this prefix" waits forever on a broadcast
@@ -366,55 +569,113 @@ export class Subscriber {
366
569
  announced.close(e);
367
570
  }
368
571
  finally {
369
- // The stream owns every advertisement it carried, so release them however it
370
- // ends: a clean close, a decode error, or the peer resetting it. Without this
371
- // each namespace keeps its count and the source never detaches, which would
372
- // pin the path for the session even after the other source withdrew.
373
- released = true;
374
- for (const path of live) {
375
- this.#detachAnnounce(path);
376
- }
377
- live.clear();
572
+ release();
378
573
  }
379
574
  }
380
575
  /**
381
576
  * Consumes a broadcast from the connection.
382
577
  *
383
- * Deduplicated per path: repeat calls for the same still-live path share one reference-counted
578
+ * Deduplicated per serving identity: repeat calls for the same path share one reference-counted
384
579
  * broadcast (and one upstream subscription). The shared broadcast closes once every caller has
385
580
  * closed its handle, so callers close normally.
386
581
  */
387
582
  consume(path) {
388
- return this.#consumes.get(path) ?? this.#consumes.insert(path, this.#createConsume(path));
583
+ const identity = this.#consumes.identity(path);
584
+ return this.#consumes.get(path, identity) ?? this.#createConsume(path, identity);
389
585
  }
390
- #createConsume(path) {
391
- // moq-transport has no one-shot group fetch; ConsumeBroadcast rejects it. Track info
392
- // is resolved by the subscribe path (the inherited resolveTrackInfo).
586
+ #createConsume(path, identity) {
393
587
  const consumer = new ConsumeBroadcast();
588
+ // Registered before anyone can list the broadcast, so no reader syncs on an empty answer.
589
+ void this.#refuseListing(wireOf(consumer).lister());
394
590
  void (async () => {
395
591
  for (;;) {
396
592
  const request = await wireOf(consumer).requested();
397
593
  if (!request)
398
594
  break;
399
- void this.#runSubscribe(path, request);
595
+ this.#streamSources.set(request, consumer);
596
+ void this.#runSubscribe(path, request, identity.validity?.signal);
400
597
  }
401
598
  })();
402
- return consumer;
599
+ void (async () => {
600
+ for (;;) {
601
+ const request = await wireOf(consumer).requestedDatagrams();
602
+ if (!request)
603
+ return;
604
+ void this.#runDatagram(consumer, request, identity.validity?.signal);
605
+ }
606
+ })();
607
+ return this.#consumes.insert(path, identity, consumer);
608
+ }
609
+ // moq-transport lists no tracks here: refuse each listing until the broadcast closes, since an
610
+ // empty answer would claim the peer lists nothing.
611
+ async #refuseListing(lister) {
612
+ try {
613
+ for (;;) {
614
+ while (!lister.wanted.peek()) {
615
+ if (lister.closed.peek() !== undefined)
616
+ return;
617
+ await race([Signal.race(lister.wanted, lister.closed)]);
618
+ }
619
+ lister.abort(new Error("track listing requires moq-lite-07 or newer"));
620
+ }
621
+ }
622
+ finally {
623
+ lister.close();
624
+ }
403
625
  }
404
- // The adapter is gone. If the transport has already closed, that close is the
626
+ // The session is gone. If the transport has already closed, that close is the
405
627
  // error. A still-open transport, such as a GOAWAY drain, has no peer code yet,
406
- // so this does not wait for it.
628
+ // so this does not wait for it. Either way the route failed, so a resumed track moves on.
407
629
  async #closedSession() {
630
+ const closed = () => new StreamError(StreamCode.SessionClosed, { message: "session closed" });
408
631
  const quic = this.#quic;
409
632
  if (!quic)
410
- return new Error("session closed");
633
+ return closed();
411
634
  return Promise.race([
412
635
  closeError(quic),
413
- new Promise((resolve) => queueMicrotask(() => resolve(new Error("session closed")))),
636
+ new Promise((resolve) => queueMicrotask(() => resolve(closed()))),
414
637
  ]);
415
638
  }
416
- async #runSubscribe(broadcast, request) {
417
- const requestId = await this.#session.nextRequestId();
639
+ async #runSubscribe(broadcast, request, valid, known) {
640
+ const refused = unauthorized(broadcast);
641
+ try {
642
+ for (;;) {
643
+ const ready = await this.#auth?.ready(broadcast, "subscribe", {
644
+ signal: valid,
645
+ until: () => demandAbandoned(request.demand()),
646
+ });
647
+ if (ready !== false)
648
+ break;
649
+ // Demand returning before we commit is not abandonment, matching the serving loop.
650
+ if (!isAbandoned(request.demand()))
651
+ continue;
652
+ request.reject(new Error("subscribe abandoned before it was authorized"));
653
+ return;
654
+ }
655
+ }
656
+ catch (err) {
657
+ request.reject(error(err));
658
+ return;
659
+ }
660
+ if (this.#denied(broadcast)) {
661
+ request.reject(refused);
662
+ return;
663
+ }
664
+ // An info lookup alone reads no groups, so it asks for the track's status rather than subscribing.
665
+ if (!known && (bounded(request.subscription.ranges ?? [{}]) || !hooks.demandSubscribed(request.demand()))) {
666
+ await this.#runHistory(broadcast, request, valid);
667
+ return;
668
+ }
669
+ let requestId;
670
+ try {
671
+ valid?.throwIfAborted();
672
+ // The allocator cancels its own wait.
673
+ requestId = await this.#session.nextRequestId(valid);
674
+ }
675
+ catch (err) {
676
+ request.reject(error(err));
677
+ return;
678
+ }
418
679
  if (requestId === undefined) {
419
680
  request.reject(await this.#closedSession());
420
681
  return;
@@ -422,100 +683,138 @@ export class Subscriber {
422
683
  console.debug(`subscribe start: id=${requestId} broadcast=${broadcast} track=${request.name}`);
423
684
  // Keep the request pending until SUBSCRIBE_OK supplies immutable track metadata.
424
685
  // Group streams already wait on the alias, so early data stays behind this response.
425
- const producer = hooks.pendingTrackProducer(request);
426
- const subscription = { track: producer, tail: new Tail() };
427
- // Open the stream and wait for SUBSCRIBE_OK under a timeout. State
428
- // flows back via `state` so the timeout path can clean up the stream
429
- // and any registration if setup eventually finishes.
430
- const state = {};
431
- const setup = this.#openSubscribe(state, broadcast, request, subscription, requestId);
686
+ // Wait for SUBSCRIBE_OK while the track is wanted, since the publisher may hold its
687
+ // answer. State lets cancellation clean up streams and registration even if setup
688
+ // finishes later.
689
+ const state = { cancel: new AbortController() };
690
+ const deadline = new Deadline();
691
+ const setup = this.#openSubscribe(state, broadcast, request, requestId, deadline, known?.producer);
432
692
  // The publisher can be serving before it answers, so waiting only on the response
433
693
  // would miss the local side going away and leave it serving a track nobody reads.
434
694
  // Demand returning before we commit is not abandonment, matching the serving loop.
695
+ const demand = request.demand();
435
696
  const waitAbandoned = async () => {
436
- // An info-only lookup attaches no subscriber yet still waits on SUBSCRIBE_OK for
437
- // the track info, so only demand that arrived and then left is abandonment.
438
- while (!producer.used.peek() && producer.closed.peek() === undefined) {
439
- await Signal.race(producer.used, producer.closed);
440
- }
441
- for (;;) {
442
- await producer.unused();
443
- if (producer.closed.peek() !== undefined || !producer.used.peek())
444
- return null;
445
- }
697
+ await demandAbandoned(demand);
698
+ return null;
446
699
  };
447
700
  let stream;
701
+ let subscription;
702
+ let binding;
448
703
  let trackAlias;
704
+ // The SUBSCRIBER_PRIORITY the request went out with.
705
+ let priority;
706
+ const abandoned = new Error("subscribe abandoned before it was accepted");
449
707
  try {
450
- const result = await race([
451
- withTimeout(setup, SUBSCRIBE_OK_TIMEOUT_MS, `subscribe timed out after ${SUBSCRIBE_OK_TIMEOUT_MS}ms waiting for SUBSCRIBE_OK (browser stream limit reached?)`),
452
- waitAbandoned(),
453
- ]);
454
- if (result === null)
455
- throw new Error("subscribe abandoned before it was accepted");
456
- stream = result.stream;
457
- trackAlias = result.alias;
708
+ // Returning demand keeps the same setup.
709
+ const accepted = deadline.wait(setup);
710
+ for (;;) {
711
+ const result = await untilAborted(race([accepted, waitAbandoned()]), valid);
712
+ if (result !== null) {
713
+ stream = result.stream;
714
+ subscription = result.subscription;
715
+ binding = result.binding;
716
+ trackAlias = result.alias;
717
+ priority = result.priority;
718
+ break;
719
+ }
720
+ if (hooks.demandReleased(demand).peek() === undefined && demand.wanted.peek())
721
+ continue;
722
+ throw abandoned;
723
+ }
458
724
  console.debug(`subscribe ok: id=${requestId} broadcast=${broadcast} track=${request.name}`);
459
725
  }
460
726
  catch (err) {
727
+ // A violation on the stream already closed the session through it.
461
728
  // A control request that timed out is not late content, so it carries its own code.
462
- const e = err instanceof TimeoutError ? controlTimeout(err) : await sessionCause(this.#quic, err);
463
- request.reject(e);
729
+ // Local abandonment must commit without yielding after the demand check.
730
+ const e = err === abandoned ? abandoned : await sessionCause(this.#quic, err);
731
+ if (known)
732
+ hooks.refuseLive(known.producer, known.edge, e);
733
+ else
734
+ request.reject(e);
464
735
  console.warn(`subscribe error: id=${requestId} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);
465
736
  // Runs now for whatever is already open, and again if `setup` settles late.
466
737
  // Retirement is repeated because a late SUBSCRIBE_OK can register an alias after
467
- // the first pass; the stream is torn down once.
468
- let torn = false;
469
- const cleanup = async (afterSetup) => {
470
- state.cancelled = true;
471
- if (state.registeredAlias !== undefined && this.#aliases.retire(state.registeredAlias, subscription)) {
472
- this.#timescales.delete(state.registeredAlias);
473
- }
474
- if (!state.stream || torn)
475
- return;
476
- // A SUBSCRIBE still being written must not be torn down from here. Aborting a
477
- // Web Stream waits for the in-flight write, so the request can still reach the
478
- // peer while the abort destroys the stream we would have cancelled on. Setup
479
- // unwinds on the cancelled flag once that write lands, and its pass below has
480
- // the finished picture.
481
- if (!state.sent && !afterSetup)
482
- return;
483
- torn = true;
484
- // Once the SUBSCRIBE is out the publisher may be serving, whether or not it has
485
- // answered yet: data streams are independent of the request stream. Aborting says
486
- // nothing on v14-16, where the request rides a virtual stream whose reset is
487
- // local, so the UNSUBSCRIBE has to go out explicitly.
488
- if (state.sent && !state.rejected)
489
- await this.#cancelSubscribe(state.stream, requestId);
490
- state.stream.abort(e);
738
+ // the first pass. The request ends once, so repeated cleanup does nothing.
739
+ const cleanup = () => {
740
+ state.cancel.abort(e);
741
+ // A fill stream waiting on SUBSCRIBE_OK gets nothing, and a head already started goes.
742
+ state.fill?.(undefined);
743
+ this.#fetches.delete(requestId);
744
+ state.subscription?.join?.cancel(e);
745
+ state.requests?.close();
746
+ if (state.registeredAlias !== undefined &&
747
+ state.binding &&
748
+ this.#aliases.retire(state.registeredAlias, state.binding)) {
749
+ this.#timing.delete(state.registeredAlias);
750
+ }
751
+ // A refusal already ended the request, so end ours cleanly: a reset would tell the
752
+ // publisher we failed.
753
+ if (state.rejected)
754
+ state.stream?.close();
755
+ else
756
+ state.stream?.abort(e);
491
757
  };
492
758
  // Tear down what is already open rather than waiting on `setup`. A peer that
493
759
  // opened the stream and then went quiet never settles it, and deferring would
494
- // leave the request outstanding for the life of the session -- which is the
495
- // timeout case, not a rare one.
496
- void cleanup(false);
497
- setup.then(() => cleanup(true), () => cleanup(true));
760
+ // leave the request outstanding for the life of the session.
761
+ cleanup();
762
+ setup.then(cleanup, cleanup);
498
763
  return;
499
764
  }
765
+ const producer = subscription.track;
766
+ if (state.requests)
767
+ void this.#runFills(broadcast, producer, state.requests, valid);
768
+ let disposeGrant;
769
+ // Ends the joining FETCH with the subscription.
770
+ const joining = new AbortController();
500
771
  try {
501
- // Which terminal fired decides whether we owe the publisher a cancellation, so
502
- // tag them rather than racing bare promises.
772
+ if (subscription.join && !isDraft20(this.#session.version)) {
773
+ void this.#runJoiningFetch(subscription, requestId, priority, joining.signal);
774
+ }
775
+ // Which terminal fired decides how the track closes, so tag them rather than
776
+ // racing bare promises.
503
777
  const publisherEnded = Symbol("publisher");
504
778
  const localEnded = Symbol("local");
779
+ const revokedEnded = Symbol("revoked");
505
780
  const idle = Symbol("idle");
781
+ // History readers may still want the track once its live part is no longer read, so
782
+ // this wake stops serving without the demand re-check `idle` takes.
783
+ const historyEnded = Symbol("history");
784
+ const historical = known
785
+ ? this.#historyOnly(producer, known.edge).then(() => historyEnded)
786
+ : new Promise(() => { });
787
+ // Losing the grant ends the subscription, leaving the session alone.
788
+ let revoke;
789
+ const revoked = new Promise((resolve) => {
790
+ revoke = () => resolve(revokedEnded);
791
+ });
792
+ disposeGrant = this.#grant?.subscribe(() => {
793
+ if (this.#denied(broadcast))
794
+ revoke();
795
+ });
796
+ // The grant may have shrunk during setup, before this watcher existed.
797
+ if (this.#denied(broadcast))
798
+ revoke();
506
799
  // Terminal conditions settle at most once (PublishDone, track close = local
507
- // unsubscribe); race them once so the demand loop doesn't re-subscribe each pass.
800
+ // unsubscribe, a revoked grant); race them once so the demand loop doesn't
801
+ // re-subscribe each pass.
802
+ const unanswered = new Signal(0);
508
803
  const done = race([
509
- this.#runPublishDone(stream, subscription).then(() => publisherEnded),
510
- producer.closed.then(() => localEnded),
804
+ this.#runPublishDone(stream, subscription, broadcast, unanswered).then(() => publisherEnded),
805
+ hooks.trackReleased(producer).then(() => localEnded),
806
+ revoked,
511
807
  ]);
808
+ const stopped = Promise.withResolvers();
809
+ const updates = this.#runUpdates(stream, requestId, producer, priority, unanswered, race([done, stopped.promise]));
512
810
  // Serve until a terminal condition fires or the last local subscriber leaves. The unused
513
811
  // wake is level-triggered: re-check demand so a subscriber that returns before we tear
514
812
  // down resumes on the same stream.
515
813
  let terminal = localEnded;
814
+ const demand = producer.demand();
516
815
  for (;;) {
517
- const reason = await race([done, producer.unused().then(() => idle)]);
518
- if (reason === idle && producer.closed.peek() === undefined && producer.used.peek())
816
+ const reason = await race([done, unwanted(demand).then(() => idle), historical]);
817
+ if (reason === idle && hooks.demandReleased(demand).peek() === undefined && demand.wanted.peek())
519
818
  continue;
520
819
  terminal = reason;
521
820
  break;
@@ -524,25 +823,351 @@ export class Subscriber {
524
823
  // reopens the window the demand re-check above just closed, and a subscriber that
525
824
  // returned during it would be closed by this line. The lite subscriber closes
526
825
  // straight out of its loop for the same reason.
527
- producer.close();
528
- // The publisher already ended the request, so there is nothing to cancel. Sending
529
- // UNSUBSCRIBE here would name a request it has already torn down.
530
- if (terminal !== publisherEnded)
531
- await this.#cancelSubscribe(stream, requestId);
826
+ if (known && terminal === publisherEnded && !hooks.trackFinished(producer)) {
827
+ const largest = producer.largest();
828
+ hooks.endTrack(producer, { group: largest ? largest.group + 1n : 0n, frame: 0 });
829
+ }
830
+ if (terminal === revokedEnded) {
831
+ console.info(`subscription no longer authorized: broadcast=${broadcast} track=${request.name}`);
832
+ hooks.abortTrack(producer, refused);
833
+ }
834
+ else {
835
+ // Only a received end declares one; a copy nobody wants anymore is released, not finished.
836
+ if (!known)
837
+ hooks.releaseTrack(producer);
838
+ }
839
+ // Closing settled `done`, so an update still being written finishes and nothing starts
840
+ // another. Its bytes must not interleave with the close.
841
+ stopped.resolve();
842
+ await updates;
532
843
  stream.close();
533
844
  console.debug(`subscribe close: id=${requestId} broadcast=${broadcast} track=${request.name}`);
534
845
  }
535
846
  catch (err) {
847
+ stream.abort(err);
536
848
  const e = await sessionCause(this.#quic, err);
537
- producer.close(this.#localClose ? undefined : e);
538
- stream.abort(e);
849
+ if (known)
850
+ hooks.refuseLive(producer, known.edge, e);
851
+ else
852
+ hooks.abortTrack(producer, e);
539
853
  console.warn(`subscribe error: id=${requestId} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);
540
854
  }
541
855
  finally {
856
+ joining.abort();
857
+ if (subscription.datagrams) {
858
+ const shared = subscription.datagrams;
859
+ shared.dispose();
860
+ const closed = hooks.trackReleased(producer).peek();
861
+ if (closed instanceof Error)
862
+ hooks.abortDatagrams(shared.producer, closed);
863
+ else if (hooks.trackFinished(producer))
864
+ shared.producer.finish();
865
+ else
866
+ shared.producer.close();
867
+ }
868
+ if (known)
869
+ hooks.cacheTrack(producer);
870
+ // A track end already settled the head; anything else leaves it for a later join.
871
+ subscription.join?.cancel(new Error("subscription ended"));
872
+ for (const id of subscription.fetchIds)
873
+ this.#fetches.delete(id);
874
+ disposeGrant?.();
542
875
  // Only the owner tears down the alias metadata: a later subscription may have
543
876
  // reclaimed the alias and installed its own timescale.
544
- if (this.#aliases.retire(trackAlias, subscription))
545
- this.#timescales.delete(trackAlias);
877
+ if (this.#aliases.retire(trackAlias, binding))
878
+ this.#timing.delete(trackAlias);
879
+ }
880
+ }
881
+ #needsLive(producer, edge) {
882
+ if (hooks.trackFinished(producer) || !hooks.subscribing(producer).peek())
883
+ return false;
884
+ const ranges = hooks.requested(producer).peek()?.ranges ?? [];
885
+ if (!bounded(ranges))
886
+ return true;
887
+ // Every range ends, at a time, so the end is known.
888
+ return (wireSpan(ranges).end ?? 0n) > edge;
889
+ }
890
+ async #historyOnly(producer, edge) {
891
+ while (this.#needsLive(producer, edge) && hooks.trackReleased(producer).peek() === undefined) {
892
+ await Signal.race(hooks.requested(producer), hooks.subscribing(producer), hooks.trackReleased(producer));
893
+ }
894
+ }
895
+ // A bounded read can be entirely below Largest, including on a finished track that refuses
896
+ // SUBSCRIBE. Learn its properties without subscribing, then let its misses ask FETCHes.
897
+ async #runHistory(broadcast, request, valid) {
898
+ const stop = new AbortController();
899
+ const signal = valid ? AbortSignal.any([valid, stop.signal]) : stop.signal;
900
+ const revoked = this.#grant?.subscribe(() => {
901
+ if (this.#denied(broadcast))
902
+ stop.abort(unauthorized(broadcast));
903
+ });
904
+ let stream;
905
+ let producer;
906
+ let fills;
907
+ const deadline = new Deadline();
908
+ try {
909
+ const setup = async () => {
910
+ const id = await this.#session.nextRequestId(signal);
911
+ if (id === undefined)
912
+ throw await this.#closedSession();
913
+ stream = await RequestStream.open(this.#session, deadline, { quic: this.#quic, signal });
914
+ if (signal.aborted) {
915
+ stream.abort(signal.reason);
916
+ signal.throwIfAborted();
917
+ }
918
+ await Message.write(stream.writer, TrackStatusRequest.id, new TrackStatusRequest({
919
+ requestId: id,
920
+ trackNamespace: broadcast,
921
+ trackName: request.name,
922
+ }), this.#session.version);
923
+ const response = await stream.next();
924
+ if (response?.type === RequestError.id) {
925
+ const err = await RequestError.decode(response.reader, this.#session.version);
926
+ throw new Error(requestReason(err.errorCode, err.reasonPhrase, "track_status", this.#session.version));
927
+ }
928
+ if (response?.type !== TrackStatusOk.id)
929
+ throw new ProtocolViolation("expected TRACK_STATUS_OK");
930
+ try {
931
+ return await TrackStatusOk.decode(response.reader, this.#session.version);
932
+ }
933
+ catch (err) {
934
+ throw malformed(err, "TRACK_STATUS_OK");
935
+ }
936
+ };
937
+ const ok = await untilAborted(race([
938
+ deadline.wait(setup()),
939
+ unwanted(request.demand()).then(() => {
940
+ throw new Error("history read abandoned");
941
+ }),
942
+ ]), signal);
943
+ stream?.close();
944
+ if (this.#denied(broadcast))
945
+ throw unauthorized(broadcast);
946
+ const cache = ok.properties.maxCacheDuration;
947
+ if (cache !== undefined && cache > BigInt(Number.MAX_SAFE_INTEGER))
948
+ throw new RangeError("max cache duration exceeds safe milliseconds");
949
+ const staged = hooks.stageRequest(request, {
950
+ timescale: ok.properties.timescale,
951
+ priority: fromWire(ok.properties.priority ?? DEFAULT_WIRE),
952
+ // No MAX_CACHE_DURATION sets no publisher limit, not the authored default.
953
+ maxAge: cache === undefined ? null : Duration.millis(Number(cache)),
954
+ ietf: this.#session.version,
955
+ });
956
+ producer = staged.producer;
957
+ // Only FETCH feeds this copy. Mark it live if a later widening opens SUBSCRIBE.
958
+ if (ok.largest)
959
+ hooks.reportedGroup(producer, ok.largest.groupId);
960
+ const requests = producer.requests();
961
+ fills = this.#runFills(broadcast, producer, requests, signal);
962
+ staged.commit();
963
+ const subscribing = hooks.subscribing(producer);
964
+ for (;;) {
965
+ if (hooks.trackReleased(producer).peek() !== undefined)
966
+ return;
967
+ const subscription = hooks.requested(producer).peek();
968
+ if (!subscription) {
969
+ hooks.releaseTrack(producer);
970
+ return;
971
+ }
972
+ const edge = (producer.largest()?.group ?? ok.largest?.groupId ?? -1n) + 1n;
973
+ if (this.#needsLive(producer, edge)) {
974
+ await this.#runSubscribe(broadcast, request, signal, { producer, edge });
975
+ continue;
976
+ }
977
+ await untilAborted(Promise.resolve(Signal.race(hooks.requested(producer), subscribing, hooks.trackReleased(producer))), signal);
978
+ }
979
+ }
980
+ catch (cause) {
981
+ const err = await sessionCause(this.#quic, cause);
982
+ stream?.abort(err);
983
+ request.reject(err);
984
+ }
985
+ finally {
986
+ stop.abort();
987
+ revoked?.();
988
+ if (producer)
989
+ hooks.releaseTrack(producer);
990
+ await fills;
991
+ }
992
+ }
993
+ // One handler per received track. Each fill owns its network request, and cancellation of
994
+ // the track stops and joins every job before releasing the handler.
995
+ async #runFills(broadcast, producer, requests, valid) {
996
+ const stop = new AbortController();
997
+ const signal = valid ? AbortSignal.any([valid, stop.signal]) : stop.signal;
998
+ const released = hooks
999
+ .trackReleased(producer)
1000
+ .subscribe(() => stop.abort(hooks.trackReleased(producer).peek()));
1001
+ const jobs = new Set();
1002
+ try {
1003
+ for (;;) {
1004
+ const fill = await untilAborted(requests.requestedFill(), signal);
1005
+ if (!fill)
1006
+ break;
1007
+ const run = async () => {
1008
+ try {
1009
+ // The join may already bring a miss in this run. Let it answer first instead
1010
+ // of fetching the same head twice.
1011
+ const join = this.#joins.get(producer);
1012
+ if (join && fill.start <= join.key && fill.end > join.key) {
1013
+ await untilAborted(join.settled, signal);
1014
+ // A failed join costs that head. Retrying it as standalone would hide a publisher bug.
1015
+ if (fill.isWanted(join.key))
1016
+ fill.refuseGroups(join.key, join.key + 1n, new NotFound("joining FETCH did not provide the head"));
1017
+ }
1018
+ for (let run = wantedRuns(fill)[0]; run; run = wantedRuns(fill)[0]) {
1019
+ await this.#runRangeFetch(broadcast, producer, { fill, ...run, signal });
1020
+ }
1021
+ }
1022
+ catch (cause) {
1023
+ fill.refuseGroups(fill.start, fill.end, error(cause));
1024
+ }
1025
+ finally {
1026
+ fill.close();
1027
+ }
1028
+ };
1029
+ const job = run();
1030
+ jobs.add(job);
1031
+ void job.then(() => jobs.delete(job));
1032
+ }
1033
+ }
1034
+ catch (cause) {
1035
+ if (!signal.aborted)
1036
+ hooks.abortTrack(producer, error(cause));
1037
+ }
1038
+ finally {
1039
+ stop.abort();
1040
+ released();
1041
+ requests.close();
1042
+ await Promise.all(jobs);
1043
+ }
1044
+ }
1045
+ async #runRangeFetch(broadcast, producer, options) {
1046
+ const { fill, start, end: until, signal } = options;
1047
+ const version = this.#session.version;
1048
+ let stream;
1049
+ let id;
1050
+ let receiving;
1051
+ const accepted = Promise.withResolvers();
1052
+ const stop = new AbortController();
1053
+ const active = AbortSignal.any([signal, stop.signal]);
1054
+ const abandoned = async () => {
1055
+ while (!receiving) {
1056
+ if (!wantedRuns(fill).some((run) => run.start < until && run.end > start))
1057
+ throw new StreamError(StreamCode.Cancel);
1058
+ await untilAborted(Promise.resolve(fillChanged(fill)), active);
1059
+ }
1060
+ await untilAborted(receiving.unwanted(), active);
1061
+ throw new StreamError(StreamCode.Cancel);
1062
+ };
1063
+ const run = async () => {
1064
+ id = await this.#session.nextRequestId(active);
1065
+ active.throwIfAborted();
1066
+ if (id === undefined)
1067
+ throw await this.#closedSession();
1068
+ this.#ranges.set(id, accepted.promise);
1069
+ stream = new RequestStream(await this.#session.openBi({ signal: active }), this.#session, this.#quic);
1070
+ if (active.aborted) {
1071
+ stream.abort(active.reason);
1072
+ active.throwIfAborted();
1073
+ }
1074
+ const last = until - 1n;
1075
+ const namespace = { trackNamespace: broadcast, trackName: producer.name };
1076
+ await Message.write(stream.writer, Fetch.id, new Fetch({
1077
+ requestId: id,
1078
+ subscriberPriority: toWire(fill.priority),
1079
+ groupOrder: "ascending",
1080
+ type: isDraft20(version)
1081
+ ? {
1082
+ kind: "filtered",
1083
+ ...namespace,
1084
+ filter: { kind: "absolute", startGroup: start, startObject: 0n, endGroup: last },
1085
+ }
1086
+ : {
1087
+ kind: "standalone",
1088
+ ...namespace,
1089
+ start: { group: start, object: 0n },
1090
+ end: { group: last, object: 0n },
1091
+ },
1092
+ }), version);
1093
+ const response = await stream.next();
1094
+ if (response?.type === RequestError.id) {
1095
+ const err = await RequestError.decode(response.reader, version);
1096
+ throw new Error(requestReason(err.errorCode, err.reasonPhrase, "fetch", version));
1097
+ }
1098
+ // FETCH_OK through draft-22, REQUEST_OK from draft-23 on; each refuses the other's.
1099
+ if (response?.type !== FetchOk.idFor(version))
1100
+ throw new ProtocolViolation("expected FETCH_OK");
1101
+ let ok;
1102
+ try {
1103
+ ok = await FetchOk.decode(response.reader, version);
1104
+ }
1105
+ catch (err) {
1106
+ throw new ProtocolViolation(`malformed FETCH_OK: ${reason(error(err))}`);
1107
+ }
1108
+ active.throwIfAborted();
1109
+ const end = ok.endLocation;
1110
+ // Draft-23 has no End Location: the answer ends at its LARGEST_OBJECT, inclusive like
1111
+ // draft-22's End Location, or without one at the end this FETCH asked for (section 3.2).
1112
+ const requested = isDraft23(version) && ok.largest === undefined;
1113
+ const whole = requested || (!isDraft20(version) && end.group === last && end.object === 0n);
1114
+ if (isDraft20(version) && !requested && (end.group < start || end.group > last))
1115
+ throw new ProtocolViolation("FETCH_OK's End Location is outside the requested range");
1116
+ if (!whole && (end.group < start || (end.group === start && end.object === 0n && !isDraft20(version))))
1117
+ throw new NotFound("empty FETCH");
1118
+ const covered = whole
1119
+ ? last
1120
+ : end.object === 0n && !isDraft20(version)
1121
+ ? min(end.group - 1n, last)
1122
+ : min(end.group, last);
1123
+ const bound = whole || end.group > last || (end.object === 0n && !isDraft20(version))
1124
+ ? undefined
1125
+ : end.object + (isDraft20(version) ? 1n : 0n);
1126
+ if (bound !== undefined && bound > BigInt(Number.MAX_SAFE_INTEGER))
1127
+ throw new ProtocolViolation("FETCH_OK Object ID exceeds the model's safe range");
1128
+ if (ok.endOfTrack)
1129
+ hooks.endTrack(producer, {
1130
+ group: end.group + (whole || isDraft20(version) || end.object > 0n ? 1n : 0n),
1131
+ frame: 0,
1132
+ });
1133
+ if (covered < last)
1134
+ fill.refuseGroups(covered + 1n, until, new NotFound("FETCH ended before the requested range"));
1135
+ const info = await producer.info();
1136
+ active.throwIfAborted();
1137
+ receiving = new RangeFetch({
1138
+ fill,
1139
+ first: start,
1140
+ track: producer,
1141
+ timescale: ok.properties.timescale ?? info.timescale ?? undefined,
1142
+ last: covered,
1143
+ bound: bound === undefined ? undefined : Number(bound),
1144
+ version,
1145
+ });
1146
+ accepted.resolve(receiving);
1147
+ const ended = stream.next().then((message) => {
1148
+ if (message !== undefined)
1149
+ throw new ProtocolViolation("unexpected message after FETCH_OK");
1150
+ return receiving?.done;
1151
+ });
1152
+ await race([receiving.done, ended]);
1153
+ stream.close();
1154
+ };
1155
+ try {
1156
+ await untilAborted(race([run(), abandoned()]), signal);
1157
+ }
1158
+ catch (cause) {
1159
+ const err = await sessionCause(this.#quic, cause);
1160
+ receiving?.cancel(err);
1161
+ fill.refuseGroups(start, until, err);
1162
+ stream?.abort(err);
1163
+ if (err instanceof ProtocolViolation)
1164
+ this.#fail(err.code, err.message);
1165
+ }
1166
+ finally {
1167
+ stop.abort();
1168
+ accepted.resolve(undefined);
1169
+ if (id !== undefined)
1170
+ this.#ranges.delete(id);
546
1171
  }
547
1172
  }
548
1173
  /**
@@ -554,124 +1179,384 @@ export class Subscriber {
554
1179
  * is only a hint: a peer may send 0 regardless, so 0 waits out the grace. A request
555
1180
  * stream that FINs without PUBLISH_DONE is a protocol violation.
556
1181
  */
557
- async #runPublishDone(stream, subscription) {
1182
+ async #runPublishDone(stream, subscription, broadcast, unanswered) {
558
1183
  const version = this.#session.version;
559
- if (await stream.reader.done())
560
- throw new ProtocolViolation("subscribe stream ended without PUBLISH_DONE");
561
- const typeId = await stream.reader.u53();
562
- if (typeId !== PublishDone.id) {
563
- throw new ProtocolViolation(`unexpected message on a subscription: 0x${typeId.toString(16)}`);
1184
+ // A refused update is followed by PUBLISH_DONE, which ends the subscription, so no
1185
+ // further answer is owed.
1186
+ let refused = false;
1187
+ let framed;
1188
+ for (;;) {
1189
+ framed = await stream.next();
1190
+ if (framed === undefined)
1191
+ throw new ProtocolViolation("subscribe stream ended without PUBLISH_DONE");
1192
+ const { type } = framed;
1193
+ if (type === PublishDone.id)
1194
+ break;
1195
+ const answer = (type === RequestOk.id || type === RequestError.id) && !refused && unanswered.peek() > 0;
1196
+ if (!answer)
1197
+ throw new ProtocolViolation(`unexpected message on a subscription: 0x${type.toString(16)}`);
1198
+ if (type === RequestOk.id) {
1199
+ await RequestOk.decode(framed.reader, version);
1200
+ unanswered.update((count) => count - 1);
1201
+ }
1202
+ else {
1203
+ const err = await RequestError.decode(framed.reader, version);
1204
+ console.debug(`subscription update refused: ${err.reasonPhrase}`);
1205
+ refused = true;
1206
+ }
1207
+ }
1208
+ const done = await PublishDone.decode(framed.reader, version);
1209
+ // A revocation reads the same as one from a moq-lite peer.
1210
+ // Draft-23's EXPIRED_AUTH_TOKEN reads as the UNAUTHORIZED an earlier publisher sends for
1211
+ // the same end. Before draft-23 the value is unassigned and stays the peer's code.
1212
+ if (done.statusCode === PublishDoneStatus.UNAUTHORIZED ||
1213
+ (done.statusCode === PublishDoneStatus.EXPIRED_AUTH_TOKEN && isDraft23(version)))
1214
+ throw unauthorized(broadcast);
1215
+ // The peer's code, as a moq-lite MALFORMED_TRACK reset reads, so a consumer can tell a
1216
+ // malformed upstream apart from a relay bug.
1217
+ if (done.statusCode === PublishDoneStatus.MALFORMED_TRACK) {
1218
+ throw new StreamError(StreamCode.MalformedTrack, {
1219
+ message: `publish done: malformed track reason=${done.reasonPhrase}`,
1220
+ });
564
1221
  }
565
- const done = await PublishDone.decode(stream.reader, version);
566
1222
  if (!publishDoneClean(done.statusCode, version)) {
567
1223
  throw new Error(`publish done: status=0x${done.statusCode.toString(16)} reason=${done.reasonPhrase}`);
568
1224
  }
569
1225
  const count = done.streamCount;
570
- const { tail, track } = subscription;
1226
+ const { tail, track, join } = subscription;
571
1227
  const complete = () => count > 0n && BigInt(tail.streams) >= count;
572
- await tail.settle(complete, track.closed);
1228
+ await tail.settle(complete, hooks.trackReleased(track));
1229
+ // SUBSCRIPTION_ENDED ends just this subscription, so the copy fails rather than declare an
1230
+ // end the track may run past: a later reader subscribes afresh, and its groups continue.
1231
+ // A head nothing claimed may be run past the same way, so it is cancelled, not finished.
1232
+ if (done.statusCode !== PublishDoneStatus.TRACK_ENDED) {
1233
+ throw new Error(`publish done: subscription ended reason=${done.reasonPhrase}`);
1234
+ }
1235
+ if (subscription.datagrams) {
1236
+ await this.#datagramsRouted();
1237
+ subscription.datagrams.producer.finish();
1238
+ }
1239
+ // The track ended and every stream is accounted for, so no tail is coming: a head nothing
1240
+ // claimed is its whole group. A draft-18 joining FETCH is not in the Stream Count; its
1241
+ // head held the settle.
1242
+ if (hooks.trackReleased(track).peek() === undefined)
1243
+ join?.end();
573
1244
  }
574
1245
  /**
575
- * Tell the publisher to stop serving a subscription we are walking away from.
576
- *
577
- * v14-16 cancel with UNSUBSCRIBE (draft-16 section 9.12), which is what lets the
578
- * publisher destroy the subscription (section 5.1.1); v17+ removed the message and
579
- * rely on the stream reset instead. Every path that abandons an Established
580
- * subscription goes through here, because those versions carry the request over a
581
- * virtual stream whose reset never reaches the peer.
1246
+ * Follow the aggregate subscriber priority upstream until `done` settles with REQUEST_UPDATE,
1247
+ * each under a Request ID of its own. The answer comes back on this stream, so one update is
1248
+ * in flight at a time and changes meanwhile coalesce. No draft lets an update change the
1249
+ * group order, so it stays as asked.
582
1250
  */
583
- async #cancelSubscribe(stream, requestId) {
1251
+ async #runUpdates(stream, requestId, producer, sent, unanswered, done) {
584
1252
  const version = this.#session.version;
585
- if (version !== Version.DRAFT_14 && version !== Version.DRAFT_15 && version !== Version.DRAFT_16)
1253
+ const stopped = done.then(() => null, () => null);
1254
+ const stop = new AbortController();
1255
+ void stopped.then(() => stop.abort());
1256
+ for (;;) {
1257
+ // With no subscriber left there is nothing to follow: the subscription is ending, or
1258
+ // keeps what it last asked for until one returns, as on lite and in Rust.
1259
+ const subscription = hooks.requested(producer).peek();
1260
+ const wanted = toWire(rangesPolicy(subscription?.ranges ?? []).priority);
1261
+ if (!subscription || wanted === sent || unanswered.peek() > 0) {
1262
+ const disposes = [];
1263
+ const wake = new Promise((resolve) => {
1264
+ disposes.push(hooks.requested(producer).changed(() => resolve()), unanswered.changed(() => resolve()));
1265
+ });
1266
+ await race([wake, stopped]);
1267
+ for (const dispose of disposes)
1268
+ dispose();
1269
+ if (stop.signal.aborted)
1270
+ return;
1271
+ continue;
1272
+ }
1273
+ let own;
1274
+ try {
1275
+ own = await this.#session.nextRequestId(stop.signal);
1276
+ }
1277
+ catch {
1278
+ return;
1279
+ }
1280
+ if (own === undefined)
1281
+ return;
1282
+ const parameters = new Parameters();
1283
+ parameters.subscriberPriority = wanted;
1284
+ const update = new SubscribeUpdate({ requestId: own, parameters });
1285
+ let message;
1286
+ try {
1287
+ message = await Message.frame(stream.writer.version, SubscribeUpdate.id, update, version);
1288
+ }
1289
+ catch (err) {
1290
+ // Nothing reached the wire, but the track can no longer follow its subscribers.
1291
+ console.warn(`subscribe update failed: id=${requestId} error=${reason(error(err))}`);
1292
+ hooks.abortTrack(producer, error(err));
1293
+ return;
1294
+ }
1295
+ // Counted before writing: the answer can be read before the write's promise resolves.
1296
+ unanswered.update((count) => count + 1);
1297
+ try {
1298
+ await stream.writer.write(message);
1299
+ }
1300
+ catch {
1301
+ // The publisher stopped reading; its responses decide how the track ends.
1302
+ return;
1303
+ }
1304
+ sent = wanted;
1305
+ console.debug(`subscribe update: id=${requestId} priority=${wanted}`);
1306
+ }
1307
+ }
1308
+ /**
1309
+ * Fetch the head of a draft-18 join's group, and keep the request open until the head is
1310
+ * in or the subscription ends.
1311
+ *
1312
+ * It asks for the group SUBSCRIBE_OK names as Largest, from object 0 up to Largest, with a
1313
+ * Relative Joining FETCH (offset 0) on its own request, outside PUBLISH_DONE's Stream Count.
1314
+ * The objects arrive on a fetch stream that {@link handleFetch} writes into the
1315
+ * {@link Join}. As in the Rust subscriber, a refusal or a failed request costs only the
1316
+ * head, and the request has no deadline of its own: it lives as long as the subscription.
1317
+ * A malformed answer closes the session, as on any request.
1318
+ */
1319
+ async #runJoiningFetch(subscription, subscribeId, priority, signal) {
1320
+ const join = subscription.join;
1321
+ if (!join)
586
1322
  return;
1323
+ const version = this.#session.version;
1324
+ let request;
587
1325
  try {
588
- await stream.writer.u53(Unsubscribe.id);
589
- await new Unsubscribe({ requestId }).encode(stream.writer, version);
1326
+ const fetchId = await this.#session.nextRequestId(signal);
1327
+ if (fetchId === undefined)
1328
+ throw await this.#closedSession();
1329
+ // Registered before the FETCH goes out: its stream can overtake FETCH_OK. It stays
1330
+ // until the subscription ends, so a head that lands after a whole group won the
1331
+ // key is read away rather than refused.
1332
+ this.#fetches.set(fetchId, Promise.resolve(subscription));
1333
+ subscription.fetchIds.push(fetchId);
1334
+ request = new RequestStream(await this.#session.openBi({ signal }), this.#session, this.#quic);
1335
+ if (signal.aborted) {
1336
+ request.abort(signal.reason);
1337
+ signal.throwIfAborted();
1338
+ }
1339
+ const msg = new Fetch({
1340
+ requestId: fetchId,
1341
+ type: { kind: "relativeJoining", subscription: subscribeId, offset: 0n },
1342
+ subscriberPriority: priority,
1343
+ groupOrder: "ascending",
1344
+ });
1345
+ await Message.write(request.writer, Fetch.id, msg, version);
1346
+ console.debug(`joining fetch: id=${fetchId} group=${join.key}`);
1347
+ const response = await untilAborted(request.next(), signal);
1348
+ if (response === undefined)
1349
+ throw new Error("joining FETCH ended before its response");
1350
+ if (response.type === RequestError.id) {
1351
+ const err = await RequestError.decode(response.reader, version);
1352
+ const why = requestReason(err.errorCode, err.reasonPhrase, "fetch", version);
1353
+ throw new Error(`joining FETCH refused: ${why}`);
1354
+ }
1355
+ if (response.type !== FetchOk.idFor(version)) {
1356
+ throw new ProtocolViolation(`unexpected answer to FETCH: 0x${response.type.toString(16)}`);
1357
+ }
1358
+ try {
1359
+ await FetchOk.decode(response.reader, version);
1360
+ }
1361
+ catch (err) {
1362
+ throw new ProtocolViolation(`malformed FETCH_OK: ${reason(error(err))}`);
1363
+ }
1364
+ // The answer is in; the head arrives on the fetch stream, or never. The request stays
1365
+ // read meanwhile: a reset means its fetch stream cannot be trusted to come, while a
1366
+ // FIN only ends the publisher's half.
1367
+ const ended = request.next().then((framed) => {
1368
+ if (framed !== undefined) {
1369
+ throw new ProtocolViolation(`unexpected message after FETCH_OK: 0x${framed.type.toString(16)}`);
1370
+ }
1371
+ return join.settled;
1372
+ });
1373
+ await untilAborted(Promise.race([join.settled, ended]), signal);
1374
+ request.close();
590
1375
  }
591
- catch {
592
- // The stream may already be gone; there is nothing further to tell the peer.
1376
+ catch (err) {
1377
+ const e = error(err);
1378
+ if (e instanceof ProtocolViolation) {
1379
+ request?.abort(e);
1380
+ this.#fail(e.code, e.message);
1381
+ }
1382
+ else if (signal.aborted) {
1383
+ request?.cancel();
1384
+ request?.close();
1385
+ }
1386
+ else {
1387
+ request?.abort(e);
1388
+ console.debug(`joining FETCH failed, joining at the next whole group: ${reason(e)}`);
1389
+ }
1390
+ join.refuse(e);
593
1391
  }
594
1392
  }
595
1393
  // Opens the subscribe stream, sends SUBSCRIBE, and reads the response.
596
1394
  // `state` is populated as soon as the stream opens and again when the
597
- // trackAlias is registered, so the caller can clean both up on timeout
1395
+ // trackAlias is registered, so the caller can clean both up once it gives up,
598
1396
  // even before this promise settles.
599
- async #openSubscribe(state, broadcast, request, subscription, requestId) {
1397
+ async #openSubscribe(state, broadcast, request, requestId, deadline, known) {
600
1398
  const version = this.#session.version;
601
- state.stream = await this.#session.openBi();
602
- // The timeout can fire while the open is still in flight, in which case cleanup ran
603
- // with nothing to release. Bail now that the stream is recorded, so settling this
604
- // promise hands it back to be torn down.
605
- if (state.cancelled)
1399
+ const cancelled = state.cancel.signal;
1400
+ state.stream = await RequestStream.open(this.#session, deadline, { quic: this.#quic, signal: cancelled });
1401
+ // Cleanup can run as the open hands over its stream, with nothing to release. Bail now
1402
+ // that the stream is recorded, so settling this promise hands it back to be torn down.
1403
+ if (cancelled.aborted)
606
1404
  throw new Error("subscribe cancelled before it was sent");
607
- await state.stream.writer.u53(Subscribe.id);
1405
+ this.#aliases.resubscribe({ broadcast, name: request.name });
1406
+ // A live join already placed starts at its group, as a time start would.
1407
+ const held = wireHeld(request.subscription);
1408
+ const ranges = placedAsTimes(held.ranges, held.placed);
1409
+ const bounds = wireSpan(ranges);
1410
+ const start = wireStart(ranges);
608
1411
  const msg = new Subscribe({
609
1412
  requestId,
610
1413
  trackNamespace: broadcast,
611
1414
  trackName: request.name,
1415
+ // Read now, since a subscriber can join while the stream opened. Updates follow it.
612
1416
  subscriberPriority: toWire(request.priority),
613
- // No fill is requested: the fill's fetch stream and the live subscription split
614
- // the group across two streams, and this subscriber does not reassemble them into
615
- // one group yet. A lenient publisher (like ours) replays the whole in-range group
616
- // on the subscription instead; a strict one only delivers from the next published
617
- // object, and that mid-group stream is dropped, degrading the join to the next
618
- // group boundary.
619
- filter: joinFilter(version),
1417
+ // Fixed for the subscription's life: no REQUEST_UPDATE parameter carries it.
1418
+ groupOrder: rangesPolicy(request.subscription.ranges ?? []).order,
1419
+ // A known start is absolute, except group 0, which joins live with no filter. A Next
1420
+ // Object join recovers its head through a fetch stream (see {@link Join}). Fixed for
1421
+ // the subscription's life.
1422
+ ...joinFilter(version, start),
620
1423
  });
621
- await msg.encode(state.stream.writer, version);
622
- state.sent = true;
623
- // The caller may have given up while that write was in flight. It deliberately left
624
- // the stream alone, so unwind here and let its cleanup send the cancellation now that
625
- // the SUBSCRIBE has actually reached the peer.
626
- if (state.cancelled)
1424
+ if (msg.fill) {
1425
+ // The fill names this request and can overtake SUBSCRIBE_OK, so it waits on it here.
1426
+ const accepted = Promise.withResolvers();
1427
+ this.#fetches.set(requestId, accepted.promise);
1428
+ state.fill = accepted.resolve;
1429
+ }
1430
+ await Message.write(state.stream.writer, Subscribe.id, msg, version);
1431
+ // The caller may have given up while that write was in flight, resetting the request
1432
+ // under it.
1433
+ if (cancelled.aborted)
627
1434
  throw new Error("subscribe cancelled while it was being sent");
628
1435
  console.debug(`subscribe written: id=${requestId} broadcast=${broadcast} track=${request.name}`);
629
- const respTypeId = await state.stream.reader.u53();
630
- if (respTypeId !== SubscribeOk.id) {
631
- let reasonPhrase = "unknown error";
1436
+ const response = await state.stream.next();
1437
+ if (response === undefined)
1438
+ throw new Error("subscription ended before its response");
1439
+ if (response.type !== SubscribeOk.id) {
1440
+ let refused;
632
1441
  try {
633
- if (respTypeId === RequestError.id) {
634
- const err = version === Version.DRAFT_14
635
- ? await SubscribeError.decode(state.stream.reader, version)
636
- : await RequestError.decode(state.stream.reader, version);
637
- reasonPhrase = requestReason(err.errorCode, err.reasonPhrase, "subscribe", version);
1442
+ if (response.type === RequestError.id) {
1443
+ refused = await RequestError.decode(response.reader, version);
1444
+ // Only a well-formed refusal ended the request; cleanup resets anything else.
1445
+ state.rejected = true;
638
1446
  }
639
1447
  }
640
1448
  catch {
641
1449
  // Decoding error response failed, use default message
642
1450
  }
643
- state.rejected = true;
644
- throw new Error(`SUBSCRIBE error: ${reasonPhrase}`);
1451
+ if (!refused)
1452
+ throw new Error("SUBSCRIBE error: unknown error");
1453
+ throw new SubscribeRefused(refused.errorCode, refused.reasonPhrase, refused.retryInterval, version);
645
1454
  }
646
- const ok = await SubscribeOk.decode(state.stream.reader, version);
647
- if (state.cancelled)
1455
+ const ok = await SubscribeOk.decode(response.reader, version);
1456
+ if (cancelled.aborted)
648
1457
  throw new Error("subscribe cancelled before acceptance");
649
- request.accept({ priority: fromWire(ok.properties.priority ?? 128) });
1458
+ const maxCacheDuration = ok.properties.maxCacheDuration;
1459
+ if (maxCacheDuration !== undefined && maxCacheDuration > BigInt(Number.MAX_SAFE_INTEGER)) {
1460
+ // Its groups may have overtaken this answer; they are dropped rather than left waiting.
1461
+ this.#aliases.refuse(ok.trackAlias, { broadcast, name: request.name });
1462
+ throw new RangeError("max cache duration exceeds safe milliseconds");
1463
+ }
1464
+ // Staged until the answer is written in below, so no reader sees the track before its
1465
+ // Largest and start.
1466
+ const staged = known
1467
+ ? undefined
1468
+ : hooks.stageRequest(request, {
1469
+ // No TIMESCALE means no timeline, and the track must not claim one when served onward.
1470
+ timescale: ok.properties.timescale,
1471
+ priority: fromWire(ok.properties.priority ?? DEFAULT_WIRE),
1472
+ // No MAX_CACHE_DURATION sets no publisher limit, not the authored default.
1473
+ maxAge: maxCacheDuration === undefined ? null : Duration.millis(Number(maxCacheDuration)),
1474
+ ietf: version,
1475
+ });
1476
+ const producer = known ?? staged?.producer;
1477
+ if (!producer)
1478
+ throw new Error("subscription has no track");
1479
+ hooks.receiveTrack(producer);
1480
+ // Its publisher starts a time anchor at the first group at or after it, so its readers do
1481
+ // too, rather than at an earlier group the copy happens to hold.
1482
+ hooks.startsAtKeys(producer);
1483
+ if (!known)
1484
+ state.requests = producer.requests();
1485
+ const tail = new Tail();
1486
+ const subscription = {
1487
+ track: producer,
1488
+ tail,
1489
+ timescale: ok.properties.timescale,
1490
+ fetchIds: [],
1491
+ };
1492
+ const binding = subscription;
1493
+ state.binding = binding;
1494
+ // A live join starts at Largest's group: a filterless one from its first object, and Next
1495
+ // Object after Largest, so the joining FETCH or the fill brings that group's head. With no
1496
+ // Largest the track is empty and every group whole. A draft-22 fill is one of the
1497
+ // subscription's own streams, so the Stream Count already waits for it.
1498
+ const live = msg.filter.kind !== "absolute";
1499
+ if (msg.filter.kind === "nextObject" && ok.largest) {
1500
+ subscription.join = new Join(ok.largest.groupId, tail, { counted: msg.fill !== undefined });
1501
+ const join = subscription.join;
1502
+ this.#joins.set(producer, join);
1503
+ void join.settled.then(() => {
1504
+ if (this.#joins.get(producer) === join)
1505
+ this.#joins.delete(producer);
1506
+ });
1507
+ }
1508
+ if (msg.fill)
1509
+ subscription.fetchIds.push(requestId);
1510
+ state.subscription = subscription;
1511
+ if (ok.largest) {
1512
+ // Object IDs can start past zero or skip, while readers see frame ordinals, so only
1513
+ // the group carries over: its first frame is the edge a reader can count on. It names
1514
+ // no object, so a Next Object join served onward still starts at the group's first.
1515
+ hooks.reportedGroup(producer, ok.largest.groupId);
1516
+ }
1517
+ // Absolute subscriptions keep their prefix even when the answer follows its first data. A
1518
+ // live join's earlier start is left to the copy's fills, one range FETCH per run. The
1519
+ // publisher placed that start at its edge, so the groups below stay fillable for whatever
1520
+ // each reader's budget reaches, even one from the oldest group, which names none of them,
1521
+ // and one that joins after this SUBSCRIBE, which no update re-asks.
1522
+ hooks.startTrack(producer, {
1523
+ start: live ? (ok.largest?.groupId ?? 0n) : (start ?? 0n),
1524
+ requested: bounds.start,
1525
+ resolved: live && ok.largest !== undefined,
1526
+ });
1527
+ // Its Largest, or none for a track with nothing yet, says where the live feed is.
1528
+ hooks.answerEdge(producer);
1529
+ const source = this.#streamSources.get(request);
1530
+ if (source)
1531
+ subscription.datagrams = this.#bindDatagrams(source, producer, {
1532
+ priority: fromWire(ok.properties.priority ?? DEFAULT_WIRE),
1533
+ timescale: ok.properties.timescale,
1534
+ });
1535
+ staged?.commit();
1536
+ state.fill?.(subscription);
650
1537
  try {
651
- this.#aliases.set(ok.trackAlias, subscription, { broadcast, name: request.name });
1538
+ this.#aliases.set(ok.trackAlias, binding, { broadcast, name: request.name });
652
1539
  const timescale = ok.properties.timescale;
653
1540
  if (timescale !== undefined) {
654
- this.#timescales.set(ok.trackAlias, timescale);
1541
+ this.#timing.set(ok.trackAlias, timescale);
655
1542
  }
656
1543
  }
657
1544
  catch (err) {
658
1545
  // Only one alias naming two different tracks is the session's problem. A publisher
659
1546
  // sharing an alias between subscriptions to one track is allowed to do that, and
660
1547
  // disconnecting over it would drop every other broadcast on the session.
661
- if (err instanceof DuplicateTrackAlias) {
662
- // Send the violation before the session's own close sends a clean code.
663
- try {
664
- this.#quic?.close({ closeCode: SessionCode.ProtocolViolation, reason: err.message });
665
- }
666
- catch {
667
- // Already closed.
668
- }
669
- this.#session.close();
670
- }
1548
+ if (err instanceof DuplicateTrackAlias)
1549
+ this.#fail(SessionCode.ProtocolViolation, err.message);
671
1550
  throw err;
672
1551
  }
673
1552
  state.registeredAlias = ok.trackAlias;
674
- return { stream: state.stream, alias: ok.trackAlias };
1553
+ return {
1554
+ stream: state.stream,
1555
+ subscription,
1556
+ binding,
1557
+ alias: ok.trackAlias,
1558
+ priority: msg.subscriberPriority,
1559
+ };
675
1560
  }
676
1561
  /**
677
1562
  * Handles an incoming PUBLISH_NAMESPACE on a bidi stream.
@@ -679,108 +1564,82 @@ export class Subscriber {
679
1564
  *
680
1565
  * @internal
681
1566
  */
682
- async runPublishNamespace(msg, stream) {
1567
+ runPublishNamespace(msg, stream) {
1568
+ const request = new RequestStream(stream, this.#session, this.#quic);
1569
+ return request.serve(this.#runPublishNamespace(msg, request));
1570
+ }
1571
+ async #runPublishNamespace(msg, request) {
1572
+ if (Namespace.reserved(msg.trackNamespace, this.#session.version)) {
1573
+ await refuseReserved(request);
1574
+ return;
1575
+ }
683
1576
  const version = this.#session.version;
684
1577
  const path = msg.trackNamespace;
685
1578
  // A path that already ran through us looped back. Refuse it rather than holding an
686
1579
  // advertisement we could never subscribe through. The peer knows our Hop ID, so a
687
1580
  // conforming one never offers it; 0 as the retry interval says not to come back.
688
- if (this.#reflected(msg.cluster)) {
1581
+ if (this.#reflected(msg.params.cluster)) {
689
1582
  console.debug(`dropping reflected publish_namespace: broadcast=${path}`);
690
- await stream.writer.u53(RequestError.id);
691
- await new RequestError({
692
- requestId: msg.requestId,
693
- errorCode: toRequestCode("uninterested", "publish_namespace", version),
1583
+ await request.refuse("publish_namespace", {
1584
+ condition: "uninterested",
694
1585
  reasonPhrase: "route loops back",
695
- }).encode(stream.writer, version);
696
- stream.close();
697
- return;
698
- }
699
- // Draft-14/15 key their namespace-scoped messages by name, not request ID, so the
700
- // adapter can hold only one request per namespace: a second would overwrite the
701
- // first, and the withdrawals would then close the wrong stream and fail to find
702
- // the other. Nothing is lost by refusing it, because the case that makes a second
703
- // reference legitimate (an inline NAMESPACE for a path a PUBLISH_NAMESPACE already
704
- // carried) needs a message those drafts do not have.
705
- const legacy = version === Version.DRAFT_14 || version === Version.DRAFT_15;
706
- if (legacy && (this.#announced.has(path) || this.#legacyRequests.has(path))) {
707
- console.warn("duplicate PublishNamespace");
708
- // No draft registers a code for a duplicate, and this refusal is a draft-14/15
709
- // implementation limit, which is what INTERNAL_ERROR describes.
710
- const errorCode = toRequestCode("internal", "publish_namespace", version);
711
- if (version === Version.DRAFT_14) {
712
- await stream.writer.u53(PublishNamespaceError.id);
713
- await new PublishNamespaceError({
714
- requestId: msg.requestId,
715
- errorCode,
716
- reasonPhrase: "duplicate namespace",
717
- }).encode(stream.writer, version);
718
- }
719
- else {
720
- await stream.writer.u53(RequestError.id);
721
- await new RequestError({
722
- requestId: msg.requestId,
723
- errorCode,
724
- reasonPhrase: "duplicate namespace",
725
- }).encode(stream.writer, version);
726
- }
727
- stream.close();
1586
+ });
728
1587
  return;
729
1588
  }
730
- // Everywhere else a path this session already knows is not refused: the same
731
- // namespace can reach us twice, and the count is what tells the second apart from
732
- // news. This request owns exactly one of those references and gives it back when
733
- // the stream ends.
734
- if (legacy)
735
- this.#legacyRequests.add(path);
736
- let attached = false;
1589
+ // A path this session already knows is not refused: the same namespace can reach us
1590
+ // twice, and each advertisement is tracked apart from news. This request owns exactly
1591
+ // one of those references, named by its id while attached, and gives it back when the
1592
+ // stream ends.
1593
+ this.#announceSlots.acquire();
1594
+ let attached;
1595
+ // Set once the peer ends the request, by FIN or reset, which withdraws the
1596
+ // advertisement; a violation or a refused update here loses it instead.
1597
+ let withdrawn = false;
737
1598
  try {
738
1599
  // Send OK first. This must complete before notifying consumers,
739
- // because consumers may trigger Subscribe writes that would
740
- // interleave with our OK on the control stream.
741
- if (version === Version.DRAFT_14) {
742
- await stream.writer.u53(PublishNamespaceOk.id);
743
- const ok = new PublishNamespaceOk({ requestId: msg.requestId });
744
- await ok.encode(stream.writer, version);
745
- }
746
- else {
747
- await stream.writer.u53(RequestOk.id);
748
- const ok = new RequestOk({
749
- requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined,
750
- });
751
- await ok.encode(stream.writer, version);
752
- }
1600
+ // because consumers may trigger Subscribe writes.
1601
+ await Message.write(request.writer, RequestOk.id, new RequestOk(), version);
753
1602
  // Only now is the advertisement ours to announce, for the reason above: a
754
1603
  // consumer reacting with a SUBSCRIBE must not interleave with that OK.
755
- attached = true;
756
- this.#attachAnnounce(path, this.#route(msg.cluster));
1604
+ attached = this.#attachAnnounce(path, this.#route(msg.params));
757
1605
  // An advertisement is updated in place with REQUEST_UPDATE on the stream that
758
1606
  // already carries it, so read until the stream ends rather than waiting on the
759
1607
  // close. Nothing else would deliver a re-parented route. What the peer holds
760
1608
  // is kept current, since an update carries only what changed.
761
- let held = msg.cluster;
762
- const done = version === Version.DRAFT_16 || legacy;
1609
+ let held = msg.params.cluster;
763
1610
  for (;;) {
764
- // Drafts 17+ withdraw by resetting the request with CANCELLED, which ends it like a
765
- // FIN. Any other reset is a failure.
766
- const ended = await stream.reader.done().catch((err) => {
767
- if (!done && err instanceof StreamError && err.code === StreamCode.Cancel)
768
- return true;
769
- throw err;
770
- });
771
- if (ended)
772
- break;
773
- const typeId = await stream.reader.u53();
774
- if (done && typeId === PublishNamespaceDone.id) {
775
- await PublishNamespaceDone.decode(stream.reader, version);
1611
+ const framed = await race([request.next(), request.ended.then(() => undefined)]);
1612
+ if (framed === undefined) {
1613
+ // FIN cancels only on some drafts; on the rest the request lasts until reset.
1614
+ await request.ended;
1615
+ withdrawn = true;
776
1616
  break;
777
1617
  }
778
1618
  // A repeated PUBLISH_NAMESPACE lands here too: a second request on the
779
1619
  // stream is the base draft's duplicate request ID.
780
- if (typeId !== PublishNamespaceUpdate.id) {
781
- throw new ProtocolViolation(`unexpected message on publish_namespace stream: 0x${typeId.toString(16)}`);
1620
+ if (framed.type !== PublishNamespaceUpdate.id) {
1621
+ throw new ProtocolViolation(`unexpected message on publish_namespace stream: 0x${framed.type.toString(16)}`);
1622
+ }
1623
+ let update;
1624
+ try {
1625
+ update = await PublishNamespaceUpdate.decode(framed.reader, version);
782
1626
  }
783
- const update = await PublishNamespaceUpdate.decode(stream.reader, version);
1627
+ catch (err) {
1628
+ if (!(err instanceof MalformedAuthToken))
1629
+ throw err;
1630
+ // A refused update's request ID is still checked.
1631
+ if (err.requestId !== undefined)
1632
+ this.#session.checkRequestId(err.requestId);
1633
+ // Section 8.9 rejects the update, which withdraws the advertisement as any
1634
+ // refused update does.
1635
+ await refuseUpdate(request.writer, version, "publish_namespace", {
1636
+ condition: "malformed_auth_token",
1637
+ reasonPhrase: err.message,
1638
+ });
1639
+ request.close();
1640
+ break;
1641
+ }
1642
+ this.#session.checkRequestId(update.requestId);
784
1643
  // The parameters exist only on a session that negotiated the extension;
785
1644
  // anywhere else they are the peer's violation.
786
1645
  if (held === undefined) {
@@ -797,34 +1656,31 @@ export class Subscriber {
797
1656
  // advertisement's only channel, so a later clean path arrives here or
798
1657
  // nowhere.
799
1658
  if (this.#reflected(held)) {
800
- if (attached) {
801
- attached = false;
1659
+ if (attached !== undefined) {
802
1660
  console.debug(`publish_namespace now loops back, detaching: broadcast=${path}`);
803
- this.#detachAnnounce(path);
1661
+ this.#detachAnnounce(path, attached, false);
1662
+ attached = undefined;
804
1663
  }
805
1664
  }
806
- else if (!attached) {
1665
+ else if (attached === undefined) {
807
1666
  // Re-attach: a clean path replaced the reflected one we detached from.
808
- attached = true;
809
- this.#attachAnnounce(path, this.#route(held));
1667
+ attached = this.#attachAnnounce(path, this.#route({ cluster: held }));
810
1668
  }
811
1669
  else {
812
- this.#updateAnnounce(path, this.#route(held));
1670
+ this.#updateAnnounce(path, attached, this.#route({ cluster: held }));
813
1671
  }
814
1672
  // Nothing here can fail to apply, so every update is acknowledged. A leaf
815
1673
  // routes nothing, so a repricing changes nothing it holds; consumers still
816
1674
  // hear the new route so a forwarder can reprice.
817
- await stream.writer.u53(RequestOk.id);
818
- await new RequestOk({}).encode(stream.writer, version);
1675
+ await Message.write(request.writer, RequestOk.id, new RequestOk(), version);
819
1676
  }
820
1677
  }
821
1678
  finally {
822
- if (legacy)
823
- this.#legacyRequests.delete(path);
1679
+ this.#announceSlots.release();
824
1680
  // Give back exactly what was taken: a request that never got its OK out never
825
1681
  // referenced the path, and retracting there would drop someone else's count.
826
- if (attached) {
827
- this.#detachAnnounce(path);
1682
+ if (attached !== undefined) {
1683
+ this.#detachAnnounce(path, attached, withdrawn);
828
1684
  }
829
1685
  }
830
1686
  }
@@ -834,33 +1690,19 @@ export class Subscriber {
834
1690
  *
835
1691
  * @internal
836
1692
  */
837
- async runPublish(msg, stream) {
838
- const version = this.#session.version;
1693
+ runPublish(msg, stream) {
1694
+ const request = new RequestStream(stream, this.#session, this.#quic);
839
1695
  // We decline the method itself rather than this particular track, which would be
840
1696
  // UNINTERESTED.
841
1697
  //
842
1698
  // The alias the message carries is deliberately not recorded. Nothing will ever bind
843
1699
  // it, and a rejected request has no lifetime of ours to hang the cleanup on.
844
- const errorCode = toRequestCode("not_supported", "publish", version);
845
- if (version === Version.DRAFT_14) {
846
- await stream.writer.u53(PublishError.id);
847
- const err = new PublishError({
848
- requestId: msg.requestId,
849
- errorCode,
850
- reasonPhrase: "publish not supported",
851
- });
852
- await err.encode(stream.writer, version);
853
- }
854
- else {
855
- await stream.writer.u53(RequestError.id);
856
- const err = new RequestError({
857
- requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined,
858
- errorCode,
1700
+ return request.serve(Namespace.reserved(msg.trackNamespace, this.#session.version)
1701
+ ? refuseReserved(request)
1702
+ : request.refuse("publish", {
1703
+ condition: "not_supported",
859
1704
  reasonPhrase: "publish not supported",
860
- });
861
- await err.encode(stream.writer, version);
862
- }
863
- stream.close();
1705
+ }));
864
1706
  }
865
1707
  /**
866
1708
  * Handles an ObjectStream message (group + frames on uni stream).
@@ -868,15 +1710,17 @@ export class Subscriber {
868
1710
  * @internal
869
1711
  */
870
1712
  async handleGroup(group, stream) {
871
- if (group.subGroupId !== 0) {
1713
+ if (group.subGroupId !== 0n) {
872
1714
  throw new Error("subgroups are not supported");
873
1715
  }
874
- let subscription;
1716
+ let binding;
875
1717
  try {
876
1718
  // The control message establishing this alias can arrive after the data stream.
877
- subscription = await this.#aliases.get(group.trackAlias);
1719
+ binding = await this.#aliases.get(group.trackAlias);
878
1720
  }
879
1721
  catch (err) {
1722
+ if (err instanceof ProtocolViolation)
1723
+ this.#fail(err.code, err.message);
880
1724
  const e = await sessionCause(this.#quic, err);
881
1725
  // Ours: we cancelled the subscription and the publisher has not stopped yet.
882
1726
  // Anything else on this alias is the publisher sending data for a track it never
@@ -887,6 +1731,7 @@ export class Subscriber {
887
1731
  stream.stop(e);
888
1732
  return;
889
1733
  }
1734
+ const subscription = binding;
890
1735
  const { track, tail } = subscription;
891
1736
  // Every data stream counts toward PUBLISH_DONE's Stream Count, even one dropped below.
892
1737
  const read = tail.open(group.groupId);
@@ -899,87 +1744,210 @@ export class Subscriber {
899
1744
  if (subscription.end !== undefined && group.groupId >= subscription.end) {
900
1745
  throw new ProtocolViolation(`group ${group.groupId} is at or past the declared end ${subscription.end}`);
901
1746
  }
902
- producer = new netGroup.Producer(group.groupId);
903
- track.writeGroup(producer);
1747
+ // A group the copy already holds arrived twice, which the received path refuses.
1748
+ producer = hooks.receiveGroup(track, { start: group.groupId, offset: 0 });
904
1749
  }
905
1750
  return producer;
906
1751
  };
907
- try {
908
- // FIRST_OBJECT clear is the publisher's claim that the stream starts partway
909
- // through the group. The first Object ID is absolute either way, and IDs start
910
- // at 0, so a clear bit on object 0 is still the whole group. Any other first ID,
911
- // or a stream with no object, has a hole at the front: drop it and pick up at
912
- // the next group.
913
- //
914
- // Drafts before the bit cannot say this in the header, so the first ID is the only
915
- // signal: a non-zero one is the same hole and is dropped the same way, but an empty
916
- // stream there is still a group. A later gap, or a header that claimed the group
917
- // starts at object 0, still fails it: `Frame.decode` refuses every non-zero delta.
918
- const legacy = !hasFirstObjectBit(this.#session.version);
919
- if (!group.flags.firstObject || legacy) {
920
- let id;
921
- try {
922
- id = await stream.peekU62();
923
- }
924
- catch (err) {
925
- if (!(err instanceof UnexpectedEnd))
926
- throw err;
927
- }
928
- if (id !== 0n && !(legacy && id === undefined)) {
929
- console.debug(`dropping a group with no head: alias=${group.trackAlias} group=${group.groupId}`);
930
- stream.stop(new Error("a group must start at object 0"));
931
- return;
932
- }
1752
+ // A group that will never arrive whole is dropped, so readers stop owing it.
1753
+ const dropHeadless = () => hooks.dropTrackGroups(track, group.groupId, group.groupId + 1n, dropHole());
1754
+ // After an END_OF_GROUP or END_OF_TRACK status only the stream's end may follow: an
1755
+ // object past the group's final one makes the track malformed.
1756
+ const last = async () => {
1757
+ const done = await race([stream.done(), producer?.closed ?? hooks.trackReleased(track)]);
1758
+ if (done === false) {
1759
+ throw new StreamError(StreamCode.MalformedTrack, {
1760
+ message: `data past the group's final object: group=${group.groupId}`,
1761
+ });
933
1762
  }
1763
+ };
1764
+ try {
934
1765
  // The alias binds after SUBSCRIBE_OK commits the track property; an omitted
935
- // header priority inherits it (draft-21 section 10.4).
1766
+ // header priority inherits it (draft-22 section 10.4).
936
1767
  if (!group.flags.hasPriority)
937
1768
  group.publisherPriority = toWire((await track.info()).priority);
938
- const decode = (c) => Frame.decode(c, group.flags, this.#timescales.get(group.trackAlias));
1769
+ const timescale = this.#timing.get(group.trackAlias);
1770
+ // A timed track's Object IDs are timestamp offsets, which skip ticks.
1771
+ const sparse = timescale !== undefined;
1772
+ // A stream for the group a join is fetching the head of may start partway
1773
+ // through it, at or past the Object ID the head ends before (see Join).
1774
+ const join = subscription.join?.key === group.groupId ? subscription.join : undefined;
1775
+ let first = join?.outstanding === true;
1776
+ // Only the first object's ID names a compact stream's subgroup; later ones are deltas.
1777
+ let flags = group.flags;
1778
+ const decode = (c) => Frame.decode(c, flags, first, sparse);
1779
+ let priorObject;
1780
+ // A Prior Group ID Gap is applied once per group.
1781
+ let gapped = false;
939
1782
  for (;;) {
940
1783
  // Every object already buffered is written without an await, so the reader wakes
941
1784
  // once per batch rather than once per object. Only the group's own stream ends it:
942
1785
  // a track that closes first has already closed (or aborted) this group through its
943
1786
  // cache.
944
1787
  const frame = stream.tryDecode(decode) ??
945
- (await (producer
946
- ? race([stream.decodeMaybe(decode), producer.closed])
947
- : stream.decodeMaybe(decode)));
948
- if (!frame || frame instanceof Error)
1788
+ (await race([stream.decodeMaybe(decode), producer?.closed ?? hooks.trackReleased(track)]));
1789
+ if (flags.hasSubgroupObject)
1790
+ flags = { ...flags, hasSubgroupObject: false };
1791
+ if (!producer && (frame === null || frame instanceof Error)) {
1792
+ stream.stop(frame ?? new StreamError(StreamCode.Cancel));
1793
+ return;
1794
+ }
1795
+ if (first && join) {
1796
+ first = false;
1797
+ const suspend = () => tail.suspend();
1798
+ // No producer yet, so a closing group or track already returned above.
1799
+ const object = frame instanceof Error ? undefined : (frame ?? undefined);
1800
+ // The first object's ID is absolute: where in the group this stream starts. An End
1801
+ // of Group there names where the group ends, past the head's last object.
1802
+ const start = object?.isObject || object?.endOfTrack || (object?.idDelta ?? 0) > 0
1803
+ ? object?.idDelta
1804
+ : undefined;
1805
+ if (object?.isObject && (group.flags.firstObject ? sparse || start === 0 : start === 0)) {
1806
+ // The whole group: it stands alone unless the head already took the key.
1807
+ if (!join.whole()) {
1808
+ stream.stop(new Error("the group's head was served twice"));
1809
+ return;
1810
+ }
1811
+ }
1812
+ else if (start === undefined || !group.flags.firstObject || start > 0) {
1813
+ // A tail with no objects ends the group wherever the head did.
1814
+ const head = await join.claim(start, suspend, sparse);
1815
+ if (head) {
1816
+ producer = head.producer;
1817
+ if (!sparse) {
1818
+ if (head.next > 0)
1819
+ priorObject = BigInt(head.next - 1);
1820
+ if (object)
1821
+ object.idDelta = 0;
1822
+ }
1823
+ }
1824
+ else if (start !== undefined && !object?.endOfTrack) {
1825
+ console.debug(`dropping a group with no head: alias=${group.trackAlias} group=${group.groupId} start=${start}`);
1826
+ dropHeadless();
1827
+ stream.stop(new Error("no head to stitch a mid-group stream onto"));
1828
+ return;
1829
+ }
1830
+ }
1831
+ }
1832
+ if (!frame || frame instanceof Error) {
1833
+ // FIRST_OBJECT clear on a stream that ends with no object: it starts partway
1834
+ // through its group and carries none of it, so drop it like any headless
1835
+ // stream.
1836
+ if (!producer && !group.flags.firstObject) {
1837
+ console.debug(`dropping a group with no head: alias=${group.trackAlias} group=${group.groupId}`);
1838
+ dropHeadless();
1839
+ stream.stop(new Error("a group must start at object 0"));
1840
+ return;
1841
+ }
949
1842
  break;
1843
+ }
950
1844
  if (frame.endOfTrack) {
1845
+ if (frame.hasProperties)
1846
+ throw new EndOfTrackProperties();
951
1847
  // No object at or past this location exists: after the group's last object
952
1848
  // the track ends with it, and at object 0 it ends before it.
953
- const end = producer ? group.groupId + 1 : group.groupId;
954
- producer?.close();
1849
+ if (producer && !sparse && frame.idDelta !== 0)
1850
+ throw new ObjectIdGap(frame.idDelta);
1851
+ await last();
1852
+ const wireObject = priorObject === undefined ? frame.idDelta : Number(priorObject + 1n) + frame.idDelta;
1853
+ // A moq-timestamp Object ID names where the track ends in time, which the frames
1854
+ // already held place: before the first frame at or past it. A group this copy
1855
+ // can't place it in ends before the next group.
1856
+ const placed = timescale !== undefined && wireObject > 0 && !producer
1857
+ ? hooks.finishedTimedFrame(track, group.groupId, BigInt(wireObject), timescale)
1858
+ : undefined;
1859
+ const end = sparse && wireObject > 0
1860
+ ? producer
1861
+ ? { group: group.groupId, frame: hooks.groupFrameCount(producer) }
1862
+ : placed !== undefined
1863
+ ? { group: group.groupId, frame: placed }
1864
+ : { group: group.groupId + 1n, frame: 0 }
1865
+ : { group: group.groupId, frame: wireObject };
1866
+ producer?.finish();
955
1867
  try {
956
- track.finishAt(end);
1868
+ hooks.endTrack(track, end);
957
1869
  }
958
1870
  catch (err) {
959
1871
  throw new ProtocolViolation(`invalid END_OF_TRACK: ${reason(error(err))}`);
960
1872
  }
961
- subscription.end ??= end;
1873
+ subscription.end ??= finalKey(end);
962
1874
  return;
963
1875
  }
964
- if (frame.payload === undefined)
1876
+ if (!frame.isObject) {
1877
+ await last();
1878
+ break;
1879
+ }
1880
+ // A stream with FIRST_OBJECT clear that wasn't stitched to a head is headless:
1881
+ // drop it before opening a producer, even on a timed track where deltas are allowed.
1882
+ if (!producer && !group.flags.firstObject && (frame.idDelta > 0 || !sparse)) {
1883
+ if (frame.idDelta > 0) {
1884
+ console.debug(`dropping a group with no head: alias=${group.trackAlias} group=${group.groupId}`);
1885
+ dropHeadless();
1886
+ stream.stop(new Error("a group must start at object 0"));
1887
+ return;
1888
+ }
1889
+ }
1890
+ if (frame.groupGap && !gapped) {
1891
+ gapped = true;
1892
+ skipPrior(track, group.groupId, frame.groupGap);
1893
+ }
1894
+ const head = priorObject === undefined;
1895
+ const objectId = priorObject === undefined ? BigInt(frame.idDelta) : priorObject + 1n + BigInt(frame.idDelta);
1896
+ priorObject = objectId;
1897
+ const timestamp = objectTime(timescale, group.groupId, objectId, frame.tie ?? 0n);
1898
+ // A timed group starts at its first object's time: one this stream carries, by
1899
+ // FIRST_OBJECT or at Object ID 0, sits at the Group ID.
1900
+ if (sparse && head && (group.flags.firstObject || objectId === 0n) && objectId !== (frame.tie ?? 0n)) {
1901
+ throw new TimestampMismatch();
1902
+ }
1903
+ if (frame.payload)
1904
+ open().writeFrame({ payload: frame.payload, timestamp });
1905
+ else if (!(await receiveFrame(stream, open(), { size: frame.streamed ?? 0, timestamp })))
965
1906
  break;
966
- open().writeFrame({ payload: frame.payload, timestamp: frame.timestamp ?? Timestamp.now() });
967
1907
  }
968
1908
  // A group with no objects still exists.
969
- open().close();
1909
+ open().finish();
970
1910
  }
971
1911
  catch (err) {
1912
+ if (err instanceof ProtocolViolation)
1913
+ this.#fail(err.code, err.message);
972
1914
  const e = await sessionCause(this.#quic, err);
973
- if (e instanceof ProtocolViolation) {
974
- // The publisher broke the track's end, which no later group can repair.
975
- producer?.close(e);
976
- track.close(e);
1915
+ // The compact form names the subgroup by its first Object ID, so a nonzero one is
1916
+ // subgroup N: stop the stream before any group exists for it.
1917
+ if (producer === undefined && e instanceof ObjectIdGap && group.flags.hasSubgroupObject) {
1918
+ console.warn(`subgroups are not supported: alias=${group.trackAlias} group=${group.groupId}`);
1919
+ stream.stop(new Error("subgroups are not supported"));
1920
+ return;
1921
+ }
1922
+ // The producer is still unopened only when the first object failed. With FIRST_OBJECT
1923
+ // clear, that non-zero delta is a headless group: drop the stream and leave the
1924
+ // subscription up for the next group. Delivering the object would renumber a P-frame
1925
+ // as the keyframe the group opens with.
1926
+ if (producer === undefined && e instanceof ObjectIdGap && !group.flags.firstObject) {
1927
+ console.debug(`dropping a group with no head: alias=${group.trackAlias} group=${group.groupId}`);
1928
+ dropHeadless();
1929
+ stream.stop(new Error("a group must start at object 0"));
1930
+ return;
1931
+ }
1932
+ if (e instanceof ObjectIdGap)
1933
+ console.warn(`unsupported object gap: ${reason(e)}`);
1934
+ if (e instanceof EndOfTrackProperties) {
1935
+ // The group before the marker is complete; only the track's end can't be carried.
1936
+ producer?.finish();
1937
+ hooks.abortTrack(track, e);
1938
+ }
1939
+ else if (e instanceof ProtocolViolation ||
1940
+ (e instanceof StreamError && e.code === StreamCode.MalformedTrack)) {
1941
+ // The publisher broke the track's end or its content, which no later group can repair.
1942
+ if (producer)
1943
+ hooks.abortGroup(producer, e);
1944
+ hooks.abortTrack(track, e);
977
1945
  }
978
1946
  else {
979
1947
  // A stream that fails before its first object still names a group, which the
980
1948
  // reader sees fail rather than silently go missing.
981
1949
  try {
982
- open().close(e);
1950
+ hooks.abortGroup(open(), e);
983
1951
  }
984
1952
  catch {
985
1953
  // The track has already closed or ended below this group.
@@ -988,23 +1956,358 @@ export class Subscriber {
988
1956
  stream.stop(e);
989
1957
  }
990
1958
  finally {
991
- read();
1959
+ read.done();
1960
+ }
1961
+ }
1962
+ /**
1963
+ * Handles a fetch stream, with its type already read: a standalone range, a draft-18
1964
+ * joining FETCH, or a draft-22 fill.
1965
+ *
1966
+ * A joining FETCH or fill asked for one group from object 0, so its first object must spell
1967
+ * `{G, 0}` and every later one follow it in that group. The head is created as soon as its
1968
+ * first object arrives and written as the objects do, so readers see it at once; the live
1969
+ * tail takes the group over through the {@link Join}. Anything the head cannot stitch,
1970
+ * another group or a gap among them, drops it, which costs only that group's head.
1971
+ *
1972
+ * @internal
1973
+ */
1974
+ async handleFetch(stream) {
1975
+ const version = this.#session.version;
1976
+ const { requestId } = await FetchHeader.decode(stream, version);
1977
+ const range = this.#ranges.get(requestId);
1978
+ if (range) {
1979
+ const receiving = await range;
1980
+ if (!receiving) {
1981
+ stream.stop(new StreamError(StreamCode.Cancel));
1982
+ return;
1983
+ }
1984
+ try {
1985
+ await receiving.receive(stream);
1986
+ }
1987
+ catch (err) {
1988
+ if (err instanceof ProtocolViolation)
1989
+ this.#fail(err.code, err.message);
1990
+ }
1991
+ return;
1992
+ }
1993
+ const subscription = await this.#fetches.get(requestId);
1994
+ // Nothing of ours asked: the publisher is answering a FETCH or fill we never sent.
1995
+ if (!subscription?.join)
1996
+ throw new Error(`unexpected fetch stream: request=${requestId}`);
1997
+ const { join, track, tail, timescale } = subscription;
1998
+ // A draft-22 fill is one of the subscription's own data streams, which PUBLISH_DONE
1999
+ // counts. A draft-18 joining FETCH is a request of its own; the join holds the end for it.
2000
+ const read = isDraft20(version) ? tail.open(join.key) : undefined;
2001
+ let producer;
2002
+ // A whole group took the key first, or the join gave up: read the rest away.
2003
+ let discarding = false;
2004
+ let next = 0;
2005
+ // The prior entry was an End of Group, so the head's group takes no more objects.
2006
+ let ended = false;
2007
+ try {
2008
+ const decode = (c) => decodeFetchObject(c);
2009
+ for (let first = true;; first = false) {
2010
+ const object = stream.tryDecode(decode) ??
2011
+ (await race([stream.decodeMaybe(decode), producer?.closed ?? hooks.trackReleased(track)]));
2012
+ if (object === null || object instanceof Error) {
2013
+ join.fail(object ?? new Error("the track closed under the head"), producer);
2014
+ stream.stop(object ?? new StreamError(StreamCode.Cancel));
2015
+ return;
2016
+ }
2017
+ if (object === undefined)
2018
+ break;
2019
+ if (discarding) {
2020
+ if (object.kind === "object" && !object.payload)
2021
+ await skipPayload(stream, object.size);
2022
+ continue;
2023
+ }
2024
+ if (object.kind === "endOfRange") {
2025
+ throw new JoinUnsupported("a head with an End of Range cannot be stitched");
2026
+ }
2027
+ // A fill ends where its subscription starts, which then says where the group ends.
2028
+ if (object.kind === "endOfGroup") {
2029
+ if (first)
2030
+ throw new ProtocolViolation("a fetch stream starts with an End of Group");
2031
+ ended = true;
2032
+ continue;
2033
+ }
2034
+ // Past an End of Group only an object that names another group can follow, which a
2035
+ // head of one group then refuses below.
2036
+ if (ended && object.group === undefined)
2037
+ throw new ProtocolViolation("a fetch object continues a group past its End of Group");
2038
+ const inherits = object.group === undefined ||
2039
+ object.object === undefined ||
2040
+ object.priority === undefined ||
2041
+ object.subgroup === "prior" ||
2042
+ object.subgroup === "next";
2043
+ if (first && inherits)
2044
+ throw new ProtocolViolation("the first fetch object refers to a prior object");
2045
+ if (object.subgroup === "datagram")
2046
+ throw new JoinUnsupported("a datagram group is not fetchable");
2047
+ if (object.subgroup === "next" || (object.subgroup === "explicit" && object.subgroupId !== 0n)) {
2048
+ throw new JoinUnsupported("subgroups are not supported");
2049
+ }
2050
+ // The first object names its group and Object ID outright; a later Group ID names
2051
+ // another group, which a head of one group does not have. A later Object ID Delta
2052
+ // is added to the prior ID. On a timed track, Object IDs encode DTS offsets.
2053
+ let oid;
2054
+ if (first) {
2055
+ if (object.group !== join.key) {
2056
+ throw new JoinUnsupported(`the head answered group ${object.group}, not ${join.key}`);
2057
+ }
2058
+ if (timescale === undefined && object.object !== 0) {
2059
+ throw new JoinUnsupported("the head does not start at object 0");
2060
+ }
2061
+ oid = BigInt(object.object ?? 0);
2062
+ }
2063
+ else if (object.group !== undefined) {
2064
+ throw new JoinUnsupported("a head spanning several groups cannot be stitched");
2065
+ }
2066
+ else if (object.object === undefined) {
2067
+ oid = BigInt(next);
2068
+ }
2069
+ else {
2070
+ const step = object.object + objectDeltaBias(version);
2071
+ if (timescale === undefined && step !== 1) {
2072
+ throw new JoinUnsupported("a gap in the head cannot be stitched");
2073
+ }
2074
+ if (step < 1) {
2075
+ throw new JoinUnsupported("non-increasing Object ID in fetch head");
2076
+ }
2077
+ oid = BigInt(next - 1 + step);
2078
+ }
2079
+ const timestamp = objectTime(timescale, join.key, oid, object.tie ?? 0n);
2080
+ // The head starts the group, so on a timed track its first object sits at the Group ID.
2081
+ if (first && timescale !== undefined && oid !== (object.tie ?? 0n))
2082
+ throw new TimestampMismatch();
2083
+ if (first) {
2084
+ producer = join.open(() => hooks.receiveGroup(track, { start: join.key, offset: 0 }));
2085
+ if (!producer) {
2086
+ discarding = true;
2087
+ if (!object.payload)
2088
+ await skipPayload(stream, object.size);
2089
+ continue;
2090
+ }
2091
+ }
2092
+ if (object.payload)
2093
+ producer?.writeFrame({ payload: object.payload, timestamp });
2094
+ else if (producer && !(await receiveFrame(stream, producer, { size: object.size, timestamp })))
2095
+ break;
2096
+ next = Number(oid) + 1;
2097
+ join.wrote(next);
2098
+ }
2099
+ console.debug(`join head: group=${join.key} objects=${next}`);
2100
+ join.finish(producer);
2101
+ }
2102
+ catch (err) {
2103
+ const e = await sessionCause(this.#quic, err);
2104
+ if (e instanceof JoinUnsupported)
2105
+ console.warn(`${e.message}, joining at the next whole group`);
2106
+ join.fail(e, producer);
2107
+ if (e instanceof ProtocolViolation)
2108
+ this.#fail(e.code, e.message);
2109
+ // As for a subgroup object: the track is malformed, not just its head.
2110
+ if (e instanceof StreamError && e.code === StreamCode.MalformedTrack)
2111
+ hooks.abortTrack(track, e);
2112
+ stream.stop(e);
2113
+ }
2114
+ finally {
2115
+ read?.done();
2116
+ }
2117
+ }
2118
+ /**
2119
+ * Receive QUIC datagrams, each an OBJECT_DATAGRAM for one of our subscriptions.
2120
+ *
2121
+ * Returns at once on a transport without datagrams, and once the datagram stream ends or
2122
+ * fails. A malformed datagram throws a {@link ProtocolViolation}, which ends the session.
2123
+ *
2124
+ * @internal
2125
+ */
2126
+ async runDatagrams() {
2127
+ if (!this.#quic || DatagramStream.maxDatagramSize(this.#quic) === 0)
2128
+ return;
2129
+ const reader = DatagramStream.datagramReader(this.#quic);
2130
+ if (!reader)
2131
+ return;
2132
+ const budget = new Budget();
2133
+ try {
2134
+ for (;;) {
2135
+ const yielded = budget.poll();
2136
+ if (yielded !== undefined)
2137
+ await this.#yieldDatagrams(yielded);
2138
+ // The stream errors once the session closes, which ends this loop like any other.
2139
+ const next = await reader.read().catch(() => undefined);
2140
+ if (!next || next.done)
2141
+ return;
2142
+ await this.#recvDatagram(next.value);
2143
+ }
2144
+ }
2145
+ finally {
2146
+ reader.releaseLock();
2147
+ }
2148
+ }
2149
+ async #yieldDatagrams(yielded) {
2150
+ this.#receiveYield = yielded;
2151
+ await yielded;
2152
+ this.#receiveYield = undefined;
2153
+ }
2154
+ // A clean end waits for datagrams already received with it. A budget yield or an
2155
+ // unanswered alias can interrupt that drain; each next host task lets it continue.
2156
+ async #datagramsRouted() {
2157
+ await yieldNow();
2158
+ while (this.#receiveYield !== undefined) {
2159
+ await this.#receiveYield;
2160
+ await yieldNow();
2161
+ }
2162
+ }
2163
+ /**
2164
+ * Route one OBJECT_DATAGRAM.
2165
+ *
2166
+ * An undefined Object Status is a protocol violation on every subscription kind.
2167
+ * A defined status is not a payload and does not end the track. Only object ID 0
2168
+ * reaches the datagram model; the stream model never receives datagrams.
2169
+ */
2170
+ async #recvDatagram(data) {
2171
+ const datagram = await ObjectDatagram.decode(data, this.#session.version);
2172
+ if ("status" in datagram.body && !statusDefined(datagram.body.status)) {
2173
+ throw new ProtocolViolation(`undefined object status ${datagram.body.status}`);
2174
+ }
2175
+ let alias = this.#aliases.peek(datagram.trackAlias);
2176
+ if (!alias) {
2177
+ // The answer can arrive in the same packet, behind its datagram. Keep only
2178
+ // this receive slot while the control stream decodes, then drop an unknown alias.
2179
+ await this.#yieldDatagrams(yieldNow());
2180
+ alias = this.#aliases.peek(datagram.trackAlias);
2181
+ }
2182
+ const binding = alias?.datagrams && {
2183
+ producer: alias.datagrams.producer,
2184
+ timescale: alias.timescale,
2185
+ };
2186
+ if (!binding) {
2187
+ console.debug(`dropping a datagram for an unknown alias: alias=${datagram.trackAlias}`);
2188
+ return;
2189
+ }
2190
+ if ("status" in datagram.body) {
2191
+ console.debug(`dropping a datagram status: alias=${datagram.trackAlias} group=${datagram.groupId}`);
2192
+ return;
2193
+ }
2194
+ const objectId = datagram.objectId ?? 0n;
2195
+ if (objectId !== 0n) {
2196
+ console.debug(`dropping a datagram with a nonzero object id: alias=${datagram.trackAlias} group=${datagram.groupId} object=${objectId}`);
2197
+ return;
2198
+ }
2199
+ let tie = 0n;
2200
+ if (datagram.properties) {
2201
+ try {
2202
+ const decoded = await new Reader(undefined, datagram.properties, this.#session.version).decode(decodeObjectProperties);
2203
+ tie = decoded.tie ?? 0n;
2204
+ }
2205
+ catch (err) {
2206
+ console.debug(`dropping a datagram with unreadable object properties: ${reason(err)}`);
2207
+ return;
2208
+ }
2209
+ }
2210
+ // Its time is its key (with optional tie), as a group's is its ID.
2211
+ let timestamp;
2212
+ try {
2213
+ timestamp = objectTime(binding.timescale, datagram.groupId, 0n, tie);
2214
+ }
2215
+ catch {
2216
+ console.debug(`dropping a datagram whose key no timestamp holds: alias=${datagram.trackAlias} group=${datagram.groupId}`);
2217
+ return;
2218
+ }
2219
+ try {
2220
+ // The Group ID rides beside the datagram, so a relay forwards it unchanged.
2221
+ hooks.writeDatagramWire(binding.producer, { timestamp, payload: datagram.body.payload }, datagram.groupId);
2222
+ }
2223
+ catch (err) {
2224
+ console.debug(`dropping a datagram the track refused: ${reason(err)}`);
2225
+ }
2226
+ }
2227
+ /** Bind both kinds to the same upstream response, without adding stream demand for passive forwarding. */
2228
+ #bindDatagrams(source, track, info) {
2229
+ const pending = this.#datagramRequests.get(source);
2230
+ const entry = pending?.get(track.name);
2231
+ let producer;
2232
+ try {
2233
+ producer = entry ? entry.request.accept(info) : wireOf(source).createDatagrams(track.name, info, false);
2234
+ }
2235
+ catch (err) {
2236
+ entry?.request.reject(error(err));
2237
+ console.debug(`serving the stream track without datagrams: ${reason(err)}`);
2238
+ return;
2239
+ }
2240
+ // A live datagram track already holds the name.
2241
+ if (!producer)
2242
+ return;
2243
+ pending?.delete(track.name);
2244
+ entry?.accepted.set(true);
2245
+ let held;
2246
+ const sync = () => {
2247
+ const priority = producer.priority.peek();
2248
+ if (priority === undefined) {
2249
+ held?.close();
2250
+ held = undefined;
2251
+ }
2252
+ else if (held)
2253
+ held.update(latestAt(priority));
2254
+ else
2255
+ held = hooks.parked(track.subscribe(latestAt(priority)));
2256
+ };
2257
+ const dispose = producer.priority.subscribe(sync);
2258
+ sync();
2259
+ return {
2260
+ producer,
2261
+ dispose: () => {
2262
+ dispose();
2263
+ held?.close();
2264
+ },
2265
+ };
2266
+ }
2267
+ /** Ask through the stream model's shared lookup, so either kind opens the same SUBSCRIBE. */
2268
+ async #runDatagram(source, request, valid) {
2269
+ if (!this.#quic || DatagramStream.maxDatagramSize(this.#quic) === 0) {
2270
+ request.reject(new Error("transport does not support datagrams"));
2271
+ return;
2272
+ }
2273
+ let pending = this.#datagramRequests.get(source);
2274
+ if (!pending) {
2275
+ pending = new Map();
2276
+ this.#datagramRequests.set(source, pending);
2277
+ }
2278
+ const entry = { request, accepted: new Once() };
2279
+ pending.set(request.name, entry);
2280
+ const subscriber = wireOf(source).subscribe(request.name, latestAt(request.priority.peek() ?? 0));
2281
+ const dispose = request.priority.subscribe((priority) => {
2282
+ if (priority !== undefined)
2283
+ subscriber.update(latestAt(priority));
2284
+ });
2285
+ try {
2286
+ await untilAborted(race([
2287
+ // Cached stream metadata alone does not accept a returning datagram request.
2288
+ Promise.all([subscriber.info(), entry.accepted]),
2289
+ Promise.resolve(request.closed).then(() => {
2290
+ throw new StreamError(StreamCode.Cancel);
2291
+ }),
2292
+ ]), valid);
2293
+ }
2294
+ catch (err) {
2295
+ if (pending.get(request.name) === entry)
2296
+ request.reject(error(err));
2297
+ }
2298
+ finally {
2299
+ dispose();
2300
+ subscriber.close();
2301
+ if (pending.get(request.name) === entry)
2302
+ pending.delete(request.name);
992
2303
  }
993
2304
  }
994
2305
  }
995
- /**
996
- * A broadcast consumed from a moq-transport session. Track info is resolved by the
997
- * subscribe path (the inherited `resolveTrackInfo`), but the protocol has no one-shot
998
- * group fetch, so `track.Consumer.fetchGroup()` is rejected.
999
- */
2306
+ // The protected broadcast constructor keeps network-backed consumers package-private.
1000
2307
  class ConsumeBroadcast extends broadcast.Consumer {
1001
2308
  constructor(state) {
1002
2309
  super(state);
1003
- overrideBroadcastWire(this, {
1004
- fetchGroup: () => Promise.reject(new Error("fetch group is not supported for moq-transport")),
1005
- });
1006
2310
  }
1007
- // Preserve the subclass when the consume cache shares this broadcast across callers.
1008
2311
  clone() {
1009
2312
  return new ConsumeBroadcast(this.shareState());
1010
2313
  }