@moq/net 0.4.8 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (662) hide show
  1. package/README.md +7 -1
  2. package/announce.d.ts +1 -1
  3. package/announce.d.ts.map +1 -1
  4. package/announce.js +1 -1
  5. package/announce.js.map +1 -1
  6. package/announced.d.ts +51 -47
  7. package/announced.d.ts.map +1 -1
  8. package/announced.js +183 -31
  9. package/announced.js.map +1 -1
  10. package/announced.test-util.d.ts +2 -0
  11. package/announced.test-util.d.ts.map +1 -0
  12. package/announced.test-util.js +27 -0
  13. package/announced.test-util.js.map +1 -0
  14. package/auth.d.ts +64 -0
  15. package/auth.d.ts.map +1 -0
  16. package/auth.js +20 -0
  17. package/auth.js.map +1 -0
  18. package/auth_gate.d.ts +2 -0
  19. package/auth_gate.d.ts.map +1 -0
  20. package/auth_gate.js +24 -0
  21. package/auth_gate.js.map +1 -0
  22. package/auth_session.d.ts +49 -0
  23. package/auth_session.d.ts.map +1 -0
  24. package/auth_session.js +1097 -0
  25. package/auth_session.js.map +1 -0
  26. package/bandwidth.d.ts +129 -25
  27. package/bandwidth.d.ts.map +1 -1
  28. package/bandwidth.js +410 -138
  29. package/bandwidth.js.map +1 -1
  30. package/bandwidth_api.d.ts +1 -1
  31. package/bandwidth_api.d.ts.map +1 -1
  32. package/bandwidth_api.js +1 -1
  33. package/bandwidth_api.js.map +1 -1
  34. package/broadcast.d.ts +62 -36
  35. package/broadcast.d.ts.map +1 -1
  36. package/broadcast.js +556 -172
  37. package/broadcast.js.map +1 -1
  38. package/cache.d.ts +103 -0
  39. package/cache.d.ts.map +1 -0
  40. package/cache.js +254 -0
  41. package/cache.js.map +1 -0
  42. package/claim.test-util.d.ts +5 -0
  43. package/claim.test-util.d.ts.map +1 -0
  44. package/claim.test-util.js +13 -0
  45. package/claim.test-util.js.map +1 -0
  46. package/connection/accept.d.ts +20 -12
  47. package/connection/accept.d.ts.map +1 -1
  48. package/connection/accept.js +97 -129
  49. package/connection/accept.js.map +1 -1
  50. package/connection/browser.d.ts.map +1 -1
  51. package/connection/browser.js +28 -19
  52. package/connection/browser.js.map +1 -1
  53. package/connection/connect.d.ts +119 -23
  54. package/connection/connect.d.ts.map +1 -1
  55. package/connection/connect.js +535 -216
  56. package/connection/connect.js.map +1 -1
  57. package/connection/dials.d.ts +45 -0
  58. package/connection/dials.d.ts.map +1 -0
  59. package/connection/dials.js +109 -0
  60. package/connection/dials.js.map +1 -0
  61. package/connection/endpoint.d.ts +60 -0
  62. package/connection/endpoint.d.ts.map +1 -0
  63. package/connection/endpoint.js +114 -0
  64. package/connection/endpoint.js.map +1 -0
  65. package/connection/forward.d.ts +7 -1
  66. package/connection/forward.d.ts.map +1 -1
  67. package/connection/forward.js +265 -80
  68. package/connection/forward.js.map +1 -1
  69. package/connection/goaway.d.ts +16 -9
  70. package/connection/goaway.d.ts.map +1 -1
  71. package/connection/goaway.js +22 -108
  72. package/connection/goaway.js.map +1 -1
  73. package/connection/handshake.d.ts +32 -6
  74. package/connection/handshake.d.ts.map +1 -1
  75. package/connection/handshake.js +97 -20
  76. package/connection/handshake.js.map +1 -1
  77. package/connection/index.d.ts +3 -6
  78. package/connection/index.d.ts.map +1 -1
  79. package/connection/index.js +1 -2
  80. package/connection/index.js.map +1 -1
  81. package/connection/liveness.d.ts +14 -0
  82. package/connection/liveness.d.ts.map +1 -0
  83. package/connection/liveness.js +30 -0
  84. package/connection/liveness.js.map +1 -0
  85. package/connection/pool.d.ts +137 -58
  86. package/connection/pool.d.ts.map +1 -1
  87. package/connection/pool.js +281 -117
  88. package/connection/pool.js.map +1 -1
  89. package/connection/reload.d.ts +60 -12
  90. package/connection/reload.d.ts.map +1 -1
  91. package/connection/reload.js +859 -233
  92. package/connection/reload.js.map +1 -1
  93. package/connection/session.d.ts +91 -0
  94. package/connection/session.d.ts.map +1 -0
  95. package/connection/session.js +2 -0
  96. package/connection/session.js.map +1 -0
  97. package/connection/stats.d.ts +20 -11
  98. package/connection/stats.d.ts.map +1 -1
  99. package/connection/stats.js +64 -8
  100. package/connection/stats.js.map +1 -1
  101. package/connection/ticker.d.ts +4 -0
  102. package/connection/ticker.d.ts.map +1 -0
  103. package/connection/ticker.js +66 -0
  104. package/connection/ticker.js.map +1 -0
  105. package/connection/tokens.d.ts +2 -0
  106. package/connection/tokens.d.ts.map +1 -0
  107. package/connection/tokens.js +404 -0
  108. package/connection/tokens.js.map +1 -0
  109. package/connection/transport.d.ts.map +1 -1
  110. package/connection/transport.js +4 -4
  111. package/connection/transport.js.map +1 -1
  112. package/connection/withdrawal.d.ts +2 -0
  113. package/connection/withdrawal.d.ts.map +1 -0
  114. package/connection/withdrawal.js +23 -0
  115. package/connection/withdrawal.js.map +1 -0
  116. package/consume.js +213 -46
  117. package/consume.js.map +1 -1
  118. package/cover.d.ts +59 -0
  119. package/cover.d.ts.map +1 -0
  120. package/cover.js +375 -0
  121. package/cover.js.map +1 -0
  122. package/datagram.d.ts +70 -11
  123. package/datagram.d.ts.map +1 -1
  124. package/datagram.js +317 -1
  125. package/datagram.js.map +1 -1
  126. package/datagram_stream.d.ts +18 -0
  127. package/datagram_stream.d.ts.map +1 -0
  128. package/datagram_stream.js +67 -0
  129. package/datagram_stream.js.map +1 -0
  130. package/defined.test-util.d.ts +2 -0
  131. package/defined.test-util.d.ts.map +1 -0
  132. package/defined.test-util.js +7 -0
  133. package/defined.test-util.js.map +1 -0
  134. package/delivered.d.ts +75 -0
  135. package/delivered.d.ts.map +1 -0
  136. package/delivered.js +228 -0
  137. package/delivered.js.map +1 -0
  138. package/demand.d.ts +173 -0
  139. package/demand.d.ts.map +1 -0
  140. package/demand.js +582 -0
  141. package/demand.js.map +1 -0
  142. package/drops.d.ts +93 -0
  143. package/drops.d.ts.map +1 -0
  144. package/drops.js +283 -0
  145. package/drops.js.map +1 -0
  146. package/error.d.ts +120 -21
  147. package/error.d.ts.map +1 -1
  148. package/error.js +230 -37
  149. package/error.js.map +1 -1
  150. package/errors.d.ts +2 -2
  151. package/errors.d.ts.map +1 -1
  152. package/errors.js +2 -2
  153. package/errors.js.map +1 -1
  154. package/fill.d.ts +174 -0
  155. package/fill.d.ts.map +1 -0
  156. package/fill.js +760 -0
  157. package/fill.js.map +1 -0
  158. package/flate/decoder.d.ts +2 -0
  159. package/flate/decoder.d.ts.map +1 -0
  160. package/flate/decoder.js +63 -0
  161. package/flate/decoder.js.map +1 -0
  162. package/flate/encoder.d.ts +2 -0
  163. package/flate/encoder.d.ts.map +1 -0
  164. package/flate/encoder.js +64 -0
  165. package/flate/encoder.js.map +1 -0
  166. package/flate/group.d.ts +34 -0
  167. package/flate/group.d.ts.map +1 -0
  168. package/flate/group.js +140 -0
  169. package/flate/group.js.map +1 -0
  170. package/frame.d.ts +80 -0
  171. package/frame.d.ts.map +1 -0
  172. package/frame.js +296 -0
  173. package/frame.js.map +1 -0
  174. package/frame.test-util.d.ts +5 -0
  175. package/frame.test-util.d.ts.map +1 -0
  176. package/frame.test-util.js +9 -0
  177. package/frame.test-util.js.map +1 -0
  178. package/group.d.ts +108 -45
  179. package/group.d.ts.map +1 -1
  180. package/group.js +1616 -307
  181. package/group.js.map +1 -1
  182. package/group_api.d.ts +7 -0
  183. package/group_api.d.ts.map +1 -0
  184. package/group_api.js +7 -0
  185. package/group_api.js.map +1 -0
  186. package/hop.d.ts +62 -76
  187. package/hop.d.ts.map +1 -1
  188. package/hop.js +92 -64
  189. package/hop.js.map +1 -1
  190. package/identity.d.ts +39 -0
  191. package/identity.d.ts.map +1 -0
  192. package/identity.js +47 -0
  193. package/identity.js.map +1 -0
  194. package/ietf/active_count.d.ts +2 -0
  195. package/ietf/active_count.d.ts.map +1 -0
  196. package/ietf/active_count.js +30 -0
  197. package/ietf/active_count.js.map +1 -0
  198. package/ietf/aliases.js +69 -35
  199. package/ietf/aliases.js.map +1 -1
  200. package/ietf/cluster.d.ts +3 -3
  201. package/ietf/cluster.js +14 -62
  202. package/ietf/cluster.js.map +1 -1
  203. package/ietf/connection.d.ts +1 -31
  204. package/ietf/connection.d.ts.map +1 -1
  205. package/ietf/connection.js +305 -143
  206. package/ietf/connection.js.map +1 -1
  207. package/ietf/datagram.d.ts +60 -0
  208. package/ietf/datagram.d.ts.map +1 -0
  209. package/ietf/datagram.js +152 -0
  210. package/ietf/datagram.js.map +1 -0
  211. package/ietf/error.d.ts +3 -3
  212. package/ietf/error.js +82 -100
  213. package/ietf/error.js.map +1 -1
  214. package/ietf/fetch.d.ts +91 -35
  215. package/ietf/fetch.d.ts.map +1 -1
  216. package/ietf/fetch.js +172 -93
  217. package/ietf/fetch.js.map +1 -1
  218. package/ietf/filter.d.ts +20 -30
  219. package/ietf/filter.d.ts.map +1 -1
  220. package/ietf/filter.js +140 -171
  221. package/ietf/filter.js.map +1 -1
  222. package/ietf/goaway.d.ts +11 -9
  223. package/ietf/goaway.d.ts.map +1 -1
  224. package/ietf/goaway.js +22 -35
  225. package/ietf/goaway.js.map +1 -1
  226. package/ietf/hidden.js +1 -1
  227. package/ietf/hidden.js.map +1 -1
  228. package/ietf/index.d.ts +2 -14
  229. package/ietf/index.d.ts.map +1 -1
  230. package/ietf/index.js +4 -14
  231. package/ietf/index.js.map +1 -1
  232. package/ietf/join.d.ts +7 -0
  233. package/ietf/join.d.ts.map +1 -0
  234. package/ietf/join.js +234 -0
  235. package/ietf/join.js.map +1 -0
  236. package/ietf/message.d.ts +18 -2
  237. package/ietf/message.d.ts.map +1 -1
  238. package/ietf/message.js +60 -40
  239. package/ietf/message.js.map +1 -1
  240. package/ietf/message.test-util.d.ts +6 -0
  241. package/ietf/message.test-util.d.ts.map +1 -0
  242. package/ietf/message.test-util.js +13 -0
  243. package/ietf/message.test-util.js.map +1 -0
  244. package/ietf/namespace.d.ts +17 -3
  245. package/ietf/namespace.d.ts.map +1 -1
  246. package/ietf/namespace.js +78 -26
  247. package/ietf/namespace.js.map +1 -1
  248. package/ietf/object.d.ts +194 -32
  249. package/ietf/object.d.ts.map +1 -1
  250. package/ietf/object.js +405 -178
  251. package/ietf/object.js.map +1 -1
  252. package/ietf/parameters.d.ts +22 -42
  253. package/ietf/parameters.d.ts.map +1 -1
  254. package/ietf/parameters.js +260 -472
  255. package/ietf/parameters.js.map +1 -1
  256. package/ietf/priority.d.ts +17 -2
  257. package/ietf/priority.d.ts.map +1 -1
  258. package/ietf/priority.js +19 -4
  259. package/ietf/priority.js.map +1 -1
  260. package/ietf/properties.d.ts +5 -4
  261. package/ietf/properties.d.ts.map +1 -1
  262. package/ietf/properties.js +78 -48
  263. package/ietf/properties.js.map +1 -1
  264. package/ietf/publish.d.ts +22 -30
  265. package/ietf/publish.d.ts.map +1 -1
  266. package/ietf/publish.js +45 -139
  267. package/ietf/publish.js.map +1 -1
  268. package/ietf/publish_namespace.d.ts +46 -69
  269. package/ietf/publish_namespace.d.ts.map +1 -1
  270. package/ietf/publish_namespace.js +66 -184
  271. package/ietf/publish_namespace.js.map +1 -1
  272. package/ietf/publisher.js +1800 -600
  273. package/ietf/publisher.js.map +1 -1
  274. package/ietf/range.d.ts +2 -0
  275. package/ietf/range.d.ts.map +1 -0
  276. package/ietf/range.js +222 -0
  277. package/ietf/range.js.map +1 -0
  278. package/ietf/request.d.ts +3 -27
  279. package/ietf/request.d.ts.map +1 -1
  280. package/ietf/request.js +41 -78
  281. package/ietf/request.js.map +1 -1
  282. package/ietf/request_stream.d.ts +1 -6
  283. package/ietf/request_stream.d.ts.map +1 -1
  284. package/ietf/request_stream.js +306 -16
  285. package/ietf/request_stream.js.map +1 -1
  286. package/ietf/session.d.ts +41 -0
  287. package/ietf/session.d.ts.map +1 -0
  288. package/ietf/session.js +65 -0
  289. package/ietf/session.js.map +1 -0
  290. package/ietf/setup.d.ts +4 -29
  291. package/ietf/setup.d.ts.map +1 -1
  292. package/ietf/setup.js +6 -117
  293. package/ietf/setup.js.map +1 -1
  294. package/ietf/setup_options.d.ts +31 -0
  295. package/ietf/setup_options.d.ts.map +1 -0
  296. package/ietf/setup_options.js +138 -0
  297. package/ietf/setup_options.js.map +1 -0
  298. package/ietf/solicit.js +4 -14
  299. package/ietf/solicit.js.map +1 -1
  300. package/ietf/subscribe.d.ts +48 -41
  301. package/ietf/subscribe.d.ts.map +1 -1
  302. package/ietf/subscribe.js +118 -239
  303. package/ietf/subscribe.js.map +1 -1
  304. package/ietf/subscribe_namespace.d.ts +13 -76
  305. package/ietf/subscribe_namespace.d.ts.map +1 -1
  306. package/ietf/subscribe_namespace.js +30 -201
  307. package/ietf/subscribe_namespace.js.map +1 -1
  308. package/ietf/subscriber.js +1839 -536
  309. package/ietf/subscriber.js.map +1 -1
  310. package/ietf/token.js +105 -27
  311. package/ietf/token.js.map +1 -1
  312. package/ietf/track.d.ts +25 -22
  313. package/ietf/track.d.ts.map +1 -1
  314. package/ietf/track.js +48 -61
  315. package/ietf/track.js.map +1 -1
  316. package/ietf/version.d.ts +13 -42
  317. package/ietf/version.d.ts.map +1 -1
  318. package/ietf/version.js +22 -48
  319. package/ietf/version.js.map +1 -1
  320. package/implementation.d.ts +2 -0
  321. package/implementation.d.ts.map +1 -0
  322. package/implementation.js +5 -0
  323. package/implementation.js.map +1 -0
  324. package/index.d.ts +25 -10
  325. package/index.d.ts.map +1 -1
  326. package/index.js +19 -6
  327. package/index.js.map +1 -1
  328. package/internal.d.ts +1512 -64
  329. package/internal.d.ts.map +1 -1
  330. package/internal.js +557 -79
  331. package/internal.js.map +1 -1
  332. package/ledger.d.ts +23 -0
  333. package/ledger.d.ts.map +1 -0
  334. package/ledger.js +247 -0
  335. package/ledger.js.map +1 -0
  336. package/listing.d.ts +132 -0
  337. package/listing.d.ts.map +1 -0
  338. package/listing.js +486 -0
  339. package/listing.js.map +1 -0
  340. package/lite/announce.d.ts +124 -63
  341. package/lite/announce.d.ts.map +1 -1
  342. package/lite/announce.js +384 -158
  343. package/lite/announce.js.map +1 -1
  344. package/lite/announce_stream.d.ts +2 -0
  345. package/lite/announce_stream.d.ts.map +1 -0
  346. package/lite/announce_stream.js +92 -0
  347. package/lite/announce_stream.js.map +1 -0
  348. package/lite/answer.d.ts +22 -0
  349. package/lite/answer.d.ts.map +1 -0
  350. package/lite/answer.js +301 -0
  351. package/lite/answer.js.map +1 -0
  352. package/lite/auth.d.ts +45 -0
  353. package/lite/auth.d.ts.map +1 -0
  354. package/lite/auth.js +204 -0
  355. package/lite/auth.js.map +1 -0
  356. package/lite/compat.d.ts +31 -0
  357. package/lite/compat.d.ts.map +1 -0
  358. package/lite/compat.js +86 -0
  359. package/lite/compat.js.map +1 -0
  360. package/lite/connection.d.ts +1 -45
  361. package/lite/connection.d.ts.map +1 -1
  362. package/lite/connection.js +360 -77
  363. package/lite/connection.js.map +1 -1
  364. package/lite/datagram-end.d.ts +26 -0
  365. package/lite/datagram-end.d.ts.map +1 -0
  366. package/lite/datagram-end.js +30 -0
  367. package/lite/datagram-end.js.map +1 -0
  368. package/lite/datagram.d.ts +73 -8
  369. package/lite/datagram.d.ts.map +1 -1
  370. package/lite/datagram.js +144 -9
  371. package/lite/datagram.js.map +1 -1
  372. package/lite/duration.d.ts +6 -0
  373. package/lite/duration.d.ts.map +1 -0
  374. package/lite/duration.js +14 -0
  375. package/lite/duration.js.map +1 -0
  376. package/lite/error.d.ts +9 -0
  377. package/lite/error.d.ts.map +1 -0
  378. package/lite/error.js +24 -0
  379. package/lite/error.js.map +1 -0
  380. package/lite/fills.d.ts +162 -0
  381. package/lite/fills.d.ts.map +1 -0
  382. package/lite/fills.js +486 -0
  383. package/lite/fills.js.map +1 -0
  384. package/lite/fit.d.ts +49 -0
  385. package/lite/fit.d.ts.map +1 -0
  386. package/lite/fit.js +305 -0
  387. package/lite/fit.js.map +1 -0
  388. package/lite/goaway.d.ts +1 -1
  389. package/lite/goaway.d.ts.map +1 -1
  390. package/lite/goaway.js +5 -13
  391. package/lite/goaway.js.map +1 -1
  392. package/lite/group.d.ts +64 -13
  393. package/lite/group.d.ts.map +1 -1
  394. package/lite/group.js +108 -30
  395. package/lite/group.js.map +1 -1
  396. package/lite/identity.d.ts +25 -0
  397. package/lite/identity.d.ts.map +1 -0
  398. package/lite/identity.js +79 -0
  399. package/lite/identity.js.map +1 -0
  400. package/lite/index.d.ts +2 -1
  401. package/lite/index.d.ts.map +1 -1
  402. package/lite/index.js +2 -1
  403. package/lite/index.js.map +1 -1
  404. package/lite/message.d.ts +9 -1
  405. package/lite/message.d.ts.map +1 -1
  406. package/lite/message.js +28 -44
  407. package/lite/message.js.map +1 -1
  408. package/lite/priority.d.ts +9 -2
  409. package/lite/priority.d.ts.map +1 -1
  410. package/lite/priority.js +11 -105
  411. package/lite/priority.js.map +1 -1
  412. package/lite/probe.d.ts.map +1 -1
  413. package/lite/probe.js +9 -0
  414. package/lite/probe.js.map +1 -1
  415. package/lite/publisher.d.ts +10 -1
  416. package/lite/publisher.d.ts.map +1 -1
  417. package/lite/publisher.js +2548 -437
  418. package/lite/publisher.js.map +1 -1
  419. package/lite/routed.d.ts +59 -0
  420. package/lite/routed.d.ts.map +1 -0
  421. package/lite/routed.js +564 -0
  422. package/lite/routed.js.map +1 -0
  423. package/lite/session.d.ts +1 -27
  424. package/lite/session.d.ts.map +1 -1
  425. package/lite/session.js +0 -99
  426. package/lite/session.js.map +1 -1
  427. package/lite/setup.d.ts +29 -2
  428. package/lite/setup.d.ts.map +1 -1
  429. package/lite/setup.js +95 -21
  430. package/lite/setup.js.map +1 -1
  431. package/lite/stream.d.ts +5 -11
  432. package/lite/stream.d.ts.map +1 -1
  433. package/lite/stream.js +5 -1
  434. package/lite/stream.js.map +1 -1
  435. package/lite/subscribe.d.ts +475 -75
  436. package/lite/subscribe.d.ts.map +1 -1
  437. package/lite/subscribe.js +1373 -142
  438. package/lite/subscribe.js.map +1 -1
  439. package/lite/subscriber.d.ts +7 -44
  440. package/lite/subscriber.d.ts.map +1 -1
  441. package/lite/subscriber.js +3290 -515
  442. package/lite/subscriber.js.map +1 -1
  443. package/lite/track.d.ts +24 -9
  444. package/lite/track.d.ts.map +1 -1
  445. package/lite/track.js +116 -37
  446. package/lite/track.js.map +1 -1
  447. package/lite/tracks.d.ts +55 -0
  448. package/lite/tracks.d.ts.map +1 -0
  449. package/lite/tracks.js +114 -0
  450. package/lite/tracks.js.map +1 -0
  451. package/lite/version.d.ts +132 -24
  452. package/lite/version.d.ts.map +1 -1
  453. package/lite/version.js +378 -33
  454. package/lite/version.js.map +1 -1
  455. package/meta.d.ts +77 -0
  456. package/meta.d.ts.map +1 -0
  457. package/meta.js +130 -0
  458. package/meta.js.map +1 -0
  459. package/meta_api.d.ts +7 -0
  460. package/meta_api.d.ts.map +1 -0
  461. package/meta_api.js +7 -0
  462. package/meta_api.js.map +1 -0
  463. package/mint.d.ts +28 -0
  464. package/mint.d.ts.map +1 -0
  465. package/mint.js +66 -0
  466. package/mint.js.map +1 -0
  467. package/open.d.ts +63 -0
  468. package/open.d.ts.map +1 -0
  469. package/open.js +250 -0
  470. package/open.js.map +1 -0
  471. package/origin.d.ts +392 -140
  472. package/origin.d.ts.map +1 -1
  473. package/origin.js +2533 -686
  474. package/origin.js.map +1 -1
  475. package/package.json +8 -13
  476. package/path.d.ts +51 -51
  477. package/path.d.ts.map +1 -1
  478. package/path.js +210 -57
  479. package/path.js.map +1 -1
  480. package/payload.d.ts +33 -0
  481. package/payload.d.ts.map +1 -0
  482. package/payload.js +65 -0
  483. package/payload.js.map +1 -0
  484. package/prefix.d.ts +152 -0
  485. package/prefix.d.ts.map +1 -0
  486. package/prefix.js +349 -0
  487. package/prefix.js.map +1 -0
  488. package/priority.d.ts +8 -0
  489. package/priority.d.ts.map +1 -0
  490. package/priority.js +185 -0
  491. package/priority.js.map +1 -0
  492. package/queue.d.ts +2 -0
  493. package/queue.d.ts.map +1 -0
  494. package/queue.js +46 -0
  495. package/queue.js.map +1 -0
  496. package/ranges.d.ts +36 -0
  497. package/ranges.d.ts.map +1 -0
  498. package/ranges.js +312 -0
  499. package/ranges.js.map +1 -0
  500. package/rescale.d.ts +24 -0
  501. package/rescale.d.ts.map +1 -0
  502. package/rescale.js +39 -0
  503. package/rescale.js.map +1 -0
  504. package/resume.d.ts +55 -0
  505. package/resume.d.ts.map +1 -0
  506. package/resume.js +4173 -0
  507. package/resume.js.map +1 -0
  508. package/resume.test-util.d.ts +2 -0
  509. package/resume.test-util.d.ts.map +1 -0
  510. package/resume.test-util.js +25 -0
  511. package/resume.test-util.js.map +1 -0
  512. package/skips.d.ts +48 -0
  513. package/skips.d.ts.map +1 -0
  514. package/skips.js +182 -0
  515. package/skips.js.map +1 -0
  516. package/stream.d.ts +75 -37
  517. package/stream.d.ts.map +1 -1
  518. package/stream.js +236 -92
  519. package/stream.js.map +1 -1
  520. package/subscription.test-util.d.ts +2 -0
  521. package/subscription.test-util.d.ts.map +1 -0
  522. package/subscription.test-util.js +49 -0
  523. package/subscription.test-util.js.map +1 -0
  524. package/tail.d.ts +23 -14
  525. package/tail.d.ts.map +1 -1
  526. package/tail.js +224 -97
  527. package/tail.js.map +1 -1
  528. package/time.d.ts +41 -102
  529. package/time.d.ts.map +1 -1
  530. package/time.js +129 -91
  531. package/time.js.map +1 -1
  532. package/timed.d.ts +21 -0
  533. package/timed.d.ts.map +1 -0
  534. package/timed.js +2 -0
  535. package/timed.js.map +1 -0
  536. package/track.d.ts +577 -245
  537. package/track.d.ts.map +1 -1
  538. package/track.js +7306 -771
  539. package/track.js.map +1 -1
  540. package/track_api.d.ts +7 -0
  541. package/track_api.d.ts.map +1 -0
  542. package/track_api.js +7 -0
  543. package/track_api.js.map +1 -0
  544. package/util/abort.d.ts +1 -0
  545. package/util/abort.d.ts.map +1 -1
  546. package/util/abort.js +23 -1
  547. package/util/abort.js.map +1 -1
  548. package/util/announce.d.ts +4 -0
  549. package/util/announce.d.ts.map +1 -0
  550. package/util/announce.js +11 -0
  551. package/util/announce.js.map +1 -0
  552. package/util/bigint.d.ts +3 -0
  553. package/util/bigint.d.ts.map +1 -0
  554. package/util/bigint.js +8 -0
  555. package/util/bigint.js.map +1 -0
  556. package/util/change.d.ts +12 -0
  557. package/util/change.d.ts.map +1 -0
  558. package/util/change.js +18 -0
  559. package/util/change.js.map +1 -0
  560. package/util/deadline.d.ts +2 -0
  561. package/util/deadline.d.ts.map +1 -0
  562. package/util/deadline.js +108 -0
  563. package/util/deadline.js.map +1 -0
  564. package/util/decode_error.d.ts +3 -0
  565. package/util/decode_error.d.ts.map +1 -0
  566. package/util/decode_error.js +11 -0
  567. package/util/decode_error.js.map +1 -0
  568. package/util/demand.d.ts +8 -0
  569. package/util/demand.d.ts.map +1 -0
  570. package/util/demand.js +24 -0
  571. package/util/demand.js.map +1 -0
  572. package/util/given_up.d.ts +2 -0
  573. package/util/given_up.d.ts.map +1 -0
  574. package/util/given_up.js +101 -0
  575. package/util/given_up.js.map +1 -0
  576. package/util/hex.d.ts +6 -0
  577. package/util/hex.d.ts.map +1 -1
  578. package/util/hex.js +19 -4
  579. package/util/hex.js.map +1 -1
  580. package/util/key.d.ts +15 -0
  581. package/util/key.d.ts.map +1 -0
  582. package/util/key.js +38 -0
  583. package/util/key.js.map +1 -0
  584. package/util/limits.d.ts +2 -0
  585. package/util/limits.d.ts.map +1 -0
  586. package/util/limits.js +76 -0
  587. package/util/limits.js.map +1 -0
  588. package/util/observed.d.ts +23 -0
  589. package/util/observed.d.ts.map +1 -0
  590. package/util/observed.js +122 -0
  591. package/util/observed.js.map +1 -0
  592. package/util/sorted.d.ts +2 -0
  593. package/util/sorted.d.ts.map +1 -0
  594. package/util/sorted.js +149 -0
  595. package/util/sorted.js.map +1 -0
  596. package/util/timeout.d.ts +2 -1
  597. package/util/timeout.d.ts.map +1 -1
  598. package/util/timeout.js +13 -9
  599. package/util/timeout.js.map +1 -1
  600. package/util/timer.d.ts +2 -0
  601. package/util/timer.d.ts.map +1 -0
  602. package/util/timer.js +19 -0
  603. package/util/timer.js.map +1 -0
  604. package/util/utf8.d.ts +2 -0
  605. package/util/utf8.d.ts.map +1 -1
  606. package/util/utf8.js +7 -1
  607. package/util/utf8.js.map +1 -1
  608. package/util/varint.d.ts.map +1 -1
  609. package/util/varint.js +8 -1
  610. package/util/varint.js.map +1 -1
  611. package/util/watch.d.ts +8 -0
  612. package/util/watch.d.ts.map +1 -0
  613. package/util/watch.js +38 -0
  614. package/util/watch.js.map +1 -0
  615. package/util/yield.d.ts +2 -0
  616. package/util/yield.d.ts.map +1 -0
  617. package/util/yield.js +31 -0
  618. package/util/yield.js.map +1 -0
  619. package/varint.d.ts +0 -29
  620. package/varint.d.ts.map +1 -1
  621. package/varint.js +7 -28
  622. package/varint.js.map +1 -1
  623. package/varint_api.d.ts +7 -0
  624. package/varint_api.d.ts.map +1 -0
  625. package/varint_api.js +7 -0
  626. package/varint_api.js.map +1 -0
  627. package/version.d.ts +2 -0
  628. package/version.d.ts.map +1 -0
  629. package/version.js +4 -0
  630. package/version.js.map +1 -0
  631. package/window.d.ts +570 -0
  632. package/window.d.ts.map +1 -0
  633. package/window.js +1677 -0
  634. package/window.js.map +1 -0
  635. package/wire.d.ts +145 -30
  636. package/wire.d.ts.map +1 -1
  637. package/wire.js +27 -0
  638. package/wire.js.map +1 -1
  639. package/connection/established.d.ts +0 -53
  640. package/connection/established.d.ts.map +0 -1
  641. package/connection/established.js +0 -2
  642. package/connection/established.js.map +0 -1
  643. package/ietf/adapter.d.ts +0 -75
  644. package/ietf/adapter.d.ts.map +0 -1
  645. package/ietf/adapter.js +0 -699
  646. package/ietf/adapter.js.map +0 -1
  647. package/lite/datagram_stream.d.ts +0 -8
  648. package/lite/datagram_stream.d.ts.map +0 -1
  649. package/lite/datagram_stream.js +0 -43
  650. package/lite/datagram_stream.js.map +0 -1
  651. package/lite/fetch.d.ts +0 -28
  652. package/lite/fetch.d.ts.map +0 -1
  653. package/lite/fetch.js +0 -78
  654. package/lite/fetch.js.map +0 -1
  655. package/util/log.d.ts +0 -5
  656. package/util/log.d.ts.map +0 -1
  657. package/util/log.js +0 -16
  658. package/util/log.js.map +0 -1
  659. package/zod.d.ts +0 -13
  660. package/zod.d.ts.map +0 -1
  661. package/zod.js +0 -18
  662. package/zod.js.map +0 -1
