@moq/net 0.4.7 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (664) hide show
  1. package/README.md +7 -1
  2. package/announce.d.ts +1 -1
  3. package/announce.d.ts.map +1 -1
  4. package/announce.js +1 -2
  5. package/announce.js.map +1 -1
  6. package/announced.d.ts +51 -47
  7. package/announced.d.ts.map +1 -1
  8. package/announced.js +183 -32
  9. package/announced.js.map +1 -1
  10. package/announced.test-util.d.ts +2 -0
  11. package/announced.test-util.d.ts.map +1 -0
  12. package/announced.test-util.js +27 -0
  13. package/announced.test-util.js.map +1 -0
  14. package/auth.d.ts +64 -0
  15. package/auth.d.ts.map +1 -0
  16. package/auth.js +20 -0
  17. package/auth.js.map +1 -0
  18. package/auth_gate.d.ts +2 -0
  19. package/auth_gate.d.ts.map +1 -0
  20. package/auth_gate.js +24 -0
  21. package/auth_gate.js.map +1 -0
  22. package/auth_session.d.ts +49 -0
  23. package/auth_session.d.ts.map +1 -0
  24. package/auth_session.js +1097 -0
  25. package/auth_session.js.map +1 -0
  26. package/bandwidth.d.ts +129 -25
  27. package/bandwidth.d.ts.map +1 -1
  28. package/bandwidth.js +410 -139
  29. package/bandwidth.js.map +1 -1
  30. package/bandwidth_api.d.ts +1 -1
  31. package/bandwidth_api.d.ts.map +1 -1
  32. package/bandwidth_api.js +1 -2
  33. package/bandwidth_api.js.map +1 -1
  34. package/broadcast.d.ts +64 -38
  35. package/broadcast.d.ts.map +1 -1
  36. package/broadcast.js +556 -173
  37. package/broadcast.js.map +1 -1
  38. package/cache.d.ts +103 -0
  39. package/cache.d.ts.map +1 -0
  40. package/cache.js +254 -0
  41. package/cache.js.map +1 -0
  42. package/claim.test-util.d.ts +5 -0
  43. package/claim.test-util.d.ts.map +1 -0
  44. package/claim.test-util.js +13 -0
  45. package/claim.test-util.js.map +1 -0
  46. package/connection/accept.d.ts +21 -13
  47. package/connection/accept.d.ts.map +1 -1
  48. package/connection/accept.js +97 -130
  49. package/connection/accept.js.map +1 -1
  50. package/connection/browser.d.ts.map +1 -1
  51. package/connection/browser.js +28 -20
  52. package/connection/browser.js.map +1 -1
  53. package/connection/connect.d.ts +120 -24
  54. package/connection/connect.d.ts.map +1 -1
  55. package/connection/connect.js +535 -217
  56. package/connection/connect.js.map +1 -1
  57. package/connection/dials.d.ts +45 -0
  58. package/connection/dials.d.ts.map +1 -0
  59. package/connection/dials.js +109 -0
  60. package/connection/dials.js.map +1 -0
  61. package/connection/endpoint.d.ts +60 -0
  62. package/connection/endpoint.d.ts.map +1 -0
  63. package/connection/endpoint.js +114 -0
  64. package/connection/endpoint.js.map +1 -0
  65. package/connection/forward.d.ts +7 -1
  66. package/connection/forward.d.ts.map +1 -1
  67. package/connection/forward.js +265 -81
  68. package/connection/forward.js.map +1 -1
  69. package/connection/goaway.d.ts +16 -9
  70. package/connection/goaway.d.ts.map +1 -1
  71. package/connection/goaway.js +22 -95
  72. package/connection/goaway.js.map +1 -1
  73. package/connection/handshake.d.ts +34 -8
  74. package/connection/handshake.d.ts.map +1 -1
  75. package/connection/handshake.js +97 -21
  76. package/connection/handshake.js.map +1 -1
  77. package/connection/index.d.ts +4 -7
  78. package/connection/index.d.ts.map +1 -1
  79. package/connection/index.js +1 -3
  80. package/connection/index.js.map +1 -1
  81. package/connection/liveness.d.ts +14 -0
  82. package/connection/liveness.d.ts.map +1 -0
  83. package/connection/liveness.js +30 -0
  84. package/connection/liveness.js.map +1 -0
  85. package/connection/pool.d.ts +142 -63
  86. package/connection/pool.d.ts.map +1 -1
  87. package/connection/pool.js +281 -118
  88. package/connection/pool.js.map +1 -1
  89. package/connection/reload.d.ts +60 -12
  90. package/connection/reload.d.ts.map +1 -1
  91. package/connection/reload.js +859 -234
  92. package/connection/reload.js.map +1 -1
  93. package/connection/session.d.ts +91 -0
  94. package/connection/session.d.ts.map +1 -0
  95. package/connection/session.js +2 -0
  96. package/connection/session.js.map +1 -0
  97. package/connection/stats.d.ts +20 -11
  98. package/connection/stats.d.ts.map +1 -1
  99. package/connection/stats.js +64 -9
  100. package/connection/stats.js.map +1 -1
  101. package/connection/ticker.d.ts +4 -0
  102. package/connection/ticker.d.ts.map +1 -0
  103. package/connection/ticker.js +66 -0
  104. package/connection/ticker.js.map +1 -0
  105. package/connection/tokens.d.ts +2 -0
  106. package/connection/tokens.d.ts.map +1 -0
  107. package/connection/tokens.js +404 -0
  108. package/connection/tokens.js.map +1 -0
  109. package/connection/transport.d.ts.map +1 -1
  110. package/connection/transport.js +4 -5
  111. package/connection/transport.js.map +1 -1
  112. package/connection/withdrawal.d.ts +2 -0
  113. package/connection/withdrawal.d.ts.map +1 -0
  114. package/connection/withdrawal.js +23 -0
  115. package/connection/withdrawal.js.map +1 -0
  116. package/consume.js +213 -47
  117. package/consume.js.map +1 -1
  118. package/cover.d.ts +59 -0
  119. package/cover.d.ts.map +1 -0
  120. package/cover.js +375 -0
  121. package/cover.js.map +1 -0
  122. package/datagram.d.ts +70 -11
  123. package/datagram.d.ts.map +1 -1
  124. package/datagram.js +317 -2
  125. package/datagram.js.map +1 -1
  126. package/datagram_stream.d.ts +18 -0
  127. package/datagram_stream.d.ts.map +1 -0
  128. package/datagram_stream.js +67 -0
  129. package/datagram_stream.js.map +1 -0
  130. package/defined.test-util.d.ts +2 -0
  131. package/defined.test-util.d.ts.map +1 -0
  132. package/defined.test-util.js +7 -0
  133. package/defined.test-util.js.map +1 -0
  134. package/delivered.d.ts +75 -0
  135. package/delivered.d.ts.map +1 -0
  136. package/delivered.js +228 -0
  137. package/delivered.js.map +1 -0
  138. package/demand.d.ts +173 -0
  139. package/demand.d.ts.map +1 -0
  140. package/demand.js +582 -0
  141. package/demand.js.map +1 -0
  142. package/drops.d.ts +93 -0
  143. package/drops.d.ts.map +1 -0
  144. package/drops.js +283 -0
  145. package/drops.js.map +1 -0
  146. package/error.d.ts +120 -21
  147. package/error.d.ts.map +1 -1
  148. package/error.js +230 -38
  149. package/error.js.map +1 -1
  150. package/errors.d.ts +2 -2
  151. package/errors.d.ts.map +1 -1
  152. package/errors.js +2 -3
  153. package/errors.js.map +1 -1
  154. package/fill.d.ts +174 -0
  155. package/fill.d.ts.map +1 -0
  156. package/fill.js +760 -0
  157. package/fill.js.map +1 -0
  158. package/flate/decoder.d.ts +2 -0
  159. package/flate/decoder.d.ts.map +1 -0
  160. package/flate/decoder.js +63 -0
  161. package/flate/decoder.js.map +1 -0
  162. package/flate/encoder.d.ts +2 -0
  163. package/flate/encoder.d.ts.map +1 -0
  164. package/flate/encoder.js +64 -0
  165. package/flate/encoder.js.map +1 -0
  166. package/flate/group.d.ts +34 -0
  167. package/flate/group.d.ts.map +1 -0
  168. package/flate/group.js +140 -0
  169. package/flate/group.js.map +1 -0
  170. package/frame.d.ts +80 -0
  171. package/frame.d.ts.map +1 -0
  172. package/frame.js +296 -0
  173. package/frame.js.map +1 -0
  174. package/frame.test-util.d.ts +5 -0
  175. package/frame.test-util.d.ts.map +1 -0
  176. package/frame.test-util.js +9 -0
  177. package/frame.test-util.js.map +1 -0
  178. package/group.d.ts +108 -45
  179. package/group.d.ts.map +1 -1
  180. package/group.js +1616 -308
  181. package/group.js.map +1 -1
  182. package/group_api.d.ts +7 -0
  183. package/group_api.d.ts.map +1 -0
  184. package/group_api.js +7 -0
  185. package/group_api.js.map +1 -0
  186. package/hop.d.ts +62 -76
  187. package/hop.d.ts.map +1 -1
  188. package/hop.js +92 -65
  189. package/hop.js.map +1 -1
  190. package/identity.d.ts +39 -0
  191. package/identity.d.ts.map +1 -0
  192. package/identity.js +47 -0
  193. package/identity.js.map +1 -0
  194. package/ietf/active_count.d.ts +2 -0
  195. package/ietf/active_count.d.ts.map +1 -0
  196. package/ietf/active_count.js +30 -0
  197. package/ietf/active_count.js.map +1 -0
  198. package/ietf/aliases.js +69 -36
  199. package/ietf/aliases.js.map +1 -1
  200. package/ietf/cluster.d.ts +3 -3
  201. package/ietf/cluster.js +14 -55
  202. package/ietf/cluster.js.map +1 -1
  203. package/ietf/connection.d.ts +1 -31
  204. package/ietf/connection.d.ts.map +1 -1
  205. package/ietf/connection.js +305 -144
  206. package/ietf/connection.js.map +1 -1
  207. package/ietf/datagram.d.ts +60 -0
  208. package/ietf/datagram.d.ts.map +1 -0
  209. package/ietf/datagram.js +152 -0
  210. package/ietf/datagram.js.map +1 -0
  211. package/ietf/error.d.ts +3 -3
  212. package/ietf/error.js +82 -101
  213. package/ietf/error.js.map +1 -1
  214. package/ietf/fetch.d.ts +93 -37
  215. package/ietf/fetch.d.ts.map +1 -1
  216. package/ietf/fetch.js +172 -94
  217. package/ietf/fetch.js.map +1 -1
  218. package/ietf/filter.d.ts +21 -31
  219. package/ietf/filter.d.ts.map +1 -1
  220. package/ietf/filter.js +140 -172
  221. package/ietf/filter.js.map +1 -1
  222. package/ietf/goaway.d.ts +12 -10
  223. package/ietf/goaway.d.ts.map +1 -1
  224. package/ietf/goaway.js +22 -36
  225. package/ietf/goaway.js.map +1 -1
  226. package/ietf/hidden.js +1 -2
  227. package/ietf/hidden.js.map +1 -1
  228. package/ietf/index.d.ts +8 -20
  229. package/ietf/index.d.ts.map +1 -1
  230. package/ietf/index.js +4 -15
  231. package/ietf/index.js.map +1 -1
  232. package/ietf/join.d.ts +7 -0
  233. package/ietf/join.d.ts.map +1 -0
  234. package/ietf/join.js +234 -0
  235. package/ietf/join.js.map +1 -0
  236. package/ietf/message.d.ts +18 -2
  237. package/ietf/message.d.ts.map +1 -1
  238. package/ietf/message.js +60 -41
  239. package/ietf/message.js.map +1 -1
  240. package/ietf/message.test-util.d.ts +6 -0
  241. package/ietf/message.test-util.d.ts.map +1 -0
  242. package/ietf/message.test-util.js +13 -0
  243. package/ietf/message.test-util.js.map +1 -0
  244. package/ietf/namespace.d.ts +19 -5
  245. package/ietf/namespace.d.ts.map +1 -1
  246. package/ietf/namespace.js +78 -27
  247. package/ietf/namespace.js.map +1 -1
  248. package/ietf/object.d.ts +195 -33
  249. package/ietf/object.d.ts.map +1 -1
  250. package/ietf/object.js +405 -179
  251. package/ietf/object.js.map +1 -1
  252. package/ietf/parameters.d.ts +25 -45
  253. package/ietf/parameters.d.ts.map +1 -1
  254. package/ietf/parameters.js +260 -473
  255. package/ietf/parameters.js.map +1 -1
  256. package/ietf/priority.d.ts +17 -2
  257. package/ietf/priority.d.ts.map +1 -1
  258. package/ietf/priority.js +19 -5
  259. package/ietf/priority.js.map +1 -1
  260. package/ietf/properties.d.ts +6 -5
  261. package/ietf/properties.d.ts.map +1 -1
  262. package/ietf/properties.js +78 -49
  263. package/ietf/properties.js.map +1 -1
  264. package/ietf/publish.d.ts +25 -33
  265. package/ietf/publish.d.ts.map +1 -1
  266. package/ietf/publish.js +45 -140
  267. package/ietf/publish.js.map +1 -1
  268. package/ietf/publish_namespace.d.ts +49 -72
  269. package/ietf/publish_namespace.d.ts.map +1 -1
  270. package/ietf/publish_namespace.js +66 -185
  271. package/ietf/publish_namespace.js.map +1 -1
  272. package/ietf/publisher.js +1800 -601
  273. package/ietf/publisher.js.map +1 -1
  274. package/ietf/range.d.ts +2 -0
  275. package/ietf/range.d.ts.map +1 -0
  276. package/ietf/range.js +222 -0
  277. package/ietf/range.js.map +1 -0
  278. package/ietf/request.d.ts +6 -30
  279. package/ietf/request.d.ts.map +1 -1
  280. package/ietf/request.js +41 -79
  281. package/ietf/request.js.map +1 -1
  282. package/ietf/request_stream.d.ts +1 -6
  283. package/ietf/request_stream.d.ts.map +1 -1
  284. package/ietf/request_stream.js +306 -17
  285. package/ietf/request_stream.js.map +1 -1
  286. package/ietf/session.d.ts +41 -0
  287. package/ietf/session.d.ts.map +1 -0
  288. package/ietf/session.js +65 -0
  289. package/ietf/session.js.map +1 -0
  290. package/ietf/setup.d.ts +5 -30
  291. package/ietf/setup.d.ts.map +1 -1
  292. package/ietf/setup.js +6 -118
  293. package/ietf/setup.js.map +1 -1
  294. package/ietf/setup_options.d.ts +31 -0
  295. package/ietf/setup_options.d.ts.map +1 -0
  296. package/ietf/setup_options.js +138 -0
  297. package/ietf/setup_options.js.map +1 -0
  298. package/ietf/solicit.js +4 -15
  299. package/ietf/solicit.js.map +1 -1
  300. package/ietf/subscribe.d.ts +52 -45
  301. package/ietf/subscribe.d.ts.map +1 -1
  302. package/ietf/subscribe.js +118 -240
  303. package/ietf/subscribe.js.map +1 -1
  304. package/ietf/subscribe_namespace.d.ts +16 -79
  305. package/ietf/subscribe_namespace.d.ts.map +1 -1
  306. package/ietf/subscribe_namespace.js +30 -202
  307. package/ietf/subscribe_namespace.js.map +1 -1
  308. package/ietf/subscriber.js +1839 -537
  309. package/ietf/subscriber.js.map +1 -1
  310. package/ietf/token.js +105 -28
  311. package/ietf/token.js.map +1 -1
  312. package/ietf/track.d.ts +27 -24
  313. package/ietf/track.d.ts.map +1 -1
  314. package/ietf/track.js +48 -62
  315. package/ietf/track.js.map +1 -1
  316. package/ietf/version.d.ts +13 -42
  317. package/ietf/version.d.ts.map +1 -1
  318. package/ietf/version.js +22 -49
  319. package/ietf/version.js.map +1 -1
  320. package/implementation.d.ts +2 -0
  321. package/implementation.d.ts.map +1 -0
  322. package/implementation.js +5 -0
  323. package/implementation.js.map +1 -0
  324. package/index.d.ts +34 -19
  325. package/index.d.ts.map +1 -1
  326. package/index.js +19 -7
  327. package/index.js.map +1 -1
  328. package/internal.d.ts +1515 -67
  329. package/internal.d.ts.map +1 -1
  330. package/internal.js +557 -80
  331. package/internal.js.map +1 -1
  332. package/ledger.d.ts +23 -0
  333. package/ledger.d.ts.map +1 -0
  334. package/ledger.js +247 -0
  335. package/ledger.js.map +1 -0
  336. package/listing.d.ts +132 -0
  337. package/listing.d.ts.map +1 -0
  338. package/listing.js +486 -0
  339. package/listing.js.map +1 -0
  340. package/lite/announce.d.ts +127 -66
  341. package/lite/announce.d.ts.map +1 -1
  342. package/lite/announce.js +384 -159
  343. package/lite/announce.js.map +1 -1
  344. package/lite/announce_stream.d.ts +2 -0
  345. package/lite/announce_stream.d.ts.map +1 -0
  346. package/lite/announce_stream.js +92 -0
  347. package/lite/announce_stream.js.map +1 -0
  348. package/lite/answer.d.ts +22 -0
  349. package/lite/answer.d.ts.map +1 -0
  350. package/lite/answer.js +301 -0
  351. package/lite/answer.js.map +1 -0
  352. package/lite/auth.d.ts +45 -0
  353. package/lite/auth.d.ts.map +1 -0
  354. package/lite/auth.js +204 -0
  355. package/lite/auth.js.map +1 -0
  356. package/lite/compat.d.ts +31 -0
  357. package/lite/compat.d.ts.map +1 -0
  358. package/lite/compat.js +86 -0
  359. package/lite/compat.js.map +1 -0
  360. package/lite/connection.d.ts +1 -45
  361. package/lite/connection.d.ts.map +1 -1
  362. package/lite/connection.js +360 -78
  363. package/lite/connection.js.map +1 -1
  364. package/lite/datagram-end.d.ts +26 -0
  365. package/lite/datagram-end.d.ts.map +1 -0
  366. package/lite/datagram-end.js +30 -0
  367. package/lite/datagram-end.js.map +1 -0
  368. package/lite/datagram.d.ts +73 -8
  369. package/lite/datagram.d.ts.map +1 -1
  370. package/lite/datagram.js +144 -10
  371. package/lite/datagram.js.map +1 -1
  372. package/lite/duration.d.ts +6 -0
  373. package/lite/duration.d.ts.map +1 -0
  374. package/lite/duration.js +14 -0
  375. package/lite/duration.js.map +1 -0
  376. package/lite/error.d.ts +9 -0
  377. package/lite/error.d.ts.map +1 -0
  378. package/lite/error.js +24 -0
  379. package/lite/error.js.map +1 -0
  380. package/lite/fills.d.ts +162 -0
  381. package/lite/fills.d.ts.map +1 -0
  382. package/lite/fills.js +486 -0
  383. package/lite/fills.js.map +1 -0
  384. package/lite/fit.d.ts +49 -0
  385. package/lite/fit.d.ts.map +1 -0
  386. package/lite/fit.js +305 -0
  387. package/lite/fit.js.map +1 -0
  388. package/lite/goaway.d.ts +2 -2
  389. package/lite/goaway.d.ts.map +1 -1
  390. package/lite/goaway.js +5 -14
  391. package/lite/goaway.js.map +1 -1
  392. package/lite/group.d.ts +67 -16
  393. package/lite/group.d.ts.map +1 -1
  394. package/lite/group.js +108 -31
  395. package/lite/group.js.map +1 -1
  396. package/lite/identity.d.ts +25 -0
  397. package/lite/identity.d.ts.map +1 -0
  398. package/lite/identity.js +79 -0
  399. package/lite/identity.js.map +1 -0
  400. package/lite/index.d.ts +14 -13
  401. package/lite/index.d.ts.map +1 -1
  402. package/lite/index.js +2 -2
  403. package/lite/index.js.map +1 -1
  404. package/lite/message.d.ts +10 -2
  405. package/lite/message.d.ts.map +1 -1
  406. package/lite/message.js +28 -45
  407. package/lite/message.js.map +1 -1
  408. package/lite/priority.d.ts +9 -2
  409. package/lite/priority.d.ts.map +1 -1
  410. package/lite/priority.js +11 -106
  411. package/lite/priority.js.map +1 -1
  412. package/lite/probe.d.ts +2 -2
  413. package/lite/probe.d.ts.map +1 -1
  414. package/lite/probe.js +9 -1
  415. package/lite/probe.js.map +1 -1
  416. package/lite/publisher.d.ts +10 -1
  417. package/lite/publisher.d.ts.map +1 -1
  418. package/lite/publisher.js +2548 -438
  419. package/lite/publisher.js.map +1 -1
  420. package/lite/routed.d.ts +59 -0
  421. package/lite/routed.d.ts.map +1 -0
  422. package/lite/routed.js +564 -0
  423. package/lite/routed.js.map +1 -0
  424. package/lite/session.d.ts +2 -28
  425. package/lite/session.d.ts.map +1 -1
  426. package/lite/session.js +0 -100
  427. package/lite/session.js.map +1 -1
  428. package/lite/setup.d.ts +32 -5
  429. package/lite/setup.d.ts.map +1 -1
  430. package/lite/setup.js +95 -22
  431. package/lite/setup.js.map +1 -1
  432. package/lite/stream.d.ts +5 -11
  433. package/lite/stream.d.ts.map +1 -1
  434. package/lite/stream.js +5 -2
  435. package/lite/stream.js.map +1 -1
  436. package/lite/subscribe.d.ts +478 -78
  437. package/lite/subscribe.d.ts.map +1 -1
  438. package/lite/subscribe.js +1373 -143
  439. package/lite/subscribe.js.map +1 -1
  440. package/lite/subscriber.d.ts +7 -44
  441. package/lite/subscriber.d.ts.map +1 -1
  442. package/lite/subscriber.js +3290 -516
  443. package/lite/subscriber.js.map +1 -1
  444. package/lite/track.d.ts +27 -12
  445. package/lite/track.d.ts.map +1 -1
  446. package/lite/track.js +116 -38
  447. package/lite/track.js.map +1 -1
  448. package/lite/tracks.d.ts +55 -0
  449. package/lite/tracks.d.ts.map +1 -0
  450. package/lite/tracks.js +114 -0
  451. package/lite/tracks.js.map +1 -0
  452. package/lite/version.d.ts +132 -24
  453. package/lite/version.d.ts.map +1 -1
  454. package/lite/version.js +378 -34
  455. package/lite/version.js.map +1 -1
  456. package/meta.d.ts +77 -0
  457. package/meta.d.ts.map +1 -0
  458. package/meta.js +130 -0
  459. package/meta.js.map +1 -0
  460. package/meta_api.d.ts +7 -0
  461. package/meta_api.d.ts.map +1 -0
  462. package/meta_api.js +7 -0
  463. package/meta_api.js.map +1 -0
  464. package/mint.d.ts +28 -0
  465. package/mint.d.ts.map +1 -0
  466. package/mint.js +66 -0
  467. package/mint.js.map +1 -0
  468. package/open.d.ts +63 -0
  469. package/open.d.ts.map +1 -0
  470. package/open.js +250 -0
  471. package/open.js.map +1 -0
  472. package/origin.d.ts +394 -142
  473. package/origin.d.ts.map +1 -1
  474. package/origin.js +2533 -687
  475. package/origin.js.map +1 -1
  476. package/package.json +8 -13
  477. package/path.d.ts +51 -51
  478. package/path.d.ts.map +1 -1
  479. package/path.js +210 -58
  480. package/path.js.map +1 -1
  481. package/payload.d.ts +33 -0
  482. package/payload.d.ts.map +1 -0
  483. package/payload.js +65 -0
  484. package/payload.js.map +1 -0
  485. package/prefix.d.ts +152 -0
  486. package/prefix.d.ts.map +1 -0
  487. package/prefix.js +349 -0
  488. package/prefix.js.map +1 -0
  489. package/priority.d.ts +8 -0
  490. package/priority.d.ts.map +1 -0
  491. package/priority.js +185 -0
  492. package/priority.js.map +1 -0
  493. package/queue.d.ts +2 -0
  494. package/queue.d.ts.map +1 -0
  495. package/queue.js +46 -0
  496. package/queue.js.map +1 -0
  497. package/ranges.d.ts +36 -0
  498. package/ranges.d.ts.map +1 -0
  499. package/ranges.js +312 -0
  500. package/ranges.js.map +1 -0
  501. package/rescale.d.ts +24 -0
  502. package/rescale.d.ts.map +1 -0
  503. package/rescale.js +39 -0
  504. package/rescale.js.map +1 -0
  505. package/resume.d.ts +55 -0
  506. package/resume.d.ts.map +1 -0
  507. package/resume.js +4173 -0
  508. package/resume.js.map +1 -0
  509. package/resume.test-util.d.ts +2 -0
  510. package/resume.test-util.d.ts.map +1 -0
  511. package/resume.test-util.js +25 -0
  512. package/resume.test-util.js.map +1 -0
  513. package/skips.d.ts +48 -0
  514. package/skips.d.ts.map +1 -0
  515. package/skips.js +182 -0
  516. package/skips.js.map +1 -0
  517. package/stream.d.ts +78 -40
  518. package/stream.d.ts.map +1 -1
  519. package/stream.js +236 -93
  520. package/stream.js.map +1 -1
  521. package/subscription.test-util.d.ts +2 -0
  522. package/subscription.test-util.d.ts.map +1 -0
  523. package/subscription.test-util.js +49 -0
  524. package/subscription.test-util.js.map +1 -0
  525. package/tail.d.ts +23 -14
  526. package/tail.d.ts.map +1 -1
  527. package/tail.js +224 -98
  528. package/tail.js.map +1 -1
  529. package/time.d.ts +41 -102
  530. package/time.d.ts.map +1 -1
  531. package/time.js +129 -92
  532. package/time.js.map +1 -1
  533. package/timed.d.ts +21 -0
  534. package/timed.d.ts.map +1 -0
  535. package/timed.js +2 -0
  536. package/timed.js.map +1 -0
  537. package/track.d.ts +578 -246
  538. package/track.d.ts.map +1 -1
  539. package/track.js +7306 -772
  540. package/track.js.map +1 -1
  541. package/track_api.d.ts +7 -0
  542. package/track_api.d.ts.map +1 -0
  543. package/track_api.js +7 -0
  544. package/track_api.js.map +1 -0
  545. package/util/abort.d.ts +1 -0
  546. package/util/abort.d.ts.map +1 -1
  547. package/util/abort.js +23 -2
  548. package/util/abort.js.map +1 -1
  549. package/util/announce.d.ts +4 -0
  550. package/util/announce.d.ts.map +1 -0
  551. package/util/announce.js +11 -0
  552. package/util/announce.js.map +1 -0
  553. package/util/bigint.d.ts +3 -0
  554. package/util/bigint.d.ts.map +1 -0
  555. package/util/bigint.js +8 -0
  556. package/util/bigint.js.map +1 -0
  557. package/util/change.d.ts +12 -0
  558. package/util/change.d.ts.map +1 -0
  559. package/util/change.js +18 -0
  560. package/util/change.js.map +1 -0
  561. package/util/deadline.d.ts +2 -0
  562. package/util/deadline.d.ts.map +1 -0
  563. package/util/deadline.js +108 -0
  564. package/util/deadline.js.map +1 -0
  565. package/util/decode_error.d.ts +3 -0
  566. package/util/decode_error.d.ts.map +1 -0
  567. package/util/decode_error.js +11 -0
  568. package/util/decode_error.js.map +1 -0
  569. package/util/demand.d.ts +8 -0
  570. package/util/demand.d.ts.map +1 -0
  571. package/util/demand.js +24 -0
  572. package/util/demand.js.map +1 -0
  573. package/util/given_up.d.ts +2 -0
  574. package/util/given_up.d.ts.map +1 -0
  575. package/util/given_up.js +101 -0
  576. package/util/given_up.js.map +1 -0
  577. package/util/hex.d.ts +6 -0
  578. package/util/hex.d.ts.map +1 -1
  579. package/util/hex.js +19 -5
  580. package/util/hex.js.map +1 -1
  581. package/util/key.d.ts +15 -0
  582. package/util/key.d.ts.map +1 -0
  583. package/util/key.js +38 -0
  584. package/util/key.js.map +1 -0
  585. package/util/limits.d.ts +2 -0
  586. package/util/limits.d.ts.map +1 -0
  587. package/util/limits.js +76 -0
  588. package/util/limits.js.map +1 -0
  589. package/util/observed.d.ts +23 -0
  590. package/util/observed.d.ts.map +1 -0
  591. package/util/observed.js +122 -0
  592. package/util/observed.js.map +1 -0
  593. package/util/sorted.d.ts +2 -0
  594. package/util/sorted.d.ts.map +1 -0
  595. package/util/sorted.js +149 -0
  596. package/util/sorted.js.map +1 -0
  597. package/util/timeout.d.ts +2 -1
  598. package/util/timeout.d.ts.map +1 -1
  599. package/util/timeout.js +13 -10
  600. package/util/timeout.js.map +1 -1
  601. package/util/timer.d.ts +2 -0
  602. package/util/timer.d.ts.map +1 -0
  603. package/util/timer.js +19 -0
  604. package/util/timer.js.map +1 -0
  605. package/util/u64.js +0 -1
  606. package/util/utf8.d.ts +2 -0
  607. package/util/utf8.d.ts.map +1 -1
  608. package/util/utf8.js +7 -2
  609. package/util/utf8.js.map +1 -1
  610. package/util/varint.d.ts.map +1 -1
  611. package/util/varint.js +8 -2
  612. package/util/varint.js.map +1 -1
  613. package/util/watch.d.ts +8 -0
  614. package/util/watch.d.ts.map +1 -0
  615. package/util/watch.js +38 -0
  616. package/util/watch.js.map +1 -0
  617. package/util/yield.d.ts +2 -0
  618. package/util/yield.d.ts.map +1 -0
  619. package/util/yield.js +31 -0
  620. package/util/yield.js.map +1 -0
  621. package/varint.d.ts +0 -29
  622. package/varint.d.ts.map +1 -1
  623. package/varint.js +7 -29
  624. package/varint.js.map +1 -1
  625. package/varint_api.d.ts +7 -0
  626. package/varint_api.d.ts.map +1 -0
  627. package/varint_api.js +7 -0
  628. package/varint_api.js.map +1 -0
  629. package/version.d.ts +2 -0
  630. package/version.d.ts.map +1 -0
  631. package/version.js +4 -0
  632. package/version.js.map +1 -0
  633. package/window.d.ts +570 -0
  634. package/window.d.ts.map +1 -0
  635. package/window.js +1677 -0
  636. package/window.js.map +1 -0
  637. package/wire.d.ts +150 -35
  638. package/wire.d.ts.map +1 -1
  639. package/wire.js +27 -1
  640. package/wire.js.map +1 -1
  641. package/connection/established.d.ts +0 -53
  642. package/connection/established.d.ts.map +0 -1
  643. package/connection/established.js +0 -3
  644. package/connection/established.js.map +0 -1
  645. package/ietf/adapter.d.ts +0 -75
  646. package/ietf/adapter.d.ts.map +0 -1
  647. package/ietf/adapter.js +0 -700
  648. package/ietf/adapter.js.map +0 -1
  649. package/lite/datagram_stream.d.ts +0 -8
  650. package/lite/datagram_stream.d.ts.map +0 -1
  651. package/lite/datagram_stream.js +0 -44
  652. package/lite/datagram_stream.js.map +0 -1
  653. package/lite/fetch.d.ts +0 -28
  654. package/lite/fetch.d.ts.map +0 -1
  655. package/lite/fetch.js +0 -79
  656. package/lite/fetch.js.map +0 -1
  657. package/util/log.d.ts +0 -5
  658. package/util/log.d.ts.map +0 -1
  659. package/util/log.js +0 -17
  660. package/util/log.js.map +0 -1
  661. package/zod.d.ts +0 -13
  662. package/zod.d.ts.map +0 -1
  663. package/zod.js +0 -19
  664. package/zod.js.map +0 -1
