@moq/net 0.4.7 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (664) hide show
  1. package/README.md +7 -1
  2. package/announce.d.ts +1 -1
  3. package/announce.d.ts.map +1 -1
  4. package/announce.js +1 -2
  5. package/announce.js.map +1 -1
  6. package/announced.d.ts +51 -47
  7. package/announced.d.ts.map +1 -1
  8. package/announced.js +183 -32
  9. package/announced.js.map +1 -1
  10. package/announced.test-util.d.ts +2 -0
  11. package/announced.test-util.d.ts.map +1 -0
  12. package/announced.test-util.js +27 -0
  13. package/announced.test-util.js.map +1 -0
  14. package/auth.d.ts +64 -0
  15. package/auth.d.ts.map +1 -0
  16. package/auth.js +20 -0
  17. package/auth.js.map +1 -0
  18. package/auth_gate.d.ts +2 -0
  19. package/auth_gate.d.ts.map +1 -0
  20. package/auth_gate.js +24 -0
  21. package/auth_gate.js.map +1 -0
  22. package/auth_session.d.ts +49 -0
  23. package/auth_session.d.ts.map +1 -0
  24. package/auth_session.js +1097 -0
  25. package/auth_session.js.map +1 -0
  26. package/bandwidth.d.ts +129 -25
  27. package/bandwidth.d.ts.map +1 -1
  28. package/bandwidth.js +410 -139
  29. package/bandwidth.js.map +1 -1
  30. package/bandwidth_api.d.ts +1 -1
  31. package/bandwidth_api.d.ts.map +1 -1
  32. package/bandwidth_api.js +1 -2
  33. package/bandwidth_api.js.map +1 -1
  34. package/broadcast.d.ts +64 -38
  35. package/broadcast.d.ts.map +1 -1
  36. package/broadcast.js +556 -173
  37. package/broadcast.js.map +1 -1
  38. package/cache.d.ts +103 -0
  39. package/cache.d.ts.map +1 -0
  40. package/cache.js +254 -0
  41. package/cache.js.map +1 -0
  42. package/claim.test-util.d.ts +5 -0
  43. package/claim.test-util.d.ts.map +1 -0
  44. package/claim.test-util.js +13 -0
  45. package/claim.test-util.js.map +1 -0
  46. package/connection/accept.d.ts +21 -13
  47. package/connection/accept.d.ts.map +1 -1
  48. package/connection/accept.js +97 -130
  49. package/connection/accept.js.map +1 -1
  50. package/connection/browser.d.ts.map +1 -1
  51. package/connection/browser.js +28 -20
  52. package/connection/browser.js.map +1 -1
  53. package/connection/connect.d.ts +120 -24
  54. package/connection/connect.d.ts.map +1 -1
  55. package/connection/connect.js +535 -217
  56. package/connection/connect.js.map +1 -1
  57. package/connection/dials.d.ts +45 -0
  58. package/connection/dials.d.ts.map +1 -0
  59. package/connection/dials.js +109 -0
  60. package/connection/dials.js.map +1 -0
  61. package/connection/endpoint.d.ts +60 -0
  62. package/connection/endpoint.d.ts.map +1 -0
  63. package/connection/endpoint.js +114 -0
  64. package/connection/endpoint.js.map +1 -0
  65. package/connection/forward.d.ts +7 -1
  66. package/connection/forward.d.ts.map +1 -1
  67. package/connection/forward.js +265 -81
  68. package/connection/forward.js.map +1 -1
  69. package/connection/goaway.d.ts +16 -9
  70. package/connection/goaway.d.ts.map +1 -1
  71. package/connection/goaway.js +22 -95
  72. package/connection/goaway.js.map +1 -1
  73. package/connection/handshake.d.ts +34 -8
  74. package/connection/handshake.d.ts.map +1 -1
  75. package/connection/handshake.js +97 -21
  76. package/connection/handshake.js.map +1 -1
  77. package/connection/index.d.ts +4 -7
  78. package/connection/index.d.ts.map +1 -1
  79. package/connection/index.js +1 -3
  80. package/connection/index.js.map +1 -1
  81. package/connection/liveness.d.ts +14 -0
  82. package/connection/liveness.d.ts.map +1 -0
  83. package/connection/liveness.js +30 -0
  84. package/connection/liveness.js.map +1 -0
  85. package/connection/pool.d.ts +142 -63
  86. package/connection/pool.d.ts.map +1 -1
  87. package/connection/pool.js +281 -118
  88. package/connection/pool.js.map +1 -1
  89. package/connection/reload.d.ts +60 -12
  90. package/connection/reload.d.ts.map +1 -1
  91. package/connection/reload.js +859 -234
  92. package/connection/reload.js.map +1 -1
  93. package/connection/session.d.ts +91 -0
  94. package/connection/session.d.ts.map +1 -0
  95. package/connection/session.js +2 -0
  96. package/connection/session.js.map +1 -0
  97. package/connection/stats.d.ts +20 -11
  98. package/connection/stats.d.ts.map +1 -1
  99. package/connection/stats.js +64 -9
  100. package/connection/stats.js.map +1 -1
  101. package/connection/ticker.d.ts +4 -0
  102. package/connection/ticker.d.ts.map +1 -0
  103. package/connection/ticker.js +66 -0
  104. package/connection/ticker.js.map +1 -0
  105. package/connection/tokens.d.ts +2 -0
  106. package/connection/tokens.d.ts.map +1 -0
  107. package/connection/tokens.js +404 -0
  108. package/connection/tokens.js.map +1 -0
  109. package/connection/transport.d.ts.map +1 -1
  110. package/connection/transport.js +4 -5
  111. package/connection/transport.js.map +1 -1
  112. package/connection/withdrawal.d.ts +2 -0
  113. package/connection/withdrawal.d.ts.map +1 -0
  114. package/connection/withdrawal.js +23 -0
  115. package/connection/withdrawal.js.map +1 -0
  116. package/consume.js +213 -47
  117. package/consume.js.map +1 -1
  118. package/cover.d.ts +59 -0
  119. package/cover.d.ts.map +1 -0
  120. package/cover.js +375 -0
  121. package/cover.js.map +1 -0
  122. package/datagram.d.ts +70 -11
  123. package/datagram.d.ts.map +1 -1
  124. package/datagram.js +317 -2
  125. package/datagram.js.map +1 -1
  126. package/datagram_stream.d.ts +18 -0
  127. package/datagram_stream.d.ts.map +1 -0
  128. package/datagram_stream.js +67 -0
  129. package/datagram_stream.js.map +1 -0
  130. package/defined.test-util.d.ts +2 -0
  131. package/defined.test-util.d.ts.map +1 -0
  132. package/defined.test-util.js +7 -0
  133. package/defined.test-util.js.map +1 -0
  134. package/delivered.d.ts +75 -0
  135. package/delivered.d.ts.map +1 -0
  136. package/delivered.js +228 -0
  137. package/delivered.js.map +1 -0
  138. package/demand.d.ts +173 -0
  139. package/demand.d.ts.map +1 -0
  140. package/demand.js +582 -0
  141. package/demand.js.map +1 -0
  142. package/drops.d.ts +93 -0
  143. package/drops.d.ts.map +1 -0
  144. package/drops.js +283 -0
  145. package/drops.js.map +1 -0
  146. package/error.d.ts +120 -21
  147. package/error.d.ts.map +1 -1
  148. package/error.js +230 -38
  149. package/error.js.map +1 -1
  150. package/errors.d.ts +2 -2
  151. package/errors.d.ts.map +1 -1
  152. package/errors.js +2 -3
  153. package/errors.js.map +1 -1
  154. package/fill.d.ts +174 -0
  155. package/fill.d.ts.map +1 -0
  156. package/fill.js +760 -0
  157. package/fill.js.map +1 -0
  158. package/flate/decoder.d.ts +2 -0
  159. package/flate/decoder.d.ts.map +1 -0
  160. package/flate/decoder.js +63 -0
  161. package/flate/decoder.js.map +1 -0
  162. package/flate/encoder.d.ts +2 -0
  163. package/flate/encoder.d.ts.map +1 -0
  164. package/flate/encoder.js +64 -0
  165. package/flate/encoder.js.map +1 -0
  166. package/flate/group.d.ts +34 -0
  167. package/flate/group.d.ts.map +1 -0
  168. package/flate/group.js +140 -0
  169. package/flate/group.js.map +1 -0
  170. package/frame.d.ts +80 -0
  171. package/frame.d.ts.map +1 -0
  172. package/frame.js +296 -0
  173. package/frame.js.map +1 -0
  174. package/frame.test-util.d.ts +5 -0
  175. package/frame.test-util.d.ts.map +1 -0
  176. package/frame.test-util.js +9 -0
  177. package/frame.test-util.js.map +1 -0
  178. package/group.d.ts +108 -45
  179. package/group.d.ts.map +1 -1
  180. package/group.js +1616 -308
  181. package/group.js.map +1 -1
  182. package/group_api.d.ts +7 -0
  183. package/group_api.d.ts.map +1 -0
  184. package/group_api.js +7 -0
  185. package/group_api.js.map +1 -0
  186. package/hop.d.ts +62 -76
  187. package/hop.d.ts.map +1 -1
  188. package/hop.js +92 -65
  189. package/hop.js.map +1 -1
  190. package/identity.d.ts +39 -0
  191. package/identity.d.ts.map +1 -0
  192. package/identity.js +47 -0
  193. package/identity.js.map +1 -0
  194. package/ietf/active_count.d.ts +2 -0
  195. package/ietf/active_count.d.ts.map +1 -0
  196. package/ietf/active_count.js +30 -0
  197. package/ietf/active_count.js.map +1 -0
  198. package/ietf/aliases.js +69 -36
  199. package/ietf/aliases.js.map +1 -1
  200. package/ietf/cluster.d.ts +3 -3
  201. package/ietf/cluster.js +14 -55
  202. package/ietf/cluster.js.map +1 -1
  203. package/ietf/connection.d.ts +1 -31
  204. package/ietf/connection.d.ts.map +1 -1
  205. package/ietf/connection.js +305 -144
  206. package/ietf/connection.js.map +1 -1
  207. package/ietf/datagram.d.ts +60 -0
  208. package/ietf/datagram.d.ts.map +1 -0
  209. package/ietf/datagram.js +152 -0
  210. package/ietf/datagram.js.map +1 -0
  211. package/ietf/error.d.ts +3 -3
  212. package/ietf/error.js +82 -101
  213. package/ietf/error.js.map +1 -1
  214. package/ietf/fetch.d.ts +93 -37
  215. package/ietf/fetch.d.ts.map +1 -1
  216. package/ietf/fetch.js +172 -94
  217. package/ietf/fetch.js.map +1 -1
  218. package/ietf/filter.d.ts +21 -31
  219. package/ietf/filter.d.ts.map +1 -1
  220. package/ietf/filter.js +140 -172
  221. package/ietf/filter.js.map +1 -1
  222. package/ietf/goaway.d.ts +12 -10
  223. package/ietf/goaway.d.ts.map +1 -1
  224. package/ietf/goaway.js +22 -36
  225. package/ietf/goaway.js.map +1 -1
  226. package/ietf/hidden.js +1 -2
  227. package/ietf/hidden.js.map +1 -1
  228. package/ietf/index.d.ts +8 -20
  229. package/ietf/index.d.ts.map +1 -1
  230. package/ietf/index.js +4 -15
  231. package/ietf/index.js.map +1 -1
  232. package/ietf/join.d.ts +7 -0
  233. package/ietf/join.d.ts.map +1 -0
  234. package/ietf/join.js +234 -0
  235. package/ietf/join.js.map +1 -0
  236. package/ietf/message.d.ts +18 -2
  237. package/ietf/message.d.ts.map +1 -1
  238. package/ietf/message.js +60 -41
  239. package/ietf/message.js.map +1 -1
  240. package/ietf/message.test-util.d.ts +6 -0
  241. package/ietf/message.test-util.d.ts.map +1 -0
  242. package/ietf/message.test-util.js +13 -0
  243. package/ietf/message.test-util.js.map +1 -0
  244. package/ietf/namespace.d.ts +19 -5
  245. package/ietf/namespace.d.ts.map +1 -1
  246. package/ietf/namespace.js +78 -27
  247. package/ietf/namespace.js.map +1 -1
  248. package/ietf/object.d.ts +195 -33
  249. package/ietf/object.d.ts.map +1 -1
  250. package/ietf/object.js +405 -179
  251. package/ietf/object.js.map +1 -1
  252. package/ietf/parameters.d.ts +25 -45
  253. package/ietf/parameters.d.ts.map +1 -1
  254. package/ietf/parameters.js +260 -473
  255. package/ietf/parameters.js.map +1 -1
  256. package/ietf/priority.d.ts +17 -2
  257. package/ietf/priority.d.ts.map +1 -1
  258. package/ietf/priority.js +19 -5
  259. package/ietf/priority.js.map +1 -1
  260. package/ietf/properties.d.ts +6 -5
  261. package/ietf/properties.d.ts.map +1 -1
  262. package/ietf/properties.js +78 -49
  263. package/ietf/properties.js.map +1 -1
  264. package/ietf/publish.d.ts +25 -33
  265. package/ietf/publish.d.ts.map +1 -1
  266. package/ietf/publish.js +45 -140
  267. package/ietf/publish.js.map +1 -1
  268. package/ietf/publish_namespace.d.ts +49 -72
  269. package/ietf/publish_namespace.d.ts.map +1 -1
  270. package/ietf/publish_namespace.js +66 -185
  271. package/ietf/publish_namespace.js.map +1 -1
  272. package/ietf/publisher.js +1800 -601
  273. package/ietf/publisher.js.map +1 -1
  274. package/ietf/range.d.ts +2 -0
  275. package/ietf/range.d.ts.map +1 -0
  276. package/ietf/range.js +222 -0
  277. package/ietf/range.js.map +1 -0
  278. package/ietf/request.d.ts +6 -30
  279. package/ietf/request.d.ts.map +1 -1
  280. package/ietf/request.js +41 -79
  281. package/ietf/request.js.map +1 -1
  282. package/ietf/request_stream.d.ts +1 -6
  283. package/ietf/request_stream.d.ts.map +1 -1
  284. package/ietf/request_stream.js +306 -17
  285. package/ietf/request_stream.js.map +1 -1
  286. package/ietf/session.d.ts +41 -0
  287. package/ietf/session.d.ts.map +1 -0
  288. package/ietf/session.js +65 -0
  289. package/ietf/session.js.map +1 -0
  290. package/ietf/setup.d.ts +5 -30
  291. package/ietf/setup.d.ts.map +1 -1
  292. package/ietf/setup.js +6 -118
  293. package/ietf/setup.js.map +1 -1
  294. package/ietf/setup_options.d.ts +31 -0
  295. package/ietf/setup_options.d.ts.map +1 -0
  296. package/ietf/setup_options.js +138 -0
  297. package/ietf/setup_options.js.map +1 -0
  298. package/ietf/solicit.js +4 -15
  299. package/ietf/solicit.js.map +1 -1
  300. package/ietf/subscribe.d.ts +52 -45
  301. package/ietf/subscribe.d.ts.map +1 -1
  302. package/ietf/subscribe.js +118 -240
  303. package/ietf/subscribe.js.map +1 -1
  304. package/ietf/subscribe_namespace.d.ts +16 -79
  305. package/ietf/subscribe_namespace.d.ts.map +1 -1
  306. package/ietf/subscribe_namespace.js +30 -202
  307. package/ietf/subscribe_namespace.js.map +1 -1
  308. package/ietf/subscriber.js +1839 -537
  309. package/ietf/subscriber.js.map +1 -1
  310. package/ietf/token.js +105 -28
  311. package/ietf/token.js.map +1 -1
  312. package/ietf/track.d.ts +27 -24
  313. package/ietf/track.d.ts.map +1 -1
  314. package/ietf/track.js +48 -62
  315. package/ietf/track.js.map +1 -1
  316. package/ietf/version.d.ts +13 -42
  317. package/ietf/version.d.ts.map +1 -1
  318. package/ietf/version.js +22 -49
  319. package/ietf/version.js.map +1 -1
  320. package/implementation.d.ts +2 -0
  321. package/implementation.d.ts.map +1 -0
  322. package/implementation.js +5 -0
  323. package/implementation.js.map +1 -0
  324. package/index.d.ts +34 -19
  325. package/index.d.ts.map +1 -1
  326. package/index.js +19 -7
  327. package/index.js.map +1 -1
  328. package/internal.d.ts +1515 -67
  329. package/internal.d.ts.map +1 -1
  330. package/internal.js +557 -80
  331. package/internal.js.map +1 -1
  332. package/ledger.d.ts +23 -0
  333. package/ledger.d.ts.map +1 -0
  334. package/ledger.js +247 -0
  335. package/ledger.js.map +1 -0
  336. package/listing.d.ts +132 -0
  337. package/listing.d.ts.map +1 -0
  338. package/listing.js +486 -0
  339. package/listing.js.map +1 -0
  340. package/lite/announce.d.ts +127 -66
  341. package/lite/announce.d.ts.map +1 -1
  342. package/lite/announce.js +384 -159
  343. package/lite/announce.js.map +1 -1
  344. package/lite/announce_stream.d.ts +2 -0
  345. package/lite/announce_stream.d.ts.map +1 -0
  346. package/lite/announce_stream.js +92 -0
  347. package/lite/announce_stream.js.map +1 -0
  348. package/lite/answer.d.ts +22 -0
  349. package/lite/answer.d.ts.map +1 -0
  350. package/lite/answer.js +301 -0
  351. package/lite/answer.js.map +1 -0
  352. package/lite/auth.d.ts +45 -0
  353. package/lite/auth.d.ts.map +1 -0
  354. package/lite/auth.js +204 -0
  355. package/lite/auth.js.map +1 -0
  356. package/lite/compat.d.ts +31 -0
  357. package/lite/compat.d.ts.map +1 -0
  358. package/lite/compat.js +86 -0
  359. package/lite/compat.js.map +1 -0
  360. package/lite/connection.d.ts +1 -45
  361. package/lite/connection.d.ts.map +1 -1
  362. package/lite/connection.js +360 -78
  363. package/lite/connection.js.map +1 -1
  364. package/lite/datagram-end.d.ts +26 -0
  365. package/lite/datagram-end.d.ts.map +1 -0
  366. package/lite/datagram-end.js +30 -0
  367. package/lite/datagram-end.js.map +1 -0
  368. package/lite/datagram.d.ts +73 -8
  369. package/lite/datagram.d.ts.map +1 -1
  370. package/lite/datagram.js +144 -10
  371. package/lite/datagram.js.map +1 -1
  372. package/lite/duration.d.ts +6 -0
  373. package/lite/duration.d.ts.map +1 -0
  374. package/lite/duration.js +14 -0
  375. package/lite/duration.js.map +1 -0
  376. package/lite/error.d.ts +9 -0
  377. package/lite/error.d.ts.map +1 -0
  378. package/lite/error.js +24 -0
  379. package/lite/error.js.map +1 -0
  380. package/lite/fills.d.ts +162 -0
  381. package/lite/fills.d.ts.map +1 -0
  382. package/lite/fills.js +486 -0
  383. package/lite/fills.js.map +1 -0
  384. package/lite/fit.d.ts +49 -0
  385. package/lite/fit.d.ts.map +1 -0
  386. package/lite/fit.js +305 -0
  387. package/lite/fit.js.map +1 -0
  388. package/lite/goaway.d.ts +2 -2
  389. package/lite/goaway.d.ts.map +1 -1
  390. package/lite/goaway.js +5 -14
  391. package/lite/goaway.js.map +1 -1
  392. package/lite/group.d.ts +67 -16
  393. package/lite/group.d.ts.map +1 -1
  394. package/lite/group.js +108 -31
  395. package/lite/group.js.map +1 -1
  396. package/lite/identity.d.ts +25 -0
  397. package/lite/identity.d.ts.map +1 -0
  398. package/lite/identity.js +79 -0
  399. package/lite/identity.js.map +1 -0
  400. package/lite/index.d.ts +14 -13
  401. package/lite/index.d.ts.map +1 -1
  402. package/lite/index.js +2 -2
  403. package/lite/index.js.map +1 -1
  404. package/lite/message.d.ts +10 -2
  405. package/lite/message.d.ts.map +1 -1
  406. package/lite/message.js +28 -45
  407. package/lite/message.js.map +1 -1
  408. package/lite/priority.d.ts +9 -2
  409. package/lite/priority.d.ts.map +1 -1
  410. package/lite/priority.js +11 -106
  411. package/lite/priority.js.map +1 -1
  412. package/lite/probe.d.ts +2 -2
  413. package/lite/probe.d.ts.map +1 -1
  414. package/lite/probe.js +9 -1
  415. package/lite/probe.js.map +1 -1
  416. package/lite/publisher.d.ts +10 -1
  417. package/lite/publisher.d.ts.map +1 -1
  418. package/lite/publisher.js +2548 -438
  419. package/lite/publisher.js.map +1 -1
  420. package/lite/routed.d.ts +59 -0
  421. package/lite/routed.d.ts.map +1 -0
  422. package/lite/routed.js +564 -0
  423. package/lite/routed.js.map +1 -0
  424. package/lite/session.d.ts +2 -28
  425. package/lite/session.d.ts.map +1 -1
  426. package/lite/session.js +0 -100
  427. package/lite/session.js.map +1 -1
  428. package/lite/setup.d.ts +32 -5
  429. package/lite/setup.d.ts.map +1 -1
  430. package/lite/setup.js +95 -22
  431. package/lite/setup.js.map +1 -1
  432. package/lite/stream.d.ts +5 -11
  433. package/lite/stream.d.ts.map +1 -1
  434. package/lite/stream.js +5 -2
  435. package/lite/stream.js.map +1 -1
  436. package/lite/subscribe.d.ts +478 -78
  437. package/lite/subscribe.d.ts.map +1 -1
  438. package/lite/subscribe.js +1373 -143
  439. package/lite/subscribe.js.map +1 -1
  440. package/lite/subscriber.d.ts +7 -44
  441. package/lite/subscriber.d.ts.map +1 -1
  442. package/lite/subscriber.js +3290 -516
  443. package/lite/subscriber.js.map +1 -1
  444. package/lite/track.d.ts +27 -12
  445. package/lite/track.d.ts.map +1 -1
  446. package/lite/track.js +116 -38
  447. package/lite/track.js.map +1 -1
  448. package/lite/tracks.d.ts +55 -0
  449. package/lite/tracks.d.ts.map +1 -0
  450. package/lite/tracks.js +114 -0
  451. package/lite/tracks.js.map +1 -0
  452. package/lite/version.d.ts +132 -24
  453. package/lite/version.d.ts.map +1 -1
  454. package/lite/version.js +378 -34
  455. package/lite/version.js.map +1 -1
  456. package/meta.d.ts +77 -0
  457. package/meta.d.ts.map +1 -0
  458. package/meta.js +130 -0
  459. package/meta.js.map +1 -0
  460. package/meta_api.d.ts +7 -0
  461. package/meta_api.d.ts.map +1 -0
  462. package/meta_api.js +7 -0
  463. package/meta_api.js.map +1 -0
  464. package/mint.d.ts +28 -0
  465. package/mint.d.ts.map +1 -0
  466. package/mint.js +66 -0
  467. package/mint.js.map +1 -0
  468. package/open.d.ts +63 -0
  469. package/open.d.ts.map +1 -0
  470. package/open.js +250 -0
  471. package/open.js.map +1 -0
  472. package/origin.d.ts +394 -142
  473. package/origin.d.ts.map +1 -1
  474. package/origin.js +2533 -687
  475. package/origin.js.map +1 -1
  476. package/package.json +8 -13
  477. package/path.d.ts +51 -51
  478. package/path.d.ts.map +1 -1
  479. package/path.js +210 -58
  480. package/path.js.map +1 -1
  481. package/payload.d.ts +33 -0
  482. package/payload.d.ts.map +1 -0
  483. package/payload.js +65 -0
  484. package/payload.js.map +1 -0
  485. package/prefix.d.ts +152 -0
  486. package/prefix.d.ts.map +1 -0
  487. package/prefix.js +349 -0
  488. package/prefix.js.map +1 -0
  489. package/priority.d.ts +8 -0
  490. package/priority.d.ts.map +1 -0
  491. package/priority.js +185 -0
  492. package/priority.js.map +1 -0
  493. package/queue.d.ts +2 -0
  494. package/queue.d.ts.map +1 -0
  495. package/queue.js +46 -0
  496. package/queue.js.map +1 -0
  497. package/ranges.d.ts +36 -0
  498. package/ranges.d.ts.map +1 -0
  499. package/ranges.js +312 -0
  500. package/ranges.js.map +1 -0
  501. package/rescale.d.ts +24 -0
  502. package/rescale.d.ts.map +1 -0
  503. package/rescale.js +39 -0
  504. package/rescale.js.map +1 -0
  505. package/resume.d.ts +55 -0
  506. package/resume.d.ts.map +1 -0
  507. package/resume.js +4173 -0
  508. package/resume.js.map +1 -0
  509. package/resume.test-util.d.ts +2 -0
  510. package/resume.test-util.d.ts.map +1 -0
  511. package/resume.test-util.js +25 -0
  512. package/resume.test-util.js.map +1 -0
  513. package/skips.d.ts +48 -0
  514. package/skips.d.ts.map +1 -0
  515. package/skips.js +182 -0
  516. package/skips.js.map +1 -0
  517. package/stream.d.ts +78 -40
  518. package/stream.d.ts.map +1 -1
  519. package/stream.js +236 -93
  520. package/stream.js.map +1 -1
  521. package/subscription.test-util.d.ts +2 -0
  522. package/subscription.test-util.d.ts.map +1 -0
  523. package/subscription.test-util.js +49 -0
  524. package/subscription.test-util.js.map +1 -0
  525. package/tail.d.ts +23 -14
  526. package/tail.d.ts.map +1 -1
  527. package/tail.js +224 -98
  528. package/tail.js.map +1 -1
  529. package/time.d.ts +41 -102
  530. package/time.d.ts.map +1 -1
  531. package/time.js +129 -92
  532. package/time.js.map +1 -1
  533. package/timed.d.ts +21 -0
  534. package/timed.d.ts.map +1 -0
  535. package/timed.js +2 -0
  536. package/timed.js.map +1 -0
  537. package/track.d.ts +578 -246
  538. package/track.d.ts.map +1 -1
  539. package/track.js +7306 -772
  540. package/track.js.map +1 -1
  541. package/track_api.d.ts +7 -0
  542. package/track_api.d.ts.map +1 -0
  543. package/track_api.js +7 -0
  544. package/track_api.js.map +1 -0
  545. package/util/abort.d.ts +1 -0
  546. package/util/abort.d.ts.map +1 -1
  547. package/util/abort.js +23 -2
  548. package/util/abort.js.map +1 -1
  549. package/util/announce.d.ts +4 -0
  550. package/util/announce.d.ts.map +1 -0
  551. package/util/announce.js +11 -0
  552. package/util/announce.js.map +1 -0
  553. package/util/bigint.d.ts +3 -0
  554. package/util/bigint.d.ts.map +1 -0
  555. package/util/bigint.js +8 -0
  556. package/util/bigint.js.map +1 -0
  557. package/util/change.d.ts +12 -0
  558. package/util/change.d.ts.map +1 -0
  559. package/util/change.js +18 -0
  560. package/util/change.js.map +1 -0
  561. package/util/deadline.d.ts +2 -0
  562. package/util/deadline.d.ts.map +1 -0
  563. package/util/deadline.js +108 -0
  564. package/util/deadline.js.map +1 -0
  565. package/util/decode_error.d.ts +3 -0
  566. package/util/decode_error.d.ts.map +1 -0
  567. package/util/decode_error.js +11 -0
  568. package/util/decode_error.js.map +1 -0
  569. package/util/demand.d.ts +8 -0
  570. package/util/demand.d.ts.map +1 -0
  571. package/util/demand.js +24 -0
  572. package/util/demand.js.map +1 -0
  573. package/util/given_up.d.ts +2 -0
  574. package/util/given_up.d.ts.map +1 -0
  575. package/util/given_up.js +101 -0
  576. package/util/given_up.js.map +1 -0
  577. package/util/hex.d.ts +6 -0
  578. package/util/hex.d.ts.map +1 -1
  579. package/util/hex.js +19 -5
  580. package/util/hex.js.map +1 -1
  581. package/util/key.d.ts +15 -0
  582. package/util/key.d.ts.map +1 -0
  583. package/util/key.js +38 -0
  584. package/util/key.js.map +1 -0
  585. package/util/limits.d.ts +2 -0
  586. package/util/limits.d.ts.map +1 -0
  587. package/util/limits.js +76 -0
  588. package/util/limits.js.map +1 -0
  589. package/util/observed.d.ts +23 -0
  590. package/util/observed.d.ts.map +1 -0
  591. package/util/observed.js +122 -0
  592. package/util/observed.js.map +1 -0
  593. package/util/sorted.d.ts +2 -0
  594. package/util/sorted.d.ts.map +1 -0
  595. package/util/sorted.js +149 -0
  596. package/util/sorted.js.map +1 -0
  597. package/util/timeout.d.ts +2 -1
  598. package/util/timeout.d.ts.map +1 -1
  599. package/util/timeout.js +13 -10
  600. package/util/timeout.js.map +1 -1
  601. package/util/timer.d.ts +2 -0
  602. package/util/timer.d.ts.map +1 -0
  603. package/util/timer.js +19 -0
  604. package/util/timer.js.map +1 -0
  605. package/util/u64.js +0 -1
  606. package/util/utf8.d.ts +2 -0
  607. package/util/utf8.d.ts.map +1 -1
  608. package/util/utf8.js +7 -2
  609. package/util/utf8.js.map +1 -1
  610. package/util/varint.d.ts.map +1 -1
  611. package/util/varint.js +8 -2
  612. package/util/varint.js.map +1 -1
  613. package/util/watch.d.ts +8 -0
  614. package/util/watch.d.ts.map +1 -0
  615. package/util/watch.js +38 -0
  616. package/util/watch.js.map +1 -0
  617. package/util/yield.d.ts +2 -0
  618. package/util/yield.d.ts.map +1 -0
  619. package/util/yield.js +31 -0
  620. package/util/yield.js.map +1 -0
  621. package/varint.d.ts +0 -29
  622. package/varint.d.ts.map +1 -1
  623. package/varint.js +7 -29
  624. package/varint.js.map +1 -1
  625. package/varint_api.d.ts +7 -0
  626. package/varint_api.d.ts.map +1 -0
  627. package/varint_api.js +7 -0
  628. package/varint_api.js.map +1 -0
  629. package/version.d.ts +2 -0
  630. package/version.d.ts.map +1 -0
  631. package/version.js +4 -0
  632. package/version.js.map +1 -0
  633. package/window.d.ts +570 -0
  634. package/window.d.ts.map +1 -0
  635. package/window.js +1677 -0
  636. package/window.js.map +1 -0
  637. package/wire.d.ts +150 -35
  638. package/wire.d.ts.map +1 -1
  639. package/wire.js +27 -1
  640. package/wire.js.map +1 -1
  641. package/connection/established.d.ts +0 -53
  642. package/connection/established.d.ts.map +0 -1
  643. package/connection/established.js +0 -3
  644. package/connection/established.js.map +0 -1
  645. package/ietf/adapter.d.ts +0 -75
  646. package/ietf/adapter.d.ts.map +0 -1
  647. package/ietf/adapter.js +0 -700
  648. package/ietf/adapter.js.map +0 -1
  649. package/lite/datagram_stream.d.ts +0 -8
  650. package/lite/datagram_stream.d.ts.map +0 -1
  651. package/lite/datagram_stream.js +0 -44
  652. package/lite/datagram_stream.js.map +0 -1
  653. package/lite/fetch.d.ts +0 -28
  654. package/lite/fetch.d.ts.map +0 -1
  655. package/lite/fetch.js +0 -79
  656. package/lite/fetch.js.map +0 -1
  657. package/util/log.d.ts +0 -5
  658. package/util/log.d.ts.map +0 -1
  659. package/util/log.js +0 -17
  660. package/util/log.js.map +0 -1
  661. package/zod.d.ts +0 -13
  662. package/zod.d.ts.map +0 -1
  663. package/zod.js +0 -19
  664. package/zod.js.map +0 -1