package/ietf/publisher.js CHANGED
@@ -1,32 +1,59 @@
1
- import { race, Signal } from "@moq/signals";
2
- import { controlTimeout, error, reason, StreamCode, StreamError } from "../error.js";
3
- import { hiddenBelow, hooks, presented } from "../internal.js";
1
+ import { Duration, now, sleep } from "@moq/clock";
2
+ import { Once, race, Signal } from "@moq/signals";
3
+ import { Gate } from "../auth_gate.js";
4
+ import { enforceGrant } from "../auth_session.js";
5
+ import { Withdrawal } from "../connection/withdrawal.js";
6
+ import * as DatagramStream from "../datagram_stream.js";
7
+ import { controlTimeout, error, NotFound, ProtocolViolation, reason, SessionCode, SessionError, StreamCode, StreamError, unauthorized, } from "../error.js";
8
+ import { datagramTrackInfo, firstEligible, hiddenBelow, hooks, presented } from "../internal.js";
4
9
  import * as Path from "../path.js";
10
+ import { sendPayload } from "../payload.js";
11
+ import { Priority, sendOrder } from "../priority.js";
12
+ import { routeFailed } from "../resume.js";
5
13
  import { Writer } from "../stream.js";
6
- import { Milli, Timescale } from "../time.js";
14
+ import { floorAt } from "../time.js";
15
+ import { Producer as TrackProducer, } from "../track.js";
16
+ import { untilAborted } from "../util/abort.js";
17
+ import { toNumber } from "../util/bigint.js";
18
+ import { nextChange } from "../util/change.js";
19
+ import { Deadline, REQUEST_TIMEOUT_MS } from "../util/deadline.js";
20
+ import { GivenUp } from "../util/given_up.js";
21
+ import { max, saturatingSub } from "../util/key.js";
7
22
  import { TimeoutError, withTimeout } from "../util/timeout.js";
8
- import * as Varint from "../varint.js";
9
- import { wireOf } from "../wire.js";
23
+ import { latestAt, rangesPolicy, withPolicy } from "../window.js";
24
+ import { sameIdentity, wireOf } from "../wire.js";
10
25
  import * as Cluster from "./cluster.js";
11
- import { requestReason, toRequestCode } from "./error.js";
12
- import { FetchError, FetchHeader } from "./fetch.js";
26
+ import { encodeDatagram } from "./datagram.js";
27
+ import { requestReason, SubscribeRefused } from "./error.js";
28
+ import { FetchHeader } from "./fetch.js";
13
29
  import * as Filter from "./filter.js";
14
30
  import * as Message from "./message.js";
15
- import { FetchFrame, Frame, Group as GroupMessage } from "./object.js";
31
+ import * as Namespace from "./namespace.js";
32
+ import { FetchFrame, Frame, Group as GroupMessage, timestampObjectId } from "./object.js";
16
33
  import { Parameters } from "./parameters.js";
17
34
  import { fromWire, toWire } from "./priority.js";
18
35
  import * as Properties from "./properties.js";
19
36
  import { PublishDone, PublishDoneStatus } from "./publish.js";
20
- import { PublishNamespace, PublishNamespaceDone, PublishNamespaceOk, PublishNamespaceUpdate, } from "./publish_namespace.js";
37
+ import { PublishNamespace, PublishNamespaceUpdate } from "./publish_namespace.js";
21
38
  import { RequestError, RequestOk } from "./request.js";
22
- import { cancelled, finCancels } from "./request_stream.js";
23
- import { SubscribeError, SubscribeOk } from "./subscribe.js";
24
- import { SubscribeNamespaceEntry, SubscribeNamespaceEntryDone, SubscribeNamespaceOk, } from "./subscribe_namespace.js";
25
- import { Version } from "./version.js";
39
+ import { malformed, namespaceUpdate, RequestStream, refuseReserved, refuseUpdate, } from "./request_stream.js";
40
+ import { GroupOrder, SubscribeOk } from "./subscribe.js";
41
+ import { SubscribeNamespaceEntry, SubscribeNamespaceEntryDone, } from "./subscribe_namespace.js";
42
+ import { MalformedAuthToken } from "./token.js";
43
+ import { TrackStatusOk } from "./track.js";
44
+ import { isDraft23 } from "./version.js";
26
45
  /** First wait before re-offering a namespace the peer refused or we couldn't open for. */
27
46
  const RETRY_BASE = 100;
28
47
  /** Ceiling on that wait. The loop retries for the life of the session, so it must not spin. */
29
48
  const RETRY_MAX = 5000;
49
+ /**
50
+ * First wait before offering again a namespace the peer refused with a retry interval of 0.
51
+ * The peer asked not to be asked, so this is far slower than {@link RETRY_BASE}, yet short
52
+ * enough that a name another session was letting go of is taken up within the handover.
53
+ */
54
+ const REOFFER_BASE = 5000;
55
+ /** Ceiling on that wait: a peer that never wants the namespace hears of it once a minute. */
56
+ const REOFFER_MAX = 60_000;
30
57
  /** Cluster parameters for one snapshot: the advertised hops, then our own id last. */