package/ietf/publisher.js CHANGED
@@ -1,33 +1,59 @@
1
- /* @ts-self-types="./publisher.d.ts" */
2
- import { race, Signal } from "@moq/signals";
3
- import { controlTimeout, error, reason, StreamCode, StreamError } from "../error.js";
4
- 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";
5
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";
6
13
  import { Writer } from "../stream.js";
7
- 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";
8
22
  import { TimeoutError, withTimeout } from "../util/timeout.js";
9
- import * as Varint from "../varint.js";
10
- import { wireOf } from "../wire.js";
23
+ import { latestAt, rangesPolicy, withPolicy } from "../window.js";
24
+ import { sameIdentity, wireOf } from "../wire.js";
11
25
  import * as Cluster from "./cluster.js";
12
- import { requestReason, toRequestCode } from "./error.js";
13
- 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";
14
29
  import * as Filter from "./filter.js";
15
30
  import * as Message from "./message.js";
16
- 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";
17
33
  import { Parameters } from "./parameters.js";
18
34
  import { fromWire, toWire } from "./priority.js";
19
35
  import * as Properties from "./properties.js";
20
36
  import { PublishDone, PublishDoneStatus } from "./publish.js";
21
- import { PublishNamespace, PublishNamespaceDone, PublishNamespaceOk, PublishNamespaceUpdate, } from "./publish_namespace.js";
37
+ import { PublishNamespace, PublishNamespaceUpdate } from "./publish_namespace.js";
22
38
  import { RequestError, RequestOk } from "./request.js";