@@ -1,46 +1,100 @@
1
- /* @ts-self-types="./subscriber.d.ts" */
2
- import { race, Signal } from "@moq/signals";
1
+ import { Duration, yieldNow } from "@moq/clock";
2
+ import { Once, race, Signal } from "@moq/signals";
3
3
  import * as announce from "../announced.js";
4
4
  import * as broadcast from "../broadcast.js";
5
5
  import { BroadcastCache } from "../consume.js";
6
- import { closeError, controlTimeout, error, ProtocolViolation, reason, SessionCode, StreamCode, StreamError, sessionCause, } from "../error.js";
7
- import * as netGroup from "../group.js";
8
- import { Cost, randomHop, routesEqual, stampHops, UNKNOWN_HOP } from "../hop.js";
9
- 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";
10
12
  import * as Path from "../path.js";
11
- import { UnexpectedEnd } from "../stream.js";
13
+ import { receiveFrame, skipPayload } from "../payload.js";
14
+ import { Reader } from "../stream.js";
12
15
  import { Tail } from "../tail.js";
13
- import { Timestamp } from "../time.js";
14
- import { TimeoutError, withTimeout } from "../util/timeout.js";
15
- 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";
16
25
  import { DuplicateTrackAlias, RetiredTrackAlias, TrackAliases } from "./aliases.js";