31
58
  function clusterFor(base, route) {
32
59
  if (!base)
@@ -35,20 +62,22 @@ function clusterFor(base, route) {
35
62
  if (self === undefined)
36
63
  return undefined;
37
64
  const hops = route.hops.at(-1) === self ? [...route.hops] : [...route.hops, self];
38
- return { hops, cost: route.cost.warm };
65
+ return { hops, cost: route.cost };
39
66
  }
40
67
  /**
41
68
  * What it takes to move the peer from `held` to `next`.
42
69
  *
43
- * - `"same"`: the peer would decode the same advertisement. The cold cost, and the whole
44
- * route without Cluster, never reach the wire, so a change there sends nothing.
70
+ * - `"same"`: the peer would decode the same advertisement. The route without Cluster
71
+ * never reaches the wire, so a change there sends nothing.
45
72
  * - `"restart"`: nothing is held, nothing is wanted, or a different broadcast, which is
46
73
  * withdrawn and advertised again.
47
- * - Otherwise the same broadcast at a new hop chain or warm cost: the cluster parameters
74
+ * - Otherwise the same broadcast at a new hop chain or static cost: the cluster parameters
48
75
  * the peer holds and the ones it should, for the target to update.
49
76
  */
50
77
  function change(base, held, next) {
51
- if (held === undefined || next === undefined || held.identity !== next.identity)
78
+ // Another publisher identity: moq-transport has no restart, so the peer sees the namespace
79
+ // end and start again, and resubscribes.
80
+ if (held === undefined || next === undefined || !sameIdentity(held, next))
52
81
  return "restart";
53
82
  const from = clusterFor(base, held.route);
54
83
  const to = clusterFor(base, next.route);
@@ -63,14 +92,59 @@ function sameHops(a, b) {
63
92
  return a.length === b.length && a.every((hop, i) => hop === b[i]);
64
93
  }
65
94
  /**
66
- * How long one advertisement may take to be answered. Matches the Rust publisher, and the
67
- * peer accepting the stream is only half the exchange: one it never answers on holds the
95
+ * How long one advertisement may take to be answered. Accepting the stream is only half
96
+ * the exchange: one it never answers on holds the
68
97
  * loop just as effectively as one it never grants.
69
98
  */
70
- const ADVERTISE_TIMEOUT_MS = 5000;
99
+ const ADVERTISE_TIMEOUT_MS = REQUEST_TIMEOUT_MS;
100
+ const ADVERTISE_TIMEOUT = Duration.millis(ADVERTISE_TIMEOUT_MS);
71
101
  /** Sleep `delay`, jittered, so a relay's namespaces don't all retry on the same tick. */
72
102
  function retryAfter(delay) {
73
- return new Promise((resolve) => setTimeout(resolve, delay * (0.5 + Math.random() / 2)));
103
+ return sleep(Duration.millis(delay * (0.5 + Math.random() / 2)));
104
+ }
105
+ /** Stop forwarding without ending the subscription. */
106
+ class Paused extends Error {
107
+ /** Whether an update asked for the pause, which is answered once forwarding stopped. */
108
+ answer;
109
+ constructor(answer = false) {
110
+ super("paused");
111
+ this.answer = answer;
112
+ }
113
+ }
114
+ // The condition a request that failed for `err` is refused with, mirroring Rust's `to_code`: a
115
+ // verdict stays one, so the peer is never invited to retry it.
116
+ function refusedAs(err) {
117
+ if (err instanceof SubscribeRefused)
118
+ return err.condition;
119
+ if (err instanceof SessionError) {
120
+ switch (err.code) {
121
+ case SessionCode.Unauthorized:
122
+ return "unauthorized";
123
+ case SessionCode.Expired:
124
+ return "expired";
125
+ case SessionCode.Timeout:
126
+ return "timeout";
127
+ case SessionCode.Version:
128
+ case SessionCode.Unsupported:
129
+ return "not_supported";
130
+ }
131
+ }
132
+ else if (err instanceof StreamError) {
133
+ switch (err.code) {
134
+ case StreamCode.Unauthorized:
135
+ return "unauthorized";
136
+ case StreamCode.DeliveryTimeout:
137
+ return "timeout";
138
+ case StreamCode.MalformedTrack:
139
+ return "malformed_track";
140
+ case StreamCode.GoingAway:
141
+ return "going_away";
142
+ case StreamCode.NotFound:
143
+ case StreamCode.Unroutable:
144
+ return "does_not_exist";
145
+ }
146
+ }
147
+ return "internal";
74
148
  }
75
149
  /**
76
150
  * Handles publishing broadcasts using moq-transport protocol.
@@ -79,113 +153,363 @@ function retryAfter(delay) {
79
153
  * @internal
80
154
  */
81
155
  export class Publisher {
156
+ #withdrawal = new Withdrawal();
157
+ withdraw() {
158
+ return this.#withdrawal.close();
159
+ }
82
160
  #quic;
161
+ #datagramWriter;
83
162
  #session;
84
163
  #requiresSolicitation;
85
164
  #hidden;
165
+ // Whether a SUBSCRIBE_NAMESPACE's REQUEST_OK counts the NAMESPACEs that follow it (MoQ Active Count).
166
+ #activeCount;
86
167
  // The origin this session serves, borrowed: it outlives the session, and closing the
87
- // session leaves its broadcasts alone. The namespaces are advertised with an unsolicited
88
- // PUBLISH_NAMESPACE (see {@link runPublishNamespaces}), or on request if the peer asked
89
- // for that (see {@link runSubscribeNamespace}).
168
+ // session leaves its broadcasts alone. Namespaces go out as an unsolicited
169
+ // PUBLISH_NAMESPACE (see {@link runPublishNamespaces}) unless the peer asked to be
170
+ // told on request. On draft-16 and later {@link runSubscribeNamespace} also carries
171
+ // every match: a NAMESPACE is discovery, not a second route.
90
172
  #advertised;
173
+ // Bumped when an idle draft-18+ advertisement ends without an update, so the announce
174
+ // loop re-offers it instead of holding a request the peer dropped.
175
+ #lapsed = new Signal(0);
91
176
  #publish;
92
177
  // What every advertisement carries on a session that negotiated the MoQ Cluster
93
178
  // extension: a hop path holding our own id, so the peer can tell that what it hears
94
179
  // back came from us. `undefined` when nothing negotiated it.
95
180
  #advert;
181
+ // Our grant: only what it lets us publish is advertised and served, and a
182
+ // shrink withdraws what it no longer covers. Undefined until the peer answers, which
183
+ // allows everything.
184
+ #grant;
185
+ // Holds every incoming request to that grant from dispatch to its end.
186
+ #gate;
187
+ // The bytes a request carries for a route's token, for only the tokens this session issued.
188
+ #auth;
96
189
  /**
97
190
  * Creates a new Publisher instance.
98
191
  *
99
192
  * @internal
100
193
  */
101
- constructor({ quic, session, publish, requiresSolicitation, hidden = false, cluster, }) {
194
+ constructor({ quic, session, publish, requiresSolicitation, hidden = false, activeCount = false, cluster, grant = new Signal(undefined), auth, }) {
102
195
  this.#quic = quic;
196
+ this.#datagramWriter = DatagramStream.datagramWriter(quic);
197
+ this.#grant = grant;
198
+ this.#gate = new Gate(grant);
199
+ this.#auth = auth;
103
200
  this.#session = session;
104
201
  const origin = publish && wireOf(publish);
105
202
  this.#advertised = origin?.advertised ?? new Signal(new Map());
106
203
  this.#publish = publish;
107
204
  this.#requiresSolicitation = requiresSolicitation;
108
205
  this.#hidden = hidden;
206
+ this.#activeCount = activeCount;
109
207
  this.#advert = Cluster.advertise(cluster);
110
208
  }
209
+ /** The origin owns broadcasts; transport teardown ends this publisher's served requests. @internal */
210
+ close() {
211
+ this.#datagramWriter?.close();
212
+ this.#datagramWriter = undefined;
213
+ }
111
214
  /**
112
215
  * Handles an incoming SUBSCRIBE request on a bidi stream.
113
216
  * Owns the full lifecycle: sends response, serves track data, waits for close.
114
217
  *
115
218
  * @internal
116
219
  */
117
- async runSubscribe(msg, stream) {
220
+ runSubscribe(msg, stream) {
221
+ const request = new RequestStream(stream, this.#session, this.#quic);
222
+ return request.serve(this.#runSubscribe(msg, request));
223
+ }
224
+ async #runSubscribe(msg, request) {
225
+ if (Namespace.reserved(msg.trackNamespace, this.#session.version)) {
226
+ await refuseReserved(request);
227
+ return;
228
+ }
229
+ await this.#serveSubscribe(msg, request);
230
+ }
231
+ async #serveSubscribe(msg, request) {
118
232
  const version = this.#session.version;
119
233
  const name = msg.trackNamespace;
120
234
  let broadcast;
121
235
  let refusal;
122
- // Legal requests we can't honor are refused one at a time. A subscription that
123
- // forwards nothing is only useful to a subscriber that later turns forwarding on,
124
- // and serving a Range Filter unfiltered would deliver objects it excluded.
125
- const unsupported = !msg.forward
126
- ? "FORWARD=0 not supported"
127
- : msg.rangeFilters
128
- ? "range filters not supported"
129
- : undefined;
130
- if (unsupported) {
131
- refusal = { errorCode: toRequestCode("not_supported", "subscribe", version), reasonPhrase: unsupported };
236
+ // The requester leaving while the broadcast and track resolve ends the request, so a
237
+ // cancelled subscription gives back its slot instead of holding it until the track
238
+ // is answered, which may be never.
239
+ const left = new AbortController();
240
+ const cancel = new StreamError(StreamCode.Cancel, { message: "cancel" });
241
+ void request.ended.then(() => left.abort(cancel));
242
+ // Legal requests we can't honor are refused one at a time: serving a Range Filter
243
+ // unfiltered would deliver objects it excluded.
244
+ const rendezvous = msg.rendezvous;
245
+ if (msg.rangeFilters) {
246
+ refusal = { condition: "invalid_filter", reasonPhrase: "range filters not supported" };
247
+ }
248
+ else if (countsBack(msg.filter)) {
249
+ refusal = { condition: "not_supported", reasonPhrase: "relative filter past the current group" };
250
+ }
251
+ else if (!this.#gate.allows(name)) {
252
+ // Serve only what our grant lets us publish. Checked before resolving, so a denied
253
+ // request never reaches the origin.
254
+ refusal = { condition: "unauthorized", reasonPhrase: "not granted" };
132
255
  }
133
256
  else {
134
257
  try {
135
- broadcast =
136
- this.#publish && (wireOf(this.#publish).local(name) ?? (await wireOf(this.#publish).demand(name)));
137
- if (!broadcast) {
138
- refusal = {
139
- errorCode: toRequestCode("does_not_exist", "subscribe", version),
140
- reasonPhrase: "broadcast not found",
141
- };
142
- }
258
+ broadcast = await this.#resolve(name, left.signal);
143
259
  }
144
260
  catch (err) {
145
- const e = error(err);
146
- const condition = e instanceof StreamError && e.code === StreamCode.NotFound ? "does_not_exist" : "internal";
147
- refusal = { errorCode: toRequestCode(condition, "subscribe", version), reasonPhrase: reason(e) };
261
+ // Nobody is left to refuse.
262
+ if (left.signal.aborted) {
263
+ request.abort(cancel);
264
+ return;
265
+ }
266
+ refusal = this.#failed(err, rendezvous);
148
267
  }
149
268
  }
150
269
  if (refusal) {
151
- if (version === Version.DRAFT_14) {
152
- await stream.writer.u53(SubscribeError.id);
153
- const err = new SubscribeError({
154
- requestId: msg.requestId,
155
- errorCode: refusal.errorCode,
156
- reasonPhrase: refusal.reasonPhrase,
270
+ await request.refuse("subscribe", refusal);
271
+ return;
272
+ }
273
+ if (!broadcast)
274
+ return;
275
+ const subscribe = (source) => {
276
+ // A range that resolves without the live edge has a fixed start, which is no join:
277
+ // bound the subscription before subscribing so the refresh ratio never judges it.
278
+ const fixed = filterRange(msg.filter, {}, this.#session.version);
279
+ // Parked past a bounded window's end: the peer reads this stream's end as the track's.
280
+ // Every other filter starts at the live edge, which resolves once subscribed.
281
+ return hooks.parked(source.track(msg.trackName).subscribe(atPolicy(fixed.start ? serveRequest(fixed) : LIVE_JOIN, {
282
+ priority: fromWire(msg.subscriberPriority),
283
+ order: msg.groupOrder,
284
+ })));
285
+ };
286
+ // Before any await, so a subscriber waiting on this priority is not stuck behind setup.
287
+ // A transport without datagrams never asks: the lookup would open an upstream
288
+ // subscription nothing here can carry.
289
+ // Set once the stream track answers a source that keeps the kinds apart: this draft keys
290
+ // a datagram and a group the same way, so the stream track alone answers its name.
291
+ let suppressed = false;
292
+ const datagramOf = () => {
293
+ if (suppressed || DatagramStream.maxDatagramSize(this.#quic) === 0)
294
+ return;
295
+ const local = wireOf(broadcast).localDatagrams;
296
+ const consumer = local
297
+ ? broadcast.datagrams(msg.trackName)
298
+ : wireOf(broadcast).liveDatagrams(msg.trackName);
299
+ if (local)
300
+ consumer?.setPriority(fromWire(msg.subscriberPriority));
301
+ return consumer;
302
+ };
303
+ let datagrams = datagramOf();
304
+ let track = subscribe(broadcast);
305
+ let datagramTrack;
306
+ const resolve = async () => {
307
+ // A relay learns both halves from the same stream response. Only local
308
+ // application handlers can answer either kind independently.
309
+ const streamInfo = track.info().then((info) => ({ kind: "stream", info }));
310
+ const consumer = datagrams;
311
+ // A name its source already publishes as a stream track is answered by that track alone,
312
+ // so the datagram metadata never races it.
313
+ const selected = await untilAborted(consumer && wireOf(broadcast).localDatagrams && !wireOf(broadcast).publishesTrack(msg.trackName)
314
+ ? Promise.any([
315
+ streamInfo,
316
+ consumer.info().then((info) => ({ kind: "datagram", info })),
317
+ ]).catch(() => streamInfo)
318
+ : streamInfo, left.signal);
319
+ if (selected.kind === "stream" && wireOf(broadcast).distinguishesKinds) {
320
+ suppressed = true;
321
+ datagrams?.close();
322
+ datagrams = undefined;
323
+ }
324
+ if (selected.kind === "datagram") {
325
+ track.close();
326
+ datagramTrack = new TrackProducer(msg.trackName, selected.info);
327
+ track = hooks.parked(datagramTrack.subscribe(latestAt(fromWire(msg.subscriberPriority))));
328
+ return datagramTrackInfo(selected.info);
329
+ }
330
+ return selected.info;
331
+ };
332
+ try {
333
+ const info = await resolve().catch(async (err) => {
334
+ if (left.signal.aborted)
335
+ request.abort(cancel);
336
+ else {
337
+ const refusal = this.#failed(err, rendezvous, true);
338
+ // An upstream's refusal goes on with the Retry Interval it asked for.
339
+ if (err instanceof SubscribeRefused)
340
+ refusal.retryInterval = err.retryInterval;
341
+ await request.refuse("subscribe", refusal);
342
+ }
343
+ return undefined;
344
+ });
345
+ if (!info)
346
+ return;
347
+ datagrams ??= datagramOf();
348
+ // Every subscription a resume makes counts toward the same PUBLISH_DONE.
349
+ const streams = { opened: 0 };
350
+ let paused = await this.#forward({
351
+ msg,
352
+ request,
353
+ track,
354
+ info,
355
+ streams,
356
+ datagrams,
357
+ datagramDemand: wireOf(broadcast).localDatagrams,
358
+ datagramTrack,
359
+ });
360
+ // A pause drops the subscription, and its demand with it; a resume subscribes again as
361
+ // a new SUBSCRIBE would, so nothing carries across but the request.
362
+ while (paused) {
363
+ track.close();
364
+ if (datagramTrack)
365
+ hooks.abortTrack(datagramTrack, cancel);
366
+ datagramTrack = undefined;
367
+ datagrams?.close();
368
+ datagrams = undefined;
369
+ if (paused.answer)
370
+ await Message.write(request.writer, RequestOk.id, new RequestOk(), version);
371
+ const answer = await this.#pausedSubscribe(msg, request, streams);
372
+ if (!answer)
373
+ return;
374
+ track = subscribe(broadcast);
375
+ // A fresh lookup, as a new SUBSCRIBE would make: the stream track may be gone.
376
+ suppressed = false;
377
+ datagrams = datagramOf();
378
+ let resumed;
379
+ try {
380
+ resumed = await resolve();
381
+ datagrams ??= datagramOf();
382
+ // A resume answers with the live edge, which only a granted subscriber learns.
383
+ if (!this.#gate.allows(name))
384
+ throw unauthorized(name);
385
+ }
386
+ catch (err) {
387
+ if (left.signal.aborted)
388
+ return;
389
+ const refusal = this.#failed(err);
390
+ if (err instanceof SubscribeRefused)
391
+ refusal.retryInterval = err.retryInterval;
392
+ await refuseUpdate(request.writer, version, "subscribe", refusal);
393
+ await this.#publishFailed(request, streams);
394
+ request.close();
395
+ return;
396
+ }
397
+ paused = await this.#forward({
398
+ msg,
399
+ request,
400
+ track,
401
+ info: resumed,
402
+ streams,
403
+ answer,
404
+ datagrams,
405
+ datagramDemand: wireOf(broadcast).localDatagrams,
406
+ datagramTrack,
157
407
  });
158
- await err.encode(stream.writer, version);
159
408
  }
160
- else {
161
- await stream.writer.u53(RequestError.id);
162
- const err = new RequestError({
163
- requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined,
164
- errorCode: refusal.errorCode,
165
- reasonPhrase: refusal.reasonPhrase,
409
+ }
410
+ finally {
411
+ track.close();
412
+ if (datagramTrack)
413
+ hooks.abortTrack(datagramTrack, cancel);
414
+ datagrams?.close();
415
+ }
416
+ }
417
+ /**
418
+ * Hold a paused SUBSCRIBE, answering its updates, until one resumes it: the update to
419
+ * answer then, or none once the request ended.
420
+ *
421
+ * A paused subscription holds nothing upstream, so only its priority and max age change
422
+ * while it waits. It still ends once our grant stops covering it, as a forwarding one does.
423
+ */
424
+ async #pausedSubscribe(msg, request, streams) {
425
+ const version = this.#session.version;
426
+ for (;;) {
427
+ const revoked = new Once();
428
+ const gate = this.#gate.watch(msg.trackNamespace, () => revoked.set(true));
429
+ if (gate.revoked())
430
+ revoked.set(true);
431
+ let framed;
432
+ try {
433
+ framed = await race([request.next(), revoked]);
434
+ }
435
+ finally {
436
+ gate.dispose();
437
+ }
438
+ if (framed === true) {
439
+ const done = new PublishDone({
440
+ statusCode: PublishDoneStatus.UNAUTHORIZED,
441
+ streamCount: BigInt(streams.opened),
442
+ reasonPhrase: "not granted",
166
443
  });
167
- await err.encode(stream.writer, version);
444
+ await Message.write(request.writer, PublishDone.id, done, version);
445
+ request.close();
446
+ return undefined;
168
447
  }
169
- stream.close();
170
- return;
448
+ if (framed === undefined) {
449
+ await request.ended;
450
+ return undefined;
451
+ }
452
+ let update;
453
+ try {
454
+ update = await this.#decodeUpdate(request, framed);
455
+ }
456
+ catch (err) {
457
+ if (!(err instanceof UpdateFailed))
458
+ throw err;
459
+ await this.#publishFailed(request, streams);
460
+ request.close();
461
+ return undefined;
462
+ }
463
+ this.#applyPublished(msg, update.params);
464
+ if (update.params.forward === true)
465
+ return { requestId: update.requestId };
466
+ await Message.write(request.writer, RequestOk.id, new RequestOk(), version);
171
467
  }
172
- if (!broadcast)
173
- return;
468
+ }
469
+ /**
470
+ * Decode a SUBSCRIBE's REQUEST_UPDATE. One this publisher cannot apply is refused on the
471
+ * wire, and the thrown {@link UpdateFailed} ends the subscription.
472
+ */
473
+ async #decodeUpdate(request, framed) {
474
+ const version = this.#session.version;
475
+ if (framed.type !== 0x02)
476
+ throw new ProtocolViolation(`unexpected message on a subscription: 0x${framed.type.toString(16)}`);
477
+ const refused = async (condition, reasonPhrase) => {
478
+ await refuseUpdate(request.writer, version, "subscribe", { condition, reasonPhrase });
479
+ return new UpdateFailed();
480
+ };
481
+ let params;
482
+ let requestId;
483
+ try {
484
+ ({ params, requestId } = await this.#subscriptionUpdate(framed));
485
+ }
486
+ catch (err) {
487
+ // Section 8.9 rejects the update, which says more than that we do not support it.
488
+ if (err instanceof MalformedAuthToken)
489
+ throw await refused("malformed_auth_token", err.message);
490
+ throw malformed(err, "REQUEST_UPDATE");
491
+ }
492
+ if (params.trackPropertyFilter)
493
+ throw new ProtocolViolation("TRACK_PROPERTY_FILTER is only allowed on SUBSCRIBE_TRACKS updates");
494
+ const unsupported = [...params.bytes.keys()].some((key) => key !== 0x21n && key !== 0x23n) ||
495
+ params.rangeFilters ||
496
+ [...params.vars.keys()].some((key) => key !== 0x02n && key !== 0x06n && key !== 0x20n && key !== 0x22n);
497
+ if (unsupported)
498
+ throw await refused("not_supported", "REQUEST_UPDATE parameters not supported");
499
+ return { params, requestId };
500
+ }
501
+ async #forward({ msg, request, track, info, streams = { opened: 0 }, answer, datagrams, datagramDemand, datagramTrack, }) {
502
+ const version = this.#session.version;
503
+ const name = msg.trackNamespace;
174
504
  const priority = fromWire(msg.subscriberPriority);
175
- const track = wireOf(broadcast).subscribe(msg.trackName, {
176
- priority,
177
- // moq-transport has no subscriber latency parameter. Keep everything the
178
- // producer retained and let the receiving subscriber enforce its own budget.
179
- // Keep the sentinel encodable if this demand crosses a Lite hop before the
180
- // producer's retention bound is known.
181
- maxAge: Milli(Varint.MAX_U53),
182
- });
505
+ const datagramPriority = new Signal(priority);
506
+ const order = msg.groupOrder;
183
507
  let cache;
508
+ let ranking;
509
+ // Assigned once forwarding starts. An early pause returns before that, and the finally
510
+ // still waits so a task begun on another path cannot outlive the subscription.
511
+ let datagramTask = Promise.resolve();
184
512
  try {
185
- // Declaring the timescale is what opts the track into timestamps; every object
186
- // Timestamp below is in these units.
187
- const info = await track.info();
188
- const timescale = info.timescale;
189
513
  // The model ranks higher-first, the IETF wire lower-first. Every group this
190
514
  // subscription serves carries the same publisher priority, which is what lets a
191
515
  // relay prefer catalog and audio over video when it has no subscriber preference
@@ -194,212 +518,347 @@ export class Publisher {
194
518
  // The filter and any fill are relative to the live edge, so snapshot it once: the
195
519
  // fill ends exactly where a Next Object subscription begins, which is what lets
196
520
  // the draft's current-group join (Next Object plus a StartGroup=1 fill) cover the
197
- // group with no gap and no overlap.
198
- const edge = liveEdge(track);
199
- const range = subscribeRange(msg, edge, version);
521
+ // group with no gap and no overlap. A timed track's Object IDs are timestamp offsets
522
+ // whether or not the request asked for track properties, so an Object ID names one frame.
523
+ const timescale = info.timescale ?? undefined;
524
+ const edge = liveEdge(track, timescale);
525
+ const fill = msg.fill && msg.forward && Filter.isDraft20(version)
526
+ ? fillRange(msg.fill, msg.filter, edge.largest)
527
+ : undefined;
528
+ const requested = filterRange(msg.filter, edge, version);
529
+ // A copy, since an update moves the cursor in place and must not move the bounds too.
530
+ const range = { ...afterFill(requested, fill, edge) };
531
+ // What the subscriber asked for, which only a narrowing changes: the fill's split
532
+ // moves the cursor alone, so it never gives up a stream still in range.
533
+ const bounds = new Signal(requested);
200
534
  // The wire request tells an upstream what we need; the cursor is what actually
201
535
  // trims this subscriber, since the producer fans every cached group out to every
202
536
  // sink regardless. An absent start joins at the latest group, which is what
203
537
  // moq-lite means by joining a live track. The range's end is the inclusive last
204
538
  // group; the model's `endGroup` is exclusive.
205
- track.update({
206
- priority,
207
- maxAge: Milli(Varint.MAX_U53),
208
- groups: {
209
- start: range.start ? { included: Number(range.start.group) } : undefined,
210
- end: range.end ? { included: Number(range.end.group) } : undefined,
211
- },
212
- });
213
- const startGroup = range.start ? Number(range.start.group) : track.latest();
539
+ track.update(atPolicy(serveRequest(range, msg.filter, edge), { priority, order }));
540
+ const startGroup = range.start ? range.start.group : hooks.latestKey(track);
214
541
  if (startGroup !== undefined)
215
- track.setGroups({ start: { included: startGroup } });
542
+ track.withRange({ ...rangeGroups(range), start: { included: startGroup } });
543
+ // The live cursor's lowest group, which a fill-only update never lowers.
544
+ let floor = startGroup ?? 0n;
216
545
  // A fill reads the group cache through its own consumer, independent of the
217
546
  // subscription's cursor. Forked from this subscriber rather than resolved through
218
547
  // the broadcast again: a dynamic serve is one request per peer subscription, so
219
548
  // asking the broadcast would mint a second producer nobody has accepted.
220
- const fill = msg.fill && Filter.isDraft20(version) ? fillRange(msg.fill, msg.filter, edge.largest) : undefined;
221
- cache = fill && fill.kind !== "empty" ? track.fork({ priority, maxAge: Milli(Varint.MAX_U53) }) : undefined;
222
- // Send SUBSCRIBE_OK
223
- await stream.writer.u53(SubscribeOk.id);
224
- const ok = new SubscribeOk({
225
- requestId: version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16
226
- ? msg.requestId
227
- : undefined,
228
- trackAlias: msg.requestId,
229
- // Required once the track has content; a fill-requesting subscriber sizes its
230
- // backfill against this. Below draft-20 round it down to the start of its
231
- // group, matching what the subscription serves there: a draft-20 subscriber
232
- // recovers a group's head with a FILL, which we serve, while older drafts
233
- // recover it with a joining FETCH, which we do not, so naming a mid-group
234
- // start would strand them.
235
- largest: edge.largest &&
236
- (Filter.isDraft20(version)
237
- ? { groupId: edge.largest.group, objectId: edge.largest.object }
238
- : { groupId: edge.largest.group, objectId: 0n }),
239
- properties: msg.propertiesWanted
240
- ? // Declaring the timescale is what opts the track into timestamps; every
241
- // object Timestamp below is in these units. We serve the newest group
242
- // first, matching moq-lite.
243
- { timescale, priority: publisherPriority, groupOrder: Properties.DESCENDING }
244
- : // INCLUDE_PROPERTIES=0. The block stays present but empty, which also means
245
- // the track opts out of timestamps for this subscriber.
246
- {},
247
- });
248
- await ok.encode(stream.writer, version);
549
+ cache =
550
+ fill && fill.kind !== "empty" ? track.fork(atPolicy({ ranges: [{}] }, { priority, order })) : undefined;
551
+ const ranked = new Priority(track, info.priority);
552
+ ranking = ranked;
553
+ const properties = trackProperties(info, msg.propertiesWanted);
554
+ if (answer) {
555
+ // The resuming update learns where the subscription now joins.
556
+ const parameters = new Parameters();
557
+ if (edge.largest)
558
+ parameters.largest = { groupId: edge.largest.group, objectId: edge.largest.object };
559
+ await Message.write(request.writer, RequestOk.id, new RequestOk({ parameters }), version);
560
+ }
561
+ else {
562
+ // Send SUBSCRIBE_OK
563
+ const ok = new SubscribeOk({
564
+ trackAlias: msg.requestId,
565
+ // Required once the track has content. A Next Object subscription starts right
566
+ // after it and recovers the group's head with a FILL from draft 20, which ends
567
+ // here. On draft 18 it carries the group whole from object 0 instead.
568
+ largest: edge.largest && { groupId: edge.largest.group, objectId: edge.largest.object },
569
+ properties,
570
+ });
571
+ await Message.write(request.writer, SubscribeOk.id, ok, version);
572
+ // A SUBSCRIBE may start paused, forwarding nothing until an update resumes it.
573
+ if (!msg.forward) {
574
+ msg.forward = true;
575
+ return new Paused();
576
+ }
577
+ }
249
578
  console.debug(`publish ok: broadcast=${name} track=${track.name}`);
579
+ // Groups are served below; datagrams ride beside them and must not fail this subscription.
580
+ // A burst stays behind the group's send order, so it cannot starve the groups.
581
+ datagramTask = datagrams
582
+ ? this.#sendDatagrams(datagrams, {
583
+ alias: msg.requestId,
584
+ priority: datagramPriority,
585
+ }).then(() => {
586
+ datagramTrack?.finish();
587
+ }, (err) => {
588
+ if (datagramTrack)
589
+ hooks.abortTrack(datagramTrack, error(err));
590
+ else
591
+ console.debug(`stopping datagrams on this subscription: ${reason(err)}`);
592
+ })
593
+ : Promise.resolve();
250
594
  // Cancels groups still queued for a stream slot. Only the subscriber leaving counts:
251
595
  // a track that ran out of groups still has to flush the ones already queued, and we
252
596
  // close the stream ourselves below to say so.
253
597
  let finished = false;
254
598
  let unsubscribe;
599
+ const fillAbort = new AbortController();
255
600
  const unsubscribed = new Promise((resolve) => {
256
- unsubscribe = resolve;
601
+ unsubscribe = () => {
602
+ fillAbort.abort(new StreamError(StreamCode.Cancel, { message: "unsubscribed before the fill finished" }));
603
+ resolve();
604
+ };
257
605
  });
258
- // Update replies and PUBLISH_DONE come from separate tasks but share this stream, and a
259
- // message is written in several pieces. Chain them so each goes out whole, in order,
260
- // and nothing follows PUBLISH_DONE.
261
- let replies = Promise.resolve();
262
- let replied = false;
263
- const reply = (write) => {
264
- const sent = replies.then(() => (replied ? undefined : write()));
265
- replies = sent.catch(() => undefined);
266
- return sent;
606
+ // The fill in flight. It never rejects.
607
+ let filling;
608
+ const startFill = (requestId, selected, source) => {
609
+ const fill = this.#runFill({
610
+ requestId,
611
+ priority: fromWire(msg.subscriberPriority),
612
+ publisherPriority,
613
+ ranking: ranked,
614
+ fill: selected,
615
+ cache: source,
616
+ unsubscribed,
617
+ cancelled: fillAbort.signal,
618
+ streams,
619
+ timescale,
620
+ }).finally(() => {
621
+ if (filling === fill)
622
+ filling = undefined;
623
+ });
624
+ filling = fill;
625
+ };
626
+ // The update being applied, from its decode until it is answered or fails.
627
+ let updating;
628
+ if (fill && cache)
629
+ startFill(answer?.requestId ?? msg.requestId, fill, cache);
630
+ // Every group started, until its stream finishes or resets, and the data streams
631
+ // opened for PUBLISH_DONE to report.
632
+ const groups = new Set();
633
+ // The stream serving the highest group, where a widening fill's tail resumes.
634
+ let live;
635
+ const serveGroup = (group, slice) => {
636
+ const stream = { key: group.start, slice, retired: false };
637
+ if (!live || group.start >= live.key)
638
+ live = stream;
639
+ const task = this.#runGroup({
640
+ track,
641
+ requestId: msg.requestId,
642
+ group,
643
+ publisherPriority,
644
+ ranking: ranked,
645
+ live: stream,
646
+ bounds,
647
+ unsubscribed,
648
+ streams,
649
+ timescale,
650
+ });
651
+ groups.add(task);
652
+ void task.finally(() => groups.delete(task));
267
653
  };
268
- let publishError;
269
654
  const updates = (async () => {
270
- if (version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16)
271
- return stream.reader.closed;
272
655
  for (;;) {
273
- if (await stream.reader.done()) {
274
- if (finCancels(version))
275
- return;
276
- return stream.writer.closed;
656
+ const framed = await request.next();
657
+ // The requester sent its last message, which ends the request only where FIN cancels.
658
+ if (framed === undefined)
659
+ return request.ended;
660
+ // A drained track waits this out, decode included, since the update may reopen its range.
661
+ const applied = Promise.withResolvers();
662
+ updating = applied.promise;
663
+ try {
664
+ const { params, requestId: ownRequestId } = await this.#decodeUpdate(request, framed);
665
+ // update() replaces every option, so carry the rest over as Rust does.
666
+ if (params.subscriberPriority !== undefined) {
667
+ const priority = fromWire(params.subscriberPriority);
668
+ const held = track.subscription.peek() ?? { ranges: [] };
669
+ track.update(atPolicy(held, { ...rangesPolicy(held.ranges ?? []), priority }));
670
+ datagramPriority.set(priority);
671
+ if (datagramDemand)
672
+ datagrams?.setPriority(priority);
673
+ }
674
+ // A fill holds one cache view. At most this decoded update waits behind
675
+ // it; request parsing then backpressures any further fill requests.
676
+ if (params.fillParameters)
677
+ await filling;
678
+ const snapshot = liveEdge(track, timescale);
679
+ this.#applyPublished(msg, params);
680
+ const selected = msg.fill && Filter.isDraft20(version)
681
+ ? fillRange(msg.fill, msg.filter, snapshot.largest)
682
+ : undefined;
683
+ // Refused as the SUBSCRIBE would have been, and ending the subscription as Rust's does.
684
+ if (params.subscriptionFilter !== undefined && countsBack(msg.filter)) {
685
+ throw new StreamError(StreamCode.Internal, {
686
+ message: "relative filter past the current group",
687
+ });
688
+ }
689
+ if (params.subscriptionFilter !== undefined || selected) {
690
+ // An update's unfiltered range explicitly lowers the floor to zero;
691
+ // an initial unfiltered subscription still joins the live group. A
692
+ // fill-only update keeps the range it already has.
693
+ const requested = params.subscriptionFilter === undefined
694
+ ? bounds.peek()
695
+ : msg.filter.kind === "unfiltered"
696
+ ? { start: { group: 0n, object: 0n } }
697
+ : filterRange(msg.filter, snapshot, version);
698
+ const tail = afterFill(requested, selected, snapshot);
699
+ range.start = tail.start;
700
+ range.end = tail.end;
701
+ bounds.set(requested, true);
702
+ // Only a new filter moves the request: the edge an old one resolved against has moved.
703
+ if (params.subscriptionFilter !== undefined)
704
+ track.update({
705
+ ...track.subscription.peek(),
706
+ ...serveRequest(range, msg.filter, snapshot),
707
+ });
708
+ // Below its floor the live cursor already passed every group or never owned it,
709
+ // so lowering it for a fill-only update would hand those groups out a second time.
710
+ let start = range.start ? range.start.group : 0n;
711
+ if (params.subscriptionFilter === undefined)
712
+ start = max(start, floor);
713
+ floor = start;
714
+ track.withRange({ ...rangeGroups(range), start: { included: start } });
715
+ // The fill took the current group's head. The cursor never hands a group out
716
+ // twice, so what its stream no longer carries resumes from the cache.
717
+ const next = tail !== requested ? tail.start : undefined;
718
+ const at = next?.group;
719
+ if (next && at !== undefined && hooks.handedOut(track, at)) {
720
+ const slice = groupSlice(range, at);
721
+ // A stream still serving this group from the fill's edge keeps what it
722
+ // covers, so the tail resumes where that stream stops.
723
+ const streaming = live?.key === at &&
724
+ live.slice.skip <= slice.skip &&
725
+ !live.retired &&
726
+ !excludes(requested, at, live.slice)
727
+ ? live
728
+ : undefined;
729
+ const resume = streaming ? streaming.slice.until : slice.skip;
730
+ if (resume !== undefined)
731
+ slice.skip = Math.max(slice.skip, resume);
732
+ const group = resume !== undefined &&
733
+ (!range.end || range.end.group >= next.group) &&
734
+ (slice.until === undefined || slice.until > slice.skip)
735
+ ? hooks.cachedGroup(track, at)
736
+ : undefined;
737
+ if (group)
738
+ serveGroup(group, slice);
739
+ }
740
+ }
741
+ if (params.groupOrder !== undefined) {
742
+ const held = track.subscription.peek() ?? { ranges: [] };
743
+ track.update(atPolicy(held, { ...rangesPolicy(held.ranges ?? []), order: msg.groupOrder }));
744
+ }
745
+ // Every data stream closes before the pause is answered.
746
+ if (params.forward === false)
747
+ throw new Paused(true);
748
+ const parameters = new Parameters();
749
+ if (snapshot.largest)
750
+ parameters.largest = { groupId: snapshot.largest.group, objectId: snapshot.largest.object };
751
+ const source = selected && selected.kind !== "empty"
752
+ ? track.fork(atPolicy({ ranges: [{}] }, { priority: fromWire(msg.subscriberPriority), order: msg.groupOrder }))
753
+ : undefined;
754
+ try {
755
+ await Message.write(request.writer, RequestOk.id, new RequestOk({ parameters }), version);
756
+ }
757
+ catch (err) {
758
+ source?.close();
759
+ throw err;
760
+ }
761
+ if (selected && source)
762
+ startFill(ownRequestId, selected, source);
277
763
  }
278
- if ((await stream.reader.u53()) !== 0x02)
279
- throw new Error("unexpected message on subscribe stream");
280
- const params = await Message.decode(stream.reader, async (r) => {
281
- await r.u62();
282
- if (version === Version.DRAFT_17)
283
- await r.u62();
284
- return Parameters.decode(r, version);
285
- });
286
- const unsupported = params.forward === false ||
287
- params.bytes.size > 0 ||
288
- params.subscriptionFilter !== undefined ||
289
- params.largest !== undefined ||
290
- params.rangeFilters ||
291
- params.trackPropertyFilter ||
292
- params.authorizationToken ||
293
- [...params.vars.keys()].some((key) => key !== 0x10n && key !== 0x20n);
294
- if (unsupported) {
295
- // Recorded before the reply, so a PUBLISH_DONE queued behind it reports the failure.
296
- const failed = new UpdateFailed();
297
- publishError = failed;
298
- await reply(async () => {
299
- await stream.writer.u53(RequestError.id);
300
- await new RequestError({
301
- requestId: undefined,
302
- errorCode: toRequestCode("not_supported", "subscribe", version),
303
- reasonPhrase: "REQUEST_UPDATE parameters not supported",
304
- }).encode(stream.writer, version);
305
- });
306
- throw failed;
764
+ finally {
765
+ updating = undefined;
766
+ applied.resolve();
307
767
  }
308
- // update() replaces every option, so carry the rest over as Rust does.
309
- if (params.subscriberPriority !== undefined)
310
- track.update({ ...track.subscription.peek(), priority: fromWire(params.subscriberPriority) });
311
- await reply(async () => {
312
- await stream.writer.u53(RequestOk.id);
313
- await new RequestOk({ requestId: undefined }).encode(stream.writer, version);
314
- });
315
768
  }
316
769
  })();
317
- const requestEnded = version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16
318
- ? updates
319
- : race([updates, stream.writer.closed]);
770
+ const requestEnded = race([updates, request.ended]);
320
771
  void requestEnded.then(() => {
321
772
  if (!finished)
322
773
  unsubscribe();
323
774
  },
324
- // Updates can fail after the serving loop ends while its last groups drain.
325
- (err) => {
326
- publishError = error(err);
327
- unsubscribe();
328
- });
329
- // Every group started, until its stream finishes or resets, and the data streams
330
- // opened for PUBLISH_DONE to report.
331
- const groups = new Set();
332
- const streams = { opened: 0 };
333
- // Serve groups until the track ends or the requester cancels.
775
+ // A reset is always the peer.
776
+ () => unsubscribe());
777
+ // Serve groups until the track ends or the requester cancels. Serving ends with the
778
+ // track only once no update or fill is in flight: an update may reopen the range, and
779
+ // a reopened group the cursor never handed out is still the cursor's to serve.
334
780
  const serving = (async () => {
335
781
  for (;;) {
336
- const group = await track.recvGroup();
337
- if (!group)
338
- return;
339
- // Past the filter's end. Dropped here rather than through `setGroups`, which
340
- // parks a capped group instead: this range is fixed for the life of the
341
- // subscription, so a group above it is never coming back in, and holding
342
- // one keeps the loop from ever ending. A producer that publishes beyond
343
- // the end and then closes would otherwise strand PUBLISH_DONE.
344
- if (range.end !== undefined && BigInt(group.sequence) > range.end.group) {
345
- group.close();
782
+ const group = await servingGroup(track);
783
+ if (group) {
784
+ serveGroup(group, groupSlice(range, group.start));
346
785
  continue;
347
786
  }
348
- const task = this.#runGroup({
349
- requestId: msg.requestId,
350
- group,
351
- timescale,
352
- publisherPriority,
353
- stamped: msg.propertiesWanted,
354
- slice: groupSlice(range, group.sequence),
355
- unsubscribed,
356
- streams,
357
- });
358
- groups.add(task);
359
- void task.finally(() => groups.delete(task));
787
+ const pending = updating ?? filling;
788
+ if (!pending)
789
+ return;
790
+ await pending;
360
791
  }
361
792
  })();
362
- // The fill (when one was requested) runs alongside on its own fetch stream; its
363
- // failures reset that stream and never touch the subscription.
364
- const filling = fill && cache
365
- ? this.#runFill({
366
- requestId: msg.requestId,
367
- priority,
368
- fill,
369
- cache,
370
- timescale,
371
- stamped: msg.propertiesWanted,
372
- unsubscribed,
373
- streams,
374
- })
375
- : Promise.resolve();
793
+ // Losing the grant ends the subscription, leaving the session alone.
794
+ let revoke;
795
+ const revoked = new Promise((resolve) => {
796
+ revoke = () => resolve("revoked");
797
+ });
798
+ const watch = this.#gate.watch(name, revoke);
799
+ // The grant may have shrunk during setup, before this watcher existed.
800
+ if (watch.revoked())
801
+ revoke();
802
+ let publishError;
803
+ let unauthorized = false;
376
804
  let ended = false;
377
805
  try {
378
806
  const served = Symbol("served");
379
- ended = (await race([Promise.all([serving, filling]).then(() => served), requestEnded])) === served;
807
+ const end = await race([serving.then(() => served), requestEnded, revoked]);
808
+ if (end === "revoked") {
809
+ console.info(`subscription no longer authorized: broadcast=${name} track=${track.name}`);
810
+ unauthorized = true;
811
+ unsubscribe();
812
+ }
813
+ ended = end === served;
380
814
  }
381
815
  catch (err) {
382
816
  publishError = error(err);
817
+ // Stop forwarding at once: a pause answers only after every data stream closed.
818
+ if (publishError instanceof Paused) {
819
+ unsubscribe();
820
+ track.close();
821
+ }
822
+ }
823
+ finally {
824
+ watch.dispose();
383
825
  }
826
+ // An update that broke the protocol, such as one whose AUTHORIZATION TOKEN names an
827
+ // alias, closes the session: the connection answers a thrown violation with its code.
828
+ if (publishError || !ended)
829
+ unsubscribe();
830
+ await filling;
831
+ if (publishError instanceof ProtocolViolation)
832
+ throw publishError;
384
833
  // PUBLISH_DONE waits until every stream this subscription will open is closed, as
385
834
  // the draft requires, so its count is final. The subscriber leaving cancels the
386
835
  // ones still queued instead.
387
836
  await race([Promise.all(groups), unsubscribed]);
388
- // An error of our own (a refused or malformed update, a failed track) ends the
389
- // subscription while the requester may still listen, so its open streams reset
390
- // rather than finish as if complete, and PUBLISH_DONE still follows them. A stream
391
- // error is the requester cancelling, which the shortcut above already covers.
392
- if (publishError && !(publishError instanceof StreamError)) {
393
- track.close(publishError);
394
- await Promise.all([...groups, filling]);
837
+ if (publishError instanceof Paused) {
838
+ track.close();
839
+ await Promise.all(groups);
840
+ return publishError;
395
841
  }
396
- // Draft 14 on has no end location in PUBLISH_DONE: an END_OF_TRACK object is what
397
- // tells the subscriber where the track ended.
398
- const final = track.final();
399
- if (ended && !publishError && final !== undefined) {
842
+ // PUBLISH_DONE has no end location: an END_OF_TRACK object is what tells the
843
+ // subscriber where the track ended. A range that stopped short of the end never saw
844
+ // it, and claiming it would end the subscriber's track early.
845
+ const final = hooks.subscriberEnd(track);
846
+ const wireEnd = final !== undefined ? this.#wireEnd(track, final, timescale) : undefined;
847
+ const reached = wireEnd !== undefined &&
848
+ (range.end === undefined ||
849
+ (wireEnd.object === 0
850
+ ? range.end.group >= wireEnd.group ||
851
+ (range.end.group + 1n === wireEnd.group &&
852
+ (range.end.object === undefined ||
853
+ this.#objectCapReachesEnd(track, range.end.group, range.end.object, timescale)))
854
+ : range.end.group > wireEnd.group ||
855
+ (range.end.group === wireEnd.group &&
856
+ (range.end.object === undefined || range.end.object + 1n >= BigInt(wireEnd.object)))));
857
+ if (!datagramTrack && ended && !publishError && wireEnd !== undefined && reached && !streams.terminalSent) {
400
858
  await this.#runEndOfTrack({
401
859
  requestId: msg.requestId,
402
- final,
860
+ group: wireEnd.group,
861
+ wireObject: wireEnd.object,
403
862
  publisherPriority,
404
863
  unsubscribed,
405
864
  streams,
@@ -409,144 +868,414 @@ export class Publisher {
409
868
  if (publishError) {
410
869
  console.warn(`publish error: broadcast=${name} track=${track.name} error=${reason(publishError)}`);
411
870
  }
871
+ // A revocation bridged from upstream, such as a moq-lite UNAUTHORIZED reset, is one here too.
872
+ // Before draft-23 PUBLISH_DONE's EXPIRED means the subscription's own lifetime ran out,
873
+ // so an expired token is reported as no longer granted. Draft-23 registers
874
+ // EXPIRED_AUTH_TOKEN for it (section 12.4).
875
+ const tokenExpired = publishError instanceof SessionError && publishError.code === SessionCode.Expired;
876
+ if ((publishError instanceof StreamError && publishError.code === StreamCode.Unauthorized) ||
877
+ (publishError instanceof SessionError &&
878
+ (publishError.code === SessionCode.Unauthorized || publishError.code === SessionCode.Expired))) {
879
+ unauthorized = true;
880
+ }
412
881
  // PUBLISH_DONE is required for every supported draft. The peer may have already
413
882
  // closed its side to unsubscribe, in which case there is nowhere to send it.
883
+ const updateFailed = publishError instanceof UpdateFailed;
884
+ // A malformed upstream, such as a moq-lite MALFORMED_TRACK reset, is passed on as one.
885
+ const malformed = publishError instanceof StreamError && publishError.code === StreamCode.MalformedTrack;
414
886
  try {
415
- await reply(async () => {
416
- replied = true;
417
- await stream.writer.u53(PublishDone.id);
418
- const done = new PublishDone({
419
- requestId: version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16
420
- ? msg.requestId
421
- : undefined,
422
- statusCode: publishError instanceof UpdateFailed
887
+ const done = new PublishDone({
888
+ statusCode: unauthorized
889
+ ? tokenExpired && isDraft23(version)
890
+ ? PublishDoneStatus.EXPIRED_AUTH_TOKEN
891
+ : PublishDoneStatus.UNAUTHORIZED
892
+ : updateFailed
423
893
  ? PublishDoneStatus.UPDATE_FAILED
424
- : publishError
425
- ? PublishDoneStatus.INTERNAL_ERROR
426
- : PublishDoneStatus.TRACK_ENDED,
427
- streamCount: BigInt(streams.opened),
428
- reasonPhrase: publishError instanceof UpdateFailed
894
+ : malformed
895
+ ? PublishDoneStatus.MALFORMED_TRACK
896
+ : publishError
897
+ ? PublishDoneStatus.INTERNAL_ERROR
898
+ : PublishDoneStatus.TRACK_ENDED,
899
+ streamCount: BigInt(streams.opened),
900
+ reasonPhrase: unauthorized
901
+ ? tokenExpired
902
+ ? "token expired"
903
+ : "not granted"
904
+ : updateFailed
429
905
  ? "update failed"
430
- : publishError
431
- ? "internal error"
432
- : "track ended",
433
- });
434
- await done.encode(stream.writer, version);
906
+ : malformed
907
+ ? "malformed track"
908
+ : publishError
909
+ ? "internal error"
910
+ : "track ended",
435
911
  });
912
+ await Message.write(request.writer, PublishDone.id, done, version);
436
913
  }
437
914
  catch {
438
915
  // Stream might already be closed by peer.
439
916
  }
440
917
  // Our close follows PUBLISH_DONE; it must not cancel data still queued for delivery.
441
918
  finished = true;
442
- stream.close();
919
+ request.close();
443
920
  }
444
921
  catch (err) {
922
+ if (err instanceof ProtocolViolation)
923
+ throw err;
445
924
  const e = error(err);
446
925
  console.warn(`publish error: broadcast=${name} track=${track.name} error=${reason(e)}`);
447
- stream.abort(e);
926
+ request.abort(e);
448
927
  }
449
928
  finally {
929
+ // Groups still draining keep being ranked until they finish.
930
+ ranking?.close();
931
+ datagrams?.close();
932
+ await datagramTask;
450
933
  track.close();
451
934
  // Idempotent, and the backstop for a throw between the fork and the fill starting:
452
935
  // #runFill closes it itself on every path it reaches.
453
936
  cache?.close();
454
937
  }
938
+ return undefined;
939
+ }
940
+ /**
941
+ * Forward one datagram track as OBJECT_DATAGRAM beside a stream subscription.
942
+ *
943
+ * Best-effort: a missing track, an oversized payload, or a datagram the draft cannot
944
+ * encode is dropped. The datagram track ending does not end the stream subscription.
945
+ */
946
+ async #sendDatagrams(datagrams, options) {
947
+ let info;
948
+ try {
949
+ info = await datagrams.info();
950
+ }
951
+ catch (err) {
952
+ console.debug(`serving the stream track without datagrams: ${reason(err)}`);
953
+ return;
954
+ }
955
+ const opened = this.#datagramWriter;
956
+ if (!opened)
957
+ return;
958
+ const publisher = info.priority;
959
+ const rank = () => sendOrder({ priority: options.priority.peek(), publisher, position: 2 ** 36 - 1 });
960
+ const sender = opened.open(rank());
961
+ const dispose = options.priority.subscribe(() => sender.setPriority(rank()));
962
+ const version = this.#session.version;
963
+ const max = DatagramStream.maxDatagramSize(this.#quic);
964
+ const left = hooks.datagramClosed(datagrams);
965
+ try {
966
+ for (;;) {
967
+ const next = await hooks.recvDatagramWire(datagrams);
968
+ if (!next)
969
+ return;
970
+ const { datagram, wire } = next;
971
+ let body;
972
+ try {
973
+ body = await encodeDatagram(datagram, {
974
+ trackAlias: options.alias,
975
+ publisherPriority: toWire(publisher),
976
+ wire,
977
+ }, version);
978
+ }
979
+ catch (err) {
980
+ console.debug(`dropping a datagram this draft cannot encode: ${reason(err)}`);
981
+ continue;
982
+ }
983
+ if (body.byteLength > max) {
984
+ console.debug(`dropping datagram larger than the transport limit: size=${body.byteLength} max=${max}`);
985
+ continue;
986
+ }
987
+ // A paused subscription must release its consumer even when transport writes stall.
988
+ await race([sender.writer.ready, left]);
989
+ if (left.peek() !== undefined)
990
+ return;
991
+ await race([sender.writer.write(body), left]);
992
+ if (left.peek() !== undefined)
993
+ return;
994
+ }
995
+ }
996
+ finally {
997
+ dispose();
998
+ await race([sender.close(), left]);
999
+ }
455
1000
  }
456
1001
  /**
457
1002
  * Runs a group and sends its frames using ObjectStream (Subgroup delivery mode).
458
1003
  */
459
1004
  async #runGroup(options) {
460
- const { requestId, group, timescale, publisherPriority, stamped, slice, unsubscribed, streams } = options;
1005
+ const { requestId, track, group, publisherPriority, ranking, live, bounds, unsubscribed, streams, timescale } = options;
1006
+ const { slice } = live;
1007
+ const excluded = Promise.withResolvers();
1008
+ let rangeError;
1009
+ // Set once the FIN is written, which keeps what the stream delivered.
1010
+ let finished = false;
1011
+ const narrowed = () => {
1012
+ if (excludes(bounds.peek(), group.start, slice)) {
1013
+ if (!finished)
1014
+ live.retired = true;
1015
+ rangeError = new StreamError(StreamCode.Cancel, { message: "group excluded by range update" });
1016
+ hooks.releaseGroupReader(group, rangeError);
1017
+ excluded.resolve();
1018
+ }
1019
+ };
1020
+ const changed = bounds.subscribe(narrowed);
1021
+ narrowed();
1022
+ // The subscription's budget, or an eviction of what is left to read, may give up on the
1023
+ // group mid-write, which abandons the stream. A group already given up never starts the write.
1024
+ const givenUp = new GivenUp(group);
461
1025
  try {
462
- // One stream per group is faster than a peer at its limit can retire them, so this
463
- // is the one path that doesn't wait for a slot: the transport would serve the opens
464
- // in the order we asked, which is oldest-first, exactly backwards for live media.
465
- // Failing here drops the group and lets the next one compete for the next slot.
466
- const stream = await Writer.tryOpen(this.#quic, {
467
- cancel: unsubscribed,
468
- version: this.#session.version,
469
- waitUntilAvailable: false,
1026
+ // Opens wait for stream credit in send order, and the place ranks this one against
1027
+ // the subscription's other groups while it waits.
1028
+ // Watch the group while the open waits, and release that watch once it settles.
1029
+ const place = ranking.reserve(group.start, slice.skip);
1030
+ const opened = Promise.withResolvers();
1031
+ let failure;
1032
+ const abandoned = givenUp
1033
+ .write(() => opened.promise)
1034
+ .then((stop) => {
1035
+ failure = stop;
470
1036
  });
1037
+ let stream;
1038
+ try {
1039
+ stream = await Writer.tryOpen(this.#quic, {
1040
+ version: this.#session.version,
1041
+ sendOrder: place.rank,
1042
+ cancel: race([unsubscribed, abandoned, excluded.promise]),
1043
+ group: true,
1044
+ });
1045
+ }
1046
+ finally {
1047
+ opened.resolve();
1048
+ place.release();
1049
+ }
471
1050
  if (!stream) {
472
- group.close(new Error("no stream slot"));
1051
+ hooks.releaseGroupReader(group, failure ?? new Error("unsubscribed while waiting for a stream"));
473
1052
  return;
474
1053
  }
475
1054
  streams.opened += 1;
1055
+ // A REQUEST_UPDATE re-ranks the subscription, so a group already on the wire follows it.
1056
+ ranking.add(stream, group.start, slice.skip);
1057
+ // Object 0 names the keys just below this group the track declared skipped, a
1058
+ // best-effort drop signal; a stream starting past object 0 carries no object 0.
1059
+ const groupGap = slice.skip === 0 ? hooks.skippedBelow(track, group.start) : 0n;
476
1060
  const header = new GroupMessage({
477
1061
  trackAlias: requestId,
478
- groupId: group.sequence,
479
- subGroupId: 0,
1062
+ groupId: group.start,
1063
+ subGroupId: 0n,
480
1064
  publisherPriority,
481
1065
  flags: {
482
- // The object properties carry the timestamp, so there is nothing to write
483
- // when the track declared no units to read one in.
484
- hasExtensions: stamped,
1066
+ // A timed track may emit TIMESTAMP_TIE on any frame, so carry extension lengths.
1067
+ hasExtensions: groupGap > 0n || timescale !== undefined,
485
1068
  hasSubgroup: false,
486
1069
  hasSubgroupObject: false,
487
- // A stream capped by the range stops before the group may end, so its FIN
488
- // cannot claim END_OF_GROUP.
489
- hasEnd: slice.until === undefined,
1070
+ // A FIN never claims the group's end: an explicit END_OF_GROUP does, once the
1071
+ // group finished, as in Rust.
1072
+ hasEnd: false,
490
1073
  hasPriority: true,
491
1074
  // Only honest when the stream really starts at the group's first object;
492
- // a trimmed head starts partway through.
1075
+ // a trimmed head starts partway through. A timed slice past Object 0 may still
1076
+ // start at frame 0, which its first read below settles.
493
1077
  firstObject: slice.skip === 0,
494
1078
  },
495
1079
  });
1080
+ // A pause or the subscriber leaving resets the stream, even mid-write: a write
1081
+ // parked on flow control would otherwise hold the pause's answer indefinitely.
1082
+ // CANCELLED, as the draft asks of a reset the subscriber caused: 0 would read as our failure.
1083
+ let left;
1084
+ const cancelled = unsubscribed.then(() => {
1085
+ left = new StreamError(StreamCode.Cancel, { message: "unsubscribed while serving the group" });
1086
+ });
1087
+ // Either ends serving the group: made once, so each read and write races one promise for both.
1088
+ const stopped = race([cancelled, excluded.promise]).then(() => false);
1089
+ // The stream closing ends the read too, told apart from the group finishing. Made once,
1090
+ // so a long group's reads all race the same promise.
1091
+ const closed = stream.closed.then(() => false);
1092
+ // A reset with no read left to race it is handled where the stream is.
1093
+ closed.catch(() => { });
1094
+ const write = async (op) => {
1095
+ const stop = await givenUp.write(op);
1096
+ if (stop)
1097
+ throw stop;
1098
+ };
1099
+ // Writing the group stops for the pause too; the drain below answers it without a reset.
1100
+ // One race covers the budget and both, rather than racing the budget's race again.
1101
+ const send = async (op) => {
1102
+ const stop = await givenUp.write(op, stopped);
1103
+ if (stop)
1104
+ throw stop;
1105
+ if (left)
1106
+ throw left;
1107
+ if (rangeError)
1108
+ throw rangeError;
1109
+ };
496
1110
  try {
497
- await hooks.guardGroup(group, () => header.encode(stream, this.#session.version));
498
- // The first written object goes on the wire as its absolute id, so a trimmed
499
- // head shows the true numbering rather than a silently renumbered group.
500
- let first = true;
501
- // The next object id that could be written, which starts at the filter rather
502
- // than at zero. A backwards range (`startObject` above `endObject` in the same
503
- // group) is empty, and starting here is what lets the check below see that
504
- // before the read parks on an object the range already excludes.
1111
+ const ids = timescale && new TimedIds(group.start, timescale);
1112
+ // Reading from the filter's start drops the objects below it: they are outside the
1113
+ // requested range, so skipping them is not a gap. A moq-timestamp ID follows the
1114
+ // one before it, so a timed read walks from frame 0.
1115
+ const readNext = () => race([hooks.readGroupFrame(group, false, ids ? 0 : slice.skip), closed, stopped]);
1116
+ // A timed slice past Object 0 starts at frame 0 only when frame 0's ID reaches it, so its
1117
+ // header waits on the first read, which the loop below then sends, as the Rust
1118
+ // `describe` waits for a write. A slice that selects nothing needs no frame.
1119
+ let held;
1120
+ if (timescale !== undefined &&
1121
+ slice.skip > 0 &&
1122
+ (slice.until === undefined || slice.until > slice.skip)) {
1123
+ const read = await readNext();
1124
+ // Frame 0's ID counts from the group's start alone.
1125
+ if (read && read.index === 0) {
1126
+ const dts = BigInt(floorAt(read.frame.timestamp, timescale));
1127
+ header.flags.firstObject =
1128
+ timestampObjectId(group.start, undefined, dts).id >= BigInt(slice.skip);
1129
+ }
1130
+ held = { read };
1131
+ }
1132
+ await send(() => header.encode(stream, this.#session.version));
1133
+ let priorObject;
505
1134
  let next = slice.skip;
1135
+ // Whether the group finished, rather than the range or a stop ending the read.
1136
+ let ended = false;
506
1137
  for (;;) {
507
1138
  // The filter ends inside this group: everything at `until` and beyond is
508
1139
  // outside the requested range, so stop without waiting for the group's end.
509
1140
  if (slice.until !== undefined && next >= slice.until)
510
1141
  break;
511
- // Reading from the filter's start drops the objects below it: they are outside
512
- // the requested range, so skipping them is not a gap.
513
- const read = await race([hooks.readGroupFrame(group, slice.skip), stream.closed]);
1142
+ const read = held ? held.read : await readNext();
1143
+ held = undefined;
1144
+ if (left)
1145
+ throw left;
1146
+ if (rangeError)
1147
+ throw rangeError;
1148
+ if (read === undefined)
1149
+ ended = true;
514
1150
  if (!read)
515
1151
  break;
516
- next = read.sequence + 1;
517
- if (slice.until !== undefined && read.sequence >= slice.until) {
518
- read.complete();
1152
+ const { id, tie } = ids ? ids.next(read) : { id: BigInt(read.index), tie: undefined };
1153
+ next = Number(id) + 1;
1154
+ if (slice.until !== undefined && Number(id) >= slice.until)
519
1155
  break;
520
- }
521
- try {
522
- const obj = new Frame({ payload: read.frame.payload, timestamp: read.frame.timestamp });
523
- const delta = first ? read.sequence : 0;
524
- first = false;
525
- await hooks.guardGroup(group, () => obj.encode(stream, header.flags, timescale, this.#session.version, delta));
526
- }
527
- finally {
528
- read.complete();
529
- }
1156
+ if (Number(id) < slice.skip)
1157
+ continue;
1158
+ // A frame written in pieces streams its payload after the header.
1159
+ const chunks = read.chunks;
1160
+ const gap = read.index === 0 ? groupGap : undefined;
1161
+ const obj = chunks?.size
1162
+ ? new Frame({ streamed: chunks.size, groupGap: gap, tie })
1163
+ : new Frame({ payload: chunks ? new Uint8Array(0) : read.frame.payload, groupGap: gap, tie });
1164
+ const delta = priorObject === undefined ? id : id - priorObject - 1n;
1165
+ priorObject = id;
1166
+ await send(() => obj.encode(stream, header.flags, this.#session.version, delta));
1167
+ // Even an empty one: it is an object only once committed, and may still be aborted.
1168
+ if (chunks)
1169
+ await send(() => sendPayload(chunks, (chunk) => stream.write(chunk), stream.closed));
1170
+ }
1171
+ // The track ends right after this group's last object, so the marker rides this
1172
+ // stream rather than a separate one.
1173
+ const last = ids ? ids.nextMin() : group.frameCount;
1174
+ const end = hooks.subscriberEnd(track);
1175
+ const inRange = last >= slice.skip && (slice.until === undefined || last < slice.until);
1176
+ const marked = ended && inRange && end?.group === group.start && end.frame === group.frameCount;
1177
+ // A finished group ends with END_OF_GROUP one past its last object, unless the
1178
+ // END_OF_TRACK below marks that place or the range misses it: a filter starting
1179
+ // past the group's end, or one stopping short of it.
1180
+ if (ended && !marked && inRange) {
1181
+ const endDelta = priorObject === undefined ? BigInt(last) : BigInt(last) - priorObject - 1n;
1182
+ await send(() => new Frame().encode(stream, header.flags, this.#session.version, endDelta));
1183
+ }
1184
+ else if (marked) {
1185
+ const endDelta = priorObject === undefined ? BigInt(last) : BigInt(last) - priorObject - 1n;
1186
+ await send(() => new Frame({ endOfTrack: true }).encode(stream, header.flags, this.#session.version, endDelta));
530
1187
  }
531
1188
  stream.close();
1189
+ finished = true;
1190
+ // The stream holds every byte it owes, so frames past a range's end failing upstream
1191
+ // can no longer give it up: release the read, leaving the budget.
1192
+ group.close();
1193
+ // Its bytes still hold the connection until acknowledged, so a group gone stale
1194
+ // meanwhile is reset like one still serving, as the Rust `GroupServe` does. Awaited
1195
+ // even without a marker: PUBLISH_DONE waits on this group, so the track, whose
1196
+ // timeline judges the budget, stays open until the stream settles.
1197
+ const delivered = await race([
1198
+ write(() => stream.closed).then(() => true),
1199
+ unsubscribed.then(() => false),
1200
+ excluded.promise.then(() => false),
1201
+ ]);
1202
+ // Only a stream that closed cleanly delivered the marker: one reset after its FIN
1203
+ // may not have, which leaves the standalone fallback in place, as in Rust.
1204
+ if (marked)
1205
+ streams.terminalSent = delivered === true;
532
1206
  }
533
1207
  catch (err) {
534
1208
  stream.reset(error(err));
535
1209
  }
1210
+ finally {
1211
+ // A closed stream may still have data queued behind its FIN, so it keeps
1212
+ // competing at its rank until the stream settles.
1213
+ void stream.closed.catch(() => { }).then(() => ranking.remove(stream));
1214
+ }
1215
+ }
1216
+ catch (err) {
1217
+ // A failed open has no stream to reset, but still ends only this group.
1218
+ hooks.releaseGroupReader(group, error(err));
536
1219
  }
537
1220
  finally {
1221
+ changed();
1222
+ givenUp.close();
538
1223
  group.close();
539
1224
  }
540
1225
  }
541
1226
  /**
542
- * Mark the track's end with an END_OF_TRACK object on its own stream, at object 0 of the
543
- * group that will never exist.
544
- *
545
- * The last group's stream has usually finished before the track ends, so the marker cannot
546
- * ride on it. A failure only costs the subscriber the early boundary.
1227
+ * Where the track ends on this subscription's wire: past the moq-timestamp ID of the last frame
1228
+ * before `final` when `timescale` is set, else `final` itself. Undefined when this copy cannot
1229
+ * prove that ID, which is no end to declare. Mirrors the Rust `wire_end`.
547
1230
  */
1231
+ #wireEnd(track, final, timescale) {
1232
+ if (!timescale || final.frame <= 0)
1233
+ return { group: final.group, object: final.frame };
1234
+ const cached = hooks.cachedGroup(track, final.group);
1235
+ if (!cached)
1236
+ return undefined;
1237
+ try {
1238
+ const settled = hooks.groupSettledFrames(cached);
1239
+ // An empty finished group was delivered, moving the subscriber's live edge past it.
1240
+ if (settled === 0)
1241
+ return { group: final.group + 1n, object: 0 };
1242
+ const frame = settled === undefined ? final.frame : Math.min(final.frame, settled);
1243
+ const id = hooks.groupTimedId(cached, frame - 1, timescale);
1244
+ return id === undefined ? undefined : { group: final.group, object: Number(id) + 1 };
1245
+ }
1246
+ finally {
1247
+ cached.close();
1248
+ }
1249
+ }
1250
+ /**
1251
+ * Whether a range ending at object `cap` of `group` reaches that group's last object, on this
1252
+ * subscription's wire. A timed group this copy cannot prove the last ID of doesn't.
1253
+ */
1254
+ #objectCapReachesEnd(track, group, cap, timescale) {
1255
+ const cached = hooks.cachedGroup(track, group);
1256
+ if (cached) {
1257
+ try {
1258
+ const count = hooks.groupSettledFrames(cached) ?? cached.frameCount;
1259
+ if (count === 0)
1260
+ return true;
1261
+ const last = timescale ? hooks.groupTimedId(cached, count - 1, timescale) : BigInt(count - 1);
1262
+ return last !== undefined && cap >= last;
1263
+ }
1264
+ finally {
1265
+ cached.close();
1266
+ }
1267
+ }
1268
+ const largest = hooks.objectLargest(track);
1269
+ if (largest === undefined || largest.group < group)
1270
+ return true;
1271
+ // An ordinal only bounds a moq-timestamp ID from below.
1272
+ if (largest.group === group && !timescale)
1273
+ return cap >= BigInt(largest.frame);
1274
+ return false;
1275
+ }
1276
+ /** Preserve the original terminal on a separate stream when its group already sent FIN. */
548
1277
  async #runEndOfTrack(options) {
549
- const { requestId, final, publisherPriority, unsubscribed, streams } = options;
1278
+ const { requestId, group, wireObject, publisherPriority, unsubscribed, streams } = options;
550
1279
  const version = this.#session.version;
551
1280
  const stream = await Writer.tryOpen(this.#quic, { cancel: unsubscribed, version }).catch(() => undefined);
552
1281
  if (!stream)
@@ -555,8 +1284,8 @@ export class Publisher {
555
1284
  try {
556
1285
  const header = new GroupMessage({
557
1286
  trackAlias: requestId,
558
- groupId: final,
559
- subGroupId: 0,
1287
+ groupId: group,
1288
+ subGroupId: 0n,
560
1289
  publisherPriority,
561
1290
  flags: {
562
1291
  hasExtensions: false,
@@ -564,11 +1293,11 @@ export class Publisher {
564
1293
  hasSubgroupObject: false,
565
1294
  hasEnd: false,
566
1295
  hasPriority: true,
567
- firstObject: true,
1296
+ firstObject: wireObject === 0,
568
1297
  },
569
1298
  });
570
1299
  await header.encode(stream, version);
571
- await new Frame({ endOfTrack: true }).encode(stream, header.flags, Timescale.MILLI, version);
1300
+ await new Frame({ endOfTrack: true }).encode(stream, header.flags, version, wireObject);
572
1301
  stream.close();
573
1302
  }
574
1303
  catch (err) {
@@ -576,15 +1305,14 @@ export class Publisher {
576
1305
  }
577
1306
  }
578
1307
  /**
579
- * Serve a draft-20 fill on its own fetch stream: the requested range, read from the
580
- * group cache, capped at the Largest Object snapshot.
1308
+ * Serve the largest group's head on its own draft-22 fetch stream.
581
1309
  *
582
1310
  * A fill is a promise once requested. An empty range opens no stream, but a range we
583
1311
  * cannot serve still opens one and resets it right after the FETCH_HEADER, the draft's
584
1312
  * fill-failure signal. Nothing here touches the subscription either way.
585
1313
  */
586
1314
  async #runFill(options) {
587
- const { requestId, fill, cache, timescale, stamped, unsubscribed, streams } = options;
1315
+ const { requestId, ranking, fill, cache, publisherPriority, unsubscribed, cancelled, streams, timescale } = options;
588
1316
  const version = this.#session.version;
589
1317
  // Everything is inside the try so the cache fork is released on every path out,
590
1318
  // including a transport failure while opening the stream.
@@ -592,24 +1320,52 @@ export class Publisher {
592
1320
  try {
593
1321
  if (fill.kind === "empty")
594
1322
  return;
595
- stream = await Writer.tryOpen(this.#quic, { cancel: unsubscribed, version });
1323
+ // A fill we cannot serve is reset right after its header, so it needs no rank.
1324
+ const key = fill.kind === "group" ? fill.start.group : undefined;
1325
+ const object = fill.kind === "group" ? frameBound(fill.start.object) : 0;
1326
+ stream = await Writer.tryOpen(this.#quic, {
1327
+ cancel: unsubscribed,
1328
+ version,
1329
+ sendOrder: key === undefined ? undefined : ranking.rank(key, object),
1330
+ });
596
1331
  if (!stream) {
597
1332
  console.debug(`fill stream failed to open: fill=${requestId}`);
598
1333
  return;
599
1334
  }
600
1335
  streams.opened += 1;
601
- await new FetchHeader({ requestId }).encode(stream, version);
1336
+ if (key !== undefined)
1337
+ ranking.add(stream, key, object);
1338
+ await untilAborted(new FetchHeader({ requestId }).encode(stream, version), cancelled);
602
1339
  if (fill.kind !== "group") {
603
- throw new Error("a fill spanning several groups is not supported");
1340
+ throw new Error("fill is not supported");
604
1341
  }
605
- const group = takeGroup(cache, Number(fill.sequence));
1342
+ const out = new FetchWriter({ stream, version, priority: publisherPriority });
1343
+ // Judged by the subscription's budget, as the Rust fill's fetched group is, so a fill
1344
+ // parked on flow control or awaiting its acknowledgement gives up once it goes stale.
1345
+ const group = hooks.judgedGroup(cache, fill.start.group);
1346
+ if (!group)
1347
+ throw new NotFound("fill group unavailable");
1348
+ const given = untilGivenUp(group, cancelled);
606
1349
  try {
607
- await this.#writeFillGroup(stream, group, fill, timescale, stamped, unsubscribed);
1350
+ await this.#writeFetchGroup({
1351
+ out,
1352
+ group,
1353
+ slice: groupSlice(fill, group.start),
1354
+ timescale,
1355
+ cancelled: given.signal,
1356
+ });
1357
+ stream.close();
1358
+ // The stream holds every byte it owes, so frames past its range failing upstream can
1359
+ // no longer give it up: release the read, leaving the budget, as `#runGroup` does.
1360
+ group.close();
1361
+ // Its bytes still hold the connection until acknowledged, so a group gone stale
1362
+ // meanwhile, or the subscriber leaving, resets it, as the Rust `RunFill` does.
1363
+ await untilAborted(stream.closed.catch(() => undefined), given.signal);
608
1364
  }
609
1365
  finally {
1366
+ given.release();
610
1367
  group.close();
611
1368
  }
612
- stream.close();
613
1369
  console.debug(`fill complete: fill=${requestId}`);
614
1370
  }
615
1371
  catch (err) {
@@ -619,143 +1375,199 @@ export class Publisher {
619
1375
  stream?.reset(e);
620
1376
  }
621
1377
  finally {
1378
+ // Ranked until it settles, like a group stream.
1379
+ if (stream) {
1380
+ const opened = stream;
1381
+ void opened.closed.catch(() => { }).then(() => ranking.remove(opened));
1382
+ }
622
1383
  cache.close();
623
1384
  }
624
1385
  }
625
1386
  /**
626
- * Write one cached group's frames as draft-20 fetch objects.
627
- *
628
- * The cap is the Largest Object snapshot: the group may keep growing, but everything
629
- * past the snapshot belongs to the subscription, not the fill.
1387
+ * Stream one group's selected objects for a FETCH or subscription fill.
1388
+ * A bound ends the response without waiting for the live group's end.
630
1389
  */
631
- async #writeFillGroup(stream, group, fill, timescale, stamped, unsubscribed) {
632
- let first = true;
633
- let next = 0n;
1390
+ async #writeFetchGroup({ out, group, slice, timescale, cancelled, }) {
1391
+ let next = slice.skip;
1392
+ const ids = timescale && new TimedIds(group.start, timescale);
634
1393
  // The subscriber leaving has to end the fill too. An absolute filter ending below the
635
1394
  // edge with no end object leaves `until` unset, so this reads until the group closes,
636
1395
  // which a still-open past group may never do. Watching only the fetch stream would
637
1396
  // then pin the group and the cache subscription behind it for the life of the track.
638
- let left = false;
639
- const cancelled = unsubscribed.then(() => {
640
- left = true;
641
- return undefined;
642
- });
643
1397
  for (;;) {
644
1398
  // The group may keep growing, but everything at `until` and beyond belongs to the
645
1399
  // subscription, so stop without waiting for the group's end.
646
- if (fill.until !== undefined && next >= fill.until)
1400
+ if (slice.until !== undefined && next >= slice.until)
647
1401
  break;
648
1402
  // Reading from the fill's start drops everything below it; see the same read in #runGroup.
649
- const frame = await race([group.readFrameSequence({ from: Number(fill.skip) }), stream.closed, cancelled]);
650
- if (left)
651
- throw new Error("unsubscribed before the fill finished");
1403
+ const frame = await untilAborted(race([hooks.readGroupFrame(group, false, ids ? 0 : slice.skip), out.stream.closed]), cancelled);
652
1404
  if (!frame)
653
1405
  break;
654
- next = BigInt(frame.sequence) + 1n;
655
- if (fill.until !== undefined && BigInt(frame.sequence) >= fill.until)
1406
+ const timed = ids?.next(frame);
1407
+ const oid = timed ? Number(timed.id) : frame.index;
1408
+ const tie = timed?.tie;
1409
+ next = oid + 1;
1410
+ if (slice.until !== undefined && oid >= slice.until)
656
1411
  break;
657
- const obj = new FetchFrame({ payload: frame.payload, timestamp: stamped ? frame.timestamp : undefined });
658
- await obj.encode(stream, { group: Number(fill.sequence), object: frame.sequence, first }, timescale, this.#session.version);
659
- first = false;
1412
+ if (oid < slice.skip)
1413
+ continue;
1414
+ await out.object(group.start, frame, cancelled, oid, tie);
660
1415
  }
661
1416
  }
1417
+ /**
1418
+ * Close the session when our origin publishes a broadcast our grant does not cover;
1419
+ * see {@link enforceGrant}.
1420
+ *
1421
+ * @internal
1422
+ */
1423
+ async runEnforce(setupAnswered, auth) {
1424
+ await enforceGrant({ quic: this.#quic, advertised: this.#advertised, grant: this.#grant, setupAnswered, auth });
1425
+ }
662
1426
  /**
663
1427
  * Handles an incoming SUBSCRIBE_NAMESPACE on a bidi stream.
664
1428
  *
665
- * Draft-16+ fills the stream with every visible match, independently of unsolicited
666
- * discovery. Draft-14/15 use PUBLISH_NAMESPACE requests instead and suppress matches
667
- * already announced on the unsolicited path. Hidden visibility applies to both.
1429
+ * On draft-16 and later every visible match is a NAMESPACE on this stream, whatever
1430
+ * the peer's SETUP said. A NAMESPACE is discovery, not a route, so a peer that also
1431
+ * hears the unsolicited PUBLISH_NAMESPACE still gets the match here.
668
1432
  *
669
1433
  * @internal
670
1434
  */
671
- async runSubscribeNamespace(msg, stream) {
1435
+ runSubscribeNamespace(msg, stream) {
1436
+ const request = new RequestStream(stream, this.#session, this.#quic);
1437
+ return this.#withdrawal.track(request.serve(this.#runSubscribeNamespace(msg, request)));
1438
+ }
1439
+ async #runSubscribeNamespace(msg, request) {
1440
+ if (Namespace.reserved(msg.namespace, this.#session.version)) {
1441
+ await refuseReserved(request);
1442
+ return;
1443
+ }
1444
+ if (this.#withdrawal.closing.peek())
1445
+ return;
672
1446
  const version = this.#session.version;
673
- const prefix = msg.namespace;
674
- const legacy = version === Version.DRAFT_14 || version === Version.DRAFT_15;
675
- // Draft-14/15: the open PUBLISH_NAMESPACE request per advertised suffix.
676
- const requests = new Map();
677
- const ending = cancelled(stream, version);
1447
+ let prefix = msg.namespace;
1448
+ const ending = request.ended;
1449
+ const readUpdate = () => (async () => {
1450
+ const framed = await request.next();
1451
+ return { update: framed && (await namespaceUpdate(framed, version)) };
1452
+ })().catch((err) => ({ error: error(err) }));
1453
+ let updating = readUpdate();
678
1454
  try {
679
- // Send OK response
680
- if (version === Version.DRAFT_14) {
681
- await stream.writer.u53(SubscribeNamespaceOk.id);
682
- const ok = new SubscribeNamespaceOk({ requestId: msg.requestId });
683
- await ok.encode(stream.writer, version);
684
- }
685
- else {
686
- await stream.writer.u53(RequestOk.id);
687
- const ok = new RequestOk({
688
- requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined,
689
- });
690
- await ok.encode(stream.writer, version);
691
- }
692
- // Only legacy requests create another route; inline entries always fill the query.
693
- // Hidden namespaces still require opt-in unless the prefix names them directly.
694
- const carries = (covered) => (!this.#hidden || msg.hidden || !hiddenBelow(prefix, covered)) &&
695
- (!legacy || this.#requiresSolicitation || (this.#hidden && hiddenBelow(Path.empty(), covered)));
1455
+ const answer = async (activeCount) => {
1456
+ const parameters = new Parameters();
1457
+ parameters.activeCount = activeCount;
1458
+ await Message.write(request.writer, RequestOk.id, new RequestOk({ parameters }), version);
1459
+ };
1460
+ // MoQ Active Count: the OK counts what the first pass below sends, so it waits for
1461
+ // that pass. Otherwise answer now.
1462
+ let answered = !this.#activeCount;
1463
+ if (answered)
1464
+ await answer();
1465
+ // Hidden namespaces are left out unless the peer opted in (MoQ Hidden).
1466
+ const visible = (covered) => !this.#hidden || msg.hidden || !hiddenBelow(prefix, covered);
1467
+ const carries = (covered) => visible(covered) && this.#gate.allows(covered);
696
1468
  // Inline entries always land, and the receiver treats a repeated NAMESPACE as a
697
1469
  // replacement, so repricing one is just sending it again, a new original
698
- // publisher included, as Rust does. Only a legacy PUBLISH_NAMESPACE request can
699
- // be declined.
1470
+ // publisher included, as Rust does.
700
1471
  const namespace = async (suffix, snap) => {
701
- await stream.writer.u53(SubscribeNamespaceEntry.id);
702
- const cluster = clusterFor(this.#advert, snap.route);
703
- await new SubscribeNamespaceEntry({ suffix, cluster }).encode(stream.writer, version);
1472
+ // MoQ Cluster puts the Parameters field on NAMESPACE.
1473
+ const params = this.#advert !== undefined ? this.#params(snap.route) : undefined;
1474
+ const entry = new SubscribeNamespaceEntry({ suffix, params });
1475
+ await Message.write(request.writer, SubscribeNamespaceEntry.id, entry, version);
704
1476
  return "held";
705
1477
  };
706
- const target = legacy
707
- ? {
708
- advertise: (suffix, snap) => this.#advertise(Path.join(prefix, suffix), requests, clusterFor(this.#advert, snap.route)),
709
- update: (suffix, _snap, reprice) => this.#update(Path.join(prefix, suffix), requests, reprice),
710
- withdraw: (suffix) => this.#withdraw(Path.join(prefix, suffix), requests),
711
- }
712
- : {
713
- advertise: namespace,
714
- update: namespace,
715
- withdraw: async (suffix) => {
716
- await stream.writer.u53(SubscribeNamespaceEntryDone.id);
717
- await new SubscribeNamespaceEntryDone({ suffix }).encode(stream.writer, version);
718
- },
719
- };
1478
+ const target = {
1479
+ advertise: namespace,
1480
+ update: namespace,
1481
+ held: () => undefined,
1482
+ carry: () => undefined,
1483
+ withdraw: async (suffix) => {
1484
+ const done = new SubscribeNamespaceEntryDone({ suffix });
1485
+ await Message.write(request.writer, SubscribeNamespaceEntryDone.id, done, version);
1486
+ },
1487
+ };
720
1488
  // Keyed by suffix, as the entries name them.
721
- const ns = { active: new Map(), refused: new Map(), offered: new Map() };
1489
+ const ns = { active: new Map(), refused: new Map(), offered: new Map(), reoffer: new Map() };
722
1490
  let retry = 0;
723
1491
  for (;;) {
724
1492
  // Subscribe BEFORE reconciling, for the same reason as
725
1493
  // {@link runPublishNamespaces}: a publish landing while an advertisement
726
1494
  // waits for its reply only notifies listeners already registered.
727
- // TODO Make a better helper within Signals.
728
- let dispose;
729
- const changed = new Promise((resolve) => {
730
- dispose = this.#advertised.changed(resolve);
731
- });
1495
+ // A grant change re-diffs the same way, withdrawing what it no longer covers.
1496
+ // The loop top re-reads the table, so an ended origin still stops it there.
1497
+ // A token that ended leaves the request carrying it to be made again without.
1498
+ const { changed, dispose } = nextChange(this.#advertised, this.#grant, this.#auth?.ended);
732
1499
  const advertised = this.#advertised.peek();
1500
+ const root = this.#publish && wireOf(this.#publish).root;
1501
+ const updated = advertised
1502
+ ? presented(prefix, advertised, carries, { root })
1503
+ : new Map();
1504
+ // A fresh pass sends a NAMESPACE for every entry, ahead of any change.
1505
+ if (!answered) {
1506
+ answered = true;
1507
+ await answer(updated.size);
1508
+ }
733
1509
  if (!advertised) {
734
1510
  dispose();
735
1511
  break;
736
1512
  }
737
- const outstanding = await this.#reconcile(ns, presented(prefix, advertised, carries), target);
1513
+ const outstanding = await this.#reconcile(ns, updated, target);
738
1514
  retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
739
1515
  // Wait for the next change, or for the peer to unsubscribe.
740
1516
  const next = await (retry
741
- ? race([changed, ending, retryAfter(retry).then(() => advertised)])
742
- : race([changed, ending]));
1517
+ ? race([
1518
+ changed,
1519
+ this.#withdrawal.closing,
1520
+ ending,
1521
+ ...(updating !== undefined ? [updating] : []),
1522
+ retryAfter(retry).then(() => advertised),
1523
+ ])
1524
+ : race([changed, this.#withdrawal.closing, ending, ...(updating !== undefined ? [updating] : [])]));
743
1525
  dispose();
744
- if (!next)
1526
+ if (!next || next === true)
745
1527
  break;
1528
+ if (typeof next === "object" && "error" in next)
1529
+ throw next.error;
1530
+ if (typeof next === "object" && "update" in next) {
1531
+ const update = next.update;
1532
+ updating = undefined;
1533
+ if (!update)
1534
+ continue;
1535
+ this.#session.checkRequestId(update.requestId);
1536
+ if (update.refused || (update.prefix !== undefined && Namespace.reserved(update.prefix, version))) {
1537
+ await refuseUpdate(request.writer, version, "subscribe_namespace", {
1538
+ condition: update.refused ?? "does_not_exist",
1539
+ reasonPhrase: "namespace update refused",
1540
+ });
1541
+ break;
1542
+ }
1543
+ if (update.prefix !== undefined && update.prefix !== prefix) {
1544
+ for (const suffix of ns.active.keys())
1545
+ await target.withdraw(suffix);
1546
+ ns.active.clear();
1547
+ ns.offered.clear();
1548
+ ns.refused.clear();
1549
+ ns.reoffer.clear();
1550
+ prefix = update.prefix;
1551
+ // A new cursor starts its backoff fresh, as in Rust.
1552
+ retry = 0;
1553
+ }
1554
+ await Message.write(request.writer, RequestOk.id, new RequestOk(), version);
1555
+ updating = readUpdate();
1556
+ }
746
1557
  }
747
- stream.close();
1558
+ request.close();
1559
+ await request.writer.closed;
748
1560
  }
749
1561
  catch (err) {
750
1562
  const e = error(err);
751
1563
  console.debug(`subscribe_namespace stream error: ${reason(e)}`);
752
- stream.abort(e);
1564
+ request.abort(e);
1565
+ if (e instanceof ProtocolViolation || this.#withdrawal.closing.peek())
1566
+ throw e;
753
1567
  }
754
1568
  finally {
755
- // This subscription's advertisements die with it.
756
- for (const path of [...requests.keys()]) {
757
- await this.#withdraw(path, requests);
758
- }
1569
+ // Closing stopped the read, which settles it.
1570
+ await updating;
759
1571
  }
760
1572
  }
761
1573
  /**
@@ -764,13 +1576,19 @@ export class Publisher {
764
1576
  *
765
1577
  * The peers that never send SUBSCRIBE_NAMESPACE are exactly the ones expecting a
766
1578
  * publisher to announce itself, so announcing is the default. A peer that would
767
- * rather ask says so in its SETUP (MoQ Solicit) and this does nothing, leaving
768
- * {@link runSubscribeNamespace} to carry the advertisements instead. Modern peers
769
- * may also discover the namespace through an inline subscription fill.
1579
+ * rather ask says so in its SETUP (MoQ Solicit) and this does nothing.
1580
+ * {@link runSubscribeNamespace} also carries every match, so a peer that
1581
+ * did not ask hears each namespace both ways. A NAMESPACE is discovery only, not a
1582
+ * second route.
770
1583
  *
771
1584
  * @internal
772
1585
  */
773
- async runPublishNamespaces() {
1586
+ runPublishNamespaces() {
1587
+ return this.#withdrawal.track(this.#runPublishNamespaces());
1588
+ }
1589
+ async #runPublishNamespaces() {
1590
+ if (this.#withdrawal.closing.peek())
1591
+ return;
774
1592
  if (this.#requiresSolicitation) {
775
1593
  // The peer asked to be told on request; runSubscribeNamespace answers it.
776
1594
  return;
@@ -778,9 +1596,11 @@ export class Publisher {
778
1596
  // The open PUBLISH_NAMESPACE request per advertised path.
779
1597
  const requests = new Map();
780
1598
  const target = {
781
- advertise: (path, snap) => this.#advertise(path, requests, clusterFor(this.#advert, snap.route)),
1599
+ advertise: (path, snap) => this.#advertise(path, requests, snap.route),
782
1600
  update: (path, _snap, reprice) => this.#update(path, requests, reprice),
783
1601
  withdraw: (path) => this.#withdraw(path, requests),
1602
+ held: (path) => requests.get(path)?.auth,
1603
+ carry: (auth) => this.#carry(auth),
784
1604
  };
785
1605
  // The origin outlives the session and its signal never ends, so this loop needs the
786
1606
  // session's own ending to stop: without it a closed connection leaves the loop parked
@@ -791,18 +1611,33 @@ export class Publisher {
791
1611
  let dispose;
792
1612
  try {
793
1613
  // Keyed by path.
794
- const ns = { active: new Map(), refused: new Map(), offered: new Map() };
1614
+ const ns = { active: new Map(), refused: new Map(), offered: new Map(), reoffer: new Map() };
1615
+ // How long to stay away the next time the peer ends each advertisement while idle,
1616
+ // and the identity that wait is about.
1617
+ const lapses = new Map();
795
1618
  let retry = 0;
796
1619
  for (;;) {
797
1620
  // Subscribe BEFORE reconciling. Each advertisement below waits a round trip
798
1621
  // for the peer's reply, and a publish that lands in that window notifies
799
1622
  // only the listeners already registered; one created afterwards would sleep
800
1623
  // through it and leave the namespace unadvertised until something unrelated
801
- // changed.
802
- // TODO Make a better helper within Signals.
803
- const changed = new Promise((resolve) => {
804
- dispose = this.#advertised.changed(resolve);
805
- });
1624
+ // changed. A grant change re-diffs the same way, withdrawing what it no longer
1625
+ // covers; the loop top re-reads the table, so an ended origin still stops it there.
1626
+ // A token that ended leaves the request carrying it to be made again without.
1627
+ const change = nextChange(this.#advertised, this.#grant, this.#auth?.ended, this.#lapsed);
1628
+ dispose = change.dispose;
1629
+ // The peer no longer holds a namespace whose request ended while idle. The wait
1630
+ // before offering it again doubles each time, so a peer that ends every one it
1631
+ // accepts sees them on a backoff rather than in a loop.
1632
+ for (const [key, snap] of [...ns.active]) {
1633
+ if (requests.has(key))
1634
+ continue;
1635
+ ns.active.delete(key);
1636
+ const wait = lapses.get(key)?.wait ?? RETRY_BASE;
1637
+ lapses.set(key, { snap, wait: Math.min(wait * 2, RETRY_MAX) });
1638
+ ns.refused.set(key, now().saturatingAdd(Duration.millis(wait)));
1639
+ ns.offered.set(key, snap);
1640
+ }
806
1641
  const advertised = this.#advertised.peek();
807
1642
  if (!advertised) {
808
1643
  dispose?.();
@@ -810,19 +1645,28 @@ export class Publisher {
810
1645
  }
811
1646
  const updated = new Map();
812
1647
  for (const [covered, candidates] of advertised) {
813
- // Only peers that declared MoQ Hidden filter unsolicited discovery.
814
- if ((this.#hidden && hiddenBelow(Path.empty(), covered)) || candidates.length === 0)
1648
+ // Only peers that declared MoQ Hidden filter unsolicited discovery, and
1649
+ // nothing our grant does not cover reaches the peer at all.
1650
+ if ((this.#hidden && hiddenBelow(Path.empty(), covered)) || !this.#gate.allows(covered))
815
1651
  continue;
816
- updated.set(covered, candidates[0]);
1652
+ const best = firstEligible(candidates);
1653
+ if (best)
1654
+ updated.set(covered, best);
1655
+ }
1656
+ // Another broadcast at the path starts its backoff fresh, as a refusal does.
1657
+ for (const [key, lapse] of lapses) {
1658
+ const snap = updated.get(key);
1659
+ if (snap === undefined || !sameIdentity(lapse.snap, snap))
1660
+ lapses.delete(key);
817
1661
  }
818
1662
  const outstanding = await this.#reconcile(ns, updated, target);
819
1663
  retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
820
1664
  // Wait for the next change, which has already fired if one landed above.
821
1665
  const next = await (retry
822
- ? race([changed, closed, retryAfter(retry).then(() => advertised)])
823
- : race([changed, closed]));
1666
+ ? race([change.changed, this.#withdrawal.closing, closed, retryAfter(retry).then(() => advertised)])
1667
+ : race([change.changed, this.#withdrawal.closing, closed]));
824
1668
  dispose?.();
825
- if (!next)
1669
+ if (!next || next === true)
826
1670
  break;
827
1671
  }
828
1672
  }
@@ -830,6 +1674,8 @@ export class Publisher {
830
1674
  // Nothing restarts this loop, so whatever got us here cost the session its
831
1675
  // discovery. Not a debug-level event.
832
1676
  console.warn(`publish_namespace loop failed: ${reason(error(err))}`);
1677
+ if (this.#withdrawal.closing.peek())
1678
+ throw err;
833
1679
  }
834
1680
  finally {
835
1681
  dispose?.();
@@ -844,7 +1690,7 @@ export class Publisher {
844
1690
  * whether anything it should hold is still missing and worth coming back for.
845
1691
  *
846
1692
  * Nothing the peer cannot see is sent, a reprice updates the namespace in place, and
847
- * anything else is withdrawn first so a republish reads as withdraw-then-advertise.
1693
+ * a changed identity is withdrawn before it is advertised again.
848
1694
  * `ns` records what the peer holds rather than what we attempted: a declined
849
1695
  * advertisement or update stays out of it, so the next turn offers it fresh instead
850
1696
  * of believing it is already up.
@@ -857,21 +1703,25 @@ export class Publisher {
857
1703
  // by rebuilding the watched entry.
858
1704
  for (const key of [...ns.refused.keys()]) {
859
1705
  const snap = updated.get(key);
860
- if (snap === undefined || ns.offered.get(key) !== snap.identity) {
1706
+ const offered = ns.offered.get(key);
1707
+ // Another publisher identity is another broadcast too.
1708
+ if (snap === undefined || offered === undefined || !sameIdentity(offered, snap)) {
861
1709
  ns.refused.delete(key);
862
1710
  ns.offered.delete(key);
1711
+ ns.reoffer.delete(key);
863
1712
  }
864
1713
  }
865
1714
  const held = new Map(ns.active);
866
1715
  for (const [key, snap] of ns.active) {
867
- if (change(this.#advert, snap, updated.get(key)) !== "restart")
1716
+ const next = updated.get(key);
1717
+ if (this.#change(key, snap, next, target) !== "restart")
868
1718
  continue;
869
1719
  await target.withdraw(key);
870
1720
  held.delete(key);
871
1721
  }
872
1722
  for (const [key, snap] of updated) {
873
1723
  const prev = held.get(key);
874
- const diff = change(this.#advert, prev, snap);
1724
+ const diff = this.#change(key, prev, snap, target);
875
1725
  if (diff === "same")
876
1726
  continue;
877
1727
  let answer;
@@ -889,32 +1739,65 @@ export class Publisher {
889
1739
  held.set(key, snap);
890
1740
  ns.refused.delete(key);
891
1741
  ns.offered.delete(key);
1742
+ // Taken: the next refusal starts its wait over.
1743
+ ns.reoffer.delete(key);
892
1744
  }
893
1745
  else {
894
1746
  held.delete(key);
895
- if (answer !== "dropped") {
1747
+ if (answer === "declined") {
1748
+ // The wait doubles each time, so a peer that could not take the name yet is
1749
+ // asked again soon, and one that never wants it once a REOFFER_MAX.
1750
+ const wait = ns.reoffer.get(key) ?? REOFFER_BASE;
1751
+ ns.reoffer.set(key, Math.min(wait * 2, REOFFER_MAX));
1752
+ ns.refused.set(key, now().saturatingAdd(Duration.millis(wait)));
1753
+ ns.offered.set(key, snap);
1754
+ }
1755
+ else if (answer !== "dropped") {
896
1756
  ns.refused.set(key, answer);
897
- ns.offered.set(key, snap.identity);
1757
+ ns.offered.set(key, snap);
898
1758
  }
899
1759
  }
900
1760
  }
901
1761
  ns.active = held;
902
- // Whatever we wanted up and could not get up. Stream credit freeing, a transient
903
- // failure clearing, or the peer starting to answer raises no signal of its own, so
904
- // the only way back is to ask again on a timer.
905
- return [...updated].some(([key, snap]) => change(this.#advert, held.get(key), snap) !== "same" && this.#pending(key, ns.refused));
1762
+ // Keep the backoff only for a peer refusal that permits another offer. Local
1763
+ // credit failures and unanswered requests are terminal for this broadcast identity.
1764
+ return [...updated].some(([key, snap]) => this.#change(key, held.get(key), snap, target) !== "same" && this.#pending(key, ns.refused));
1765
+ }
1766
+ /**
1767
+ * What it takes to move the peer from `held` to `next` at `key`: {@link change}, plus
1768
+ * the token the request carries.
1769
+ *
1770
+ * moq-transport renames a request's token with REQUEST_UPDATE, but cannot name one on a
1771
+ * request that had none, nor drop one: those withdraw the request and make it again.
1772
+ */
1773
+ #change(key, held, next, target) {
1774
+ const diff = change(this.#advert, held, next);
1775
+ if (diff === "restart" || held === undefined || next === undefined)
1776
+ return diff;
1777
+ const from = target.held(key);
1778
+ const to = target.carry(next.route.auth);
1779
+ if (from === to)
1780
+ return diff;
1781
+ if (from === undefined || to === undefined)
1782
+ return "restart";
1783
+ return { ...(diff === "same" ? {} : diff), token: to };
1784
+ }
1785
+ /** `auth` when a request of this session can carry it. */
1786
+ #carry(auth) {
1787
+ return this.#auth?.carried(auth) === undefined ? undefined : auth;
906
1788
  }
907
1789
  /**
908
1790
  * Whether a namespace may be offered to the peer right now.
909
1791
  *
910
- * A peer that asked never to be offered it again means it, whatever brought us back;
911
- * one that named a minimum wait gets it, even when our own backoff comes round sooner.
1792
+ * A refusal there is no coming back from stays one, whatever brought us back; a peer
1793
+ * that named a minimum wait gets it, even when our own backoff comes round sooner, and
1794
+ * so does one that asked not to be offered the namespace again (see {@link Answer}).
912
1795
  */
913
1796
  #offerable(key, refused) {
914
1797
  const entry = refused.get(key);
915
1798
  if (entry === undefined)
916
1799
  return true;
917
- return entry !== "never" && Date.now() >= entry;
1800
+ return entry !== "never" && now().ge(entry);
918
1801
  }
919
1802
  /**
920
1803
  * Whether the loop should keep coming back to a namespace the peer does not hold.
@@ -922,72 +1805,78 @@ export class Publisher {
922
1805
  * Distinct from {@link offerable}, and the difference is what arms the retry: a
923
1806
  * namespace waiting out a minimum is not offerable yet but is still pending, and
924
1807
  * gating the timer on offerable instead would disarm it for exactly the wait it is
925
- * supposed to be counting. Only a refusal that forbids retrying ends it.
1808
+ * supposed to be counting. A terminal local failure or a refusal past the clock's range
1809
+ * ends it.
926
1810
  */
927
1811
  #pending(key, refused) {
928
1812
  return refused.get(key) !== "never";
929
1813
  }
930
1814
  /**
931
1815
  * What a REQUEST_ERROR's retry interval, in milliseconds, says about re-offering the
932
- * namespace.
933
- *
934
- * Draft-14/15 carry no such field, so a 0 there says nothing and our own backoff
935
- * stands; everywhere else 0 means the peer does not want this again.
1816
+ * namespace: 0 means the peer does not want this again, which the caller turns into a
1817
+ * long wait, and an interval past the clock's range has no coming back.
936
1818
  */
937
1819
  #refusal(err) {
938
- const version = this.#session.version;
939
- if (version === Version.DRAFT_14 || version === Version.DRAFT_15)
940
- return "dropped";
941
- return err.retryInterval === 0n ? "never" : Date.now() + Number(err.retryInterval);
1820
+ if (err.retryInterval === 0n)
1821
+ return "declined";
1822
+ return now().checkedAdd(Duration.millis(toNumber(err.retryInterval))) ?? "never";
1823
+ }
1824
+ /**
1825
+ * The extension parameters an advertisement of `route` carries.
1826
+ */
1827
+ #params(route) {
1828
+ return { cluster: clusterFor(this.#advert, route) };
942
1829
  }
943
1830
  /**
944
1831
  * Advertise one namespace on its own PUBLISH_NAMESPACE request. A declined request
945
1832
  * is logged and skipped: a peer that wants none of this rejects each one and stays
946
1833
  * connected.
947
1834
  */
948
- async #advertise(path, requests, cluster = this.#advert) {
1835
+ async #advertise(path, requests, route) {
1836
+ const params = this.#params(route);
1837
+ const auth = this.#carry(route.auth);
949
1838
  const requestId = await this.#session.nextRequestId();
950
1839
  if (requestId === undefined)
951
1840
  return "dropped";
952
1841
  // Opening is inside the try because it fails like any other advertisement does:
953
1842
  // a peer out of stream credit rejects here, and letting that escape would unwind
954
1843
  // the announce loop and take discovery down for the whole session, rather than
955
- // costing this one namespace a turn.
1844
+ // leaving this one namespace unadvertised.
956
1845
  let request;
957
1846
  try {
958
- request = await this.#session.openBi();
959
- const stream = request;
960
- // Bounded, like the subscriber's own request: the loop is single-threaded over
961
- // advertisements, so a peer that takes the stream and answers nothing strands
962
- // every publish and withdrawal behind it. Timing out costs this namespace a
963
- // turn and leaves it outstanding, which the retry above re-offers.
964
- const answer = await withTimeout((async () => {
965
- await stream.writer.u53(PublishNamespace.id);
966
- const msg = new PublishNamespace({ requestId, trackNamespace: path, cluster });
967
- await msg.encode(stream.writer, this.#session.version);
968
- // Read response (RequestOk and PublishNamespaceOk share 0x07)
969
- const respTypeId = await stream.reader.u53();
970
- if (respTypeId === RequestError.id) {
971
- const err = await RequestError.decode(stream.reader, this.#session.version);
1847
+ const deadline = new Deadline(Duration.millis(ADVERTISE_TIMEOUT_MS));
1848
+ const answer = await deadline.wait((async () => {
1849
+ const opened = await RequestStream.open(this.#session, deadline, { quic: this.#quic });
1850
+ request = opened;
1851
+ const version = this.#session.version;
1852
+ const token = this.#auth?.carried(auth);
1853
+ const msg = new PublishNamespace({ requestId, trackNamespace: path, params, token });
1854
+ await deadline.send(opened, async () => {
1855
+ await Message.write(opened.writer, PublishNamespace.id, msg, version);
1856
+ });
1857
+ // Read response
1858
+ const response = await opened.next();
1859
+ if (response === undefined)
1860
+ throw new Error("advertisement ended before its response");
1861
+ if (response.type === RequestError.id) {
1862
+ const err = await RequestError.decode(response.reader, this.#session.version);
972
1863
  const why = requestReason(err.errorCode, err.reasonPhrase, "publish_namespace", this.#session.version);
973
1864
  console.warn(`announce refused: broadcast=${path} error=${why}`);
974
- stream.abort(new Error(`PublishNamespace rejected: ${why}`));
1865
+ opened.abort(new Error(`PublishNamespace rejected: ${why}`));
975
1866
  return this.#refusal(err);
976
1867
  }
977
- if (respTypeId !== RequestOk.id) {
978
- throw new Error(`PublishNamespace rejected: typeId=0x${respTypeId.toString(16)}`);
1868
+ if (response.type !== RequestOk.id) {
1869
+ throw new Error(`PublishNamespace rejected: typeId=0x${response.type.toString(16)}`);
979
1870
  }
980
1871
  // Draft-14 sends PublishNamespaceOk (requestId only, no parameters)
981
- if (this.#session.version === Version.DRAFT_14) {
982
- await PublishNamespaceOk.decode(stream.reader, this.#session.version);
983
- }
984
- else {
985
- await RequestOk.decode(stream.reader, this.#session.version);
986
- }
1872
+ this.#answered(await RequestOk.decode(response.reader, this.#session.version));
987
1873
  return "held";
988
- })(), ADVERTISE_TIMEOUT_MS, `advertisement timed out after ${ADVERTISE_TIMEOUT_MS}ms waiting for the peer's answer`);
989
- if (answer === "held")
990
- requests.set(path, { path, requestId, stream });
1874
+ })());
1875
+ if (answer === "held" && request) {
1876
+ const held = { path, requestId, stream: request, auth };
1877
+ requests.set(path, held);
1878
+ held.reply = this.#readAdvertisement(held, requests);
1879
+ }
991
1880
  return answer;
992
1881
  }
993
1882
  catch (err) {
@@ -995,9 +1884,45 @@ export class Publisher {
995
1884
  const e = err instanceof TimeoutError ? controlTimeout(err) : error(err);
996
1885
  console.warn(`announce failed: broadcast=${path} error=${reason(e)}`);
997
1886
  request?.abort(e);
998
- return "dropped";
1887
+ return e instanceof StreamError && e.code === StreamCode.ControlTimeout ? "never" : "dropped";
999
1888
  }
1000
1889
  }
1890
+ /**
1891
+ * Keep reading while an advertisement is idle, so GOAWAY validation never waits for an
1892
+ * update. A stream that ends while idle drops the request, and the announce loop re-offers it
1893
+ * after a backoff.
1894
+ */
1895
+ #readAdvertisement(request, requests) {
1896
+ const reply = request.stream.next().then((framed) => {
1897
+ if (framed !== undefined && !request.updating)
1898
+ throw new ProtocolViolation("unexpected message on an idle advertisement");
1899
+ return framed;
1900
+ });
1901
+ // A later update consumes an answer; an end is acted on as soon as it arrives.
1902
+ void reply.then((framed) => framed === undefined && this.#lapse(request, requests), (err) => {
1903
+ if (err instanceof ProtocolViolation)
1904
+ request.stream.abort(err);
1905
+ this.#lapse(request, requests);
1906
+ });
1907
+ return reply;
1908
+ }
1909
+ /** Drop an idle advertisement whose stream ended, unless an update already took it over. */
1910
+ #lapse(request, requests) {
1911
+ if (request.updating || requests.get(request.path) !== request)
1912
+ return;
1913
+ requests.delete(request.path);
1914
+ request.stream.abort(new StreamError(StreamCode.Cancel, { message: "advertisement ended" }));
1915
+ this.#lapsed.update((n) => n + 1);
1916
+ }
1917
+ /**
1918
+ * Check a REQUEST_OK answering a PUBLISH_NAMESPACE. ACTIVE_COUNT only answers
1919
+ * SUBSCRIBE_NAMESPACE (MoQ Active Count), and reading one too large to hold throws the
1920
+ * same violation.
1921
+ */
1922
+ #answered(ok) {
1923
+ if (ok.parameters.activeCount !== undefined)
1924
+ throw new ProtocolViolation("ACTIVE_COUNT on a PUBLISH_NAMESPACE answer");
1925
+ }
1001
1926
  /**
1002
1927
  * Update a namespace the peer holds: REQUEST_UPDATE on the request that carries it,
1003
1928
  * with only the parameters that changed, then its answer.
@@ -1006,20 +1931,21 @@ export class Publisher {
1006
1931
  * MAX_REQUEST_UPDATES the peer set without reading it; a change landing meanwhile waits
1007
1932
  * for the next turn. The answer decides whether the peer still holds the namespace: a
1008
1933
  * REQUEST_ERROR closes the peer's side and withdraws the advertisement, so ours is
1009
- * finished too, and an unanswered update is dropped abruptly, since a peer that ignored
1010
- * it cannot be assumed to hold either price. Either way the retry re-offers it fresh.
1934
+ * finished too, and an unanswered update is dropped, since a peer that
1935
+ * ignored it cannot be assumed to hold either price. Either way the retry re-offers it fresh.
1011
1936
  *
1012
1937
  * A different original publisher is an update like any other: the receiver drains what
1013
1938
  * it already serves from the old one and never splices the two.
1014
1939
  */
1015
- async #update(path, requests, { from, to }) {
1940
+ async #update(path, requests, { from, to, token: auth }) {
1016
1941
  const request = requests.get(path);
1017
1942
  if (!request)
1018
1943
  return "dropped";
1019
1944
  const update = {
1020
- hops: sameHops(from.hops, to.hops) ? undefined : to.hops,
1021
- cost: from.cost === to.cost ? undefined : to.cost,
1945
+ hops: from && to && !sameHops(from.hops, to.hops) ? to.hops : undefined,
1946
+ cost: from && to && from.cost !== to.cost ? to.cost : undefined,
1022
1947
  };
1948
+ const token = auth && this.#auth?.carried(auth);
1023
1949
  const version = this.#session.version;
1024
1950
  let answer;
1025
1951
  try {
@@ -1027,22 +1953,27 @@ export class Publisher {
1027
1953
  if (requestId === undefined)
1028
1954
  throw new Error("no request ID for the update");
1029
1955
  answer = await withTimeout((async () => {
1030
- const { writer, reader } = request.stream;
1031
- await writer.u53(PublishNamespaceUpdate.id);
1032
- await new PublishNamespaceUpdate({ requestId, update }).encode(writer, version);
1033
- const typeId = await reader.u53();
1034
- if (typeId === RequestError.id) {
1035
- const err = await RequestError.decode(reader, version);
1956
+ const writer = request.stream.writer;
1957
+ request.updating = true;
1958
+ const msg = new PublishNamespaceUpdate({ requestId, update, token });
1959
+ await Message.write(writer, PublishNamespaceUpdate.id, msg, version);
1960
+ const response = await (request.reply ?? request.stream.next());
1961
+ if (response === undefined)
1962
+ throw new Error("advertisement ended before its update response");
1963
+ if (response.type === RequestError.id) {
1964
+ const err = await RequestError.decode(response.reader, version);
1036
1965
  const why = requestReason(err.errorCode, err.reasonPhrase, "publish_namespace", version);
1037
1966
  console.warn(`publish_namespace update refused: broadcast=${path} error=${why}`);
1038
1967
  return this.#refusal(err);
1039
1968
  }
1040
- if (typeId !== RequestOk.id) {
1041
- throw new Error(`unexpected answer to the update: typeId=0x${typeId.toString(16)}`);
1969
+ if (response.type !== RequestOk.id) {
1970
+ throw new Error(`unexpected answer to the update: typeId=0x${response.type.toString(16)}`);
1042
1971
  }
1043
- await RequestOk.decode(reader, version);
1972
+ this.#answered(await RequestOk.decode(response.reader, version));
1973
+ request.updating = false;
1974
+ request.reply = this.#readAdvertisement(request, requests);
1044
1975
  return "held";
1045
- })(), ADVERTISE_TIMEOUT_MS, `update timed out after ${ADVERTISE_TIMEOUT_MS}ms waiting for the peer's answer`);
1976
+ })(), ADVERTISE_TIMEOUT, `update timed out after ${ADVERTISE_TIMEOUT_MS}ms waiting for the peer's answer`);
1046
1977
  }
1047
1978
  catch (err) {
1048
1979
  const e = err instanceof TimeoutError ? controlTimeout(err) : error(err);
@@ -1051,160 +1982,411 @@ export class Publisher {
1051
1982
  request.stream.abort(e);
1052
1983
  return "dropped";
1053
1984
  }
1054
- // The peer may already have closed out a refused request. Ending it again is the
1055
- // withdrawal finishing, not a reason to end the loop.
1056
- if (answer !== "held")
1057
- await this.#withdraw(path, requests).catch(() => undefined);
1985
+ if (answer === "held") {
1986
+ if (auth)
1987
+ request.auth = auth;
1988
+ return answer;
1989
+ }
1990
+ // The peer already closed out a refused request, and its STOP_SENDING can
1991
+ // reject the wait on our FIN. That is the withdrawal finishing, not a reason to end
1992
+ // the loop.
1993
+ await this.#withdraw(path, requests).catch(() => undefined);
1058
1994
  return answer;
1059
1995
  }
1060
- /**
1061
- * End a namespace's PUBLISH_NAMESPACE request: PUBLISH_NAMESPACE_DONE then FIN before
1062
- * draft-17, a cancel in both directions after. Neither waits on the peer.
1063
- */
1064
1996
  async #withdraw(path, requests) {
1065
1997
  const request = requests.get(path);
1066
1998
  if (!request)
1067
1999
  return;
1068
2000
  requests.delete(path);
1069
- // Draft-17+ withdraws by cancelling the request in both directions; a FIN is only
1070
- // allowed to end SUBSCRIBE_NAMESPACE and SUBSCRIBE_TRACKS.
1071
- const version = this.#session.version;
1072
- if (version !== Version.DRAFT_14 && version !== Version.DRAFT_15 && version !== Version.DRAFT_16) {
1073
- request.stream.abort(new StreamError(StreamCode.Cancel, { message: "withdrawn" }));
1074
- return;
1075
- }
1076
- try {
1077
- await request.stream.writer.u53(PublishNamespaceDone.id);
1078
- const done = new PublishNamespaceDone({ trackNamespace: request.path, requestId: request.requestId });
1079
- await done.encode(request.stream.writer, version);
1080
- }
1081
- catch {
1082
- // Stream might already be closed
1083
- }
1084
- request.stream.close();
2001
+ await this.#end(request);
1085
2002
  }
1086
2003
  /**
1087
- * Handles an incoming TRACK_STATUS_REQUEST on a bidi stream.
1088
- *
1089
- * @internal
2004
+ * Withdraw one PUBLISH_NAMESPACE request, already out of its map, by cancelling it in both
2005
+ * directions: a FIN is only allowed to end SUBSCRIBE_NAMESPACE and SUBSCRIBE_TRACKS.
1090
2006
  */
1091
- async runTrackStatusRequest(msg, stream) {
1092
- // TRACK_STATUS_ERROR is 0x0f on draft-14.
1093
- await this.#refuseUnsupported(stream, msg.requestId, "track_status", 0x0f, "TRACK_STATUS is not supported");
2007
+ async #end(request) {
2008
+ request.stream.abort(new StreamError(StreamCode.Cancel, { message: "withdrawn" }));
1094
2009
  }
1095
2010
  /**
1096
- * Refuses an incoming SUBSCRIBE_TRACKS (draft-18+): we never send the PUBLISH it asks for.
1097
- * The reply carries no Request ID, so the message body is left unread.
2011
+ * Answers an incoming TRACK_STATUS with what a SUBSCRIBE_OK for the track would carry,
2012
+ * without subscribing.
2013
+ *
2014
+ * The track resolves as it would for a SUBSCRIBE, dynamic handlers included, and the
2015
+ * answer waits on its info. The Largest Location is whatever the cache holds now.
1098
2016
  *
1099
2017
  * @internal
1100
2018
  */
1101
- async runSubscribeTracks(stream) {
2019
+ runTrackStatusRequest(msg, stream) {
2020
+ // Nothing can follow a TRACK_STATUS, so a FIN only ends the requester's input; a reset or
2021
+ // STOP_SENDING withdraws it.
2022
+ const request = new RequestStream(stream, this.#session, this.#quic, { finCancels: false });
2023
+ return request.serve(this.#runTrackStatusRequest(msg, request));
2024
+ }
2025
+ async #runTrackStatusRequest(msg, request) {
2026
+ if (Namespace.reserved(msg.trackNamespace, this.#session.version)) {
2027
+ await refuseReserved(request);
2028
+ return;
2029
+ }
2030
+ const version = this.#session.version;
2031
+ const name = msg.trackNamespace;
2032
+ const denied = { condition: "unauthorized", reasonPhrase: "not granted" };
2033
+ // Answer only for what our grant lets us publish. Checked before the track resolves,
2034
+ // so a denied request never reaches the origin.
2035
+ if (!this.#gate.allows(name)) {
2036
+ await request.refuse("track_status", denied);
2037
+ return;
2038
+ }
2039
+ // Holds the track wanted until the answer is out. The requester leaving is owed
2040
+ // nothing, and lets go of the broadcast and track lookups.
2041
+ const hold = new AbortController();
2042
+ const cancel = new StreamError(StreamCode.Cancel, { message: "cancel" });
2043
+ void request.ended.then(() => hold.abort(cancel));
2044
+ // Nothing may follow the request.
2045
+ void request.next().then((framed) => framed && request.abort(new ProtocolViolation("unexpected request stream message")),
2046
+ // The request ended, which the hold already heard.
2047
+ () => undefined);
2048
+ // A grant that narrows abandons the lookup, and resets an answer the transport has
2049
+ // not taken yet rather than delivering it.
2050
+ let answering = false;
2051
+ const watch = this.#gate.watch(name, () => {
2052
+ hold.abort();
2053
+ if (answering)
2054
+ request.abort(unauthorized(name));
2055
+ });
2056
+ try {
2057
+ let answer;
2058
+ try {
2059
+ const broadcast = await this.#resolve(name, hold.signal);
2060
+ const info = await wireOf(broadcast).resolveTrackInfo(msg.trackName, hold.signal);
2061
+ const timescale = info.timescale ?? undefined;
2062
+ const largest = wireOf(broadcast).largest(msg.trackName, timescale);
2063
+ answer = new TrackStatusOk({
2064
+ largest: largest && { groupId: largest.group, objectId: BigInt(largest.frame) },
2065
+ properties: trackProperties(info, msg.propertiesWanted),
2066
+ });
2067
+ }
2068
+ catch (err) {
2069
+ if (hold.signal.reason === cancel) {
2070
+ request.abort(cancel);
2071
+ return;
2072
+ }
2073
+ const refusal = !this.#gate.allows(name) ? denied : this.#failed(err);
2074
+ await request.refuse("track_status", refusal);
2075
+ return;
2076
+ }
2077
+ answering = true;
2078
+ await Message.write(request.writer, TrackStatusOk.id, answer, version);
2079
+ // The answer is all this stream carries.
2080
+ request.close();
2081
+ await request.writer.closed.catch(() => undefined);
2082
+ }
2083
+ finally {
2084
+ watch.dispose();
2085
+ hold.abort();
2086
+ }
2087
+ }
2088
+ async #subscriptionUpdate(framed) {
1102
2089
  const version = this.#session.version;
1103
- await stream.writer.u53(RequestError.id);
1104
- await new RequestError({
1105
- errorCode: toRequestCode("not_supported", "subscribe_namespace", version),
1106
- reasonPhrase: "SUBSCRIBE_TRACKS is not supported",
1107
- }).encode(stream.writer, version);
1108
- stream.close();
2090
+ const update = await Message.decode(framed.reader, async (body) => {
2091
+ const requestId = await body.u62();
2092
+ this.#session.checkRequestId(requestId);
2093
+ const params = await Parameters.decode(body, version, "request-update");
2094
+ return { params, requestId };
2095
+ });
2096
+ if (update.params.trackPropertyFilter)
2097
+ throw new ProtocolViolation("TRACK_PROPERTY_FILTER is only allowed on SUBSCRIBE_TRACKS updates");
2098
+ return update;
2099
+ }
2100
+ /** End a subscription whose update failed. */
2101
+ async #publishFailed(request, streams) {
2102
+ await Message.write(request.writer, PublishDone.id, new PublishDone({
2103
+ statusCode: PublishDoneStatus.UPDATE_FAILED,
2104
+ streamCount: BigInt(streams.opened),
2105
+ reasonPhrase: "update failed",
2106
+ }), this.#session.version);
2107
+ }
2108
+ #applyPublished(msg, params) {
2109
+ msg.subscriberPriority = params.subscriberPriority ?? msg.subscriberPriority;
2110
+ msg.groupOrder =
2111
+ params.groupOrder === undefined
2112
+ ? msg.groupOrder
2113
+ : params.groupOrder === GroupOrder.Ascending
2114
+ ? "ascending"
2115
+ : "descending";
2116
+ msg.filter = params.subscriptionFilter ?? msg.filter;
2117
+ try {
2118
+ msg.fill = params.fillParameters
2119
+ ? Filter.decodeFill(params.fillParameters, this.#session.version)
2120
+ : undefined;
2121
+ }
2122
+ catch (err) {
2123
+ throw malformed(err, "FILL_PARAMETERS");
2124
+ }
1109
2125
  }
1110
2126
  /**
1111
- * Handles an incoming FETCH on a bidi stream. We serve none.
1112
- *
1113
- * @internal
2127
+ * What a request that failed to resolve is refused with. A missing publisher a rendezvous
2128
+ * waited for is a timeout, which, like Rust's `rendezvous_error`, invites no retry.
1114
2129
  */
1115
- async runFetch(msg, stream) {
1116
- await this.#refuseUnsupported(stream, msg.requestId, "fetch", FetchError.id, "FETCH is not supported");
2130
+ #failed(err, wait = false, resolved = false) {
2131
+ const e = error(err);
2132
+ const reasonPhrase = reason(e);
2133
+ const missing = e instanceof StreamError &&
2134
+ (e.code === StreamCode.Unroutable || (e.code === StreamCode.NotFound && !resolved));
2135
+ if (wait && missing)
2136
+ return { condition: "timeout", reasonPhrase };
2137
+ return { condition: refusedAs(e), reasonPhrase, retryable: routeFailed(e) };
1117
2138
  }
1118
2139
  /**
1119
- * Refuse a request NOT_SUPPORTED. Draft-14 gives each request its own error message,
1120
- * `errorId14`, with the SUBSCRIBE_ERROR body; later drafts use REQUEST_ERROR.
2140
+ * Resolve the broadcast a request names for serving: a local publish, or else the
2141
+ * origin's routes and dynamic handlers. Rejects with the abort once `signal` aborts.
1121
2142
  */
1122
- async #refuseUnsupported(stream, requestId, kind, errorId14, reasonPhrase) {
1123
- const version = this.#session.version;
1124
- const errorCode = toRequestCode("not_supported", kind, version);
1125
- if (version === Version.DRAFT_14) {
1126
- await stream.writer.u53(errorId14);
1127
- await new SubscribeError({ requestId, errorCode, reasonPhrase }).encode(stream.writer, version);
1128
- }
1129
- else {
1130
- await stream.writer.u53(RequestError.id);
1131
- await new RequestError({
1132
- requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? requestId : undefined,
1133
- errorCode,
1134
- reasonPhrase,
1135
- }).encode(stream.writer, version);
1136
- }
1137
- stream.close();
2143
+ async #resolve(name, signal) {
2144
+ const broadcast = this.#publish &&
2145
+ (wireOf(this.#publish).local(name) ?? (await wireOf(this.#publish).demand(name, undefined, signal)));
2146
+ if (!broadcast)
2147
+ throw new NotFound(`broadcast ${name}`);
2148
+ return broadcast;
1138
2149
  }
1139
2150
  }
2151
+ // A filter keeps its peer-chosen Object IDs as bigint. Its derived frame selection
2152
+ // bound can stop at the model's count ceiling: no object exists at or above it,
2153
+ // so clamping either a skip or an exclusive end selects exactly the same frames.
2154
+ function frameBound(object) {
2155
+ return object > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(object);
2156
+ }
2157
+ /** Write one group's fetch objects, inheriting the first object's priority. */
2158
+ class FetchWriter {
2159
+ stream;
2160
+ #version;
2161
+ /** The track's Publisher Priority on the wire, which the first object states for all. */
2162
+ #priority;
2163
+ #written = false;
2164
+ #previousObject;
2165
+ constructor({ stream, version, priority }) {
2166
+ this.stream = stream;
2167
+ this.#version = version;
2168
+ this.#priority = priority;
2169
+ }
2170
+ /** Write `read` of group `key`, following the prior object of that group, if any. */
2171
+ async object(key, read, stop, object = read.index, tie) {
2172
+ const chunks = read.chunks;
2173
+ const obj = new FetchFrame({
2174
+ payload: chunks ? undefined : read.frame.payload,
2175
+ streamed: chunks?.size || undefined,
2176
+ priority: this.#priority,
2177
+ tie,
2178
+ });
2179
+ const position = {
2180
+ group: key,
2181
+ object,
2182
+ first: !this.#written,
2183
+ previousObject: this.#previousObject,
2184
+ };
2185
+ await untilAborted(obj.encode(this.stream, position, this.#version), stop);
2186
+ // Even an empty payload: the object exists only once committed, and may still be aborted.
2187
+ if (chunks)
2188
+ await untilAborted(sendPayload(chunks, (chunk) => this.stream.write(chunk), this.stream.closed), stop);
2189
+ this.#written = true;
2190
+ this.#previousObject = object;
2191
+ }
2192
+ }
2193
+ /**
2194
+ * `signal`, also aborted with why `group` was given up: its copy failed with no route to continue
2195
+ * it, it was evicted, or it expired. A write parked on flow control never reads the group, so
2196
+ * without this a FETCH would hold its reader until the request ends. Release once nothing is
2197
+ * left to write.
2198
+ */
2199
+ function untilGivenUp(group, signal) {
2200
+ const givenUp = new GivenUp(group);
2201
+ const failed = new AbortController();
2202
+ const released = Promise.withResolvers();
2203
+ void givenUp
2204
+ .write(() => released.promise)
2205
+ .then((reason) => {
2206
+ if (reason)
2207
+ failed.abort(reason);
2208
+ });
2209
+ return {
2210
+ signal: AbortSignal.any([signal, failed.signal]),
2211
+ release: () => {
2212
+ givenUp.close();
2213
+ released.resolve();
2214
+ },
2215
+ };
2216
+ }
1140
2217
  /**
1141
- * Take one group out of a cache view, without waiting.
2218
+ * The Track Properties a SUBSCRIBE_OK, TRACK_STATUS, or FETCH_OK answers with.
1142
2219
  *
1143
- * A fill's group is at or below the Largest Object snapshot, so it is either still in the
1144
- * retained window or gone for good: nothing republishes an old sequence, and waiting for one
1145
- * would park for the life of the track. Scanning past it, or running dry, is a cache miss,
1146
- * which the caller turns into the draft's fill-failure reset.
2220
+ * @internal Exported for tests.
1147
2221
  */
1148
- function takeGroup(cache, sequence) {
2222
+ export function trackProperties(info, wanted) {
2223
+ // INCLUDE_PROPERTIES=0. The block stays present but empty.
2224
+ if (!wanted)
2225
+ return {};
2226
+ // ID_TIMESCALE declares the units of the track's Group IDs, which are its groups' starts.
2227
+ return {
2228
+ // An untimed track declares none, so it stays untimed downstream.
2229
+ timescale: info.timescale ?? undefined,
2230
+ priority: toWire(info.priority),
2231
+ // The publisher's default, newest first.
2232
+ groupOrder: Properties.DESCENDING,
2233
+ // No MAX_CACHE_DURATION: our max age expires only superseded groups, while that
2234
+ // property expires every object, the newest included, after the given time.
2235
+ };
2236
+ }
2237
+ /** Read within a fixed filter, ending at its cap once the track itself finishes. */
2238
+ async function servingGroup(track) {
1149
2239
  for (;;) {
1150
- const group = cache.tryRecvGroup();
1151
- if (!group)
1152
- throw new Error(`group not found: ${sequence}`);
1153
- if (group.sequence === sequence)
1154
- return group;
1155
- group.close();
1156
- if (group.sequence > sequence)
1157
- throw new Error(`group not found: ${sequence}`);
2240
+ const recv = hooks.tryRecvGroup(track, false);
2241
+ if (recv.kind === "group")
2242
+ return recv.group;
2243
+ if (recv.kind === "error")
2244
+ throw recv.error;
2245
+ // A boundary only follows the source's real end. Its cached excluded groups
2246
+ // cannot delay PUBLISH_DONE; while the source is live the cursor reports idle.
2247
+ if (recv.kind === "done" || recv.kind === "boundary")
2248
+ return undefined;
2249
+ if (recv.kind === "drop")
2250
+ continue;
2251
+ await new Promise((resolve) => {
2252
+ const dispose = hooks.groupChanged(track, () => {
2253
+ dispose();
2254
+ resolve();
2255
+ });
2256
+ });
1158
2257
  }
1159
2258
  }
1160
- /** `a - b`, saturating at zero the way the draft's unsigned arithmetic does. */
1161
- function saturatingSub(a, b) {
1162
- return a > b ? a - b : 0n;
2259
+ /**
2260
+ * A live join with no lag, as a SUBSCRIBE without an absolute start asks: a range from the oldest
2261
+ * group would have a relay's route replay everything it retains, and SUBSCRIBE_OK then name the
2262
+ * oldest group replayed so far as Largest. No group of it expires short of the publisher's max
2263
+ * age, since moq-transport's SUBSCRIBE carries none. Mirrors the Rust `live_join`.
2264
+ */
2265
+ const LIVE_JOIN = {
2266
+ ranges: [{ start: { live: { min: Duration.ZERO, max: null } } }],
2267
+ };
2268
+ // `subscription` with every range at `policy`: moq-transport carries one priority and group order
2269
+ // for a whole subscription.
2270
+ function atPolicy(subscription, policy) {
2271
+ return { ...subscription, ranges: (subscription.ranges ?? []).map((range) => withPolicy(range, policy)) };
1163
2272
  }
1164
- /** Snapshot the live edge of a track. */
1165
- function liveEdge(track) {
1166
- const latest = track.latest();
1167
- if (latest === undefined)
1168
- return {};
1169
- const largest = track.largest();
1170
- if (!largest)
1171
- return { latest: BigInt(latest), next: { group: BigInt(latest), object: 0n } };
1172
- const group = BigInt(largest.group);
1173
- const object = BigInt(largest.frame);
1174
- return { latest: BigInt(latest), largest: { group, object }, next: { group, object: object + 1n } };
2273
+ /**
2274
+ * What to ask for a {@link ServeRange} resolved from `filter` against `edge`. A filter other
2275
+ * than an absolute one starting at the latest group or past it stays a {@link LIVE_JOIN}, which
2276
+ * the serve's cursor trims to the range: a time start there would also have the route replay
2277
+ * what it retains. On a track with no group yet it asks from the oldest group, since nothing is
2278
+ * retained, and a live join would start at whichever group lands first. Mirrors the Rust
2279
+ * `ServeRange::request`.
2280
+ */
2281
+ function serveRequest(range, filter, edge) {
2282
+ const latest = edge?.latest;
2283
+ const live = filter !== undefined &&
2284
+ filter.kind !== "absolute" &&
2285
+ range.end === undefined &&
2286
+ latest !== undefined &&
2287
+ (range.start === undefined || range.start.group >= latest);
2288
+ if (live)
2289
+ return LIVE_JOIN;
2290
+ // From time zero rather than with no start: replacing a live join's range with an equal one
2291
+ // would leave it where it already resolved.
2292
+ const out = { start: range.start?.group ?? 0n };
2293
+ if (range.end)
2294
+ out.end = range.end.group;
2295
+ return { ranges: [out] };
2296
+ }
2297
+ function rangeGroups(range) {
2298
+ return {
2299
+ start: range.start ? { included: range.start.group } : undefined,
2300
+ end: range.end ? { included: range.end.group } : undefined,
2301
+ };
1175
2302
  }
1176
2303
  /**
1177
- * Resolve a SUBSCRIBE's Location Filter into the range to serve.
1178
- *
1179
- * Only draft-20 is honored. Earlier drafts have a Filter Type tag whose absolute forms we
1180
- * never served, and starting to interpret them now would change what an existing peer
1181
- * receives; draft-20 is also the first version whose relative forms can name a past group
1182
- * without the subscriber knowing Largest Object.
2304
+ * Assigns moq-timestamp Object IDs to a group's frames as one stream reads them in order from frame
2305
+ * 0 (draft-lcurley-moq-timestamp): each is its timestamp's offset from the group start, or one past
2306
+ * the previous ID when a run of tied timestamps pushed that ID higher. Mirrors the Rust `TimedIds`.
1183
2307
  */
1184
- function subscribeRange(msg, edge, version) {
1185
- if (!Filter.isDraft20(version)) {
1186
- if (msg.filter.kind !== "nextObject" && msg.filter.kind !== "unfiltered") {
1187
- console.warn(`filter not supported before draft-20, ignoring: ${msg.filter.kind}`);
1188
- }
1189
- return {};
2308
+ class TimedIds {
2309
+ #start;
2310
+ #timescale;
2311
+ #prior;
2312
+ // The frame `next` reads, which follows the last.
2313
+ #index = 0;
2314
+ constructor(start, timescale) {
2315
+ this.#start = start;
2316
+ this.#timescale = timescale;
2317
+ }
2318
+ /** The lowest ID the next frame can take. */
2319
+ nextMin() {
2320
+ return this.#prior === undefined ? 0 : Number(this.#prior) + 1;
2321
+ }
2322
+ /**
2323
+ * The ID of `read`, the next frame, and its `TIMESTAMP_TIE` when non-zero. A copy that no longer
2324
+ * holds the frames before it cannot prove its ID, so the read fails.
2325
+ */
2326
+ next(read) {
2327
+ if (read.index !== this.#index)
2328
+ throw new StreamError(StreamCode.Internal, {
2329
+ message: "the group's head is gone, so its Object IDs are unknown",
2330
+ });
2331
+ const dts = BigInt(floorAt(read.frame.timestamp, this.#timescale));
2332
+ this.#index++;
2333
+ const { id, tie } = timestampObjectId(this.#start, this.#prior, dts);
2334
+ this.#prior = id;
2335
+ return { id, tie: tie > 0n ? tie : undefined };
1190
2336
  }
1191
- return filterRange(msg.filter, edge);
2337
+ }
2338
+ /** Snapshot the live edge of a track, in moq-timestamp Object IDs at `timescale` when set. */
2339
+ function liveEdge(track, timescale) {
2340
+ const latest = hooks.latestKey(track);
2341
+ const largest = hooks.objectLargest(track);
2342
+ if (!largest)
2343
+ return latest === undefined ? {} : { latest, next: { group: latest, object: 0n } };
2344
+ const group = largest.group;
2345
+ const object = timescale ? timedObject(track, largest, timescale) : BigInt(largest.frame);
2346
+ return {
2347
+ latest,
2348
+ largest: { group, object },
2349
+ next: { group, object: object + 1n },
2350
+ };
2351
+ }
2352
+ /**
2353
+ * The moq-timestamp Object ID of frame `at`, from the group cached for it. A copy that cannot prove
2354
+ * it answers the frame's ordinal, which the ID is never below: a Next Object subscription then
2355
+ * starts at or before the true edge rather than past objects still to come.
2356
+ */
2357
+ function timedObject(track, at, timescale) {
2358
+ return hooks.cachedTimedId(track, at.group, at.frame, timescale) ?? BigInt(at.frame);
2359
+ }
2360
+ /**
2361
+ * Whether `filter` counts groups back past the current one, which we refuse with
2362
+ * NOT_SUPPORTED: keys are group starts, so no arithmetic on one counts groups, and a moq-lite
2363
+ * range has no such start to serve it with.
2364
+ */
2365
+ function countsBack(filter) {
2366
+ return filter.kind === "relative" && filter.groups > 1n;
1192
2367
  }
1193
2368
  /** The Locations a single Location Filter selects, resolved against the live edge. */
1194
- function filterRange(filter, edge) {
2369
+ function filterRange(filter, edge, version) {
1195
2370
  switch (filter.kind) {
1196
2371
  // No restriction. moq-lite starts at the beginning of the latest group, which is the
1197
2372
  // join point it is built around; a subscription passes objects as they are published,
1198
- // so an absent filter is not a request to replay history.
2373
+ // so an absent filter is not a request to replay history. A subscriber that wants the
2374
+ // track from its start fetches the groups before the live one.
1199
2375
  case "unfiltered":
1200
2376
  return {};
1201
2377
  // `{Largest.Group, Largest.Object + 1}`. Everything below it, including the already
1202
2378
  // published head of the current group, is outside the requested range, so the join is
1203
- // mid-group by construction. The draft pairs this with a fill when the subscriber
1204
- // wants the head; see {@link Publisher.runFill}.
2379
+ // mid-group by construction. From draft-20 the draft pairs this with a fill when the
2380
+ // subscriber wants the head. Before it, the head comes from a joining FETCH, which we
2381
+ // refuse, so the subscription carries the current group whole instead: a subscriber
2382
+ // starting at object 0 takes it as the whole group, and the head still reaches one that
2383
+ // sends no joining FETCH.
1205
2384
  case "nextObject":
1206
- return { start: edge.next };
1207
- // `{Largest.Group + 1 - groups, 0}`: 0 is the next group and 1 is the current one.
2385
+ if (!edge.next || Filter.isDraft20(version))
2386
+ return { start: edge.next };
2387
+ return { start: { group: edge.next.group, object: 0n } };
2388
+ // `{Largest.Group + 1 - groups, 0}`: 0 is the next group and 1 is the current one, a
2389
+ // live join; anything further back is refused before this (see `countsBack`).
1208
2390
  // Counted from `Largest.Group`, which sits below the newest group while that group has
1209
2391
  // no objects yet; only with no largest at all does the newest group stand in for it.
1210
2392
  case "relative": {
@@ -1224,13 +2406,32 @@ function filterRange(filter, edge) {
1224
2406
  * Trim a group to the filter's object bounds, so nothing outside the requested range is
1225
2407
  * sent. Interior groups are served whole.
1226
2408
  */
1227
- function groupSlice(range, sequence) {
1228
- const at = BigInt(sequence);
2409
+ function groupSlice(range, key) {
1229
2410
  return {
1230
- skip: range.start?.group === at ? Number(range.start.object) : 0,
1231
- until: range.end?.group === at && range.end.object !== undefined ? Number(range.end.object) + 1 : undefined,
2411
+ skip: range.start?.group === key ? frameBound(range.start.object) : 0,
2412
+ until: range.end?.group === key && range.end.object !== undefined ? frameBound(range.end.object + 1n) : undefined,
1232
2413
  };
1233
2414
  }
2415
+ /** Whether `range` drops objects a stream serving `slice` of group `key` would send. */
2416
+ function excludes(range, key, slice) {
2417
+ const ours = groupSlice(range, key);
2418
+ return ((range.start !== undefined && key < range.start.group) ||
2419
+ (range.end !== undefined && key > range.end.group) ||
2420
+ ours.skip > slice.skip ||
2421
+ (ours.until !== undefined && (slice.until === undefined || ours.until < slice.until)));
2422
+ }
2423
+ /** A fill covering the whole requested prefix owns it; the live cursor starts after its snapshot. */
2424
+ function afterFill(range, fill, edge) {
2425
+ if (fill?.kind !== "group" || !edge.largest || !edge.next)
2426
+ return range;
2427
+ const start = range.start ?? { group: edge.latest ?? 0n, object: 0n };
2428
+ if (start.group > edge.next.group || (start.group === edge.next.group && start.object >= edge.next.object))
2429
+ return range;
2430
+ const coversStart = fill.start.group < start.group || (fill.start.group === start.group && fill.start.object <= start.object);
2431
+ const coversEnd = fill.end.group === edge.largest.group &&
2432
+ (fill.end.object === undefined || fill.end.object >= edge.largest.object);
2433
+ return coversStart && coversEnd ? { ...range, start: edge.next } : range;
2434
+ }
1234
2435
  /**
1235
2436
  * Resolve a fill request using the Fetch rules: relative to Largest Object and never
1236
2437
  * extending beyond it. An omitted Location Filter inherits the subscription's.
@@ -1273,13 +2474,12 @@ function fillRange(fill, subscription, largest) {
1273
2474
  (start.group === end.group && end.object !== undefined && end.object < start.object)) {
1274
2475
  return { kind: "empty" };
1275
2476
  }
1276
- if (start.group !== end.group)
2477
+ if (start.group !== largest.group || end.group !== largest.group)
1277
2478
  return { kind: "unsupported" };
1278
2479
  return {
1279
2480
  kind: "group",
1280
- sequence: start.group,
1281
- skip: start.object,
1282
- until: end.object === undefined ? undefined : end.object + 1n,
2481
+ start,
2482
+ end,
1283
2483
  };
1284
2484
  }
1285
2485
  class UpdateFailed extends Error {