23
- import { cancelled, finCancels } from "./request_stream.js";
24
- import { SubscribeError, SubscribeOk } from "./subscribe.js";
25
- import { SubscribeNamespaceEntry, SubscribeNamespaceEntryDone, SubscribeNamespaceOk, } from "./subscribe_namespace.js";
26
- 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";
27
45
  /** First wait before re-offering a namespace the peer refused or we couldn't open for. */
28
46
  const RETRY_BASE = 100;
29
47
  /** Ceiling on that wait. The loop retries for the life of the session, so it must not spin. */
30
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;
31
57
  /** Cluster parameters for one snapshot: the advertised hops, then our own id last. */
32
58
  function clusterFor(base, route) {
33
59
  if (!base)
@@ -36,20 +62,22 @@ function clusterFor(base, route) {
36
62
  if (self === undefined)
37
63
  return undefined;
38
64
  const hops = route.hops.at(-1) === self ? [...route.hops] : [...route.hops, self];
39
- return { hops, cost: route.cost.warm };
65
+ return { hops, cost: route.cost };
40
66
  }
41
67
  /**
42
68
  * What it takes to move the peer from `held` to `next`.
43
69
  *
44
- * - `"same"`: the peer would decode the same advertisement. The cold cost, and the whole
45
- * 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.
46
72
  * - `"restart"`: nothing is held, nothing is wanted, or a different broadcast, which is
47
73
  * withdrawn and advertised again.
48
- * - 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
49
75
  * the peer holds and the ones it should, for the target to update.
50
76
  */
51
77
  function change(base, held, next) {
52
- 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))
53
81
  return "restart";