17
26
  import * as Cluster from "./cluster.js";
18
- import { requestReason, toRequestCode } from "./error.js";
19
- import { Frame, hasFirstObjectBit } from "./object.js";
20
- import { fromWire, toWire } from "./priority.js";
21
- import { PublishDone, PublishError, publishDoneClean } from "./publish.js";
22
- 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";
23
40
  import { RequestError, RequestOk } from "./request.js";
24
- import { joinFilter, Subscribe, SubscribeError, SubscribeOk, Unsubscribe } from "./subscribe.js";
25
- import { PublishBlocked, SubscribeNamespace, SubscribeNamespaceEntry, SubscribeNamespaceEntryDone, SubscribeNamespaceLegacy, SubscribeNamespaceOk, UnsubscribeNamespace, } from "./subscribe_namespace.js";
26
- import { Version } from "./version.js";
27
- // Bound on how long stream-open plus SUBSCRIBE_OK may take. Browsers cap
28
- // concurrent QUIC streams (Chrome ~100); past the cap openBi() silently
29
- // blocks. The timeout turns that into a clear error.
30
- const SUBSCRIBE_OK_TIMEOUT_MS = 10_000;
31
- /** 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. */
32
55
  function sees(filter, path) {
33
- 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
+ }
34
87
  }
35
88
  /**
36
89
  * Handles subscribing to broadcasts using moq-transport protocol.
37
- * Uses the stream-per-request pattern (real bidi streams for v17, virtual for v14-v16).
90
+ * Each request rides its own bidi stream.
38
91
  *
39
92
  * @internal
40
93
  */