54
82
  const from = clusterFor(base, held.route);
55
83
  const to = clusterFor(base, next.route);
@@ -64,14 +92,59 @@ function sameHops(a, b) {
64
92
  return a.length === b.length && a.every((hop, i) => hop === b[i]);
65
93
  }
66
94
  /**
67
- * How long one advertisement may take to be answered. Matches the Rust publisher, and the
68
- * 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
69
97
  * loop just as effectively as one it never grants.
70
98
  */
71
- const ADVERTISE_TIMEOUT_MS = 5000;
99
+ const ADVERTISE_TIMEOUT_MS = REQUEST_TIMEOUT_MS;
100
+ const ADVERTISE_TIMEOUT = Duration.millis(ADVERTISE_TIMEOUT_MS);
72
101
  /** Sleep `delay`, jittered, so a relay's namespaces don't all retry on the same tick. */
73
102
  function retryAfter(delay) {
74
- 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";
75
148
  }
76
149
  /**
77
150
  * Handles publishing broadcasts using moq-transport protocol.
@@ -80,113 +153,363 @@ function retryAfter(delay) {
80
153
  * @internal
81
154
  */
82
155
  export class Publisher {
156
+ #withdrawal = new Withdrawal();
157
+ withdraw() {
158
+ return this.#withdrawal.close();
159
+ }
83
160
  #quic;
161
+ #datagramWriter;
84
162
  #session;
85
163
  #requiresSolicitation;
86
164
  #hidden;
165
+ // Whether a SUBSCRIBE_NAMESPACE's REQUEST_OK counts the NAMESPACEs that follow it (MoQ Active Count).
166
+ #activeCount;
87
167
  // The origin this session serves, borrowed: it outlives the session, and closing the
88
- // session leaves its broadcasts alone. The namespaces are advertised with an unsolicited
89
- // PUBLISH_NAMESPACE (see {@link runPublishNamespaces}), or on request if the peer asked
90
- // 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.
91
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);
92
176
  #publish;
93
177
  // What every advertisement carries on a session that negotiated the MoQ Cluster
94
178
  // extension: a hop path holding our own id, so the peer can tell that what it hears
95
179
  // back came from us. `undefined` when nothing negotiated it.
96
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;
97
189
  /**
98
190
  * Creates a new Publisher instance.
99
191
  *
100
192
  * @internal
101
193
  */
102
- constructor({ quic, session, publish, requiresSolicitation, hidden = false, cluster, }) {
194
+ constructor({ quic, session, publish, requiresSolicitation, hidden = false, activeCount = false, cluster, grant = new Signal(undefined), auth, }) {
103
195
  this.#quic = quic;
196
+ this.#datagramWriter = DatagramStream.datagramWriter(quic);
197
+ this.#grant = grant;
198
+ this.#gate = new Gate(grant);
199
+ this.#auth = auth;
104
200
  this.#session = session;
105
201
  const origin = publish && wireOf(publish);
106
202
  this.#advertised = origin?.advertised ?? new Signal(new Map());
107
203
  this.#publish = publish;
108
204
  this.#requiresSolicitation = requiresSolicitation;
109
205
  this.#hidden = hidden;
206
+ this.#activeCount = activeCount;
110
207
  this.#advert = Cluster.advertise(cluster);
111
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
+ }
112
214
  /**
113
215
  * Handles an incoming SUBSCRIBE request on a bidi stream.
114
216
  * Owns the full lifecycle: sends response, serves track data, waits for close.
115
217
  *
116
218
  * @internal
117
219
  */
118
- 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) {
119
232
  const version = this.#session.version;
120
233
  const name = msg.trackNamespace;
121
234
  let broadcast;
122
235
  let refusal;
123
- // Legal requests we can't honor are refused one at a time. A subscription that
124
- // forwards nothing is only useful to a subscriber that later turns forwarding on,
125
- // and serving a Range Filter unfiltered would deliver objects it excluded.
126
- const unsupported = !msg.forward
127
- ? "FORWARD=0 not supported"
128
- : msg.rangeFilters
129
- ? "range filters not supported"
130
- : undefined;
131
- if (unsupported) {
132
- 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" };
133
255
  }
134
256
  else {
135
257
  try {
136
- broadcast =
137
- this.#publish && (wireOf(this.#publish).local(name) ?? (await wireOf(this.#publish).demand(name)));
138
- if (!broadcast) {
139
- refusal = {
140
- errorCode: toRequestCode("does_not_exist", "subscribe", version),
141
- reasonPhrase: "broadcast not found",
142
- };
143
- }
258
+ broadcast = await this.#resolve(name, left.signal);
144
259
  }
145
260
  catch (err) {
146
- const e = error(err);
147
- const condition = e instanceof StreamError && e.code === StreamCode.NotFound ? "does_not_exist" : "internal";
148
- 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);
149
267
  }
150
268
  }
151
269
  if (refusal) {
152
- if (version === Version.DRAFT_14) {
153
- await stream.writer.u53(SubscribeError.id);
154
- const err = new SubscribeError({
155
- requestId: msg.requestId,
156
- errorCode: refusal.errorCode,
157
- 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,
158
407
  });
159
- await err.encode(stream.writer, version);
160
408
  }
161
- else {
162
- await stream.writer.u53(RequestError.id);
163
- const err = new RequestError({
164
- requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined,
165
- errorCode: refusal.errorCode,
166
- 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",
167
443
  });
168
- await err.encode(stream.writer, version);
444
+ await Message.write(request.writer, PublishDone.id, done, version);
445
+ request.close();
446
+ return undefined;
169
447
  }
170
- stream.close();
171
- 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);
172
467
  }
173
- if (!broadcast)
174
- 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;
175
504
  const priority = fromWire(msg.subscriberPriority);
176
- const track = wireOf(broadcast).subscribe(msg.trackName, {
177
- priority,
178
- // moq-transport has no subscriber latency parameter. Keep everything the
179
- // producer retained and let the receiving subscriber enforce its own budget.
180
- // Keep the sentinel encodable if this demand crosses a Lite hop before the
181
- // producer's retention bound is known.
182
- maxAge: Milli(Varint.MAX_U53),
183
- });
505
+ const datagramPriority = new Signal(priority);
506
+ const order = msg.groupOrder;
184
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();
185
512
  try {
186
- // Declaring the timescale is what opts the track into timestamps; every object
187
- // Timestamp below is in these units.
188
- const info = await track.info();
189
- const timescale = info.timescale;
190
513
  // The model ranks higher-first, the IETF wire lower-first. Every group this
191
514
  // subscription serves carries the same publisher priority, which is what lets a
192
515
  // relay prefer catalog and audio over video when it has no subscriber preference
@@ -195,212 +518,347 @@ export class Publisher {
195
518
  // The filter and any fill are relative to the live edge, so snapshot it once: the
196
519
  // fill ends exactly where a Next Object subscription begins, which is what lets
197
520
  // the draft's current-group join (Next Object plus a StartGroup=1 fill) cover the
198
- // group with no gap and no overlap.
199
- const edge = liveEdge(track);
200
- 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);
201
534
  // The wire request tells an upstream what we need; the cursor is what actually
202
535
  // trims this subscriber, since the producer fans every cached group out to every
203
536
  // sink regardless. An absent start joins at the latest group, which is what
204
537
  // moq-lite means by joining a live track. The range's end is the inclusive last
205
538
  // group; the model's `endGroup` is exclusive.
206
- track.update({
207
- priority,
208
- maxAge: Milli(Varint.MAX_U53),
209
- groups: {
210
- start: range.start ? { included: Number(range.start.group) } : undefined,
211
- end: range.end ? { included: Number(range.end.group) } : undefined,
212
- },
213
- });
214
- 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);
215
541
  if (startGroup !== undefined)
216
- 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;
217
545
  // A fill reads the group cache through its own consumer, independent of the
218
546
  // subscription's cursor. Forked from this subscriber rather than resolved through
219
547
  // the broadcast again: a dynamic serve is one request per peer subscription, so
220
548
  // asking the broadcast would mint a second producer nobody has accepted.
221
- const fill = msg.fill && Filter.isDraft20(version) ? fillRange(msg.fill, msg.filter, edge.largest) : undefined;
222
- cache = fill && fill.kind !== "empty" ? track.fork({ priority, maxAge: Milli(Varint.MAX_U53) }) : undefined;
223
- // Send SUBSCRIBE_OK
224
- await stream.writer.u53(SubscribeOk.id);
225
- const ok = new SubscribeOk({
226
- requestId: version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16
227
- ? msg.requestId
228
- : undefined,
229
- trackAlias: msg.requestId,
230
- // Required once the track has content; a fill-requesting subscriber sizes its
231
- // backfill against this. Below draft-20 round it down to the start of its
232
- // group, matching what the subscription serves there: a draft-20 subscriber
233
- // recovers a group's head with a FILL, which we serve, while older drafts
234
- // recover it with a joining FETCH, which we do not, so naming a mid-group
235
- // start would strand them.
236
- largest: edge.largest &&
237
- (Filter.isDraft20(version)
238
- ? { groupId: edge.largest.group, objectId: edge.largest.object }
239
- : { groupId: edge.largest.group, objectId: 0n }),
240
- properties: msg.propertiesWanted
241
- ? // Declaring the timescale is what opts the track into timestamps; every
242
- // object Timestamp below is in these units. We serve the newest group
243
- // first, matching moq-lite.
244
- { timescale, priority: publisherPriority, groupOrder: Properties.DESCENDING }
245
- : // INCLUDE_PROPERTIES=0. The block stays present but empty, which also means
246
- // the track opts out of timestamps for this subscriber.
247
- {},
248
- });
249
- 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
+ }
250
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();
251
594
  // Cancels groups still queued for a stream slot. Only the subscriber leaving counts:
252
595
  // a track that ran out of groups still has to flush the ones already queued, and we
253
596
  // close the stream ourselves below to say so.
254
597
  let finished = false;
255
598
  let unsubscribe;
599
+ const fillAbort = new AbortController();
256
600
  const unsubscribed = new Promise((resolve) => {
257
- unsubscribe = resolve;
601
+ unsubscribe = () => {
602
+ fillAbort.abort(new StreamError(StreamCode.Cancel, { message: "unsubscribed before the fill finished" }));
603
+ resolve();
604
+ };
258
605
  });