41
94
  export class Subscriber {
95
+ #streamSources = new WeakMap();
96
+ #datagramRequests = new WeakMap();
42
97
  #session;
43
- #localClose = false;
44
98
  // The transport, so a request cut off by the session's close ends with the session's
45
99
  // error. Optional for tests that drive a bare session.
46
100
  #quic;
@@ -50,45 +104,90 @@ export class Subscriber {
50
104
  #cluster;
51
105
  // Publisher-chosen aliases used by incoming group streams.
52
106
  #aliases = new TrackAliases();
53
- // Units for each track's object Timestamps, from the TIMESCALE Track Property in
54
- // SUBSCRIBE_OK. A track missing from this map declared no timeline, so the publisher
55
- // opted out of timestamps and its frames are stamped on arrival instead.
56
- #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();
57
117
  // Dedup consumed broadcasts per path: repeat consume() calls share one subscription.
58
118
  #consumes = new BroadcastCache();
59
- // A random Hop ID of this connection's own, written as the first hop of any path that
60
- // names no publisher, so a publisher that reconnects reads as a new one.
61
- #stamp = randomHop();
62
- // Paths with a legacy PUBLISH_NAMESPACE request in flight, reserved synchronously.
63
- // The count below is only taken once the OK is written, and two requests that both
64
- // got past the duplicate check before either attached would both take one.
65
- #legacyRequests = new Set();
66
- // Every announced path, counted by how many live advertisements reference it.
119
+ // Every announced path, with the live advertisements that reference it.
67
120
  //
68
121
  // A peer may advertise one namespace twice on a session: an unsolicited
69
122
  // PUBLISH_NAMESPACE and an inline NAMESPACE answering our own SUBSCRIBE_NAMESPACE are
70
123
  // two messages about one source, which the MoQ Solicit draft requires us to tolerate.
71
- // Counting them is what keeps the second from duplicating the announce and the first
72
- // 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.
73
130
  #announced = new Map();
74
- // 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.
75
136
  #announcedConsumers = new Map();
76
137
  // Whether the peer understands the HIDDEN parameter (MoQ Hidden).
77
138
  #hidden;
78
- /** Marks this subscriber's deliberate local session close. @internal */
79
- close() {
80
- this.#localClose = true;
81
- }
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;
82
149
  /**
83
150
  * Creates a new Subscriber instance.
84
151
  *
85
152
  * @internal
86
153
  */
87
- 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 }, }) {
88
155
  this.#session = session;
156
+ this.#link = link;
89
157
  this.#quic = quic;
158
+ this.#announceSlots = new Slots(limits.announces, { quic, reason: "too many announcements" });
90
159
  this.#cluster = cluster;
91
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);
92
191
  }
93
192
  /**
94
193
  * Whether an advertisement is ours coming back: its hop path already ran through us, so
@@ -102,220 +201,344 @@ export class Subscriber {
102
201
  return advert !== undefined && this.#cluster !== undefined && Cluster.loops(advert, this.#cluster.self);
103
202
  }
104
203
  /**
105
- * The route an advertisement carries; one without a path is free. A path that names no
106
- * 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.
107
206
  */
108
- #route(advert) {
109
- if (advert === undefined)
110
- return { hops: [this.#stamp, UNKNOWN_HOP], cost: Cost.zero };
111
- // A full chain, or a stamp colliding with an entry (a 1-in-2^53 draw), keeps the
112
- // path as sent.
113
- const hops = stampHops(advert.hops, this.#stamp) ?? [...advert.hops];
114
- 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 };
115
210
  }
116
211
  /**
117
- * Gets an announced reader matching `scope`. Paths are relative to the session,
118
- * 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.
119
214
  *
120
215
  * The peer is asked with SUBSCRIBE_NAMESPACE regardless of what it declared, and an
121
216
  * unsolicited PUBLISH_NAMESPACE lands here too, so a peer that only tells and one
122
217
  * that only answers are both discovered.
123
218
  *
124
- * 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
125
220
  * `options.hidden` opts in. The opt-in rides the SUBSCRIBE_NAMESPACE when the peer
126
221
  * understands it (MoQ Hidden); the rule is also applied here, since an unsolicited
127
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.
128
229
  */
129
- announced(scope = Path.Pattern.all(), options) {
130
- // The wire speaks announce interest by prefix.
131
- const prefix = scopeHead(scope);
132
- 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
+ }
133
250
  const announced = new announce.Producer();
134
251
  for (const [active, info] of this.#announced) {
135
252
  if (!sees(filter, active))
136
253
  continue;
137
254
  announced.append({
138
255
  prefix: active,
139
- captures: scopeCaptures(scope, active),
140
- kind: "announced",
256
+ kind: "start",
141
257
  route: info.route,
142
258
  });
143
259
  }
144
260
  this.#announcedConsumers.set(announced, filter);
145
- 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(() => {
146
265
  this.#announcedConsumers.delete(announced);
147
266
  announced.close();
148
267
  });
149
- return announced.consume();
268
+ return consumer;
150
269
  }
151
270
  /**
152
- * Record one more advertisement for a path, telling consumers only when it is the
153
- * 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`).
154
273
  */
155
274
  #attachAnnounce(path, route) {
275
+ const id = this.#nextAdvert++;
156
276
  const existing = this.#announced.get(path);
157
277
  if (existing) {
158
- existing.count += 1;
159
- return;
278
+ existing.adverts.push({ id, route });
279
+ this.#settleAnnounce(path, existing);
280
+ return id;
160
281
  }
161
- 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);
162
288
  console.debug(`announced: broadcast=${path} active=true`);
163
289
  for (const [consumer, filter] of this.#announcedConsumers) {
164
- 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)
165
292
  continue;
166
- const scope = filter.scope;
167
- consumer.append({ prefix: path, captures: scopeCaptures(scope, path), kind: "announced", route });
293
+ consumer.append({ prefix: path, kind: "start", route });
168
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);
169
305
  }