259
- // Update replies and PUBLISH_DONE come from separate tasks but share this stream, and a
260
- // message is written in several pieces. Chain them so each goes out whole, in order,
261
- // and nothing follows PUBLISH_DONE.
262
- let replies = Promise.resolve();
263
- let replied = false;
264
- const reply = (write) => {
265
- const sent = replies.then(() => (replied ? undefined : write()));
266
- replies = sent.catch(() => undefined);
267
- 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));
268
653
  };
269
- let publishError;
270
654
  const updates = (async () => {
271
- if (version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16)
272
- return stream.reader.closed;
273
655
  for (;;) {
274
- if (await stream.reader.done()) {
275
- if (finCancels(version))
276
- return;
277
- 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);
278
763
  }
279
- if ((await stream.reader.u53()) !== 0x02)
280
- throw new Error("unexpected message on subscribe stream");
281
- const params = await Message.decode(stream.reader, async (r) => {
282
- await r.u62();
283
- if (version === Version.DRAFT_17)
284
- await r.u62();
285
- return Parameters.decode(r, version);
286
- });
287
- const unsupported = params.forward === false ||
288
- params.bytes.size > 0 ||
289
- params.subscriptionFilter !== undefined ||
290
- params.largest !== undefined ||
291
- params.rangeFilters ||
292
- params.trackPropertyFilter ||
293
- params.authorizationToken ||
294
- [...params.vars.keys()].some((key) => key !== 0x10n && key !== 0x20n);
295
- if (unsupported) {
296
- // Recorded before the reply, so a PUBLISH_DONE queued behind it reports the failure.
297
- const failed = new UpdateFailed();
298
- publishError = failed;
299
- await reply(async () => {
300
- await stream.writer.u53(RequestError.id);
301
- await new RequestError({
302
- requestId: undefined,
303
- errorCode: toRequestCode("not_supported", "subscribe", version),
304
- reasonPhrase: "REQUEST_UPDATE parameters not supported",
305
- }).encode(stream.writer, version);
306
- });
307
- throw failed;
764
+ finally {
765
+ updating = undefined;
766
+ applied.resolve();
308
767
  }
309
- // update() replaces every option, so carry the rest over as Rust does.
310
- if (params.subscriberPriority !== undefined)
311
- track.update({ ...track.subscription.peek(), priority: fromWire(params.subscriberPriority) });
312
- await reply(async () => {
313
- await stream.writer.u53(RequestOk.id);
314
- await new RequestOk({ requestId: undefined }).encode(stream.writer, version);
315
- });
316
768
  }
317
769
  })();
318
- const requestEnded = version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16
319
- ? updates
320
- : race([updates, stream.writer.closed]);
770
+ const requestEnded = race([updates, request.ended]);
321
771
  void requestEnded.then(() => {
322
772
  if (!finished)
323
773
  unsubscribe();
324
774
  },
325
- // Updates can fail after the serving loop ends while its last groups drain.
326
- (err) => {
327
- publishError = error(err);
328
- unsubscribe();
329
- });
330
- // Every group started, until its stream finishes or resets, and the data streams
331
- // opened for PUBLISH_DONE to report.
332
- const groups = new Set();
333
- const streams = { opened: 0 };
334
- // 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.
335
780
  const serving = (async () => {
336
781
  for (;;) {
337
- const group = await track.recvGroup();
338
- if (!group)
339
- return;
340
- // Past the filter's end. Dropped here rather than through `setGroups`, which
341
- // parks a capped group instead: this range is fixed for the life of the
342
- // subscription, so a group above it is never coming back in, and holding
343
- // one keeps the loop from ever ending. A producer that publishes beyond
344
- // the end and then closes would otherwise strand PUBLISH_DONE.
345
- if (range.end !== undefined && BigInt(group.sequence) > range.end.group) {
346
- group.close();
782
+ const group = await servingGroup(track);
783
+ if (group) {
784
+ serveGroup(group, groupSlice(range, group.start));
347
785
  continue;
348
786
  }
349
- const task = this.#runGroup({
350
- requestId: msg.requestId,
351
- group,
352
- timescale,
353
- publisherPriority,
354
- stamped: msg.propertiesWanted,
355
- slice: groupSlice(range, group.sequence),
356
- unsubscribed,
357
- streams,
358
- });
359
- groups.add(task);
360
- void task.finally(() => groups.delete(task));
787
+ const pending = updating ?? filling;
788
+ if (!pending)
789
+ return;
790
+ await pending;
361
791
  }
362
792
  })();
363
- // The fill (when one was requested) runs alongside on its own fetch stream; its
364
- // failures reset that stream and never touch the subscription.
365
- const filling = fill && cache
366
- ? this.#runFill({
367
- requestId: msg.requestId,
368
- priority,
369
- fill,
370
- cache,
371
- timescale,
372
- stamped: msg.propertiesWanted,
373
- unsubscribed,
374
- streams,
375
- })
376
- : 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;
377
804
  let ended = false;
378
805
  try {
379
806
  const served = Symbol("served");
380
- 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;
381
814
  }
382
815
  catch (err) {
383
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();
384
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;
385
833
  // PUBLISH_DONE waits until every stream this subscription will open is closed, as
386
834
  // the draft requires, so its count is final. The subscriber leaving cancels the
387
835
  // ones still queued instead.
388
836
  await race([Promise.all(groups), unsubscribed]);
389
- // An error of our own (a refused or malformed update, a failed track) ends the
390
- // subscription while the requester may still listen, so its open streams reset
391
- // rather than finish as if complete, and PUBLISH_DONE still follows them. A stream
392
- // error is the requester cancelling, which the shortcut above already covers.
393
- if (publishError && !(publishError instanceof StreamError)) {
394
- track.close(publishError);
395
- await Promise.all([...groups, filling]);
837
+ if (publishError instanceof Paused) {
838
+ track.close();
839
+ await Promise.all(groups);
840
+ return publishError;
396
841
  }
397
- // Draft 14 on has no end location in PUBLISH_DONE: an END_OF_TRACK object is what
398
- // tells the subscriber where the track ended.
399
- const final = track.final();
400
- 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) {
401
858
  await this.#runEndOfTrack({
402
859
  requestId: msg.requestId,
403
- final,
860
+ group: wireEnd.group,
861
+ wireObject: wireEnd.object,
404
862
  publisherPriority,
405
863
  unsubscribed,
406
864
  streams,
@@ -410,144 +868,414 @@ export class Publisher {
410
868
  if (publishError) {
411
869
  console.warn(`publish error: broadcast=${name} track=${track.name} error=${reason(publishError)}`);
412
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
+ }
413
881
  // PUBLISH_DONE is required for every supported draft. The peer may have already
414
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;
415
886
  try {
416
- await reply(async () => {
417
- replied = true;
418
- await stream.writer.u53(PublishDone.id);
419
- const done = new PublishDone({
420
- requestId: version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16
421
- ? msg.requestId
422
- : undefined,
423
- 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
424
893
  ? PublishDoneStatus.UPDATE_FAILED
425
- : publishError
426
- ? PublishDoneStatus.INTERNAL_ERROR
427
- : PublishDoneStatus.TRACK_ENDED,
428
- streamCount: BigInt(streams.opened),
429
- 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
430
905
  ? "update failed"
431
- : publishError
432
- ? "internal error"
433
- : "track ended",
434
- });
435
- await done.encode(stream.writer, version);
906
+ : malformed
907
+ ? "malformed track"
908
+ : publishError
909
+ ? "internal error"
910
+ : "track ended",
436
911
  });
912
+ await Message.write(request.writer, PublishDone.id, done, version);
437
913
  }
438
914
  catch {
439
915
  // Stream might already be closed by peer.
440
916
  }
441
917
  // Our close follows PUBLISH_DONE; it must not cancel data still queued for delivery.
442
918
  finished = true;
443
- stream.close();
919
+ request.close();
444
920
  }
445
921
  catch (err) {
922
+ if (err instanceof ProtocolViolation)
923
+ throw err;
446
924
  const e = error(err);
447
925
  console.warn(`publish error: broadcast=${name} track=${track.name} error=${reason(e)}`);
448
- stream.abort(e);
926
+ request.abort(e);
449
927
  }
450
928
  finally {
929
+ // Groups still draining keep being ranked until they finish.
930
+ ranking?.close();
931
+ datagrams?.close();
932
+ await datagramTask;
451
933
  track.close();
452
934
  // Idempotent, and the backstop for a throw between the fork and the fill starting:
453
935
  // #runFill closes it itself on every path it reaches.
454
936
  cache?.close();
455
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
+ }
456
1000
  }
457
1001
  /**
458
1002
  * Runs a group and sends its frames using ObjectStream (Subgroup delivery mode).
459
1003
  */
460
1004
  async #runGroup(options) {
461
- 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);
462
1025
  try {
463
- // One stream per group is faster than a peer at its limit can retire them, so this
464
- // is the one path that doesn't wait for a slot: the transport would serve the opens
465
- // in the order we asked, which is oldest-first, exactly backwards for live media.
466
- // Failing here drops the group and lets the next one compete for the next slot.
467
- const stream = await Writer.tryOpen(this.#quic, {
468
- cancel: unsubscribed,
469
- version: this.#session.version,
470
- 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;
471
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
+ }
472
1050
  if (!stream) {
473
- group.close(new Error("no stream slot"));
1051
+ hooks.releaseGroupReader(group, failure ?? new Error("unsubscribed while waiting for a stream"));
474
1052
  return;
475
1053
  }
476
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;
477
1060
  const header = new GroupMessage({
478
1061
  trackAlias: requestId,
479
- groupId: group.sequence,
480
- subGroupId: 0,
1062
+ groupId: group.start,
1063
+ subGroupId: 0n,
481
1064
  publisherPriority,
482
1065
  flags: {
483
- // The object properties carry the timestamp, so there is nothing to write
484
- // when the track declared no units to read one in.
485
- hasExtensions: stamped,
1066
+ // A timed track may emit TIMESTAMP_TIE on any frame, so carry extension lengths.
1067
+ hasExtensions: groupGap > 0n || timescale !== undefined,
486
1068
  hasSubgroup: false,
487
1069
  hasSubgroupObject: false,
488
- // A stream capped by the range stops before the group may end, so its FIN
489
- // cannot claim END_OF_GROUP.
490
- 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,
491
1073
  hasPriority: true,
492
1074
  // Only honest when the stream really starts at the group's first object;
493
- // 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.
494
1077
  firstObject: slice.skip === 0,
495
1078
  },
496
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
+ };
497
1110
  try {
498
- await hooks.guardGroup(group, () => header.encode(stream, this.#session.version));
499
- // The first written object goes on the wire as its absolute id, so a trimmed
500
- // head shows the true numbering rather than a silently renumbered group.
501
- let first = true;
502
- // The next object id that could be written, which starts at the filter rather
503
- // than at zero. A backwards range (`startObject` above `endObject` in the same
504
- // group) is empty, and starting here is what lets the check below see that
505
- // 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;
506
1134
  let next = slice.skip;
1135
+ // Whether the group finished, rather than the range or a stop ending the read.
1136
+ let ended = false;
507
1137
  for (;;) {
508
1138
  // The filter ends inside this group: everything at `until` and beyond is
509
1139
  // outside the requested range, so stop without waiting for the group's end.
510
1140
  if (slice.until !== undefined && next >= slice.until)
511
1141
  break;
512
- // Reading from the filter's start drops the objects below it: they are outside
513
- // the requested range, so skipping them is not a gap.
514
- 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;
515
1150
  if (!read)
516
1151
  break;
517
- next = read.sequence + 1;
518
- if (slice.until !== undefined && read.sequence >= slice.until) {
519
- 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)
520
1155
  break;
521
- }
522
- try {
523
- const obj = new Frame({ payload: read.frame.payload, timestamp: read.frame.timestamp });
524
- const delta = first ? read.sequence : 0;
525
- first = false;
526
- await hooks.guardGroup(group, () => obj.encode(stream, header.flags, timescale, this.#session.version, delta));
527
- }
528
- finally {
529
- read.complete();
530
- }
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));
531
1187
  }
532
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;
533
1206
  }
534
1207
  catch (err) {
535
1208
  stream.reset(error(err));
536
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));
537
1219
  }
538
1220
  finally {
1221
+ changed();
1222
+ givenUp.close();
539
1223
  group.close();
540
1224
  }
541
1225
  }