170
306
  /**
171
- * Replace the stored route for a path that is already announced. A no-op when the
172
- * hops and cost did not change; otherwise consumers hear `updated` so a forwarder
173
- * can reprice without retracting.
174
- *
175
- * A new first hop is a new publisher: holders keep their broadcast to drain, but the
176
- * 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.
177
310
  */
178
- #updateAnnounce(path, route) {
179
- const existing = this.#announced.get(path);
180
- 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))
181
319
  return;
182
- if (existing.route.hops[0] !== route.hops[0])
183
- this.#consumes.evict(path);
184
320
  existing.route = route;
321
+ this.#consumes.announce(path, existing, route, false);
185
322
  console.debug(`announced: broadcast=${path} rerouted`);
186
323
  for (const [consumer, filter] of this.#announcedConsumers) {
187
- 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)
188
326
  continue;
189
- const scope = filter.scope;
190
- consumer.append({ prefix: path, captures: scopeCaptures(scope, path), kind: "updated", route });
327
+ consumer.append({ prefix: path, kind: "update", route });
191
328
  }
192
329
  }
193
330
  /**
194
- * 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.
195
332
  */
196
- #detachAnnounce(path) {
333
+ #detachAnnounce(path, id, ended) {
197
334
  const existing = this.#announced.get(path);
198
- if (existing === undefined)
335
+ const index = existing?.adverts.findIndex((advert) => advert.id === id) ?? -1;
336
+ if (existing === undefined || index === -1)
199
337
  return;
200
- if (existing.count > 1) {
201
- 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);
202
342
  return;
203
343
  }
204
344
  this.#announced.delete(path);
205
345
  // The path is gone, so stop sharing its broadcast: a holder outliving the publisher
206
346
  // would otherwise hand the dead generation to whoever consumes the path next.
207
- this.#consumes.evict(path);
347
+ this.#consumes.withdraw(path, existing);
208
348
  console.debug(`announced: broadcast=${path} active=false`);
209
349
  for (const [consumer, filter] of this.#announcedConsumers) {
210
- 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)
211
352
  continue;
212
- const scope = filter.scope;
213
- try {
214
- consumer.append({
215
- prefix: path,
216
- captures: scopeCaptures(scope, path),
217
- kind: "retracted",
218
- route: existing.route,
219
- });
220
- }
221
- catch {
222
- // Consumer already closed, will be cleaned up
223
- }
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
+ });
224
359
  }
225
360
  }
226
- 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) {
227
373
  const version = this.#session.version;
228
- // Suffixes live on this stream, so a repeat is recognized as an update to the
229
- // advertisement rather than a second one, which would leak the count.
230
- const live = new Set();
231
- // Set once the teardown below has given back everything this stream held. The read
232
- // loop is not awaited when the local consumer closes first, and closing the stream
233
- // cancels the transport without discarding what the reader already buffered, so a
234
- // fully buffered entry can still decode afterwards. Attaching one then would take a
235
- // 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.
236
384
  let released = false;
237
- // v14/v15: SubscribeNamespace on control stream (via adapter virtual stream)
238
- // v16+: SubscribeNamespace on its own real bidi stream
239
- 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
+ }
240
419
  if (requestId === undefined)
241
420
  return;
242
421
  try {
243
- // v16: use a real bidi stream (not virtual control stream)
244
- const stream = version === Version.DRAFT_16 && this.#session.openNativeBi
245
- ? await this.#session.openNativeBi()
246
- : await this.#session.openBi();
247
- try {
248
- // Draft-18+ uses SUBSCRIBE_NAMESPACE (0x50); earlier drafts use the
249
- // legacy 0x11 message with a Subscribe Options field.
250
- if (version === Version.DRAFT_14 ||
251
- version === Version.DRAFT_15 ||
252
- version === Version.DRAFT_16 ||
253
- version === Version.DRAFT_17) {
254
- await stream.writer.u53(SubscribeNamespaceLegacy.id);
255
- await new SubscribeNamespaceLegacy({ namespace: prefix, requestId, hidden }).encode(stream.writer, version);
256
- }
257
- else {
258
- await stream.writer.u53(SubscribeNamespace.id);
259
- await new SubscribeNamespace({ namespace: prefix, requestId, hidden }).encode(stream.writer, version);
260
- }
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);
261
427
  console.debug(`subscribe_namespace written: requestId=${requestId}`);
262
- // Read response
263
- const respTypeId = await stream.reader.u53();
264
- if (respTypeId === RequestOk.id) {
265
- await RequestOk.decode(stream.reader, version);
266
- }
267
- else if (respTypeId === SubscribeNamespaceOk.id) {
268
- // v14: SubscribeNamespaceOk
269
- const size = await stream.reader.u16();
270
- await stream.reader.read(size);
271
- }
272
- else {
273
- 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;
274
473
  }
474
+ let initial = answered;
275
475
  // Loop reading Namespace/NamespaceDone entries
276
476
  const readLoop = (async () => {
277
477
  for (;;) {
278
- const done = await stream.reader.done();
279
- if (done)
478
+ if (initial === 0)
479
+ announced.synced();
480
+ const framed = await request.next();
481
+ // Ending: `end` drains the rest.
482
+ if (released)
280
483
  break;
281
- 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
+ }
282
494
  if (msgType === SubscribeNamespaceEntry.id) {
283
- 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;
284
501
  if (released)
285
502
  break;
286
- 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, {});
287
512
  // A repeat updates the advertisement in place, so one that now
288
513
  // loops back through us has taken a route we can't subscribe
289
514
  // over: the path is gone even though the message says active.
290
- if (this.#reflected(entry.cluster)) {
515
+ if (this.#reflected(params.cluster)) {
291
516
  console.debug(`dropping reflected namespace: broadcast=${path}`);
292
- if (live.delete(path))
293
- this.#detachAnnounce(path);
517
+ if (held?.id !== undefined)
518
+ this.#detachAnnounce(path, held.id, false);
519
+ live.set(path, {});
294
520
  continue;
295
521
  }
296
- // A repeat replaces the advertisement in place: HOP_PATH / ROUTE_COST
297
- // can change without a NAMESPACE_DONE. Only the first is a new path.
298
- const route = this.#route(entry.cluster);
299
- if (live.has(path)) {
300
- 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);
301
526
  }
302
527
  else {
303
- live.add(path);
304
- this.#attachAnnounce(path, route);
528
+ live.set(path, { id: this.#attachAnnounce(path, route) });
305
529
  }
306
530
  }
307
531
  else if (msgType === SubscribeNamespaceEntryDone.id) {
308
- const entry = await SubscribeNamespaceEntryDone.decode(stream.reader, version);
532
+ const entry = await SubscribeNamespaceEntryDone.decode(framed.reader, version);
309
533
  if (released)
310
534
  break;
311
- const path = Path.join(prefix, entry.suffix);
312
- if (live.delete(path)) {
313
- this.#detachAnnounce(path);
314
- }
315
- }
316
- else if (msgType === PublishBlocked.id && version === Version.DRAFT_17) {
317
- const blocked = await PublishBlocked.decode(stream.reader, version);
318
- 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);
319
542
  }
320
543
  else {
321
544
  throw new Error(`unexpected message on subscribe_namespace stream: 0x${msgType.toString(16)}`);
@@ -324,42 +547,21 @@ export class Subscriber {
324
547
  })();
325
548
  // The race below can end through the consumer's close while a message that
326
549
  // already arrived is still decoding, which leaves the loop with nothing
327
- // awaiting it: a violation decoded after that would land nowhere, and its
328
- // rejection would go unhandled. Idempotent with the catch below, which is
329
- // what runs when the loop is the one that ends the race.
330
- readLoop.catch((err) => {
331
- if (err instanceof ProtocolViolation)
332
- this.#session.close();
333
- });
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));
334
556
  // Wait for either the read loop or the announced to close
335
557
  await race([readLoop, announced.closed]);
336
- // For v14/v15: send UnsubscribeNamespace before closing
337
- if (version === Version.DRAFT_14 || version === Version.DRAFT_15) {
338
- try {
339
- await stream.writer.u53(UnsubscribeNamespace.id);
340
- const unsub = new UnsubscribeNamespace({ requestId });
341
- await unsub.encode(stream.writer, version);
342
- }
343
- catch {
344
- // Stream might already be closed
345
- }
346
- }
347
- stream.close();
348
- }
349
- catch (err) {
350
- stream.abort(error(err));
351
- throw err;
352
- }
558
+ await end(readLoop);
559
+ };
560
+ await request.serve(run());
353
561
  }
354
562
  catch (err) {
355
563
  const e = error(err);
356
564
  console.warn(`subscribe_namespace error: ${reason(e)}`);
357
- // An advertisement is decoded here rather than in the session dispatch, so this
358
- // is the only place a malformed one surfaces. The cluster draft requires closing
359
- // the session over those, and the stream alone is not enough: the peer would
360
- // just repeat it on the next SUBSCRIBE_NAMESPACE.
361
- if (e instanceof ProtocolViolation)
362
- this.#session.close();
363
565
  // Abort the stream rather than letting the caller's `finally` close it cleanly.
364
566
  // A rejected namespace subscription is a failure, and a consumer that can't tell
365
567
  // it from "nothing is published under this prefix" waits forever on a broadcast
@@ -367,55 +569,113 @@ export class Subscriber {
367
569
  announced.close(e);
368
570
  }
369
571
  finally {
370
- // The stream owns every advertisement it carried, so release them however it
371
- // ends: a clean close, a decode error, or the peer resetting it. Without this
372
- // each namespace keeps its count and the source never detaches, which would
373
- // pin the path for the session even after the other source withdrew.
374
- released = true;
375
- for (const path of live) {
376
- this.#detachAnnounce(path);
377
- }
378
- live.clear();
572
+ release();
379
573
  }
380
574
  }
381
575
  /**
382
576
  * Consumes a broadcast from the connection.
383
577
  *
384
- * 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
385
579
  * broadcast (and one upstream subscription). The shared broadcast closes once every caller has
386
580
  * closed its handle, so callers close normally.
387
581
  */
388
582
  consume(path) {
389
- 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);
390
585
  }
391
- #createConsume(path) {
392
- // moq-transport has no one-shot group fetch; ConsumeBroadcast rejects it. Track info
393
- // is resolved by the subscribe path (the inherited resolveTrackInfo).
586
+ #createConsume(path, identity) {
394
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());
395
590
  void (async () => {
396
591
  for (;;) {
397
592
  const request = await wireOf(consumer).requested();
398
593
  if (!request)
399
594
  break;
400
- void this.#runSubscribe(path, request);
595
+ this.#streamSources.set(request, consumer);
596
+ void this.#runSubscribe(path, request, identity.validity?.signal);
401
597
  }
402
598
  })();
403
- 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
+ }
404
625
  }
405
- // 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
406
627
  // error. A still-open transport, such as a GOAWAY drain, has no peer code yet,
407
- // 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.
408
629
  async #closedSession() {
630
+ const closed = () => new StreamError(StreamCode.SessionClosed, { message: "session closed" });
409
631
  const quic = this.#quic;
410
632
  if (!quic)
411
- return new Error("session closed");
633
+ return closed();
412
634
  return Promise.race([
413
635
  closeError(quic),
414
- new Promise((resolve) => queueMicrotask(() => resolve(new Error("session closed")))),
636
+ new Promise((resolve) => queueMicrotask(() => resolve(closed()))),
415
637
  ]);
416
638
  }
417
- async #runSubscribe(broadcast, request) {
418
- 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
+ }
419
679
  if (requestId === undefined) {
420
680
  request.reject(await this.#closedSession());
421
681
  return;
@@ -423,100 +683,138 @@ export class Subscriber {
423
683
  console.debug(`subscribe start: id=${requestId} broadcast=${broadcast} track=${request.name}`);
424
684
  // Keep the request pending until SUBSCRIBE_OK supplies immutable track metadata.
425
685
  // Group streams already wait on the alias, so early data stays behind this response.
426
- const producer = hooks.pendingTrackProducer(request);
427
- const subscription = { track: producer, tail: new Tail() };
428
- // Open the stream and wait for SUBSCRIBE_OK under a timeout. State
429
- // flows back via `state` so the timeout path can clean up the stream
430
- // and any registration if setup eventually finishes.
431
- const state = {};
432
- 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);
433
692
  // The publisher can be serving before it answers, so waiting only on the response
434
693
  // would miss the local side going away and leave it serving a track nobody reads.
435
694
  // Demand returning before we commit is not abandonment, matching the serving loop.
695
+ const demand = request.demand();
436
696
  const waitAbandoned = async () => {
437
- // An info-only lookup attaches no subscriber yet still waits on SUBSCRIBE_OK for
438
- // the track info, so only demand that arrived and then left is abandonment.
439
- while (!producer.used.peek() && producer.closed.peek() === undefined) {
440
- await Signal.race(producer.used, producer.closed);
441
- }
442
- for (;;) {
443
- await producer.unused();
444
- if (producer.closed.peek() !== undefined || !producer.used.peek())
445
- return null;
446
- }
697
+ await demandAbandoned(demand);
698
+ return null;
447
699
  };
448
700
  let stream;
701
+ let subscription;
702
+ let binding;
449
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");
450
707
  try {
451
- const result = await race([
452
- withTimeout(setup, SUBSCRIBE_OK_TIMEOUT_MS, `subscribe timed out after ${SUBSCRIBE_OK_TIMEOUT_MS}ms waiting for SUBSCRIBE_OK (browser stream limit reached?)`),
453
- waitAbandoned(),
454
- ]);
455
- if (result === null)
456
- throw new Error("subscribe abandoned before it was accepted");
457
- stream = result.stream;
458
- 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
+ }
459
724
  console.debug(`subscribe ok: id=${requestId} broadcast=${broadcast} track=${request.name}`);
460
725
  }
461
726
  catch (err) {
727
+ // A violation on the stream already closed the session through it.
462
728
  // A control request that timed out is not late content, so it carries its own code.
463
- const e = err instanceof TimeoutError ? controlTimeout(err) : await sessionCause(this.#quic, err);
464
- 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);
465
735
  console.warn(`subscribe error: id=${requestId} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);
466
736
  // Runs now for whatever is already open, and again if `setup` settles late.
467
737
  // Retirement is repeated because a late SUBSCRIBE_OK can register an alias after
468
- // the first pass; the stream is torn down once.
469
- let torn = false;
470
- const cleanup = async (afterSetup) => {
471
- state.cancelled = true;
472
- if (state.registeredAlias !== undefined && this.#aliases.retire(state.registeredAlias, subscription)) {
473
- this.#timescales.delete(state.registeredAlias);
474
- }
475
- if (!state.stream || torn)
476
- return;
477
- // A SUBSCRIBE still being written must not be torn down from here. Aborting a
478
- // Web Stream waits for the in-flight write, so the request can still reach the
479
- // peer while the abort destroys the stream we would have cancelled on. Setup
480
- // unwinds on the cancelled flag once that write lands, and its pass below has
481
- // the finished picture.
482
- if (!state.sent && !afterSetup)
483
- return;
484
- torn = true;
485
- // Once the SUBSCRIBE is out the publisher may be serving, whether or not it has
486
- // answered yet: data streams are independent of the request stream. Aborting says
487
- // nothing on v14-16, where the request rides a virtual stream whose reset is
488
- // local, so the UNSUBSCRIBE has to go out explicitly.
489
- if (state.sent && !state.rejected)
490
- await this.#cancelSubscribe(state.stream, requestId);
491
- 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);
492
757
  };
493
758
  // Tear down what is already open rather than waiting on `setup`. A peer that
494
759
  // opened the stream and then went quiet never settles it, and deferring would
495
- // leave the request outstanding for the life of the session -- which is the
496
- // timeout case, not a rare one.
497
- void cleanup(false);
498
- setup.then(() => cleanup(true), () => cleanup(true));
760
+ // leave the request outstanding for the life of the session.
761
+ cleanup();
762
+ setup.then(cleanup, cleanup);
499
763
  return;
500
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();
501
771
  try {
502
- // Which terminal fired decides whether we owe the publisher a cancellation, so
503
- // 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.
504
777
  const publisherEnded = Symbol("publisher");
505
778
  const localEnded = Symbol("local");
779
+ const revokedEnded = Symbol("revoked");
506
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();
507
799
  // Terminal conditions settle at most once (PublishDone, track close = local
508
- // 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);
509
803
  const done = race([
510
- this.#runPublishDone(stream, subscription).then(() => publisherEnded),
511
- producer.closed.then(() => localEnded),
804
+ this.#runPublishDone(stream, subscription, broadcast, unanswered).then(() => publisherEnded),
805
+ hooks.trackReleased(producer).then(() => localEnded),
806
+ revoked,
512
807
  ]);
808
+ const stopped = Promise.withResolvers();
809
+ const updates = this.#runUpdates(stream, requestId, producer, priority, unanswered, race([done, stopped.promise]));
513
810
  // Serve until a terminal condition fires or the last local subscriber leaves. The unused
514
811
  // wake is level-triggered: re-check demand so a subscriber that returns before we tear
515
812
  // down resumes on the same stream.
516
813
  let terminal = localEnded;
814
+ const demand = producer.demand();
517
815
  for (;;) {
518
- const reason = await race([done, producer.unused().then(() => idle)]);
519
- 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())
520
818
  continue;
521
819
  terminal = reason;
522
820
  break;
@@ -525,25 +823,351 @@ export class Subscriber {
525
823
  // reopens the window the demand re-check above just closed, and a subscriber that
526
824
  // returned during it would be closed by this line. The lite subscriber closes
527
825
  // straight out of its loop for the same reason.
528
- producer.close();
529
- // The publisher already ended the request, so there is nothing to cancel. Sending
530
- // UNSUBSCRIBE here would name a request it has already torn down.
531
- if (terminal !== publisherEnded)
532
- 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;
533
843
  stream.close();
534
844
  console.debug(`subscribe close: id=${requestId} broadcast=${broadcast} track=${request.name}`);
535
845
  }
536
846
  catch (err) {
847
+ stream.abort(err);
537
848
  const e = await sessionCause(this.#quic, err);
538
- producer.close(this.#localClose ? undefined : e);
539
- stream.abort(e);
849
+ if (known)
850
+ hooks.refuseLive(producer, known.edge, e);
851
+ else
852
+ hooks.abortTrack(producer, e);
540
853
  console.warn(`subscribe error: id=${requestId} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);
541
854
  }
542
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?.();
543
875
  // Only the owner tears down the alias metadata: a later subscription may have
544
876
  // reclaimed the alias and installed its own timescale.
545
- if (this.#aliases.retire(trackAlias, subscription))
546
- 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);
547
1171
  }
548
1172
  }
549
1173
  /**
@@ -555,124 +1179,384 @@ export class Subscriber {
555
1179
  * is only a hint: a peer may send 0 regardless, so 0 waits out the grace. A request
556
1180
  * stream that FINs without PUBLISH_DONE is a protocol violation.
557
1181
  */
558
- async #runPublishDone(stream, subscription) {
1182
+ async #runPublishDone(stream, subscription, broadcast, unanswered) {
559
1183
  const version = this.#session.version;
560
- if (await stream.reader.done())
561
- throw new ProtocolViolation("subscribe stream ended without PUBLISH_DONE");
562
- const typeId = await stream.reader.u53();
563
- if (typeId !== PublishDone.id) {
564
- 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
+ });
565
1221
  }
566
- const done = await PublishDone.decode(stream.reader, version);
567
1222
  if (!publishDoneClean(done.statusCode, version)) {
568
1223
  throw new Error(`publish done: status=0x${done.statusCode.toString(16)} reason=${done.reasonPhrase}`);
569
1224
  }
570
1225
  const count = done.streamCount;
571
- const { tail, track } = subscription;
1226
+ const { tail, track, join } = subscription;
572
1227
  const complete = () => count > 0n && BigInt(tail.streams) >= count;
573
- 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();
574
1244
  }
575
1245
  /**
576
- * Tell the publisher to stop serving a subscription we are walking away from.
577
- *
578
- * v14-16 cancel with UNSUBSCRIBE (draft-16 section 9.12), which is what lets the
579
- * publisher destroy the subscription (section 5.1.1); v17+ removed the message and
580
- * rely on the stream reset instead. Every path that abandons an Established
581
- * subscription goes through here, because those versions carry the request over a
582
- * 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.
583
1250
  */
584
- async #cancelSubscribe(stream, requestId) {
1251
+ async #runUpdates(stream, requestId, producer, sent, unanswered, done) {
585
1252
  const version = this.#session.version;