542
1226
  /**
543
- * Mark the track's end with an END_OF_TRACK object on its own stream, at object 0 of the
544
- * group that will never exist.
545
- *
546
- * The last group's stream has usually finished before the track ends, so the marker cannot
547
- * 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`.
548
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. */
549
1277
  async #runEndOfTrack(options) {
550
- const { requestId, final, publisherPriority, unsubscribed, streams } = options;
1278
+ const { requestId, group, wireObject, publisherPriority, unsubscribed, streams } = options;
551
1279
  const version = this.#session.version;
552
1280
  const stream = await Writer.tryOpen(this.#quic, { cancel: unsubscribed, version }).catch(() => undefined);
553
1281
  if (!stream)
@@ -556,8 +1284,8 @@ export class Publisher {
556
1284
  try {
557
1285
  const header = new GroupMessage({
558
1286
  trackAlias: requestId,
559
- groupId: final,
560
- subGroupId: 0,
1287
+ groupId: group,
1288
+ subGroupId: 0n,
561
1289
  publisherPriority,
562
1290
  flags: {
563
1291
  hasExtensions: false,
@@ -565,11 +1293,11 @@ export class Publisher {
565
1293
  hasSubgroupObject: false,
566
1294
  hasEnd: false,
567
1295
  hasPriority: true,
568
- firstObject: true,
1296
+ firstObject: wireObject === 0,
569
1297
  },
570
1298
  });
571
1299
  await header.encode(stream, version);
572
- await new Frame({ endOfTrack: true }).encode(stream, header.flags, Timescale.MILLI, version);
1300
+ await new Frame({ endOfTrack: true }).encode(stream, header.flags, version, wireObject);
573
1301
  stream.close();
574
1302
  }
575
1303
  catch (err) {
@@ -577,15 +1305,14 @@ export class Publisher {
577
1305
  }
578
1306
  }
579
1307
  /**
580
- * Serve a draft-20 fill on its own fetch stream: the requested range, read from the
581
- * group cache, capped at the Largest Object snapshot.
1308
+ * Serve the largest group's head on its own draft-22 fetch stream.
582
1309
  *
583
1310
  * A fill is a promise once requested. An empty range opens no stream, but a range we
584
1311
  * cannot serve still opens one and resets it right after the FETCH_HEADER, the draft's
585
1312
  * fill-failure signal. Nothing here touches the subscription either way.
586
1313
  */
587
1314
  async #runFill(options) {
588
- const { requestId, fill, cache, timescale, stamped, unsubscribed, streams } = options;
1315
+ const { requestId, ranking, fill, cache, publisherPriority, unsubscribed, cancelled, streams, timescale } = options;
589
1316
  const version = this.#session.version;
590
1317
  // Everything is inside the try so the cache fork is released on every path out,
591
1318
  // including a transport failure while opening the stream.
@@ -593,24 +1320,52 @@ export class Publisher {
593
1320
  try {
594
1321
  if (fill.kind === "empty")
595
1322
  return;
596
- 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
+ });
597
1331
  if (!stream) {
598
1332
  console.debug(`fill stream failed to open: fill=${requestId}`);
599
1333
  return;
600
1334
  }
601
1335
  streams.opened += 1;
602
- 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);
603
1339
  if (fill.kind !== "group") {
604
- throw new Error("a fill spanning several groups is not supported");
1340
+ throw new Error("fill is not supported");
605
1341
  }
606
- 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);
607
1349
  try {
608
- 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);
609
1364
  }
610
1365
  finally {
1366
+ given.release();
611
1367
  group.close();
612
1368
  }
613
- stream.close();
614
1369
  console.debug(`fill complete: fill=${requestId}`);
615
1370
  }
616
1371
  catch (err) {
@@ -620,143 +1375,199 @@ export class Publisher {
620
1375
  stream?.reset(e);
621
1376
  }
622
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
+ }
623
1383
  cache.close();
624
1384
  }
625
1385
  }
626
1386
  /**
627
- * Write one cached group's frames as draft-20 fetch objects.
628
- *
629
- * The cap is the Largest Object snapshot: the group may keep growing, but everything
630
- * 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.
631
1389
  */
632
- async #writeFillGroup(stream, group, fill, timescale, stamped, unsubscribed) {
633
- let first = true;
634
- 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);
635
1393
  // The subscriber leaving has to end the fill too. An absolute filter ending below the
636
1394
  // edge with no end object leaves `until` unset, so this reads until the group closes,
637
1395
  // which a still-open past group may never do. Watching only the fetch stream would
638
1396
  // then pin the group and the cache subscription behind it for the life of the track.
639
- let left = false;
640
- const cancelled = unsubscribed.then(() => {
641
- left = true;
642
- return undefined;
643
- });
644
1397
  for (;;) {
645
1398
  // The group may keep growing, but everything at `until` and beyond belongs to the
646
1399
  // subscription, so stop without waiting for the group's end.
647
- if (fill.until !== undefined && next >= fill.until)
1400
+ if (slice.until !== undefined && next >= slice.until)
648
1401
  break;
649
1402
  // Reading from the fill's start drops everything below it; see the same read in #runGroup.
650
- const frame = await race([group.readFrameSequence({ from: Number(fill.skip) }), stream.closed, cancelled]);
651
- if (left)
652
- 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);
653
1404
  if (!frame)
654
1405
  break;
655
- next = BigInt(frame.sequence) + 1n;
656
- 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)
657
1411
  break;
658
- const obj = new FetchFrame({ payload: frame.payload, timestamp: stamped ? frame.timestamp : undefined });
659
- await obj.encode(stream, { group: Number(fill.sequence), object: frame.sequence, first }, timescale, this.#session.version);
660
- first = false;
1412
+ if (oid < slice.skip)
1413
+ continue;
1414
+ await out.object(group.start, frame, cancelled, oid, tie);
661
1415
  }
662
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
+ }
663
1426
  /**
664
1427
  * Handles an incoming SUBSCRIBE_NAMESPACE on a bidi stream.
665
1428
  *
666
- * Draft-16+ fills the stream with every visible match, independently of unsolicited
667
- * discovery. Draft-14/15 use PUBLISH_NAMESPACE requests instead and suppress matches
668
- * 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.
669
1432
  *
670
1433
  * @internal
671
1434
  */
672
- 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;
673
1446
  const version = this.#session.version;
674
- const prefix = msg.namespace;
675
- const legacy = version === Version.DRAFT_14 || version === Version.DRAFT_15;
676
- // Draft-14/15: the open PUBLISH_NAMESPACE request per advertised suffix.
677
- const requests = new Map();
678
- 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();
679
1454
  try {
680
- // Send OK response
681
- if (version === Version.DRAFT_14) {
682
- await stream.writer.u53(SubscribeNamespaceOk.id);
683
- const ok = new SubscribeNamespaceOk({ requestId: msg.requestId });
684
- await ok.encode(stream.writer, version);
685
- }
686
- else {
687
- await stream.writer.u53(RequestOk.id);
688
- const ok = new RequestOk({
689
- requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined,
690
- });
691
- await ok.encode(stream.writer, version);
692
- }
693
- // Only legacy requests create another route; inline entries always fill the query.
694
- // Hidden namespaces still require opt-in unless the prefix names them directly.
695
- const carries = (covered) => (!this.#hidden || msg.hidden || !hiddenBelow(prefix, covered)) &&
696
- (!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);
697
1468
  // Inline entries always land, and the receiver treats a repeated NAMESPACE as a
698
1469
  // replacement, so repricing one is just sending it again, a new original
699
- // publisher included, as Rust does. Only a legacy PUBLISH_NAMESPACE request can
700
- // be declined.
1470
+ // publisher included, as Rust does.
701
1471
  const namespace = async (suffix, snap) => {
702
- await stream.writer.u53(SubscribeNamespaceEntry.id);
703
- const cluster = clusterFor(this.#advert, snap.route);
704
- 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);
705
1476
  return "held";
706
1477
  };
707
- const target = legacy
708
- ? {
709
- advertise: (suffix, snap) => this.#advertise(Path.join(prefix, suffix), requests, clusterFor(this.#advert, snap.route)),
710
- update: (suffix, _snap, reprice) => this.#update(Path.join(prefix, suffix), requests, reprice),
711
- withdraw: (suffix) => this.#withdraw(Path.join(prefix, suffix), requests),
712
- }
713
- : {
714
- advertise: namespace,
715
- update: namespace,
716
- withdraw: async (suffix) => {
717
- await stream.writer.u53(SubscribeNamespaceEntryDone.id);
718
- await new SubscribeNamespaceEntryDone({ suffix }).encode(stream.writer, version);
719
- },
720
- };
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
+ };
721
1488
  // Keyed by suffix, as the entries name them.
722
- 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() };
723
1490
  let retry = 0;
724
1491
  for (;;) {
725
1492
  // Subscribe BEFORE reconciling, for the same reason as
726
1493
  // {@link runPublishNamespaces}: a publish landing while an advertisement
727
1494
  // waits for its reply only notifies listeners already registered.
728
- // TODO Make a better helper within Signals.
729
- let dispose;
730
- const changed = new Promise((resolve) => {
731
- dispose = this.#advertised.changed(resolve);
732
- });
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);
733
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
+ }
734
1509
  if (!advertised) {
735
1510
  dispose();
736
1511
  break;
737
1512
  }
738
- const outstanding = await this.#reconcile(ns, presented(prefix, advertised, carries), target);
1513
+ const outstanding = await this.#reconcile(ns, updated, target);
739
1514
  retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
740
1515
  // Wait for the next change, or for the peer to unsubscribe.
741
1516
  const next = await (retry
742
- ? race([changed, ending, retryAfter(retry).then(() => advertised)])
743
- : 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] : [])]));
744
1525
  dispose();
745
- if (!next)
1526
+ if (!next || next === true)
746
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
+ }
747
1557
  }
748
- stream.close();
1558
+ request.close();
1559
+ await request.writer.closed;
749
1560
  }
750
1561
  catch (err) {
751
1562
  const e = error(err);
752
1563
  console.debug(`subscribe_namespace stream error: ${reason(e)}`);
753
- stream.abort(e);
1564
+ request.abort(e);
1565
+ if (e instanceof ProtocolViolation || this.#withdrawal.closing.peek())
1566
+ throw e;
754
1567
  }
755
1568
  finally {
756
- // This subscription's advertisements die with it.
757
- for (const path of [...requests.keys()]) {
758
- await this.#withdraw(path, requests);
759
- }
1569
+ // Closing stopped the read, which settles it.
1570
+ await updating;
760
1571
  }
761
1572
  }