586
- 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)
587
1322
  return;
1323
+ const version = this.#session.version;
1324
+ let request;
588
1325
  try {
589
- await stream.writer.u53(Unsubscribe.id);
590
- 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();
591
1375
  }
592
- catch {
593
- // 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);
594
1391
  }
595
1392
  }
596
1393
  // Opens the subscribe stream, sends SUBSCRIBE, and reads the response.
597
1394
  // `state` is populated as soon as the stream opens and again when the
598
- // 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,
599
1396
  // even before this promise settles.
600
- async #openSubscribe(state, broadcast, request, subscription, requestId) {
1397
+ async #openSubscribe(state, broadcast, request, requestId, deadline, known) {
601
1398
  const version = this.#session.version;
602
- state.stream = await this.#session.openBi();
603
- // The timeout can fire while the open is still in flight, in which case cleanup ran
604
- // with nothing to release. Bail now that the stream is recorded, so settling this
605
- // promise hands it back to be torn down.
606
- 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)
607
1404
  throw new Error("subscribe cancelled before it was sent");
608
- 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);
609
1411
  const msg = new Subscribe({
610
1412
  requestId,
611
1413
  trackNamespace: broadcast,
612
1414
  trackName: request.name,
1415
+ // Read now, since a subscriber can join while the stream opened. Updates follow it.
613
1416
  subscriberPriority: toWire(request.priority),
614
- // No fill is requested: the fill's fetch stream and the live subscription split
615
- // the group across two streams, and this subscriber does not reassemble them into
616
- // one group yet. A lenient publisher (like ours) replays the whole in-range group
617
- // on the subscription instead; a strict one only delivers from the next published
618
- // object, and that mid-group stream is dropped, degrading the join to the next
619
- // group boundary.
620
- 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),
621
1423
  });
622
- await msg.encode(state.stream.writer, version);
623
- state.sent = true;
624
- // The caller may have given up while that write was in flight. It deliberately left
625
- // the stream alone, so unwind here and let its cleanup send the cancellation now that
626
- // the SUBSCRIBE has actually reached the peer.
627
- 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)
628
1434
  throw new Error("subscribe cancelled while it was being sent");
629
1435
  console.debug(`subscribe written: id=${requestId} broadcast=${broadcast} track=${request.name}`);
630
- const respTypeId = await state.stream.reader.u53();
631
- if (respTypeId !== SubscribeOk.id) {
632
- 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;
633
1441
  try {
634
- if (respTypeId === RequestError.id) {
635
- const err = version === Version.DRAFT_14
636
- ? await SubscribeError.decode(state.stream.reader, version)
637
- : await RequestError.decode(state.stream.reader, version);
638
- 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;
639
1446
  }
640
1447
  }
641
1448
  catch {
642
1449
  // Decoding error response failed, use default message
643
1450
  }
644
- state.rejected = true;
645
- 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);
646
1454
  }
647
- const ok = await SubscribeOk.decode(state.stream.reader, version);
648
- if (state.cancelled)
1455
+ const ok = await SubscribeOk.decode(response.reader, version);
1456
+ if (cancelled.aborted)
649
1457
  throw new Error("subscribe cancelled before acceptance");
650
- 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);
651
1537
  try {
652
- this.#aliases.set(ok.trackAlias, subscription, { broadcast, name: request.name });
1538
+ this.#aliases.set(ok.trackAlias, binding, { broadcast, name: request.name });
653
1539
  const timescale = ok.properties.timescale;
654
1540
  if (timescale !== undefined) {
655
- this.#timescales.set(ok.trackAlias, timescale);
1541
+ this.#timing.set(ok.trackAlias, timescale);
656
1542
  }
657
1543
  }
658
1544
  catch (err) {
659
1545
  // Only one alias naming two different tracks is the session's problem. A publisher
660
1546
  // sharing an alias between subscriptions to one track is allowed to do that, and
661
1547
  // disconnecting over it would drop every other broadcast on the session.
662
- if (err instanceof DuplicateTrackAlias) {
663
- // Send the violation before the session's own close sends a clean code.
664
- try {
665
- this.#quic?.close({ closeCode: SessionCode.ProtocolViolation, reason: err.message });
666
- }
667
- catch {
668
- // Already closed.
669
- }
670
- this.#session.close();
671
- }
1548
+ if (err instanceof DuplicateTrackAlias)
1549
+ this.#fail(SessionCode.ProtocolViolation, err.message);
672
1550
  throw err;
673
1551
  }
674
1552
  state.registeredAlias = ok.trackAlias;
675
- 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
+ };
676
1560
  }
677
1561
  /**
678
1562
  * Handles an incoming PUBLISH_NAMESPACE on a bidi stream.
@@ -680,108 +1564,82 @@ export class Subscriber {
680
1564
  *
681
1565
  * @internal
682
1566
  */
683
- 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
+ }
684
1576
  const version = this.#session.version;
685
1577
  const path = msg.trackNamespace;
686
1578
  // A path that already ran through us looped back. Refuse it rather than holding an
687
1579
  // advertisement we could never subscribe through. The peer knows our Hop ID, so a
688
1580
  // conforming one never offers it; 0 as the retry interval says not to come back.