762
1573
  /**
@@ -765,13 +1576,19 @@ export class Publisher {
765
1576
  *
766
1577
  * The peers that never send SUBSCRIBE_NAMESPACE are exactly the ones expecting a
767
1578
  * publisher to announce itself, so announcing is the default. A peer that would
768
- * rather ask says so in its SETUP (MoQ Solicit) and this does nothing, leaving
769
- * {@link runSubscribeNamespace} to carry the advertisements instead. Modern peers
770
- * 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.
771
1583
  *
772
1584
  * @internal
773
1585
  */
774
- async runPublishNamespaces() {
1586
+ runPublishNamespaces() {
1587
+ return this.#withdrawal.track(this.#runPublishNamespaces());
1588
+ }
1589
+ async #runPublishNamespaces() {
1590
+ if (this.#withdrawal.closing.peek())
1591
+ return;
775
1592
  if (this.#requiresSolicitation) {
776
1593
  // The peer asked to be told on request; runSubscribeNamespace answers it.
777
1594
  return;
@@ -779,9 +1596,11 @@ export class Publisher {
779
1596
  // The open PUBLISH_NAMESPACE request per advertised path.
780
1597
  const requests = new Map();
781
1598
  const target = {
782
- advertise: (path, snap) => this.#advertise(path, requests, clusterFor(this.#advert, snap.route)),
1599
+ advertise: (path, snap) => this.#advertise(path, requests, snap.route),
783
1600
  update: (path, _snap, reprice) => this.#update(path, requests, reprice),
784
1601
  withdraw: (path) => this.#withdraw(path, requests),
1602
+ held: (path) => requests.get(path)?.auth,
1603
+ carry: (auth) => this.#carry(auth),
785
1604
  };
786
1605
  // The origin outlives the session and its signal never ends, so this loop needs the
787
1606
  // session's own ending to stop: without it a closed connection leaves the loop parked
@@ -792,18 +1611,33 @@ export class Publisher {
792
1611
  let dispose;
793
1612
  try {
794
1613
  // Keyed by path.
795
- 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();
796
1618
  let retry = 0;
797
1619
  for (;;) {
798
1620
  // Subscribe BEFORE reconciling. Each advertisement below waits a round trip
799
1621
  // for the peer's reply, and a publish that lands in that window notifies
800
1622
  // only the listeners already registered; one created afterwards would sleep
801
1623
  // through it and leave the namespace unadvertised until something unrelated
802
- // changed.
803
- // TODO Make a better helper within Signals.
804
- const changed = new Promise((resolve) => {
805
- dispose = this.#advertised.changed(resolve);
806
- });
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
+ }
807
1641
  const advertised = this.#advertised.peek();
808
1642
  if (!advertised) {
809
1643
  dispose?.();
@@ -811,19 +1645,28 @@ export class Publisher {
811
1645
  }
812
1646
  const updated = new Map();
813
1647
  for (const [covered, candidates] of advertised) {
814
- // Only peers that declared MoQ Hidden filter unsolicited discovery.
815
- 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))
816
1651
  continue;
817
- 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);
818
1661
  }
819
1662
  const outstanding = await this.#reconcile(ns, updated, target);
820
1663
  retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
821
1664
  // Wait for the next change, which has already fired if one landed above.
822
1665
  const next = await (retry
823
- ? race([changed, closed, retryAfter(retry).then(() => advertised)])
824
- : race([changed, closed]));
1666
+ ? race([change.changed, this.#withdrawal.closing, closed, retryAfter(retry).then(() => advertised)])
1667
+ : race([change.changed, this.#withdrawal.closing, closed]));
825
1668
  dispose?.();
826
- if (!next)
1669
+ if (!next || next === true)
827
1670
  break;
828
1671
  }
829
1672
  }
@@ -831,6 +1674,8 @@ export class Publisher {
831
1674
  // Nothing restarts this loop, so whatever got us here cost the session its
832
1675
  // discovery. Not a debug-level event.
833
1676
  console.warn(`publish_namespace loop failed: ${reason(error(err))}`);
1677
+ if (this.#withdrawal.closing.peek())
1678
+ throw err;
834
1679
  }
835
1680
  finally {
836
1681
  dispose?.();
@@ -845,7 +1690,7 @@ export class Publisher {
845
1690
  * whether anything it should hold is still missing and worth coming back for.
846
1691
  *
847
1692
  * Nothing the peer cannot see is sent, a reprice updates the namespace in place, and
848
- * anything else is withdrawn first so a republish reads as withdraw-then-advertise.
1693
+ * a changed identity is withdrawn before it is advertised again.
849
1694
  * `ns` records what the peer holds rather than what we attempted: a declined
850
1695
  * advertisement or update stays out of it, so the next turn offers it fresh instead
851
1696
  * of believing it is already up.
@@ -858,21 +1703,25 @@ export class Publisher {
858
1703
  // by rebuilding the watched entry.
859
1704
  for (const key of [...ns.refused.keys()]) {
860
1705
  const snap = updated.get(key);
861
- 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)) {
862
1709
  ns.refused.delete(key);
863
1710
  ns.offered.delete(key);
1711
+ ns.reoffer.delete(key);
864
1712
  }
865
1713
  }
866
1714
  const held = new Map(ns.active);
867
1715
  for (const [key, snap] of ns.active) {
868
- if (change(this.#advert, snap, updated.get(key)) !== "restart")
1716
+ const next = updated.get(key);
1717
+ if (this.#change(key, snap, next, target) !== "restart")
869
1718
  continue;
870
1719
  await target.withdraw(key);
871
1720
  held.delete(key);
872
1721
  }
873
1722
  for (const [key, snap] of updated) {
874
1723
  const prev = held.get(key);
875
- const diff = change(this.#advert, prev, snap);
1724
+ const diff = this.#change(key, prev, snap, target);
876
1725
  if (diff === "same")
877
1726
  continue;
878
1727
  let answer;
@@ -890,32 +1739,65 @@ export class Publisher {
890
1739
  held.set(key, snap);
891
1740
  ns.refused.delete(key);
892
1741
  ns.offered.delete(key);
1742
+ // Taken: the next refusal starts its wait over.
1743
+ ns.reoffer.delete(key);
893
1744
  }
894
1745
  else {
895
1746
  held.delete(key);
896
- 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") {
897
1756
  ns.refused.set(key, answer);
898
- ns.offered.set(key, snap.identity);
1757
+ ns.offered.set(key, snap);
899
1758
  }
900
1759
  }
901
1760
  }
902
1761
  ns.active = held;
903
- // Whatever we wanted up and could not get up. Stream credit freeing, a transient
904
- // failure clearing, or the peer starting to answer raises no signal of its own, so
905
- // the only way back is to ask again on a timer.
906
- 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;
907
1788
  }
908
1789
  /**
909
1790
  * Whether a namespace may be offered to the peer right now.
910
1791
  *
911
- * A peer that asked never to be offered it again means it, whatever brought us back;
912
- * 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}).
913
1795
  */
914
1796
  #offerable(key, refused) {
915
1797
  const entry = refused.get(key);
916
1798
  if (entry === undefined)
917
1799
  return true;
918
- return entry !== "never" && Date.now() >= entry;
1800
+ return entry !== "never" && now().ge(entry);
919
1801
  }
920
1802
  /**
921
1803
  * Whether the loop should keep coming back to a namespace the peer does not hold.
@@ -923,72 +1805,78 @@ export class Publisher {
923
1805
  * Distinct from {@link offerable}, and the difference is what arms the retry: a
924
1806
  * namespace waiting out a minimum is not offerable yet but is still pending, and
925
1807
  * gating the timer on offerable instead would disarm it for exactly the wait it is
926
- * 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.
927
1810
  */
928
1811
  #pending(key, refused) {
929
1812
  return refused.get(key) !== "never";
930
1813
  }
931
1814
  /**
932
1815
  * What a REQUEST_ERROR's retry interval, in milliseconds, says about re-offering the
933
- * namespace.
934
- *
935
- * Draft-14/15 carry no such field, so a 0 there says nothing and our own backoff
936
- * 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.
937
1818
  */
938
1819
  #refusal(err) {
939
- const version = this.#session.version;
940
- if (version === Version.DRAFT_14 || version === Version.DRAFT_15)
941
- return "dropped";
942
- 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) };
943
1829
  }
944
1830
  /**
945
1831
  * Advertise one namespace on its own PUBLISH_NAMESPACE request. A declined request
946
1832
  * is logged and skipped: a peer that wants none of this rejects each one and stays
947
1833
  * connected.
948
1834
  */
949
- 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);
950
1838
  const requestId = await this.#session.nextRequestId();
951
1839
  if (requestId === undefined)
952
1840
  return "dropped";
953
1841
  // Opening is inside the try because it fails like any other advertisement does:
954
1842
  // a peer out of stream credit rejects here, and letting that escape would unwind
955
1843
  // the announce loop and take discovery down for the whole session, rather than
956
- // costing this one namespace a turn.
1844
+ // leaving this one namespace unadvertised.
957
1845
  let request;
958
1846
  try {
959
- request = await this.#session.openBi();
960
- const stream = request;
961
- // Bounded, like the subscriber's own request: the loop is single-threaded over
962
- // advertisements, so a peer that takes the stream and answers nothing strands
963
- // every publish and withdrawal behind it. Timing out costs this namespace a
964
- // turn and leaves it outstanding, which the retry above re-offers.
965
- const answer = await withTimeout((async () => {
966
- await stream.writer.u53(PublishNamespace.id);
967
- const msg = new PublishNamespace({ requestId, trackNamespace: path, cluster });
968
- await msg.encode(stream.writer, this.#session.version);
969
- // Read response (RequestOk and PublishNamespaceOk share 0x07)
970
- const respTypeId = await stream.reader.u53();
971
- if (respTypeId === RequestError.id) {
972
- 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);
973
1863
  const why = requestReason(err.errorCode, err.reasonPhrase, "publish_namespace", this.#session.version);
974
1864
  console.warn(`announce refused: broadcast=${path} error=${why}`);
975
- stream.abort(new Error(`PublishNamespace rejected: ${why}`));
1865
+ opened.abort(new Error(`PublishNamespace rejected: ${why}`));
976
1866
  return this.#refusal(err);
977
1867
  }
978
- if (respTypeId !== RequestOk.id) {
979
- 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)}`);
980
1870
  }
981
1871
  // Draft-14 sends PublishNamespaceOk (requestId only, no parameters)
982
- if (this.#session.version === Version.DRAFT_14) {
983
- await PublishNamespaceOk.decode(stream.reader, this.#session.version);
984
- }
985
- else {
986
- await RequestOk.decode(stream.reader, this.#session.version);
987
- }
1872
+ this.#answered(await RequestOk.decode(response.reader, this.#session.version));
988
1873
  return "held";
989
- })(), ADVERTISE_TIMEOUT_MS, `advertisement timed out after ${ADVERTISE_TIMEOUT_MS}ms waiting for the peer's answer`);
990
- if (answer === "held")
991
- 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
+ }
992
1880
  return answer;
993
1881
  }
994
1882
  catch (err) {
@@ -996,9 +1884,45 @@ export class Publisher {
996
1884
  const e = err instanceof TimeoutError ? controlTimeout(err) : error(err);
997
1885
  console.warn(`announce failed: broadcast=${path} error=${reason(e)}`);
998
1886
  request?.abort(e);
999
- return "dropped";
1887
+ return e instanceof StreamError && e.code === StreamCode.ControlTimeout ? "never" : "dropped";
1000
1888
  }
1001
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
+ }
1002
1926
  /**
1003
1927
  * Update a namespace the peer holds: REQUEST_UPDATE on the request that carries it,
1004
1928
  * with only the parameters that changed, then its answer.
@@ -1007,20 +1931,21 @@ export class Publisher {
1007
1931
  * MAX_REQUEST_UPDATES the peer set without reading it; a change landing meanwhile waits
1008
1932
  * for the next turn. The answer decides whether the peer still holds the namespace: a
1009
1933
  * REQUEST_ERROR closes the peer's side and withdraws the advertisement, so ours is
1010
- * finished too, and an unanswered update is dropped abruptly, since a peer that ignored
1011
- * 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.
1012
1936
  *
1013
1937
  * A different original publisher is an update like any other: the receiver drains what
1014
1938
  * it already serves from the old one and never splices the two.
1015
1939
  */
1016
- async #update(path, requests, { from, to }) {
1940
+ async #update(path, requests, { from, to, token: auth }) {
1017
1941
  const request = requests.get(path);
1018
1942
  if (!request)
1019
1943
  return "dropped";
1020
1944
  const update = {
1021
- hops: sameHops(from.hops, to.hops) ? undefined : to.hops,
1022
- 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,
1023
1947
  };
1948
+ const token = auth && this.#auth?.carried(auth);
1024
1949
  const version = this.#session.version;
1025
1950
  let answer;
1026
1951
  try {
@@ -1028,22 +1953,27 @@ export class Publisher {
1028
1953
  if (requestId === undefined)
1029
1954
  throw new Error("no request ID for the update");
1030
1955
  answer = await withTimeout((async () => {
1031
- const { writer, reader } = request.stream;
1032
- await writer.u53(PublishNamespaceUpdate.id);
1033
- await new PublishNamespaceUpdate({ requestId, update }).encode(writer, version);
1034
- const typeId = await reader.u53();
1035
- if (typeId === RequestError.id) {
1036
- 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);
1037
1965
  const why = requestReason(err.errorCode, err.reasonPhrase, "publish_namespace", version);
1038
1966
  console.warn(`publish_namespace update refused: broadcast=${path} error=${why}`);
1039
1967
  return this.#refusal(err);
1040
1968
  }
1041
- if (typeId !== RequestOk.id) {
1042
- 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)}`);
1043
1971
  }
1044
- 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);
1045
1975
  return "held";
1046
- })(), 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`);
1047
1977
  }
1048
1978
  catch (err) {
1049
1979
  const e = err instanceof TimeoutError ? controlTimeout(err) : error(err);
@@ -1052,160 +1982,411 @@ export class Publisher {
1052
1982
  request.stream.abort(e);
1053
1983
  return "dropped";
1054
1984
  }
1055
- // The peer may already have closed out a refused request. Ending it again is the
1056
- // withdrawal finishing, not a reason to end the loop.
1057
- if (answer !== "held")
1058
- 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);
1059
1994
  return answer;
1060
1995
  }
1061
- /**
1062
- * End a namespace's PUBLISH_NAMESPACE request: PUBLISH_NAMESPACE_DONE then FIN before
1063
- * draft-17, a cancel in both directions after. Neither waits on the peer.
1064
- */
1065
1996
  async #withdraw(path, requests) {
1066
1997
  const request = requests.get(path);
1067
1998
  if (!request)
1068
1999
  return;
1069
2000
  requests.delete(path);
1070
- // Draft-17+ withdraws by cancelling the request in both directions; a FIN is only
1071
- // allowed to end SUBSCRIBE_NAMESPACE and SUBSCRIBE_TRACKS.
1072
- const version = this.#session.version;
1073
- if (version !== Version.DRAFT_14 && version !== Version.DRAFT_15 && version !== Version.DRAFT_16) {
1074
- request.stream.abort(new StreamError(StreamCode.Cancel, { message: "withdrawn" }));
1075
- return;
1076
- }
1077
- try {
1078
- await request.stream.writer.u53(PublishNamespaceDone.id);
1079
- const done = new PublishNamespaceDone({ trackNamespace: request.path, requestId: request.requestId });
1080
- await done.encode(request.stream.writer, version);
1081
- }
1082
- catch {
1083
- // Stream might already be closed
1084
- }
1085
- request.stream.close();
2001
+ await this.#end(request);
1086
2002
  }
1087
2003
  /**
1088
- * Handles an incoming TRACK_STATUS_REQUEST on a bidi stream.
1089
- *
1090
- * @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.
1091
2006
  */
1092
- async runTrackStatusRequest(msg, stream) {
1093
- // TRACK_STATUS_ERROR is 0x0f on draft-14.
1094
- 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" }));
1095
2009
  }
1096
2010
  /**
1097
- * Refuses an incoming SUBSCRIBE_TRACKS (draft-18+): we never send the PUBLISH it asks for.
1098
- * 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.
1099
2016
  *
1100
2017
  * @internal
1101
2018
  */
1102
- 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) {
1103
2089
  const version = this.#session.version;
1104
- await stream.writer.u53(RequestError.id);
1105
- await new RequestError({
1106
- errorCode: toRequestCode("not_supported", "subscribe_namespace", version),
1107
- reasonPhrase: "SUBSCRIBE_TRACKS is not supported",
1108
- }).encode(stream.writer, version);
1109
- 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
+ }
1110
2125
  }
1111
2126
  /**
1112
- * Handles an incoming FETCH on a bidi stream. We serve none.
1113
- *
1114
- * @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.
1115
2129
  */
1116
- async runFetch(msg, stream) {
1117
- 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) };
1118
2138
  }
1119
2139
  /**
1120
- * Refuse a request NOT_SUPPORTED. Draft-14 gives each request its own error message,
1121
- * `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.
1122
2142
  */
1123
- async #refuseUnsupported(stream, requestId, kind, errorId14, reasonPhrase) {
1124
- const version = this.#session.version;
1125
- const errorCode = toRequestCode("not_supported", kind, version);
1126
- if (version === Version.DRAFT_14) {
1127
- await stream.writer.u53(errorId14);
1128
- await new SubscribeError({ requestId, errorCode, reasonPhrase }).encode(stream.writer, version);
1129
- }
1130
- else {
1131
- await stream.writer.u53(RequestError.id);
1132
- await new RequestError({
1133
- requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? requestId : undefined,
1134
- errorCode,
1135
- reasonPhrase,
1136
- }).encode(stream.writer, version);
1137
- }
1138
- 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;
1139
2149
  }
1140
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
+ }
1141
2217
  /**
1142
- * Take one group out of a cache view, without waiting.
2218
+ * The Track Properties a SUBSCRIBE_OK, TRACK_STATUS, or FETCH_OK answers with.
1143
2219
  *
1144
- * A fill's group is at or below the Largest Object snapshot, so it is either still in the
1145
- * retained window or gone for good: nothing republishes an old sequence, and waiting for one
1146
- * would park for the life of the track. Scanning past it, or running dry, is a cache miss,
1147
- * which the caller turns into the draft's fill-failure reset.
2220
+ * @internal Exported for tests.
1148
2221
  */
1149
- 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) {
1150
2239
  for (;;) {
1151
- const group = cache.tryRecvGroup();
1152
- if (!group)
1153
- throw new Error(`group not found: ${sequence}`);
1154
- if (group.sequence === sequence)
1155
- return group;
1156
- group.close();
1157
- if (group.sequence > sequence)
1158
- 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
+ });
1159
2257
  }
1160
2258
  }
1161
- /** `a - b`, saturating at zero the way the draft's unsigned arithmetic does. */
1162
- function saturatingSub(a, b) {
1163
- 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)) };
1164
2272
  }
1165
- /** Snapshot the live edge of a track. */
1166
- function liveEdge(track) {
1167
- const latest = track.latest();
1168
- if (latest === undefined)
1169
- return {};
1170
- const largest = track.largest();
1171
- if (!largest)
1172
- return { latest: BigInt(latest), next: { group: BigInt(latest), object: 0n } };
1173
- const group = BigInt(largest.group);
1174
- const object = BigInt(largest.frame);
1175
- 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
+ };
1176
2302
  }
1177
2303
  /**
1178
- * Resolve a SUBSCRIBE's Location Filter into the range to serve.
1179
- *
1180
- * Only draft-20 is honored. Earlier drafts have a Filter Type tag whose absolute forms we
1181
- * never served, and starting to interpret them now would change what an existing peer
1182
- * receives; draft-20 is also the first version whose relative forms can name a past group
1183
- * 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`.
1184
2307
  */
1185
- function subscribeRange(msg, edge, version) {
1186
- if (!Filter.isDraft20(version)) {
1187
- if (msg.filter.kind !== "nextObject" && msg.filter.kind !== "unfiltered") {
1188
- console.warn(`filter not supported before draft-20, ignoring: ${msg.filter.kind}`);
1189
- }
1190
- 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 };
1191
2336
  }
1192
- 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;
1193
2367
  }
1194
2368
  /** The Locations a single Location Filter selects, resolved against the live edge. */
1195
- function filterRange(filter, edge) {
2369
+ function filterRange(filter, edge, version) {
1196
2370
  switch (filter.kind) {
1197
2371
  // No restriction. moq-lite starts at the beginning of the latest group, which is the
1198
2372
  // join point it is built around; a subscription passes objects as they are published,
1199
- // 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.
1200
2375
  case "unfiltered":
1201
2376
  return {};
1202
2377
  // `{Largest.Group, Largest.Object + 1}`. Everything below it, including the already
1203
2378
  // published head of the current group, is outside the requested range, so the join is
1204
- // mid-group by construction. The draft pairs this with a fill when the subscriber
1205
- // 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.
1206
2384
  case "nextObject":
1207
- return { start: edge.next };
1208
- // `{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`).
1209
2390
  // Counted from `Largest.Group`, which sits below the newest group while that group has
1210
2391
  // no objects yet; only with no largest at all does the newest group stand in for it.
1211
2392
  case "relative": {
@@ -1225,13 +2406,32 @@ function filterRange(filter, edge) {
1225
2406
  * Trim a group to the filter's object bounds, so nothing outside the requested range is
1226
2407
  * sent. Interior groups are served whole.
1227
2408
  */
1228
- function groupSlice(range, sequence) {
1229
- const at = BigInt(sequence);
2409
+ function groupSlice(range, key) {
1230
2410
  return {
1231
- skip: range.start?.group === at ? Number(range.start.object) : 0,
1232
- 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,
1233
2413
  };
1234
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
+ }
1235
2435
  /**
1236
2436
  * Resolve a fill request using the Fetch rules: relative to Largest Object and never
1237
2437
  * extending beyond it. An omitted Location Filter inherits the subscription's.
@@ -1274,13 +2474,12 @@ function fillRange(fill, subscription, largest) {
1274
2474
  (start.group === end.group && end.object !== undefined && end.object < start.object)) {
1275
2475
  return { kind: "empty" };
1276
2476
  }
1277
- if (start.group !== end.group)
2477
+ if (start.group !== largest.group || end.group !== largest.group)
1278
2478
  return { kind: "unsupported" };
1279
2479
  return {
1280
2480
  kind: "group",
1281
- sequence: start.group,
1282
- skip: start.object,
1283
- until: end.object === undefined ? undefined : end.object + 1n,
2481
+ start,
2482
+ end,
1284
2483
  };
1285
2484
  }
1286
2485
  class UpdateFailed extends Error {