689
- if (this.#reflected(msg.cluster)) {
1581
+ if (this.#reflected(msg.params.cluster)) {
690
1582
  console.debug(`dropping reflected publish_namespace: broadcast=${path}`);
691
- await stream.writer.u53(RequestError.id);
692
- await new RequestError({
693
- requestId: msg.requestId,
694
- errorCode: toRequestCode("uninterested", "publish_namespace", version),
1583
+ await request.refuse("publish_namespace", {
1584
+ condition: "uninterested",
695
1585
  reasonPhrase: "route loops back",
696
- }).encode(stream.writer, version);
697
- stream.close();
698
- return;
699
- }
700
- // Draft-14/15 key their namespace-scoped messages by name, not request ID, so the
701
- // adapter can hold only one request per namespace: a second would overwrite the
702
- // first, and the withdrawals would then close the wrong stream and fail to find
703
- // the other. Nothing is lost by refusing it, because the case that makes a second
704
- // reference legitimate (an inline NAMESPACE for a path a PUBLISH_NAMESPACE already
705
- // carried) needs a message those drafts do not have.
706
- const legacy = version === Version.DRAFT_14 || version === Version.DRAFT_15;
707
- if (legacy && (this.#announced.has(path) || this.#legacyRequests.has(path))) {
708
- console.warn("duplicate PublishNamespace");
709
- // No draft registers a code for a duplicate, and this refusal is a draft-14/15
710
- // implementation limit, which is what INTERNAL_ERROR describes.
711
- const errorCode = toRequestCode("internal", "publish_namespace", version);
712
- if (version === Version.DRAFT_14) {
713
- await stream.writer.u53(PublishNamespaceError.id);
714
- await new PublishNamespaceError({
715
- requestId: msg.requestId,
716
- errorCode,
717
- reasonPhrase: "duplicate namespace",
718
- }).encode(stream.writer, version);
719
- }
720
- else {
721
- await stream.writer.u53(RequestError.id);
722
- await new RequestError({
723
- requestId: msg.requestId,
724
- errorCode,
725
- reasonPhrase: "duplicate namespace",
726
- }).encode(stream.writer, version);
727
- }
728
- stream.close();
1586
+ });
729
1587
  return;
730
1588
  }
731
- // Everywhere else a path this session already knows is not refused: the same
732
- // namespace can reach us twice, and the count is what tells the second apart from
733
- // news. This request owns exactly one of those references and gives it back when
734
- // the stream ends.
735
- if (legacy)
736
- this.#legacyRequests.add(path);
737
- 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;
738
1598
  try {
739
1599
  // Send OK first. This must complete before notifying consumers,
740
- // because consumers may trigger Subscribe writes that would
741
- // interleave with our OK on the control stream.
742
- if (version === Version.DRAFT_14) {
743
- await stream.writer.u53(PublishNamespaceOk.id);
744
- const ok = new PublishNamespaceOk({ requestId: msg.requestId });
745
- await ok.encode(stream.writer, version);
746
- }
747
- else {
748
- await stream.writer.u53(RequestOk.id);
749
- const ok = new RequestOk({
750
- requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined,
751
- });
752
- await ok.encode(stream.writer, version);
753
- }
1600
+ // because consumers may trigger Subscribe writes.
1601
+ await Message.write(request.writer, RequestOk.id, new RequestOk(), version);
754
1602
  // Only now is the advertisement ours to announce, for the reason above: a
755
1603
  // consumer reacting with a SUBSCRIBE must not interleave with that OK.
756
- attached = true;
757
- this.#attachAnnounce(path, this.#route(msg.cluster));
1604
+ attached = this.#attachAnnounce(path, this.#route(msg.params));
758
1605
  // An advertisement is updated in place with REQUEST_UPDATE on the stream that
759
1606
  // already carries it, so read until the stream ends rather than waiting on the
760
1607
  // close. Nothing else would deliver a re-parented route. What the peer holds
761
1608
  // is kept current, since an update carries only what changed.
762
- let held = msg.cluster;
763
- const done = version === Version.DRAFT_16 || legacy;
1609
+ let held = msg.params.cluster;
764
1610
  for (;;) {
765
- // Drafts 17+ withdraw by resetting the request with CANCELLED, which ends it like a
766
- // FIN. Any other reset is a failure.
767
- const ended = await stream.reader.done().catch((err) => {
768
- if (!done && err instanceof StreamError && err.code === StreamCode.Cancel)
769
- return true;
770
- throw err;
771
- });
772
- if (ended)
773
- break;
774
- const typeId = await stream.reader.u53();
775
- if (done && typeId === PublishNamespaceDone.id) {
776
- 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;
777
1616
  break;
778
1617
  }
779
1618
  // A repeated PUBLISH_NAMESPACE lands here too: a second request on the
780
1619
  // stream is the base draft's duplicate request ID.
781
- if (typeId !== PublishNamespaceUpdate.id) {
782
- 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);
783
1626
  }
784
- 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);
785
1643
  // The parameters exist only on a session that negotiated the extension;
786
1644
  // anywhere else they are the peer's violation.
787
1645
  if (held === undefined) {
@@ -798,34 +1656,31 @@ export class Subscriber {
798
1656
  // advertisement's only channel, so a later clean path arrives here or
799
1657
  // nowhere.
800
1658
  if (this.#reflected(held)) {
801
- if (attached) {
802
- attached = false;
1659
+ if (attached !== undefined) {
803
1660
  console.debug(`publish_namespace now loops back, detaching: broadcast=${path}`);
804
- this.#detachAnnounce(path);
1661
+ this.#detachAnnounce(path, attached, false);
1662
+ attached = undefined;
805
1663
  }
806
1664
  }
807
- else if (!attached) {
1665
+ else if (attached === undefined) {
808
1666
  // Re-attach: a clean path replaced the reflected one we detached from.
809
- attached = true;
810
- this.#attachAnnounce(path, this.#route(held));
1667
+ attached = this.#attachAnnounce(path, this.#route({ cluster: held }));
811
1668
  }
812
1669
  else {
813
- this.#updateAnnounce(path, this.#route(held));
1670
+ this.#updateAnnounce(path, attached, this.#route({ cluster: held }));
814
1671
  }
815
1672
  // Nothing here can fail to apply, so every update is acknowledged. A leaf
816
1673
  // routes nothing, so a repricing changes nothing it holds; consumers still
817
1674
  // hear the new route so a forwarder can reprice.
818
- await stream.writer.u53(RequestOk.id);
819
- await new RequestOk({}).encode(stream.writer, version);
1675
+ await Message.write(request.writer, RequestOk.id, new RequestOk(), version);
820
1676
  }
821
1677
  }
822
1678
  finally {
823
- if (legacy)
824
- this.#legacyRequests.delete(path);
1679
+ this.#announceSlots.release();
825
1680
  // Give back exactly what was taken: a request that never got its OK out never
826
1681
  // referenced the path, and retracting there would drop someone else's count.
827
- if (attached) {
828
- this.#detachAnnounce(path);
1682
+ if (attached !== undefined) {
1683
+ this.#detachAnnounce(path, attached, withdrawn);
829
1684
  }
830
1685
  }
831
1686
  }
@@ -835,33 +1690,19 @@ export class Subscriber {
835
1690
  *
836
1691
  * @internal
837
1692
  */
838
- async runPublish(msg, stream) {
839
- const version = this.#session.version;
1693
+ runPublish(msg, stream) {
1694
+ const request = new RequestStream(stream, this.#session, this.#quic);
840
1695
  // We decline the method itself rather than this particular track, which would be
841
1696
  // UNINTERESTED.
842
1697
  //
843
1698
  // The alias the message carries is deliberately not recorded. Nothing will ever bind
844
1699
  // it, and a rejected request has no lifetime of ours to hang the cleanup on.
845
- const errorCode = toRequestCode("not_supported", "publish", version);
846
- if (version === Version.DRAFT_14) {
847
- await stream.writer.u53(PublishError.id);
848
- const err = new PublishError({
849
- requestId: msg.requestId,
850
- errorCode,
851
- reasonPhrase: "publish not supported",
852
- });
853
- await err.encode(stream.writer, version);
854
- }
855
- else {
856
- await stream.writer.u53(RequestError.id);
857
- const err = new RequestError({
858
- requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined,
859
- errorCode,
1700
+ return request.serve(Namespace.reserved(msg.trackNamespace, this.#session.version)
1701
+ ? refuseReserved(request)
1702
+ : request.refuse("publish", {
1703
+ condition: "not_supported",
860
1704
  reasonPhrase: "publish not supported",
861
- });
862
- await err.encode(stream.writer, version);
863
- }
864
- stream.close();
1705
+ }));
865
1706
  }
866
1707
  /**
867
1708
  * Handles an ObjectStream message (group + frames on uni stream).
@@ -869,15 +1710,17 @@ export class Subscriber {
869
1710
  * @internal
870
1711
  */
871
1712
  async handleGroup(group, stream) {
872
- if (group.subGroupId !== 0) {
1713
+ if (group.subGroupId !== 0n) {
873
1714
  throw new Error("subgroups are not supported");
874
1715
  }
875
- let subscription;
1716
+ let binding;
876
1717
  try {
877
1718
  // The control message establishing this alias can arrive after the data stream.
878
- subscription = await this.#aliases.get(group.trackAlias);
1719
+ binding = await this.#aliases.get(group.trackAlias);
879
1720
  }
880
1721
  catch (err) {
1722
+ if (err instanceof ProtocolViolation)
1723
+ this.#fail(err.code, err.message);
881
1724
  const e = await sessionCause(this.#quic, err);
882
1725
  // Ours: we cancelled the subscription and the publisher has not stopped yet.
883
1726
  // Anything else on this alias is the publisher sending data for a track it never
@@ -888,6 +1731,7 @@ export class Subscriber {
888
1731
  stream.stop(e);
889
1732
  return;
890
1733
  }
1734
+ const subscription = binding;
891
1735
  const { track, tail } = subscription;
892
1736
  // Every data stream counts toward PUBLISH_DONE's Stream Count, even one dropped below.
893
1737
  const read = tail.open(group.groupId);
@@ -900,87 +1744,210 @@ export class Subscriber {
900
1744
  if (subscription.end !== undefined && group.groupId >= subscription.end) {
901
1745
  throw new ProtocolViolation(`group ${group.groupId} is at or past the declared end ${subscription.end}`);
902
1746
  }
903
- producer = new netGroup.Producer(group.groupId);
904
- 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 });
905
1749
  }
906
1750
  return producer;
907
1751
  };
908
- try {
909
- // FIRST_OBJECT clear is the publisher's claim that the stream starts partway
910
- // through the group. The first Object ID is absolute either way, and IDs start
911
- // at 0, so a clear bit on object 0 is still the whole group. Any other first ID,
912
- // or a stream with no object, has a hole at the front: drop it and pick up at
913
- // the next group.
914
- //
915
- // Drafts before the bit cannot say this in the header, so the first ID is the only
916
- // signal: a non-zero one is the same hole and is dropped the same way, but an empty
917
- // stream there is still a group. A later gap, or a header that claimed the group
918
- // starts at object 0, still fails it: `Frame.decode` refuses every non-zero delta.
919
- const legacy = !hasFirstObjectBit(this.#session.version);
920
- if (!group.flags.firstObject || legacy) {
921
- let id;
922
- try {
923
- id = await stream.peekU62();
924
- }
925
- catch (err) {
926
- if (!(err instanceof UnexpectedEnd))
927
- throw err;
928
- }
929
- if (id !== 0n && !(legacy && id === undefined)) {
930
- console.debug(`dropping a group with no head: alias=${group.trackAlias} group=${group.groupId}`);
931
- stream.stop(new Error("a group must start at object 0"));
932
- return;
933
- }
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
+ });
934
1762
  }
1763
+ };
1764
+ try {
935
1765
  // The alias binds after SUBSCRIBE_OK commits the track property; an omitted
936
- // header priority inherits it (draft-21 section 10.4).
1766
+ // header priority inherits it (draft-22 section 10.4).
937
1767
  if (!group.flags.hasPriority)
938
1768
  group.publisherPriority = toWire((await track.info()).priority);
939
- 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;
940
1782
  for (;;) {
941
1783
  // Every object already buffered is written without an await, so the reader wakes
942
1784
  // once per batch rather than once per object. Only the group's own stream ends it:
943
1785
  // a track that closes first has already closed (or aborted) this group through its
944
1786
  // cache.
945
1787
  const frame = stream.tryDecode(decode) ??
946
- (await (producer
947
- ? race([stream.decodeMaybe(decode), producer.closed])
948
- : stream.decodeMaybe(decode)));
949
- 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
+ }
950
1842
  break;
1843
+ }
951
1844
  if (frame.endOfTrack) {
1845
+ if (frame.hasProperties)
1846
+ throw new EndOfTrackProperties();
952
1847
  // No object at or past this location exists: after the group's last object
953
1848
  // the track ends with it, and at object 0 it ends before it.
954
- const end = producer ? group.groupId + 1 : group.groupId;
955
- 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();
956
1867
  try {
957
- track.finishAt(end);
1868
+ hooks.endTrack(track, end);
958
1869
  }
959
1870
  catch (err) {
960
1871
  throw new ProtocolViolation(`invalid END_OF_TRACK: ${reason(error(err))}`);
961
1872
  }
962
- subscription.end ??= end;
1873
+ subscription.end ??= finalKey(end);
963
1874
  return;
964
1875
  }
965
- 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 })))
966
1906
  break;
967
- open().writeFrame({ payload: frame.payload, timestamp: frame.timestamp ?? Timestamp.now() });
968
1907
  }
969
1908
  // A group with no objects still exists.
970
- open().close();
1909
+ open().finish();
971
1910
  }
972
1911
  catch (err) {
1912
+ if (err instanceof ProtocolViolation)
1913
+ this.#fail(err.code, err.message);
973
1914
  const e = await sessionCause(this.#quic, err);
974
- if (e instanceof ProtocolViolation) {
975
- // The publisher broke the track's end, which no later group can repair.
976
- producer?.close(e);
977
- 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);
978
1945
  }
979
1946
  else {
980
1947
  // A stream that fails before its first object still names a group, which the
981
1948
  // reader sees fail rather than silently go missing.
982
1949
  try {
983
- open().close(e);
1950
+ hooks.abortGroup(open(), e);
984
1951
  }
985
1952
  catch {
986
1953
  // The track has already closed or ended below this group.
@@ -989,23 +1956,358 @@ export class Subscriber {
989
1956
  stream.stop(e);
990
1957
  }
991
1958
  finally {
992
- 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);
993
2303
  }
994
2304
  }
995
2305
  }
996
- /**
997
- * A broadcast consumed from a moq-transport session. Track info is resolved by the
998
- * subscribe path (the inherited `resolveTrackInfo`), but the protocol has no one-shot
999
- * group fetch, so `track.Consumer.fetchGroup()` is rejected.
1000
- */
2306
+ // The protected broadcast constructor keeps network-backed consumers package-private.
1001
2307
  class ConsumeBroadcast extends broadcast.Consumer {
1002
2308
  constructor(state) {
1003
2309
  super(state);
1004
- overrideBroadcastWire(this, {
1005
- fetchGroup: () => Promise.reject(new Error("fetch group is not supported for moq-transport")),
1006
- });
1007
2310
  }
1008
- // Preserve the subclass when the consume cache shares this broadcast across callers.
1009
2311
  clone() {
1010
2312
  return new ConsumeBroadcast(this.shareState());
1011
2313
  }