@moq/net 0.4.8 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (662) hide show
  1. package/README.md +7 -1
  2. package/announce.d.ts +1 -1
  3. package/announce.d.ts.map +1 -1
  4. package/announce.js +1 -1
  5. package/announce.js.map +1 -1
  6. package/announced.d.ts +51 -47
  7. package/announced.d.ts.map +1 -1
  8. package/announced.js +183 -31
  9. package/announced.js.map +1 -1
  10. package/announced.test-util.d.ts +2 -0
  11. package/announced.test-util.d.ts.map +1 -0
  12. package/announced.test-util.js +27 -0
  13. package/announced.test-util.js.map +1 -0
  14. package/auth.d.ts +64 -0
  15. package/auth.d.ts.map +1 -0
  16. package/auth.js +20 -0
  17. package/auth.js.map +1 -0
  18. package/auth_gate.d.ts +2 -0
  19. package/auth_gate.d.ts.map +1 -0
  20. package/auth_gate.js +24 -0
  21. package/auth_gate.js.map +1 -0
  22. package/auth_session.d.ts +49 -0
  23. package/auth_session.d.ts.map +1 -0
  24. package/auth_session.js +1097 -0
  25. package/auth_session.js.map +1 -0
  26. package/bandwidth.d.ts +129 -25
  27. package/bandwidth.d.ts.map +1 -1
  28. package/bandwidth.js +410 -138
  29. package/bandwidth.js.map +1 -1
  30. package/bandwidth_api.d.ts +1 -1
  31. package/bandwidth_api.d.ts.map +1 -1
  32. package/bandwidth_api.js +1 -1
  33. package/bandwidth_api.js.map +1 -1
  34. package/broadcast.d.ts +62 -36
  35. package/broadcast.d.ts.map +1 -1
  36. package/broadcast.js +556 -172
  37. package/broadcast.js.map +1 -1
  38. package/cache.d.ts +103 -0
  39. package/cache.d.ts.map +1 -0
  40. package/cache.js +254 -0
  41. package/cache.js.map +1 -0
  42. package/claim.test-util.d.ts +5 -0
  43. package/claim.test-util.d.ts.map +1 -0
  44. package/claim.test-util.js +13 -0
  45. package/claim.test-util.js.map +1 -0
  46. package/connection/accept.d.ts +20 -12
  47. package/connection/accept.d.ts.map +1 -1
  48. package/connection/accept.js +97 -129
  49. package/connection/accept.js.map +1 -1
  50. package/connection/browser.d.ts.map +1 -1
  51. package/connection/browser.js +28 -19
  52. package/connection/browser.js.map +1 -1
  53. package/connection/connect.d.ts +119 -23
  54. package/connection/connect.d.ts.map +1 -1
  55. package/connection/connect.js +535 -216
  56. package/connection/connect.js.map +1 -1
  57. package/connection/dials.d.ts +45 -0
  58. package/connection/dials.d.ts.map +1 -0
  59. package/connection/dials.js +109 -0
  60. package/connection/dials.js.map +1 -0
  61. package/connection/endpoint.d.ts +60 -0
  62. package/connection/endpoint.d.ts.map +1 -0
  63. package/connection/endpoint.js +114 -0
  64. package/connection/endpoint.js.map +1 -0
  65. package/connection/forward.d.ts +7 -1
  66. package/connection/forward.d.ts.map +1 -1
  67. package/connection/forward.js +265 -80
  68. package/connection/forward.js.map +1 -1
  69. package/connection/goaway.d.ts +16 -9
  70. package/connection/goaway.d.ts.map +1 -1
  71. package/connection/goaway.js +22 -108
  72. package/connection/goaway.js.map +1 -1
  73. package/connection/handshake.d.ts +32 -6
  74. package/connection/handshake.d.ts.map +1 -1
  75. package/connection/handshake.js +97 -20
  76. package/connection/handshake.js.map +1 -1
  77. package/connection/index.d.ts +3 -6
  78. package/connection/index.d.ts.map +1 -1
  79. package/connection/index.js +1 -2
  80. package/connection/index.js.map +1 -1
  81. package/connection/liveness.d.ts +14 -0
  82. package/connection/liveness.d.ts.map +1 -0
  83. package/connection/liveness.js +30 -0
  84. package/connection/liveness.js.map +1 -0
  85. package/connection/pool.d.ts +137 -58
  86. package/connection/pool.d.ts.map +1 -1
  87. package/connection/pool.js +281 -117
  88. package/connection/pool.js.map +1 -1
  89. package/connection/reload.d.ts +60 -12
  90. package/connection/reload.d.ts.map +1 -1
  91. package/connection/reload.js +859 -233
  92. package/connection/reload.js.map +1 -1
  93. package/connection/session.d.ts +91 -0
  94. package/connection/session.d.ts.map +1 -0
  95. package/connection/session.js +2 -0
  96. package/connection/session.js.map +1 -0
  97. package/connection/stats.d.ts +20 -11
  98. package/connection/stats.d.ts.map +1 -1
  99. package/connection/stats.js +64 -8
  100. package/connection/stats.js.map +1 -1
  101. package/connection/ticker.d.ts +4 -0
  102. package/connection/ticker.d.ts.map +1 -0
  103. package/connection/ticker.js +66 -0
  104. package/connection/ticker.js.map +1 -0
  105. package/connection/tokens.d.ts +2 -0
  106. package/connection/tokens.d.ts.map +1 -0
  107. package/connection/tokens.js +404 -0
  108. package/connection/tokens.js.map +1 -0
  109. package/connection/transport.d.ts.map +1 -1
  110. package/connection/transport.js +4 -4
  111. package/connection/transport.js.map +1 -1
  112. package/connection/withdrawal.d.ts +2 -0
  113. package/connection/withdrawal.d.ts.map +1 -0
  114. package/connection/withdrawal.js +23 -0
  115. package/connection/withdrawal.js.map +1 -0
  116. package/consume.js +213 -46
  117. package/consume.js.map +1 -1
  118. package/cover.d.ts +59 -0
  119. package/cover.d.ts.map +1 -0
  120. package/cover.js +375 -0
  121. package/cover.js.map +1 -0
  122. package/datagram.d.ts +70 -11
  123. package/datagram.d.ts.map +1 -1
  124. package/datagram.js +317 -1
  125. package/datagram.js.map +1 -1
  126. package/datagram_stream.d.ts +18 -0
  127. package/datagram_stream.d.ts.map +1 -0
  128. package/datagram_stream.js +67 -0
  129. package/datagram_stream.js.map +1 -0
  130. package/defined.test-util.d.ts +2 -0
  131. package/defined.test-util.d.ts.map +1 -0
  132. package/defined.test-util.js +7 -0
  133. package/defined.test-util.js.map +1 -0
  134. package/delivered.d.ts +75 -0
  135. package/delivered.d.ts.map +1 -0
  136. package/delivered.js +228 -0
  137. package/delivered.js.map +1 -0
  138. package/demand.d.ts +173 -0
  139. package/demand.d.ts.map +1 -0
  140. package/demand.js +582 -0
  141. package/demand.js.map +1 -0
  142. package/drops.d.ts +93 -0
  143. package/drops.d.ts.map +1 -0
  144. package/drops.js +283 -0
  145. package/drops.js.map +1 -0
  146. package/error.d.ts +120 -21
  147. package/error.d.ts.map +1 -1
  148. package/error.js +230 -37
  149. package/error.js.map +1 -1
  150. package/errors.d.ts +2 -2
  151. package/errors.d.ts.map +1 -1
  152. package/errors.js +2 -2
  153. package/errors.js.map +1 -1
  154. package/fill.d.ts +174 -0
  155. package/fill.d.ts.map +1 -0
  156. package/fill.js +760 -0
  157. package/fill.js.map +1 -0
  158. package/flate/decoder.d.ts +2 -0
  159. package/flate/decoder.d.ts.map +1 -0
  160. package/flate/decoder.js +63 -0
  161. package/flate/decoder.js.map +1 -0
  162. package/flate/encoder.d.ts +2 -0
  163. package/flate/encoder.d.ts.map +1 -0
  164. package/flate/encoder.js +64 -0
  165. package/flate/encoder.js.map +1 -0
  166. package/flate/group.d.ts +34 -0
  167. package/flate/group.d.ts.map +1 -0
  168. package/flate/group.js +140 -0
  169. package/flate/group.js.map +1 -0
  170. package/frame.d.ts +80 -0
  171. package/frame.d.ts.map +1 -0
  172. package/frame.js +296 -0
  173. package/frame.js.map +1 -0
  174. package/frame.test-util.d.ts +5 -0
  175. package/frame.test-util.d.ts.map +1 -0
  176. package/frame.test-util.js +9 -0
  177. package/frame.test-util.js.map +1 -0
  178. package/group.d.ts +108 -45
  179. package/group.d.ts.map +1 -1
  180. package/group.js +1616 -307
  181. package/group.js.map +1 -1
  182. package/group_api.d.ts +7 -0
  183. package/group_api.d.ts.map +1 -0
  184. package/group_api.js +7 -0
  185. package/group_api.js.map +1 -0
  186. package/hop.d.ts +62 -76
  187. package/hop.d.ts.map +1 -1
  188. package/hop.js +92 -64
  189. package/hop.js.map +1 -1
  190. package/identity.d.ts +39 -0
  191. package/identity.d.ts.map +1 -0
  192. package/identity.js +47 -0
  193. package/identity.js.map +1 -0
  194. package/ietf/active_count.d.ts +2 -0
  195. package/ietf/active_count.d.ts.map +1 -0
  196. package/ietf/active_count.js +30 -0
  197. package/ietf/active_count.js.map +1 -0
  198. package/ietf/aliases.js +69 -35
  199. package/ietf/aliases.js.map +1 -1
  200. package/ietf/cluster.d.ts +3 -3
  201. package/ietf/cluster.js +14 -62
  202. package/ietf/cluster.js.map +1 -1
  203. package/ietf/connection.d.ts +1 -31
  204. package/ietf/connection.d.ts.map +1 -1
  205. package/ietf/connection.js +305 -143
  206. package/ietf/connection.js.map +1 -1
  207. package/ietf/datagram.d.ts +60 -0
  208. package/ietf/datagram.d.ts.map +1 -0
  209. package/ietf/datagram.js +152 -0
  210. package/ietf/datagram.js.map +1 -0
  211. package/ietf/error.d.ts +3 -3
  212. package/ietf/error.js +82 -100
  213. package/ietf/error.js.map +1 -1
  214. package/ietf/fetch.d.ts +91 -35
  215. package/ietf/fetch.d.ts.map +1 -1
  216. package/ietf/fetch.js +172 -93
  217. package/ietf/fetch.js.map +1 -1
  218. package/ietf/filter.d.ts +20 -30
  219. package/ietf/filter.d.ts.map +1 -1
  220. package/ietf/filter.js +140 -171
  221. package/ietf/filter.js.map +1 -1
  222. package/ietf/goaway.d.ts +11 -9
  223. package/ietf/goaway.d.ts.map +1 -1
  224. package/ietf/goaway.js +22 -35
  225. package/ietf/goaway.js.map +1 -1
  226. package/ietf/hidden.js +1 -1
  227. package/ietf/hidden.js.map +1 -1
  228. package/ietf/index.d.ts +2 -14
  229. package/ietf/index.d.ts.map +1 -1
  230. package/ietf/index.js +4 -14
  231. package/ietf/index.js.map +1 -1
  232. package/ietf/join.d.ts +7 -0
  233. package/ietf/join.d.ts.map +1 -0
  234. package/ietf/join.js +234 -0
  235. package/ietf/join.js.map +1 -0
  236. package/ietf/message.d.ts +18 -2
  237. package/ietf/message.d.ts.map +1 -1
  238. package/ietf/message.js +60 -40
  239. package/ietf/message.js.map +1 -1
  240. package/ietf/message.test-util.d.ts +6 -0
  241. package/ietf/message.test-util.d.ts.map +1 -0
  242. package/ietf/message.test-util.js +13 -0
  243. package/ietf/message.test-util.js.map +1 -0
  244. package/ietf/namespace.d.ts +17 -3
  245. package/ietf/namespace.d.ts.map +1 -1
  246. package/ietf/namespace.js +78 -26
  247. package/ietf/namespace.js.map +1 -1
  248. package/ietf/object.d.ts +194 -32
  249. package/ietf/object.d.ts.map +1 -1
  250. package/ietf/object.js +405 -178
  251. package/ietf/object.js.map +1 -1
  252. package/ietf/parameters.d.ts +22 -42
  253. package/ietf/parameters.d.ts.map +1 -1
  254. package/ietf/parameters.js +260 -472
  255. package/ietf/parameters.js.map +1 -1
  256. package/ietf/priority.d.ts +17 -2
  257. package/ietf/priority.d.ts.map +1 -1
  258. package/ietf/priority.js +19 -4
  259. package/ietf/priority.js.map +1 -1
  260. package/ietf/properties.d.ts +5 -4
  261. package/ietf/properties.d.ts.map +1 -1
  262. package/ietf/properties.js +78 -48
  263. package/ietf/properties.js.map +1 -1
  264. package/ietf/publish.d.ts +22 -30
  265. package/ietf/publish.d.ts.map +1 -1
  266. package/ietf/publish.js +45 -139
  267. package/ietf/publish.js.map +1 -1
  268. package/ietf/publish_namespace.d.ts +46 -69
  269. package/ietf/publish_namespace.d.ts.map +1 -1
  270. package/ietf/publish_namespace.js +66 -184
  271. package/ietf/publish_namespace.js.map +1 -1
  272. package/ietf/publisher.js +1800 -600
  273. package/ietf/publisher.js.map +1 -1
  274. package/ietf/range.d.ts +2 -0
  275. package/ietf/range.d.ts.map +1 -0
  276. package/ietf/range.js +222 -0
  277. package/ietf/range.js.map +1 -0
  278. package/ietf/request.d.ts +3 -27
  279. package/ietf/request.d.ts.map +1 -1
  280. package/ietf/request.js +41 -78
  281. package/ietf/request.js.map +1 -1
  282. package/ietf/request_stream.d.ts +1 -6
  283. package/ietf/request_stream.d.ts.map +1 -1
  284. package/ietf/request_stream.js +306 -16
  285. package/ietf/request_stream.js.map +1 -1
  286. package/ietf/session.d.ts +41 -0
  287. package/ietf/session.d.ts.map +1 -0
  288. package/ietf/session.js +65 -0
  289. package/ietf/session.js.map +1 -0
  290. package/ietf/setup.d.ts +4 -29
  291. package/ietf/setup.d.ts.map +1 -1
  292. package/ietf/setup.js +6 -117
  293. package/ietf/setup.js.map +1 -1
  294. package/ietf/setup_options.d.ts +31 -0
  295. package/ietf/setup_options.d.ts.map +1 -0
  296. package/ietf/setup_options.js +138 -0
  297. package/ietf/setup_options.js.map +1 -0
  298. package/ietf/solicit.js +4 -14
  299. package/ietf/solicit.js.map +1 -1
  300. package/ietf/subscribe.d.ts +48 -41
  301. package/ietf/subscribe.d.ts.map +1 -1
  302. package/ietf/subscribe.js +118 -239
  303. package/ietf/subscribe.js.map +1 -1
  304. package/ietf/subscribe_namespace.d.ts +13 -76
  305. package/ietf/subscribe_namespace.d.ts.map +1 -1
  306. package/ietf/subscribe_namespace.js +30 -201
  307. package/ietf/subscribe_namespace.js.map +1 -1
  308. package/ietf/subscriber.js +1839 -536
  309. package/ietf/subscriber.js.map +1 -1
  310. package/ietf/token.js +105 -27
  311. package/ietf/token.js.map +1 -1
  312. package/ietf/track.d.ts +25 -22
  313. package/ietf/track.d.ts.map +1 -1
  314. package/ietf/track.js +48 -61
  315. package/ietf/track.js.map +1 -1
  316. package/ietf/version.d.ts +13 -42
  317. package/ietf/version.d.ts.map +1 -1
  318. package/ietf/version.js +22 -48
  319. package/ietf/version.js.map +1 -1
  320. package/implementation.d.ts +2 -0
  321. package/implementation.d.ts.map +1 -0
  322. package/implementation.js +5 -0
  323. package/implementation.js.map +1 -0
  324. package/index.d.ts +25 -10
  325. package/index.d.ts.map +1 -1
  326. package/index.js +19 -6
  327. package/index.js.map +1 -1
  328. package/internal.d.ts +1512 -64
  329. package/internal.d.ts.map +1 -1
  330. package/internal.js +557 -79
  331. package/internal.js.map +1 -1
  332. package/ledger.d.ts +23 -0
  333. package/ledger.d.ts.map +1 -0
  334. package/ledger.js +247 -0
  335. package/ledger.js.map +1 -0
  336. package/listing.d.ts +132 -0
  337. package/listing.d.ts.map +1 -0
  338. package/listing.js +486 -0
  339. package/listing.js.map +1 -0
  340. package/lite/announce.d.ts +124 -63
  341. package/lite/announce.d.ts.map +1 -1
  342. package/lite/announce.js +384 -158
  343. package/lite/announce.js.map +1 -1
  344. package/lite/announce_stream.d.ts +2 -0
  345. package/lite/announce_stream.d.ts.map +1 -0
  346. package/lite/announce_stream.js +92 -0
  347. package/lite/announce_stream.js.map +1 -0
  348. package/lite/answer.d.ts +22 -0
  349. package/lite/answer.d.ts.map +1 -0
  350. package/lite/answer.js +301 -0
  351. package/lite/answer.js.map +1 -0
  352. package/lite/auth.d.ts +45 -0
  353. package/lite/auth.d.ts.map +1 -0
  354. package/lite/auth.js +204 -0
  355. package/lite/auth.js.map +1 -0
  356. package/lite/compat.d.ts +31 -0
  357. package/lite/compat.d.ts.map +1 -0
  358. package/lite/compat.js +86 -0
  359. package/lite/compat.js.map +1 -0
  360. package/lite/connection.d.ts +1 -45
  361. package/lite/connection.d.ts.map +1 -1
  362. package/lite/connection.js +360 -77
  363. package/lite/connection.js.map +1 -1
  364. package/lite/datagram-end.d.ts +26 -0
  365. package/lite/datagram-end.d.ts.map +1 -0
  366. package/lite/datagram-end.js +30 -0
  367. package/lite/datagram-end.js.map +1 -0
  368. package/lite/datagram.d.ts +73 -8
  369. package/lite/datagram.d.ts.map +1 -1
  370. package/lite/datagram.js +144 -9
  371. package/lite/datagram.js.map +1 -1
  372. package/lite/duration.d.ts +6 -0
  373. package/lite/duration.d.ts.map +1 -0
  374. package/lite/duration.js +14 -0
  375. package/lite/duration.js.map +1 -0
  376. package/lite/error.d.ts +9 -0
  377. package/lite/error.d.ts.map +1 -0
  378. package/lite/error.js +24 -0
  379. package/lite/error.js.map +1 -0
  380. package/lite/fills.d.ts +162 -0
  381. package/lite/fills.d.ts.map +1 -0
  382. package/lite/fills.js +486 -0
  383. package/lite/fills.js.map +1 -0
  384. package/lite/fit.d.ts +49 -0
  385. package/lite/fit.d.ts.map +1 -0
  386. package/lite/fit.js +305 -0
  387. package/lite/fit.js.map +1 -0
  388. package/lite/goaway.d.ts +1 -1
  389. package/lite/goaway.d.ts.map +1 -1
  390. package/lite/goaway.js +5 -13
  391. package/lite/goaway.js.map +1 -1
  392. package/lite/group.d.ts +64 -13
  393. package/lite/group.d.ts.map +1 -1
  394. package/lite/group.js +108 -30
  395. package/lite/group.js.map +1 -1
  396. package/lite/identity.d.ts +25 -0
  397. package/lite/identity.d.ts.map +1 -0
  398. package/lite/identity.js +79 -0
  399. package/lite/identity.js.map +1 -0
  400. package/lite/index.d.ts +2 -1
  401. package/lite/index.d.ts.map +1 -1
  402. package/lite/index.js +2 -1
  403. package/lite/index.js.map +1 -1
  404. package/lite/message.d.ts +9 -1
  405. package/lite/message.d.ts.map +1 -1
  406. package/lite/message.js +28 -44
  407. package/lite/message.js.map +1 -1
  408. package/lite/priority.d.ts +9 -2
  409. package/lite/priority.d.ts.map +1 -1
  410. package/lite/priority.js +11 -105
  411. package/lite/priority.js.map +1 -1
  412. package/lite/probe.d.ts.map +1 -1
  413. package/lite/probe.js +9 -0
  414. package/lite/probe.js.map +1 -1
  415. package/lite/publisher.d.ts +10 -1
  416. package/lite/publisher.d.ts.map +1 -1
  417. package/lite/publisher.js +2548 -437
  418. package/lite/publisher.js.map +1 -1
  419. package/lite/routed.d.ts +59 -0
  420. package/lite/routed.d.ts.map +1 -0
  421. package/lite/routed.js +564 -0
  422. package/lite/routed.js.map +1 -0
  423. package/lite/session.d.ts +1 -27
  424. package/lite/session.d.ts.map +1 -1
  425. package/lite/session.js +0 -99
  426. package/lite/session.js.map +1 -1
  427. package/lite/setup.d.ts +29 -2
  428. package/lite/setup.d.ts.map +1 -1
  429. package/lite/setup.js +95 -21
  430. package/lite/setup.js.map +1 -1
  431. package/lite/stream.d.ts +5 -11
  432. package/lite/stream.d.ts.map +1 -1
  433. package/lite/stream.js +5 -1
  434. package/lite/stream.js.map +1 -1
  435. package/lite/subscribe.d.ts +475 -75
  436. package/lite/subscribe.d.ts.map +1 -1
  437. package/lite/subscribe.js +1373 -142
  438. package/lite/subscribe.js.map +1 -1
  439. package/lite/subscriber.d.ts +7 -44
  440. package/lite/subscriber.d.ts.map +1 -1
  441. package/lite/subscriber.js +3290 -515
  442. package/lite/subscriber.js.map +1 -1
  443. package/lite/track.d.ts +24 -9
  444. package/lite/track.d.ts.map +1 -1
  445. package/lite/track.js +116 -37
  446. package/lite/track.js.map +1 -1
  447. package/lite/tracks.d.ts +55 -0
  448. package/lite/tracks.d.ts.map +1 -0
  449. package/lite/tracks.js +114 -0
  450. package/lite/tracks.js.map +1 -0
  451. package/lite/version.d.ts +132 -24
  452. package/lite/version.d.ts.map +1 -1
  453. package/lite/version.js +378 -33
  454. package/lite/version.js.map +1 -1
  455. package/meta.d.ts +77 -0
  456. package/meta.d.ts.map +1 -0
  457. package/meta.js +130 -0
  458. package/meta.js.map +1 -0
  459. package/meta_api.d.ts +7 -0
  460. package/meta_api.d.ts.map +1 -0
  461. package/meta_api.js +7 -0
  462. package/meta_api.js.map +1 -0
  463. package/mint.d.ts +28 -0
  464. package/mint.d.ts.map +1 -0
  465. package/mint.js +66 -0
  466. package/mint.js.map +1 -0
  467. package/open.d.ts +63 -0
  468. package/open.d.ts.map +1 -0
  469. package/open.js +250 -0
  470. package/open.js.map +1 -0
  471. package/origin.d.ts +392 -140
  472. package/origin.d.ts.map +1 -1
  473. package/origin.js +2533 -686
  474. package/origin.js.map +1 -1
  475. package/package.json +8 -13
  476. package/path.d.ts +51 -51
  477. package/path.d.ts.map +1 -1
  478. package/path.js +210 -57
  479. package/path.js.map +1 -1
  480. package/payload.d.ts +33 -0
  481. package/payload.d.ts.map +1 -0
  482. package/payload.js +65 -0
  483. package/payload.js.map +1 -0
  484. package/prefix.d.ts +152 -0
  485. package/prefix.d.ts.map +1 -0
  486. package/prefix.js +349 -0
  487. package/prefix.js.map +1 -0
  488. package/priority.d.ts +8 -0
  489. package/priority.d.ts.map +1 -0
  490. package/priority.js +185 -0
  491. package/priority.js.map +1 -0
  492. package/queue.d.ts +2 -0
  493. package/queue.d.ts.map +1 -0
  494. package/queue.js +46 -0
  495. package/queue.js.map +1 -0
  496. package/ranges.d.ts +36 -0
  497. package/ranges.d.ts.map +1 -0
  498. package/ranges.js +312 -0
  499. package/ranges.js.map +1 -0
  500. package/rescale.d.ts +24 -0
  501. package/rescale.d.ts.map +1 -0
  502. package/rescale.js +39 -0
  503. package/rescale.js.map +1 -0
  504. package/resume.d.ts +55 -0
  505. package/resume.d.ts.map +1 -0
  506. package/resume.js +4173 -0
  507. package/resume.js.map +1 -0
  508. package/resume.test-util.d.ts +2 -0
  509. package/resume.test-util.d.ts.map +1 -0
  510. package/resume.test-util.js +25 -0
  511. package/resume.test-util.js.map +1 -0
  512. package/skips.d.ts +48 -0
  513. package/skips.d.ts.map +1 -0
  514. package/skips.js +182 -0
  515. package/skips.js.map +1 -0
  516. package/stream.d.ts +75 -37
  517. package/stream.d.ts.map +1 -1
  518. package/stream.js +236 -92
  519. package/stream.js.map +1 -1
  520. package/subscription.test-util.d.ts +2 -0
  521. package/subscription.test-util.d.ts.map +1 -0
  522. package/subscription.test-util.js +49 -0
  523. package/subscription.test-util.js.map +1 -0
  524. package/tail.d.ts +23 -14
  525. package/tail.d.ts.map +1 -1
  526. package/tail.js +224 -97
  527. package/tail.js.map +1 -1
  528. package/time.d.ts +41 -102
  529. package/time.d.ts.map +1 -1
  530. package/time.js +129 -91
  531. package/time.js.map +1 -1
  532. package/timed.d.ts +21 -0
  533. package/timed.d.ts.map +1 -0
  534. package/timed.js +2 -0
  535. package/timed.js.map +1 -0
  536. package/track.d.ts +577 -245
  537. package/track.d.ts.map +1 -1
  538. package/track.js +7306 -771
  539. package/track.js.map +1 -1
  540. package/track_api.d.ts +7 -0
  541. package/track_api.d.ts.map +1 -0
  542. package/track_api.js +7 -0
  543. package/track_api.js.map +1 -0
  544. package/util/abort.d.ts +1 -0
  545. package/util/abort.d.ts.map +1 -1
  546. package/util/abort.js +23 -1
  547. package/util/abort.js.map +1 -1
  548. package/util/announce.d.ts +4 -0
  549. package/util/announce.d.ts.map +1 -0
  550. package/util/announce.js +11 -0
  551. package/util/announce.js.map +1 -0
  552. package/util/bigint.d.ts +3 -0
  553. package/util/bigint.d.ts.map +1 -0
  554. package/util/bigint.js +8 -0
  555. package/util/bigint.js.map +1 -0
  556. package/util/change.d.ts +12 -0
  557. package/util/change.d.ts.map +1 -0
  558. package/util/change.js +18 -0
  559. package/util/change.js.map +1 -0
  560. package/util/deadline.d.ts +2 -0
  561. package/util/deadline.d.ts.map +1 -0
  562. package/util/deadline.js +108 -0
  563. package/util/deadline.js.map +1 -0
  564. package/util/decode_error.d.ts +3 -0
  565. package/util/decode_error.d.ts.map +1 -0
  566. package/util/decode_error.js +11 -0
  567. package/util/decode_error.js.map +1 -0
  568. package/util/demand.d.ts +8 -0
  569. package/util/demand.d.ts.map +1 -0
  570. package/util/demand.js +24 -0
  571. package/util/demand.js.map +1 -0
  572. package/util/given_up.d.ts +2 -0
  573. package/util/given_up.d.ts.map +1 -0
  574. package/util/given_up.js +101 -0
  575. package/util/given_up.js.map +1 -0
  576. package/util/hex.d.ts +6 -0
  577. package/util/hex.d.ts.map +1 -1
  578. package/util/hex.js +19 -4
  579. package/util/hex.js.map +1 -1
  580. package/util/key.d.ts +15 -0
  581. package/util/key.d.ts.map +1 -0
  582. package/util/key.js +38 -0
  583. package/util/key.js.map +1 -0
  584. package/util/limits.d.ts +2 -0
  585. package/util/limits.d.ts.map +1 -0
  586. package/util/limits.js +76 -0
  587. package/util/limits.js.map +1 -0
  588. package/util/observed.d.ts +23 -0
  589. package/util/observed.d.ts.map +1 -0
  590. package/util/observed.js +122 -0
  591. package/util/observed.js.map +1 -0
  592. package/util/sorted.d.ts +2 -0
  593. package/util/sorted.d.ts.map +1 -0
  594. package/util/sorted.js +149 -0
  595. package/util/sorted.js.map +1 -0
  596. package/util/timeout.d.ts +2 -1
  597. package/util/timeout.d.ts.map +1 -1
  598. package/util/timeout.js +13 -9
  599. package/util/timeout.js.map +1 -1
  600. package/util/timer.d.ts +2 -0
  601. package/util/timer.d.ts.map +1 -0
  602. package/util/timer.js +19 -0
  603. package/util/timer.js.map +1 -0
  604. package/util/utf8.d.ts +2 -0
  605. package/util/utf8.d.ts.map +1 -1
  606. package/util/utf8.js +7 -1
  607. package/util/utf8.js.map +1 -1
  608. package/util/varint.d.ts.map +1 -1
  609. package/util/varint.js +8 -1
  610. package/util/varint.js.map +1 -1
  611. package/util/watch.d.ts +8 -0
  612. package/util/watch.d.ts.map +1 -0
  613. package/util/watch.js +38 -0
  614. package/util/watch.js.map +1 -0
  615. package/util/yield.d.ts +2 -0
  616. package/util/yield.d.ts.map +1 -0
  617. package/util/yield.js +31 -0
  618. package/util/yield.js.map +1 -0
  619. package/varint.d.ts +0 -29
  620. package/varint.d.ts.map +1 -1
  621. package/varint.js +7 -28
  622. package/varint.js.map +1 -1
  623. package/varint_api.d.ts +7 -0
  624. package/varint_api.d.ts.map +1 -0
  625. package/varint_api.js +7 -0
  626. package/varint_api.js.map +1 -0
  627. package/version.d.ts +2 -0
  628. package/version.d.ts.map +1 -0
  629. package/version.js +4 -0
  630. package/version.js.map +1 -0
  631. package/window.d.ts +570 -0
  632. package/window.d.ts.map +1 -0
  633. package/window.js +1677 -0
  634. package/window.js.map +1 -0
  635. package/wire.d.ts +145 -30
  636. package/wire.d.ts.map +1 -1
  637. package/wire.js +27 -0
  638. package/wire.js.map +1 -1
  639. package/connection/established.d.ts +0 -53
  640. package/connection/established.d.ts.map +0 -1
  641. package/connection/established.js +0 -2
  642. package/connection/established.js.map +0 -1
  643. package/ietf/adapter.d.ts +0 -75
  644. package/ietf/adapter.d.ts.map +0 -1
  645. package/ietf/adapter.js +0 -699
  646. package/ietf/adapter.js.map +0 -1
  647. package/lite/datagram_stream.d.ts +0 -8
  648. package/lite/datagram_stream.d.ts.map +0 -1
  649. package/lite/datagram_stream.js +0 -43
  650. package/lite/datagram_stream.js.map +0 -1
  651. package/lite/fetch.d.ts +0 -28
  652. package/lite/fetch.d.ts.map +0 -1
  653. package/lite/fetch.js +0 -78
  654. package/lite/fetch.js.map +0 -1
  655. package/util/log.d.ts +0 -5
  656. package/util/log.d.ts.map +0 -1
  657. package/util/log.js +0 -16
  658. package/util/log.js.map +0 -1
  659. package/zod.d.ts +0 -13
  660. package/zod.d.ts.map +0 -1
  661. package/zod.js +0 -18
  662. package/zod.js.map +0 -1
package/lite/publisher.js CHANGED
@@ -1,55 +1,184 @@
1
- import { race, Signal } from "@moq/signals";
2
- import { error, NotFound, reason, StreamCode, StreamError } from "../error.js";
1
+ import { Duration, now, sleep, yieldNow } 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 { statsOf } from "../connection/stats.js";
6
+ import { Withdrawal } from "../connection/withdrawal.js";
7
+ import { Counts } from "../cover.js";
8
+ import * as DatagramStream from "../datagram_stream.js";
9
+ import { Runs } from "../drops.js";
10
+ import { error, NotFound, ProtocolViolation, reason, StreamCode, StreamError, TimestampMismatch, toStreamCode, unauthorized, } from "../error.js";
3
11
  import { Cost, routesEqual } from "../hop.js";
4
- import { hiddenBelow, hooks, presented } from "../internal.js";
5
- import { Writer } from "../stream.js";
6
- import { Milli, Timescale } from "../time.js";
7
- import { wireOf } from "../wire.js";
12
+ import { datagramTrackInfo, dropHole, finalKey, hiddenBelow, holeOf, hooks, insertRun, NO_MAX_DELAY, presented, runGaps, sameHole, skipHole, staleHole, } from "../internal.js";
13
+ import * as Path from "../path.js";
14
+ import { readSize, sendPayload } from "../payload.js";
15
+ import { Priority, sendOrder } from "../priority.js";
16
+ import { concat, encodeVarint, Writer } from "../stream.js";
17
+ import { floorAt } from "../time.js";
18
+ import { untilAborted } from "../util/abort.js";
19
+ import { nextChange } from "../util/change.js";
20
+ import { GivenUp } from "../util/given_up.js";
21
+ import { max, min } from "../util/key.js";
22
+ import { Budget } from "../util/yield.js";
23
+ import { isEmpty, rangeKey } from "../window.js";
24
+ import { sameIdentity, trackMetaOf, wireOf } from "../wire.js";
8
25
  import { AnnounceInit, AnnounceOk, encodeAnnounceBroadcast } from "./announce.js";
9
- import { Datagram as DatagramMessage } from "./datagram.js";
10
- import * as DatagramStream from "./datagram_stream.js";
26
+ import { AnnounceStream } from "./announce_stream.js";
27
+ import { Answer } from "./answer.js";
28
+ import { Datagram as DatagramMessage, DatagramsInfo, DatagramsUpdate } from "./datagram.js";
29
+ import { DatagramEnd } from "./datagram-end.js";
30
+ import { closeViolation, servedError } from "./error.js";
11
31
  import { Group as GroupMessage } from "./group.js";
12
- import { Priority, sendOrder } from "./priority.js";
13
- import { Probe } from "./probe.js";
14
- import { encodeSubscribeResponse, exclusiveGroupEnd, SubscribeEnd, SubscribeOk, SubscribeStart, SubscribeUpdate, } from "./subscribe.js";
32
+ import { Probe, probeBitrate } from "./probe.js";
33
+ import { ExactRanges, encodeSubscribeResponse, givenUp, groupPolicy, LiveRanges, legacyStart, policyOf, positionFrames, positionStops, rangeBounds, rangesOf, requestedPlaced, requestedRange, requestedRanges, SubscribeDrop, SubscribeEnd, SubscribeOk, SubscribeStart, SubscribeUpdate, spanBetween, subscriptionPolicy, } from "./subscribe.js";
15
34
  import { TrackInfo as TrackInfoMessage } from "./track.js";
16
- import { hasAnnounceId, hasAnnounceOk, hasDatagrams, hasProbeRtt, hasRouteCost, hasStreamCount, resolvesStart, Version, } from "./version.js";
35
+ import { encodeTracksEvent } from "./tracks.js";
36
+ import { hasAnnounceId, hasAnnounceOk, hasCompression, hasDatagrams, hasDatagramTracks, hasGroupEnd, hasLargest, hasLengthFirst, hasProbeRtt, hasRanges, hasReliableReset, hasRouteCost, hasRoutes, hasTrackStream, keepsSubscribeOpen, resolvesStart, Version, waitsForSubscriberFin, wireTimescale, } from "./version.js";
17
37
  const PROBE_INTERVAL = 100; // ms
18
38
  const PROBE_MAX_AGE = 10_000; // ms
19
39
  const PROBE_MAX_DELTA = 0.25;
20
40
  const PROBE_RTT_DELTA = 0.25;
21
- /** Map a signed delta to an unsigned zigzag varint value (mirrors Rust `VarInt::from_zigzag`). */
41
+ const datagramBudget = new Budget();
42
+ // Shared by every subscription's walk of what a lowered start owes before lite-07.
43
+ const replayBudget = new Budget();
44
+ /** Map a signed delta to an unsigned zigzag varint value (mirrors Rust `varint::zigzag`). */
22
45
  function zigzag(delta) {
23
46
  return delta >= 0n ? delta << 1n : (-delta << 1n) - 1n;
24
47
  }
25
- // The TRACK stream, implicit SUBSCRIBE acceptance, and SUBSCRIBE_START/END are
26
- // all lite-05+.
27
- function supportsTrackStream(version) {
28
- switch (version) {
29
- case Version.DRAFT_01:
30
- case Version.DRAFT_02:
31
- case Version.DRAFT_03:
32
- case Version.DRAFT_04:
33
- return false;
34
- default:
35
- return true;
48
+ // The track a SUBSCRIBE reads: a metadata subscription reads the copy kept apart for it where the
49
+ // broadcast keeps one, so no payload crosses a hop for it.
50
+ function subscribed(front, msg) {
51
+ return msg.meta ? trackMetaOf(msg.track, front) : front.track(msg.track);
52
+ }
53
+ /**
54
+ * A frame's fields ahead of its payload, built in memory for one write: a stream write is far
55
+ * costlier than a varint, and a backlog pays it for every frame. The timestamp `delta` is present
56
+ * when the track is stamped, and `inflated` when the frame was decompressed. Lite-07 leads with the
57
+ * size plus one, leaving 0 for GROUP_END, and carries each delta unsigned, since a group's
58
+ * timestamps never decrease, omitting frame 0's (`implicit`): a group starts at its first frame.
59
+ * Before lite-07 every delta is zigzagged and the header ends with the size.
60
+ */
61
+ export function frameHeader(version, delta, inflated, size, lengthFirst, implicit) {
62
+ const parts = [];
63
+ if (lengthFirst)
64
+ parts.push(encodeVarint(size + 1, version));
65
+ if (delta !== undefined) {
66
+ // Lite-07 carries unsigned deltas and places frame 0 at the group's start.
67
+ if (lengthFirst && (delta < 0n || (implicit && delta !== 0n)))
68
+ throw new TimestampMismatch();
69
+ if (!(lengthFirst && implicit))
70
+ parts.push(encodeVarint(lengthFirst ? delta : zigzag(delta), version));
36
71
  }
72
+ if (inflated !== undefined)
73
+ parts.push(encodeVarint(inflated, version));
74
+ if (!lengthFirst)
75
+ parts.push(encodeVarint(size, version));
76
+ return concat(parts);
77
+ }
78
+ /**
79
+ * Lite-07 GROUP_END, after a finished group's last frame: a zero `Payload Length`, where a frame
80
+ * would start, then the group's exclusive `end` as a delta from `base`: the last timestamp the
81
+ * stream carried, or the group's start when it carried none. A finished group's end is at or
82
+ * above both, so an `end` below `base` throws {@link TimestampMismatch}.
83
+ */
84
+ function groupEnd(version, end, base) {
85
+ if (end < base)
86
+ throw new TimestampMismatch();
87
+ return concat([encodeVarint(0, version), encodeVarint(end - base, version)]);
37
88
  }
38
89
  /**
39
- * The frames of `sequence` a subscription asked for, as a start index and an inclusive end.
90
+ * How `version` stamps a track with `info`, or undefined when its frames carry no timestamps:
91
+ * before lite-05, and on a scale-less lite-07 track, whose frame's time is its group's start (its
92
+ * datagrams go out bare). Lite-05/06 declare milliseconds for a scale-less track, whose frames
93
+ * carry 0.
94
+ */
95
+ function stamping(version, info) {
96
+ const wire = wireTimescale(version, info.timescale);
97
+ if (wire === undefined)
98
+ return undefined;
99
+ return { timescale: wire };
100
+ }
101
+ /**
102
+ * A frame or datagram's `timestamp` as its raw wire value. A scale-less track's carries no time: on
103
+ * lite-05/06, which declare it milliseconds, it goes out as 0, since a wide key would overflow a
104
+ * zigzag delta and receivers drop it; a lite-07 datagram's goes out bare. Mirrors the Rust
105
+ * `Stamp::wire`.
106
+ */
107
+ function wireTime(timestamp, stamp) {
108
+ if (timestamp.scale === undefined)
109
+ return stamp.timescale === undefined ? BigInt(timestamp.value) : 0n;
110
+ // A timed timestamp on a track declared scale-less: the model never writes one.
111
+ if (stamp.timescale === undefined)
112
+ throw new TimestampMismatch();
113
+ return BigInt(floorAt(timestamp, stamp.timescale));
114
+ }
115
+ /**
116
+ * Settles once the peer acknowledged everything written before the FIN, or the stream failed.
117
+ * Closing the session sooner would discard bytes still in flight.
118
+ */
119
+ function acknowledged(writer) {
120
+ return writer.closed.catch(() => { });
121
+ }
122
+ /**
123
+ * Lite-07: whether a Group Stream this side just reset still accounts for its group, `held` once
124
+ * a reset delivers its whole header. A reset of this side's delivers the held header, which does.
125
+ * A STOP_SENDING owes a drop only when it evicted the stream before the peer acknowledged the
126
+ * header, since the subscriber may never have read which group it carried; any other the
127
+ * subscriber sent knowing the group, or wanting none of it. Mirrors the Rust `accounts`.
128
+ */
129
+ async function accounts(stream, held) {
130
+ const stop = stream.stopped;
131
+ if (stop === undefined)
132
+ return held;
133
+ return stop !== StreamCode.Evicted || (await stream.heldAcknowledged());
134
+ }
135
+ // The TRACK_INFO a TRACK stream, or a listing's TRACKS_ADD, answers for a track.
136
+ /** A listing event as TRACKS carries it: an added track's info as its kind's request would answer. */
137
+ function tracksEvent(event, version) {
138
+ if (event.kind !== "added")
139
+ return event;
140
+ if (event.type === "datagrams")
141
+ return { kind: "added", name: event.name, type: "datagrams", info: new DatagramsInfo(event.info) };
142
+ return { kind: "added", name: event.name, type: "track", info: trackInfoMessage(event.info, version) };
143
+ }
144
+ function trackInfoMessage(info, version) {
145
+ return new TrackInfoMessage({
146
+ priority: info.priority,
147
+ refresh: info.refresh.ratio ?? undefined,
148
+ refreshInterval: info.refresh.interval?.asMillis(),
149
+ // Publisher Max Age: the publisher's staleness bound, advertised so relays re-serve
150
+ // with the same bound.
151
+ maxAge: info.maxAge?.asMillis(),
152
+ // `#serveGroup` emits each frame converted to it.
153
+ timescale: info.timescale ?? undefined,
154
+ // An older peer is served the frames inflated.
155
+ compress: hasCompression(version) && info.compression === "deflate",
156
+ });
157
+ }
158
+ /** Whether two frame-end tables hold the same stops. */
159
+ function sameStops(a, b) {
160
+ if (a.size !== b.size)
161
+ return false;
162
+ for (const [group, frame] of a)
163
+ if (b.get(group) !== frame)
164
+ return false;
165
+ return true;
166
+ }
167
+ /**
168
+ * The frames of `key` a subscription asked for, as a start index and an inclusive end.
40
169
  *
41
170
  * The frame bounds qualify the start and end group only; every other group is served whole.
42
- * Which groups are served at all is the subscriber's read cursor (`replaceGroups`),
171
+ * Which groups are served at all is the serving subscriber's ranges and floor,
43
172
  * applied when a group is popped rather than re-checked here.
44
173
  *
45
174
  * The serving loop calls this synchronously after the pop, before any SUBSCRIBE_UPDATE can
46
175
  * change `bounds`. Nothing downstream trims the frame range: it is a wire request,
47
176
  * deliberately decoupled from the receiver's local read cursor.
48
177
  */
49
- function frameRange(bounds, sequence) {
178
+ function frameRange(bounds, key) {
50
179
  return {
51
- start: bounds.startGroup === sequence ? bounds.startFrame : 0,
52
- end: bounds.endGroup === sequence ? bounds.endFrame : undefined,
180
+ start: bounds.starts.get(key) ?? (bounds.startGroup === key ? bounds.startFrame : 0),
181
+ end: bounds.endGroup === key ? bounds.endFrame : undefined,
53
182
  };
54
183
  }
55
184
  /**
@@ -67,20 +196,28 @@ function frameRange(bounds, sequence) {
67
196
  */
68
197
  class SubscriptionControls {
69
198
  #writer;
199
+ #live;
200
+ // The latest update the loop has yet to take, with every edit since the last one it took: a
201
+ // range added then retired before then was never live, so it is in neither.
70
202
  #update;
71
203
  // Sticky, first one wins: null once the stream is over, an Error once it failed.
72
204
  #end;
205
+ // Lite-07: the subscriber cleanly FIN'd its send half (no further updates).
206
+ #peerFin = false;
207
+ #finTaken = false;
73
208
  #ended;
74
209
  #resolveEnd;
75
210
  #changed = new Signal(0);
76
211
  /** Settles once decoding stops, so teardown can wait for it rather than leaving it running. */
77
212
  decoding;
78
- constructor({ reader, writer, version, apply }) {
213
+ constructor(options) {
214
+ const { writer, live } = options;
79
215
  this.#writer = writer;
216
+ this.#live = live;
80
217
  this.#ended = new Promise((resolve) => {
81
218
  this.#resolveEnd = resolve;
82
219
  });
83
- this.decoding = this.#decode(reader, version, apply);
220
+ this.decoding = this.#decode(options);
84
221
  // Our own half going away ends the loop too, and has to reach it the same way: the
85
222
  // loop looks at nothing else.
86
223
  void writer.closed.then(() => this.#finish(null), (err) => this.#finish(error(err)));
@@ -91,11 +228,43 @@ class SubscriptionControls {
91
228
  this.#update = undefined;
92
229
  // An update decoded before the stream ended still applies before the sticky end.
93
230
  if (update)
94
- return { kind: "update", update };
231
+ return {
232
+ kind: "update",
233
+ update: update.update,
234
+ applied: { retired: update.retired, added: [...update.added], retuned: [...update.retuned] },
235
+ };
236
+ if (this.#peerFin && !this.#finTaken) {
237
+ this.#finTaken = true;
238
+ return { kind: "fin" };
239
+ }
95
240
  if (this.#end === undefined)
96
241
  return undefined;
97
242
  return this.#end === null ? { kind: "done" } : { kind: "error", error: this.#end };
98
243
  }
244
+ /**
245
+ * Where each live Range ID sits among the track model's ranges, which hold them in Range ID
246
+ * order. The decoder applies each update to the model as it decodes it, ahead of {@link take},
247
+ * so this rather than the last control taken is what indexes the model. Costs every range.
248
+ */
249
+ positions() {
250
+ return new Map(this.#live.ids().map((id, index) => [id, index]));
251
+ }
252
+ /** Whether the track model holds Range ID `id`, as {@link positions} would index it. */
253
+ holds(id) {
254
+ return this.#live.get(id) !== undefined;
255
+ }
256
+ /** The live range with Range ID `id`, as the subscriber asked it. */
257
+ range(id) {
258
+ return this.#live.get(id);
259
+ }
260
+ /** Whether {@link take} has a control to answer with now. */
261
+ pending() {
262
+ return this.#update !== undefined || (this.#peerFin && !this.#finTaken) || this.#end !== undefined;
263
+ }
264
+ /** Whether the subscriber cleanly FIN'd its send half (lite-07). */
265
+ get peerFin() {
266
+ return this.#peerFin;
267
+ }
99
268
  /** Calls `fn` once {@link take} may answer differently. */
100
269
  changed(fn) {
101
270
  return this.#changed.changed(fn);
@@ -129,80 +298,332 @@ class SubscriptionControls {
129
298
  this.#resolveEnd(end);
130
299
  this.#changed.update((value) => value + 1);
131
300
  }
132
- async #decode(reader, version, apply) {
301
+ async #decode({ reader, version, live, apply, quic }) {
133
302
  try {
134
- while (this.#end === undefined) {
303
+ // Runs until the peer's half ends, even past our own FIN: a lite-05+ publisher waits
304
+ // for that end, and every other teardown stops the reader.
305
+ for (;;) {
135
306
  const update = await SubscribeUpdate.decodeMaybe(reader, version);
136
307
  if (!update)
137
308
  break;
138
- apply(update);
139
- this.#update = update;
309
+ // Each lite-07 update edits the live ranges, which only the stream's history names.
310
+ const edit = live.apply(update);
311
+ // Lite-07 carries a priority and order per range, which rank each group by the ranges
312
+ // wanting it (see `groupPolicy`). The subscription's as a whole still ranks a group no range
313
+ // wants, and is what a copy asks upstream.
314
+ if (hasRanges(version))
315
+ Object.assign(update, subscriptionPolicy(live.ranges()));
316
+ apply(update, edit);
317
+ // The latest one replaces any the loop has yet to take, its edit folded in.
318
+ const pending = this.#update ?? {
319
+ update,
320
+ retired: [],
321
+ added: new Map(),
322
+ retuned: new Map(),
323
+ };
324
+ pending.update = update;
325
+ for (const id of edit.retired) {
326
+ pending.retuned.delete(id);
327
+ if (!pending.added.delete(id))
328
+ pending.retired.push(id);
329
+ }
330
+ // A later retune of a range this added is that range added as it now reads, and one
331
+ // of a range this retuned replaces that retune. Mirrors the Rust `Applied::then`.
332
+ for (const [id, range] of edit.retuned) {
333
+ if (pending.added.has(id))
334
+ pending.added.set(id, range);
335
+ else
336
+ pending.retuned.set(id, range);
337
+ }
338
+ for (const [id, range] of edit.added)
339
+ pending.added.set(id, range);
340
+ this.#update = pending;
140
341
  this.#changed.update((value) => value + 1);
141
342
  }
142
343
  }
143
344
  catch (err) {
345
+ closeViolation(quic, err);
144
346
  this.#finish(error(err));
145
347
  return;
146
348
  }
349
+ if (keepsSubscribeOpen(version)) {
350
+ this.#peerFin = true;
351
+ this.#changed.update((value) => value + 1);
352
+ return;
353
+ }
147
354
  this.#finish(null);
148
355
  }
149
356
  }
150
- // A microtask is too short: decoding one framed update crosses several awaits, each of which
151
- // can requeue behind the serving continuation. A task boundary lets the decoder finish whatever
152
- // the transport already delivered before the next group pop. Updates are rare, so groups do not
153
- // pay this scheduling cost on the normal path.
154
- const yieldToControls = () => new Promise((resolve) => setTimeout(resolve, 0));
357
+ /**
358
+ * A subscription's requested ranges by Range ID, as the model holds them, with the bounds the read
359
+ * cursor takes from them counted, so an edit moves them in what it costs. Mirrors the Rust
360
+ * `Requested`.
361
+ */
362
+ class Requested {
363
+ #ranges = new Map();
364
+ // The groups the ranges start at, and how many count back from the latest group instead.
365
+ #starts = new Counts();
366
+ #unnamed = 0;
367
+ // The exclusive groups the ranges end before, and how many have no such end.
368
+ #ends = new Counts();
369
+ #unbounded = 0;
370
+ /** The ranges a SUBSCRIBE carried, by position. */
371
+ constructor(ranges) {
372
+ for (const [id, range] of ranges.entries())
373
+ this.insert(BigInt(id), range);
374
+ }
375
+ get(id) {
376
+ return this.#ranges.get(id);
377
+ }
378
+ /** Every live range. */
379
+ values() {
380
+ return this.#ranges.values();
381
+ }
382
+ /**
383
+ * The narrowest max age in milliseconds a live join among the ranges asks, undefined when none
384
+ * limits it. Mirrors the Rust `Subscription::narrowest`.
385
+ */
386
+ narrowest() {
387
+ let narrowest;
388
+ for (const range of this.#ranges.values()) {
389
+ const max = range.start?.live?.max ?? range.start?.joined?.max;
390
+ if (typeof max === "number" && max < NO_MAX_DELAY)
391
+ narrowest = Math.min(narrowest ?? max, max);
392
+ }
393
+ return narrowest;
394
+ }
395
+ /** Hold `range` as Range ID `id`, replacing any it held. */
396
+ insert(id, range) {
397
+ this.remove(id);
398
+ this.#count(range, true);
399
+ this.#ranges.set(id, range);
400
+ }
401
+ remove(id) {
402
+ const range = this.#ranges.get(id);
403
+ if (range === undefined)
404
+ return;
405
+ this.#count(range, false);
406
+ this.#ranges.delete(id);
407
+ }
408
+ #count(range, add) {
409
+ const [from, to] = rangeBounds(range);
410
+ if (from === undefined)
411
+ this.#unnamed += add ? 1 : -1;
412
+ else if (add)
413
+ this.#starts.add(from);
414
+ else
415
+ this.#starts.remove(from);
416
+ if (to === undefined)
417
+ this.#unbounded += add ? 1 : -1;
418
+ else if (add)
419
+ this.#ends.add(to);
420
+ else
421
+ this.#ends.remove(to);
422
+ }
423
+ /** The lowest group the ranges start at, undefined unless each names its start; see {@link spanOf}. */
424
+ start() {
425
+ return this.#unnamed > 0 ? undefined : this.#starts.first();
426
+ }
427
+ /** The exclusive end past every range, undefined when one has no such end; see {@link spanOf}. */
428
+ end() {
429
+ return this.#unbounded > 0 ? undefined : this.#ends.last();
430
+ }
431
+ }
432
+ /**
433
+ * Lite-07 ranges whose time starts, live joins, or time ends may still resolve, by Range ID, each
434
+ * due once the latest group reaches the lowest start that could resolve it. Mirrors the Rust
435
+ * `Unpinned`.
436
+ */
437
+ class Unpinned {
438
+ #due = new Map();
439
+ #byDue = new Map();
440
+ #dues = new Counts();
441
+ /** Hold range `id` until `due`, or let it go for undefined. */
442
+ insert(id, due) {
443
+ this.remove(id);
444
+ if (due === undefined)
445
+ return;
446
+ this.#due.set(id, due);
447
+ let ids = this.#byDue.get(due);
448
+ if (!ids) {
449
+ ids = new Set();
450
+ this.#byDue.set(due, ids);
451
+ this.#dues.add(due);
452
+ }
453
+ ids.add(id);
454
+ }
455
+ remove(id) {
456
+ const due = this.#due.get(id);
457
+ if (due === undefined)
458
+ return;
459
+ this.#due.delete(id);
460
+ const ids = this.#byDue.get(due);
461
+ ids?.delete(id);
462
+ if (ids?.size === 0) {
463
+ this.#byDue.delete(due);
464
+ this.#dues.remove(due);
465
+ }
466
+ }
467
+ /** The ranges due once the latest group starts at `latest`. */
468
+ due(latest) {
469
+ return this.#dues.through(latest).flatMap((due) => [...(this.#byDue.get(due) ?? [])]);
470
+ }
471
+ }
472
+ /**
473
+ * The lowest latest group start that could resolve `range`'s time start, unless `started`, then
474
+ * its time end. Undefined once neither can move. A live join is never pinned: as a time start its
475
+ * groups would turn from live ones that expire past its max into history, and the model already
476
+ * keeps it placed by its Range ID. Mirrors the Rust `due`.
477
+ */
478
+ function due(range, started) {
479
+ if (range.start?.live !== undefined || range.start?.joined !== undefined || isEmpty(requestedRange(range)))
480
+ return undefined;
481
+ if (!started && range.start !== undefined && range.start.absolute === undefined)
482
+ return 0n;
483
+ if (range.end?.time !== undefined)
484
+ return range.end.time + 1n;
485
+ return undefined;
486
+ }
487
+ // Whether `range` starts partway through its group: a Position start, or a placed join's.
488
+ function framed(range) {
489
+ const start = range.start?.joined ?? range.start;
490
+ return start?.absolute !== undefined && !!start.frame;
491
+ }
492
+ // `entry`, a range this subscription already held, resolved as it was: a range resolves once, so
493
+ // an update that leaves it live never looks a time start up again in newer holdings. A live join
494
+ // stays as asked (see `due`). A start reaching back to the oldest group held stays as it was, since
495
+ // an absolute start would turn it into a floor the subscriber never named.
496
+ function pin(asked, resolved) {
497
+ if (!resolved)
498
+ return asked;
499
+ const range = { ...asked };
500
+ if (resolved.floored && range.start?.absolute === undefined)
501
+ range.start = { absolute: resolved.start };
502
+ // An end resolves once it settles; until then it is reported open.
503
+ if (range.end?.time !== undefined && resolved.end !== undefined)
504
+ range.end = { absolute: resolved.end };
505
+ return range;
506
+ }
507
+ // `current`, a held range, at the policy a retune `asked` for, and a live join at its new max.
508
+ function retunedRange(current, asked) {
509
+ const range = { ...current, priority: asked.priority, order: asked.order };
510
+ // `null` is no limit, so pick the anchor before reading its max.
511
+ const join = asked.start?.live ?? asked.start?.joined;
512
+ if (join === undefined)
513
+ return range;
514
+ if (range.start?.live)
515
+ range.start = { live: { ...range.start.live, max: join.max } };
516
+ else if (range.start?.joined)
517
+ range.start = { joined: { ...range.start.joined, max: join.max } };
518
+ return range;
519
+ }
520
+ function asked(range) {
521
+ const live = range.start?.live !== undefined || range.end === undefined;
522
+ return { joins: range.start?.live !== undefined, live, oldest: range.start === undefined, time: range.start?.time };
523
+ }
524
+ /**
525
+ * What the subscribe stream has said of where delivery starts. Mirrors the Rust `Answer`, with
526
+ * lite-07's per-range answers kept beside it as the ranges still `unstarted`.
527
+ *
528
+ * - `legacy`: lite-03/04 send no SUBSCRIBE_START, and so no drops either.
529
+ * - `waiting`: lite-05/06, whose one START is the first message and names where delivery starts for
530
+ * good, so the `first` servable group and the edge seen before it was popped wait for the source to
531
+ * say where its feed starts. The groups given up meanwhile are named once the start is.
532
+ * - `started`: lite-05/06, delivery starts at `from`.
533
+ * - `unresolved`: lite-07, where delivery starts is not known yet. Groups are served meanwhile, the
534
+ * lowest at `served`, which delivery starts at or below, so a range waiting on its start holds back
535
+ * no other's. The groups given up meanwhile are named once delivery resolves.
536
+ * - `withheld`: lite-07, delivery starts at `from`, but no range is answered yet, as one following an
537
+ * edge this hop does not know leaves it: the drops given up since go out after the first START.
538
+ * - `answered`: lite-07, a range is answered, so drops go out as they are given up.
539
+ */
540
+ /** The narrower of two max ages in milliseconds, undefined being no limit. */
541
+ function narrower(a, b) {
542
+ if (a === undefined)
543
+ return b;
544
+ if (b === undefined)
545
+ return a;
546
+ return Math.min(a, b);
547
+ }
548
+ /** What `version` has said of where delivery starts before anything resolved it. */
549
+ function startAnswer(version) {
550
+ if (!hasTrackStream(version))
551
+ return { kind: "legacy" };
552
+ const skipped = new Runs((a, b) => a.reason === "held-old" || b.reason === "held-old" ? a.reason === b.reason : sameHole(a, b));
553
+ return hasRanges(version) ? { kind: "unresolved", skipped } : { kind: "waiting", skipped };
554
+ }
555
+ /** Where delivery starts once `answer` resolved it. */
556
+ function answerFrom(answer) {
557
+ return answer.kind === "started" || answer.kind === "withheld" || answer.kind === "answered"
558
+ ? answer.from
559
+ : undefined;
560
+ }
561
+ // The later of two locations, either of which may be unknown.
562
+ function newer(a, b) {
563
+ if (!a || !b)
564
+ return a ?? b;
565
+ return b.group > a.group || (b.group === a.group && b.frame > a.frame) ? b : a;
566
+ }
155
567
  // Register both readiness sources in the same turn after the caller observed neither ready.
156
568
  // The winner disposes both registrations, so an idle subscription accumulates nothing no
157
569
  // matter how many times it wakes.
158
- function waitForSubscription(controls, subscriber) {
159
- return new Promise((resolve) => {
160
- let settled = false;
161
- const dispose = [];
570
+ function waitForSubscription(controls, subscriber, drops) {
571
+ return armSubscription(controls, subscriber, drops).woke;
572
+ }
573
+ // `waitForSubscription`, registered now and awaited later, so a change between the two still wakes
574
+ // it. `dispose` drops a registration left unawaited.
575
+ function armSubscription(controls, subscriber, drops) {
576
+ const dispose = [];
577
+ let settled = false;
578
+ const settle = () => {
579
+ if (settled)
580
+ return false;
581
+ settled = true;
582
+ for (const close of dispose)
583
+ close();
584
+ return true;
585
+ };
586
+ const woke = new Promise((resolve) => {
162
587
  const wake = () => {
163
- if (settled)
164
- return;
165
- settled = true;
166
- for (const close of dispose)
167
- close();
168
- resolve();
588
+ if (settle())
589
+ resolve();
169
590
  };
170
591
  dispose.push(controls.changed(wake), hooks.groupChanged(subscriber, wake));
592
+ dispose.push(drops.changed(wake));
171
593
  });
594
+ return { woke, dispose: () => void settle() };
172
595
  }
173
- /**
174
- * The budget to serve a peer with, given what its wire could tell us.
175
- *
176
- * A version without the field decodes as `0`, which is indistinguishable from a peer
177
- * genuinely asking for the live edge. Serving that as real time would discard backlog
178
- * a legacy subscriber never declined, so fall back to a window wide enough not to drop
179
- * and leave enforcement to the receiver, as the IETF path does for the same reason.
180
- */
181
- function servingMaxAge(version, requested) {
182
- return carriesMaxAge(version) ? (requested ?? 0) : Number.MAX_SAFE_INTEGER;
183
- }
184
- /** Whether this version's SUBSCRIBE carries Subscriber Max Age at all. */
185
- function carriesMaxAge(version) {
186
- return version !== Version.DRAFT_01 && version !== Version.DRAFT_02;
596
+ /** Resolves once the subscriber's next control (an update, its FIN, or a failure) arrives. */
597
+ function waitForControl(controls) {
598
+ return new Promise((resolve) => {
599
+ const dispose = controls.changed(() => {
600
+ dispose();
601
+ resolve();
602
+ });
603
+ });
187
604
  }
188
605
  /**
189
- * Position a subscription's read cursor for the wire serving it.
606
+ * The floor of a subscription's read cursor for the wire serving it.
190
607
  *
191
- * On lite-06 there is nothing to do: the cursor is floored at the group the subscription
192
- * named (or 0), and its Max Age decides what above the floor is worth delivering.
608
+ * Lite-07 has none: its ranges name the group containing a time start, which a floor at the time
609
+ * would cut. Before lite-07 a start names the first group starting at or after it, so the floor
610
+ * is the start the subscription named (or 0 on lite-06), and its max delay decides what above the
611
+ * floor is worth delivering. Mirrors the Rust `Frames::floor`.
193
612
  *
194
613
  * Pre-06 wires are the exception: their drafts define an absent `Group Start` as the
195
614
  * latest group, so say so explicitly rather than letting the budget reach back. Lite-03/04/05
196
- * carry a Max Age, but there it is a staleness tolerance only; lite-01/02 additionally get
197
- * an unbounded budget so nothing is dropped under them (see {@link servingMaxAge}), which
615
+ * carry a `Subscriber Max Age`, but there it is a staleness tolerance only; lite-01/02 additionally get
616
+ * an unbounded budget so nothing is dropped under them (they carry no max age, which decodes as none), which
198
617
  * must not read as a request to replay the whole cache on join.
199
618
  */
200
- function positionCursor(track, version, startGroup) {
201
- if (resolvesStart(version) || startGroup !== undefined)
202
- return;
203
- const latest = track.latest();
204
- if (latest !== undefined)
205
- hooks.replaceGroups(track, { start: { included: latest } });
619
+ function cursorFloor(version, startGroup, latest) {
620
+ if (hasRanges(version))
621
+ return 0n;
622
+ if (startGroup !== undefined)
623
+ return startGroup;
624
+ if (resolvesStart(version))
625
+ return 0n;
626
+ return latest ?? 0n;
206
627
  }
207
628
  /**
208
629
  * Handles publishing broadcasts and managing their lifecycle.
@@ -210,6 +631,10 @@ function positionCursor(track, version, startGroup) {
210
631
  * @internal
211
632
  */
212
633
  export class Publisher {
634
+ #withdrawal = new Withdrawal();
635
+ // Served SUBSCRIBE, DATAGRAMS, and TRACK requests, from dispatch until they end, which a
636
+ // draining close waits for.
637
+ #owed = new Set();
213
638
  // The version of the connection.
214
639
  version;
215
640
  // Per-connection origin appended to outbound Announce hops, so the peer
@@ -218,14 +643,23 @@ export class Publisher {
218
643
  // own announcements.
219
644
  hop;
220
645
  #quic;
221
- // The one writer for the outbound datagram stream (getWriter locks it), acquired once at
222
- // construction when this version + transport carry datagrams, released in close(). Its
223
- // presence is the gate: undefined means datagrams aren't served on this connection. All
224
- // subscriptions share it, since a second getWriter on the same stream would throw.
646
+ // Select the transport's current or legacy datagram send API once at setup.
225
647
  #datagramWriter;
226
648
  // Originated advertisements this session forwards.
227
649
  #advertised;
228
650
  #publish;
651
+ // Our grant: only what it lets us publish is announced and served, and a shrink
652
+ // withdraws what it no longer covers. Undefined until the peer answers, and forever on a
653
+ // version without AUTH, which allows everything.
654
+ #grant;
655
+ // Holds every incoming request to that grant from dispatch to its end.
656
+ #gate;
657
+ // Resolves once the tokens this session presented at setup are answered, so nothing is
658
+ // announced before the grant it would be checked against.
659
+ #ready;
660
+ // Lite-07: answers the prefixes the peer asks for, and its loop once the peer asked.
661
+ #answer;
662
+ #answering;
229
663
  // TRACK_INFO is immutable per track, so resolve it from the application once
230
664
  // (via a throwaway subscribe whose info() resolves when the app calls accept)
231
665
  // and reuse it for every later TRACK request of the same track. Keyed by the
@@ -233,22 +667,48 @@ export class Publisher {
233
667
  // republish puts a different one on the path, so its entries must not be reused.
234
668
  // A rejected lookup is evicted so a retry can re-probe.
235
669
  #trackInfo = new WeakMap();
670
+ // Lite-05/06: the datagram tracks this session's answered TRACKs hold, read from each
671
+ // answer on, oldest first. The requester reads TRACK_INFO as the publisher accepting the
672
+ // name, but the datagrams flow on the SUBSCRIBE it sends alongside, which can arrive later.
673
+ // That SUBSCRIBE reads from a clone of the hold, keeping its position, rather than from its
674
+ // own arrival, which would lose what was written in between. The requester keeps its TRACK
675
+ // open until the SUBSCRIBE has a response, so the hold outlasts its arrival. A hold is
676
+ // matched by the track it reads, not by name, so one left on a replaced track never stands
677
+ // in for the current one. It is a passive observer: it keeps a position without adding
678
+ // demand, which the SUBSCRIBE adds when it reads the track.
679
+ #heldDatagrams = new Set();
236
680
  /**
237
681
  * Creates a new Publisher instance.
238
682
  * @param quic - The WebTransport session to use
239
683
  * @param version - Negotiated protocol version
240
684
  * @param origin - Hop id shared with the Subscriber
241
685
  * @param publish - The origin whose broadcasts this session serves; omit to publish nothing
686
+ * @param auth - The union of our tokens' grants, which bounds what we publish, and when the
687
+ * setup tokens are answered
242
688
  *
243
689
  * @internal
244
690
  */
245
- constructor(quic, version, hop, publish) {
691
+ constructor(quic, version, hop, publish, auth) {
246
692
  this.#quic = quic;
693
+ this.#grant = auth?.grant;
694
+ this.#gate = new Gate(auth?.grant);
695
+ this.#ready = auth?.ready ?? Promise.resolve();
247
696
  this.version = version;
248
697
  this.hop = hop;
249
698
  const origin = publish && wireOf(publish);
250
699
  this.#advertised = origin?.advertised ?? new Signal(new Map());
251
700
  this.#publish = publish;
701
+ if (hasRoutes(version)) {
702
+ this.#answer = new Answer({
703
+ version,
704
+ advertised: this.#advertised,
705
+ origin,
706
+ grant: this.#grant,
707
+ ready: this.#ready,
708
+ closing: this.#withdrawal.closing,
709
+ stream: AnnounceStream.of(quic, version),
710
+ });
711
+ }
252
712
  // Grab the datagram writer up front when the transport carries datagrams (no group
253
713
  // fallback, so it stays undefined otherwise). One writer for all subscriptions.
254
714
  if (hasDatagrams(version)) {
@@ -256,36 +716,76 @@ export class Publisher {
256
716
  }
257
717
  }
258
718
  /**
259
- * Handles an announce interest message.
719
+ * Whether the peer's edit continues in its next message, which must be its next ANNOUNCE_REQUEST.
720
+ *
721
+ * @internal
722
+ */
723
+ continuing() {
724
+ return this.#answer?.continuing() ?? false;
725
+ }
726
+ /**
727
+ * Lite-07 ANNOUNCE_REQUEST: the peer edits the prefixes it asks for, answered on this
728
+ * session's Announce Stream. Throws a {@link ProtocolViolation} for an edit the peer may not send.
729
+ *
730
+ * @internal
731
+ */
732
+ request(more, remove, add) {
733
+ if (!this.#answer)
734
+ throw new ProtocolViolation("ANNOUNCE_REQUEST before lite-07");
735
+ const started = this.#answering === undefined;
736
+ const answering = this.#answer.request(more, remove, add);
737
+ if (!started)
738
+ return;
739
+ this.#answering = this.#withdrawal.track(answering);
740
+ // The session is ending under it, or its Announce Stream broke, which closes it: its close
741
+ // says why.
742
+ this.#answering.catch((err) => console.debug("announce stream failed:", err));
743
+ }
744
+ /**
745
+ * Handles a pre-lite-07 announce interest message.
260
746
  * @param msg - The announce interest message
261
747
  * @param stream - The stream to write announcements to
262
748
  *
263
749
  * @internal
264
750
  */
265
- async runAnnounce(msg, stream) {
751
+ runAnnounce(msg, stream) {
752
+ return this.#withdrawal.track(this.#runAnnounce(msg, stream));
753
+ }
754
+ async #runAnnounce(msg, stream) {
755
+ if (this.#withdrawal.closing.peek())
756
+ return;
266
757
  console.debug(`announce: prefix=${msg.prefix}`);
267
- // Keyed by suffix, valued by identity plus route, so a republish diffs as
268
- // ended-then-active and a re-price as a restart.
758
+ // Keyed by suffix, valued by ref plus route, so a republish diffs as a restart
759
+ // and a re-price as an update.
269
760
  let active = new Map();
270
- // Lite06+: announce ids. Every active we send implicitly assigns the next
271
- // per-stream ordinal; ended/restart reference the id instead of repeating the path.
761
+ // Lite06+: announce ids. Every active we send implicitly assigns the next per-stream
762
+ // ordinal; ended/update/restart reference the id instead of repeating the path.
272
763
  let nextAnnounceId = 0n;
273
764
  const announceIds = new Map();
274
765
  const wireHops = (route) => {
275
766
  if (hasAnnounceOk(this.version))
276
- return route.hops;
767
+ return [...route.hops];
277
768
  return [...route.hops, this.hop];
278
769
  };
279
770
  // What the peer decodes for a route: pre-lite-06 wires carry no cost, so a re-price
280
771
  // there must not restart.
281
- const onWire = (route) => (hasRouteCost(this.version) ? route : { ...route, cost: Cost.zero });
772
+ // moq-lite carries no per-request auth, so a swap alone sends nothing.
773
+ // A drain is this node's ranking, never an announcement: the peer hears the route as it is.
774
+ const onWire = (route) => ({
775
+ ...route,
776
+ cost: hasRouteCost(this.version) ? route.cost : Cost.zero,
777
+ auth: undefined,
778
+ draining: undefined,
779
+ });
780
+ // Another identity is another stream, which these versions announce as an end and a start.
781
+ const restarted = (prev, next) => !sameIdentity(prev, next);
282
782
  const announce = async (suffix, route) => {
283
- console.debug(`announce: broadcast=${suffix} active=true`);
783
+ console.debug(`announce: broadcast=${suffix} active=true identity=${route.identity}`);
284
784
  if (hasAnnounceId(this.version))
285
785
  announceIds.set(suffix, nextAnnounceId++);
286
786
  await encodeAnnounceBroadcast(stream.writer, { status: "active", suffix, hops: wireHops(route), cost: route.cost }, this.version);
287
787
  };
288
- const restart = async (suffix, route) => {
788
+ const update = async (suffix, route) => {
289
789
  if (!hasAnnounceId(this.version)) {
290
790
  await retract(suffix);
291
791
  await announce(suffix, route);
@@ -296,8 +796,13 @@ export class Publisher {
296
796
  await announce(suffix, route);
297
797
  return;
298
798
  }
299
- console.debug(`announce: broadcast=${suffix} restart=true`);
300
- await encodeAnnounceBroadcast(stream.writer, { status: "restart", id, hops: wireHops(route), cost: route.cost }, this.version);
799
+ console.debug(`announce: broadcast=${suffix} update=true`);
800
+ await encodeAnnounceBroadcast(stream.writer, { status: "update", id, hops: wireHops(route), cost: route.cost }, this.version);
801
+ };
802
+ // Another identity: an end and a start.
803
+ const restart = async (suffix, route) => {
804
+ await retract(suffix);
805
+ await announce(suffix, route);
301
806
  };
302
807
  // Lite06+ retracts by announce id; older versions repeat the path (ended announces
303
808
  // don't need hops).
@@ -313,22 +818,43 @@ export class Publisher {
313
818
  return; // never announced
314
819
  await encodeAnnounceBroadcast(stream.writer, { status: "endedId", id }, this.version);
315
820
  };
821
+ // A hidden route stays off the wire: only a lite-07 request can opt in.
822
+ const carries = (covered) => !hiddenBelow(msg.prefix, covered);
823
+ // What the peer currently sees: the table under the prefix, less whatever our grant
824
+ // does not let us publish.
825
+ const visible = (table) => {
826
+ const out = presented(msg.prefix, table, carries, { root: this.#publish && wireOf(this.#publish).root });
827
+ const grant = this.#grant?.peek();
828
+ if (grant) {
829
+ for (const suffix of [...out.keys()]) {
830
+ if (!grant.publish.matches(Path.join(msg.prefix, suffix)))
831
+ out.delete(suffix);
832
+ }
833
+ }
834
+ return out;
835
+ };
316
836
  // Subscribe BEFORE writing anything: every encode below awaits the wire, and a publish
317
837
  // landing in that window only notifies the listeners already registered. One created
318
838
  // afterwards would sleep through it, leaving the change unannounced until something
319
- // unrelated moved.
320
- // TODO Make a better helper within Signals.
321
- let dispose;
322
- let changed = new Promise((resolve) => {
323
- dispose = this.#advertised.changed(resolve);
324
- });
325
- // A hidden route stays off the wire unless the request opted in.
326
- const carries = (covered) => msg.hidden || !hiddenBelow(msg.prefix, covered);
839
+ // unrelated moved. A grant change re-diffs the same way, withdrawing what it no longer
840
+ // covers and announcing what it now does.
841
+ const arm = () => nextChange(this.#advertised, this.#grant);
842
+ let { changed, dispose } = arm();
327
843
  try {
844
+ // Nothing is announced before the grant it would be checked against. A local close
845
+ // meanwhile finishes the stream with nothing announced.
846
+ const ready = this.#ready.then(() => "ready");
847
+ if ((await race([ready, stream.reader.closed, this.#withdrawal.closing])) !== "ready") {
848
+ if (this.#withdrawal.closing.peek()) {
849
+ stream.close();
850
+ await stream.writer.closed;
851
+ }
852
+ return;
853
+ }
328
854
  const initial = this.#advertised.peek();
329
855
  if (!initial)
330
856
  return; // closed
331
- for (const [name, snap] of presented(msg.prefix, initial, carries)) {
857
+ for (const [name, snap] of visible(initial)) {
332
858
  active.set(name, snap);
333
859
  }
334
860
  switch (this.version) {
@@ -357,42 +883,52 @@ export class Publisher {
357
883
  }
358
884
  }
359
885
  for (;;) {
360
- const advertised = await race([changed, stream.reader.closed]);
886
+ const woke = await race([changed, stream.reader.closed, this.#withdrawal.closing]);
361
887
  dispose();
362
- if (!advertised)
888
+ if (woke !== "changed")
363
889
  break;
364
890
  // Re-arm before reading, so an advertise that lands while we write is not lost.
365
- changed = new Promise((resolve) => {
366
- dispose = this.#advertised.changed(resolve);
367
- });
891
+ ({ changed, dispose } = arm());
368
892
  const latest = this.#advertised.peek();
369
893
  if (!latest)
370
894
  break;
371
- const updated = new Map();
372
- for (const [name, snap] of presented(msg.prefix, latest, carries)) {
373
- updated.set(name, snap);
374
- }
375
- for (const [suffix, snap] of active) {
376
- const cur = updated.get(suffix);
377
- if (!cur || cur.identity !== snap.identity)
895
+ const updated = visible(latest);
896
+ for (const suffix of active.keys()) {
897
+ if (!updated.has(suffix))
378
898
  await retract(suffix);
379
899
  }
380
900
  for (const [suffix, snap] of updated) {
381
901
  const prev = active.get(suffix);
382
- if (!prev || prev.identity !== snap.identity) {
902
+ if (!prev) {
383
903
  await announce(suffix, snap.route);
384
904
  }
385
- else if (!routesEqual(onWire(prev.route), onWire(snap.route))) {
905
+ else if (restarted(prev, snap)) {
386
906
  await restart(suffix, snap.route);
387
907
  }
908
+ else if (!routesEqual(onWire(prev.route), onWire(snap.route))) {
909
+ await update(suffix, snap.route);
910
+ }
388
911
  }
389
912
  active = updated;
390
913
  }
914
+ if (this.#withdrawal.closing.peek()) {
915
+ for (const suffix of active.keys())
916
+ await retract(suffix);
917
+ stream.close();
918
+ await stream.writer.closed;
919
+ }
391
920
  }
392
921
  finally {
393
922
  dispose();
394
923
  }
395
924
  }
925
+ /** The broadcast a request names, from this session's origin. */
926
+ async #resolve(msg, signal) {
927
+ const origin = this.#publish && wireOf(this.#publish);
928
+ if (!origin)
929
+ return undefined;
930
+ return origin.local(msg.broadcast, msg.identity) ?? (await origin.demand(msg.broadcast, msg.identity, signal));
931
+ }
396
932
  /**
397
933
  * Handles a subscribe message.
398
934
  * @param msg - The subscribe message
@@ -401,57 +937,177 @@ export class Publisher {
401
937
  * @internal
402
938
  */
403
939
  async runSubscribe(msg, stream) {
940
+ // Serve only what our grant lets us publish, and stop once it no longer does. The
941
+ // watch is armed before the first check and held to the end, so a shrink while the
942
+ // broadcast resolves is never missed.
943
+ const revoked = unauthorized(msg.broadcast);
944
+ let serving;
945
+ const watch = this.#gate.watch(msg.broadcast, () => {
946
+ console.debug(`publish revoked: broadcast=${msg.broadcast} track=${msg.track}`);
947
+ serving?.close(revoked);
948
+ stream.abort(revoked);
949
+ });
950
+ try {
951
+ await this.#serveSubscribe(msg, stream, watch, (track) => {
952
+ serving = track;
953
+ });
954
+ }
955
+ finally {
956
+ watch.dispose();
957
+ }
958
+ }
959
+ async #serveSubscribe(msg, stream, watch, serving) {
960
+ // Checked before resolving, so a denied request never reaches the origin.
961
+ if (watch.revoked()) {
962
+ stream.writer.reset(unauthorized(msg.broadcast));
963
+ return;
964
+ }
965
+ // The requester leaving while the broadcast and track resolve ends the request, as
966
+ // Rust polls the requester throughout, so a cancelled subscription gives back its
967
+ // charge instead of holding it until the track is answered, which may be never. A
968
+ // subscriber's close (STOP_SENDING) and its abort (RESET_STREAM) both land here.
969
+ const left = new AbortController();
970
+ const cancel = new StreamError(StreamCode.Cancel, { message: "cancel" });
971
+ const leave = () => left.abort(cancel);
972
+ // On lite-07, clean subscriber FIN means "no further updates; deliver what was requested",
973
+ // so only STOP_SENDING (writer.closed) or RESET_STREAM (reader.closed rejection) cancels.
974
+ if (keepsSubscribeOpen(this.version)) {
975
+ void stream.writer.closed.then(leave, leave);
976
+ void stream.reader.closed.then(undefined, leave);
977
+ }
978
+ else {
979
+ void race([stream.reader.closed, stream.writer.closed]).then(leave, leave);
980
+ }
404
981
  let front;
405
982
  try {
406
- front =
407
- this.#publish &&
408
- (wireOf(this.#publish).local(msg.broadcast) ?? (await wireOf(this.#publish).demand(msg.broadcast)));
983
+ front = await this.#resolve(msg, left.signal);
409
984
  }
410
985
  catch (err) {
411
- stream.writer.reset(error(err));
986
+ stream.writer.reset(servedError(error(err)));
412
987
  return;
413
988
  }
989
+ // Revoked while the broadcast resolved: the watch already reset the stream.
990
+ if (watch.revoked())
991
+ return;
414
992
  if (!front) {
415
993
  console.debug(`publish unknown: broadcast=${msg.broadcast}`);
416
994
  stream.writer.reset(new NotFound(`broadcast ${msg.broadcast}`));
417
995
  return;
418
996
  }
419
- const endGroup = exclusiveGroupEnd(msg.endGroup);
420
- const track = wireOf(front).subscribe(msg.track, {
421
- priority: msg.priority,
422
- maxAge: Milli(servingMaxAge(this.version, msg.maxAge)),
423
- groups: {
424
- start: msg.startGroup === undefined ? undefined : { included: msg.startGroup },
425
- end: endGroup === undefined ? undefined : { excluded: endGroup },
426
- },
427
- });
428
- positionCursor(track, this.version, msg.startGroup);
429
- hooks.replaceGroups(track, { end: endGroup === undefined ? undefined : { excluded: endGroup } });
430
- // The best-effort datagram loop, started once serving begins. It parks when the
431
- // track finishes (recvDatagram returns undefined), so #runTrack alone ends the
432
- // subscription; awaited during teardown so it doesn't outlive the subscription.
997
+ const consumer = subscribed(front, msg);
998
+ // The live joins already placed, which start where they were placed.
999
+ const absent = legacyStart(this.version, msg.maxDelay);
1000
+ const placed = requestedPlaced(msg, absent);
1001
+ const subscription = (ranges) => {
1002
+ const out = { ranges };
1003
+ if (placed.size > 0)
1004
+ out.placed = placed;
1005
+ return out;
1006
+ };
1007
+ let ranges;
1008
+ try {
1009
+ ranges = requestedRanges(msg, absent);
1010
+ }
1011
+ catch (err) {
1012
+ stream.writer.reset(error(err));
1013
+ return;
1014
+ }
1015
+ // Parked past a bounded window's end: the peer reads this stream's end as the track's.
1016
+ const track = hooks.parked(consumer.subscribe(subscription(ranges)));
1017
+ // Lite-07: how each live range counts toward a fetch, as its subscriber asked it: pinning a
1018
+ // time start to the group it resolved to leaves it no fetch.
1019
+ const exact = new ExactRanges(rangesOf(msg));
1020
+ if (hasRanges(this.version))
1021
+ hooks.fetches(track, exact.fetches());
1022
+ serving(track);
1023
+ if (watch.revoked()) {
1024
+ track.close();
1025
+ return;
1026
+ }
1027
+ const latest = hooks.latestKey(track);
1028
+ let floor = cursorFloor(this.version, msg.startGroup, latest);
1029
+ // The ranges cap what is served; the floor only pins where an older wire starts.
1030
+ track.withRange({ start: { included: floor } });
1031
+ // An old subscription carries both kinds until its stream track ends.
433
1032
  let datagrams = Promise.resolve();
1033
+ const bounds = {
1034
+ startGroup: msg.startGroup,
1035
+ startFrame: msg.startFrame,
1036
+ endGroup: msg.endGroup,
1037
+ endFrame: msg.endFrame,
1038
+ starts: hasRanges(this.version) ? positionFrames(msg.ranges ?? []) : new Map(),
1039
+ startsAfter: new WeakMap(),
1040
+ stops: new Signal(hasRanges(this.version) ? positionStops(msg.ranges ?? []) : new Map()),
1041
+ stopsAfter: new WeakMap(),
1042
+ };
1043
+ // A group is served whole from the frame asked: the reader fetches what its copy lacks.
1044
+ hooks.wholeGroups(track, (key) => frameRange(bounds, key).start);
1045
+ let legacy;
1046
+ // The sequences the carried datagrams went out under, which the end declares.
1047
+ const sent = new DatagramEnd();
1048
+ const legacyPriority = new Signal(msg.priority);
434
1049
  let controls;
1050
+ // Lite-05 and later name every key below the end that this subscription never
1051
+ // got with SUBSCRIBE_DROP, so the subscriber settles without waiting out its grace
1052
+ // for a group that will not come. A gap that never arrived stays until the end sweep
1053
+ // names it: this side cannot tell when the subscriber stopped waiting for it.
1054
+ const named = hasTrackStream(this.version);
435
1055
  try {
436
- let timescale = Timescale.MILLI;
437
- if (supportsTrackStream(this.version)) {
1056
+ // Every draft waits for the track's info, as Rust does: it surfaces a rejected track
1057
+ // (accept never called, track closed) as an error here, which resets the stream, and
1058
+ // its priority breaks ties between this session's subscriptions at one subscriber
1059
+ // priority.
1060
+ let info;
1061
+ try {
1062
+ info = await untilAborted(track.info(), left.signal);
1063
+ }
1064
+ catch (err) {
1065
+ if (hasDatagrams(this.version) &&
1066
+ !hasDatagramTracks(this.version) &&
1067
+ toStreamCode(error(err)) === StreamCode.NotFound) {
1068
+ track.close();
1069
+ await this.#serveLegacyDatagrams(front, msg, stream, left.signal);
1070
+ return;
1071
+ }
1072
+ throw err;
1073
+ }
1074
+ const publisher = info.priority;
1075
+ // A SUBSCRIBE can arrive before its track resolves, such as one a relay serves from a
1076
+ // copy still fetching upstream, or on lite-05 one sent alongside its TRACK: the newest
1077
+ // group known once it resolves stands in, including a largest the upstream's answer
1078
+ // reported, whether or not the copy already held a group. A newer group the answer
1079
+ // brings later is not waited for. Lite-01/02 keep their arrival floor, as Rust does.
1080
+ if (this.version !== Version.DRAFT_01 && this.version !== Version.DRAFT_02) {
1081
+ let newest = latest;
1082
+ for (const known of [hooks.latestKey(track), hooks.peekLargest(track).largest?.group]) {
1083
+ if (known !== undefined)
1084
+ newest = newest === undefined ? known : max(newest, known);
1085
+ }
1086
+ const resolved = cursorFloor(this.version, msg.startGroup, newest);
1087
+ if (resolved !== floor) {
1088
+ floor = resolved;
1089
+ track.withRange({ start: { included: floor } });
1090
+ }
1091
+ }
1092
+ // Older drafts carry no timestamps.
1093
+ let stamp;
1094
+ let compress = false;
1095
+ if (hasTrackStream(this.version)) {
438
1096
  // Lite-05+ accepts implicitly: no SUBSCRIBE_OK (the immutable
439
1097
  // properties live in TRACK_INFO), and the resolved range arrives as
440
1098
  // SUBSCRIBE_START / SUBSCRIBE_END emitted from #runTrack.
441
1099
  //
442
1100
  // The timescale is an immutable property, so serving MUST use exactly
443
1101
  // what TRACK_INFO advertised. It comes from the producer's accept(), so
444
- // they always agree. Awaiting info() also surfaces a rejected track
445
- // (accept never called, track closed) as an error here, which resets the
446
- // stream.
447
- const info = await track.info();
448
- timescale = info.timescale;
1102
+ // they always agree.
1103
+ stamp = stamping(this.version, info);
1104
+ compress = hasCompression(this.version) && info.compression === "deflate";
449
1105
  }
450
1106
  else {
451
1107
  // Older drafts acknowledge with SUBSCRIBE_OK and stream frames verbatim.
452
1108
  const ok = new SubscribeOk({
453
1109
  priority: msg.priority,
454
- maxAge: msg.maxAge,
1110
+ maxDelay: msg.maxDelay ?? 0,
455
1111
  startGroup: msg.startGroup,
456
1112
  endGroup: msg.endGroup,
457
1113
  });
@@ -460,158 +1116,868 @@ export class Publisher {
460
1116
  console.debug(`publish ok: broadcast=${msg.broadcast} track=${track.name}`);
461
1117
  // Serve datagrams concurrently with groups whenever the transport carries them
462
1118
  // (the writer exists iff so). No group fallback: otherwise they simply aren't sent.
463
- if (this.#datagramWriter) {
464
- datagrams = this.#runDatagrams(msg.id, track, timescale);
1119
+ if (this.#datagramWriter && !hasDatagramTracks(this.version)) {
1120
+ const live = wireOf(front).liveDatagrams(msg.track);
1121
+ legacy = live && this.#adopt(live);
1122
+ if (legacy) {
1123
+ if (wireOf(front).localDatagrams)
1124
+ legacy.setPriority(msg.priority);
1125
+ datagrams = this.#runDatagrams(legacy, { sub: msg.id, stamp, priority: legacyPriority, sent })
1126
+ .then(() => { })
1127
+ .catch((err) => console.debug(`datagram send stopped: ${reason(err)}`));
1128
+ }
465
1129
  }
1130
+ // The SUBSCRIBE's ranges, whose positions are their Range IDs, which key them in the model.
1131
+ const asked = rangesOf(msg);
1132
+ // The ranges as the model holds them, pinned, by Range ID, with the read cursor's bounds.
1133
+ const requested = new Requested(asked);
1134
+ // Lite-07: the Range IDs of the live ranges that start partway through a group, so an
1135
+ // edit recomputes the frame starts only while one is live.
1136
+ const positions = new Set();
1137
+ for (const [id, range] of asked.entries())
1138
+ if (framed(range))
1139
+ positions.add(BigInt(id));
1140
+ // Lite-07: the Range IDs of the live ranges that end partway through a group, likewise.
1141
+ const stopping = new Set();
1142
+ for (const [id, range] of asked.entries())
1143
+ if (range.end?.absolute !== undefined && range.end.frame)
1144
+ stopping.add(BigInt(id));
1145
+ // Lite-07: the ranges whose starts or time ends may still resolve.
1146
+ const unpinned = new Unpinned();
1147
+ if (hasRanges(this.version))
1148
+ for (const [id, range] of asked.entries())
1149
+ unpinned.insert(BigInt(id), due(range, false));
1150
+ // Each live range due once the latest group reached where it may resolve, with its start and
1151
+ // end replaced by the groups they resolved to: a range resolves once, so an update that
1152
+ // leaves it live never places a live join again against a newer live edge, nor looks a time
1153
+ // start up again in newer holdings, here or on a relay's copies. Only the ranges still
1154
+ // waiting are asked, and each is let go once its anchors settle, so this costs those ranges
1155
+ // rather than every range. Mirrors the Rust `TrackRun::pin`.
1156
+ const pinDue = () => {
1157
+ const latest = hooks.latestKey(track);
1158
+ if (latest === undefined)
1159
+ return [];
1160
+ const pins = [];
1161
+ const asking = [];
1162
+ for (const id of unpinned.due(latest)) {
1163
+ const range = requested.get(id);
1164
+ if (range === undefined)
1165
+ unpinned.remove(id);
1166
+ else
1167
+ asking.push([id, range]);
1168
+ }
1169
+ const resolution = hooks.servingResolvedKeys(track, asking.map(([id]) => id));
1170
+ for (const [index, [id, range]] of asking.entries()) {
1171
+ const resolved = resolution[index];
1172
+ if (!resolved)
1173
+ continue;
1174
+ const pinned = pin(range, resolved);
1175
+ // The start settled; the end is due again once it may settle.
1176
+ unpinned.insert(id, resolved.end === undefined ? due(pinned, true) : undefined);
1177
+ // One pinned to the groups it already names holds the same model range.
1178
+ if (rangeKey(requestedRange(pinned)) === rangeKey(requestedRange(range)))
1179
+ requested.insert(id, pinned);
1180
+ else
1181
+ pins.push([id, pinned]);
1182
+ }
1183
+ return pins;
1184
+ };
466
1185
  controls = new SubscriptionControls({
1186
+ quic: this.#quic,
467
1187
  reader: stream.reader,
468
1188
  writer: stream.writer,
469
1189
  version: this.version,
470
- apply: (update) => {
471
- const end = exclusiveGroupEnd(update.endGroup);
472
- track.update({
473
- priority: update.priority,
474
- maxAge: Milli(servingMaxAge(this.version, update.maxAge)),
475
- groups: {
476
- start: update.startGroup === undefined ? undefined : { included: update.startGroup },
477
- end: end === undefined ? undefined : { excluded: end },
478
- },
1190
+ live: new LiveRanges(this.version, asked),
1191
+ apply: (update, { retired, added, retuned }) => {
1192
+ legacyPriority.set(update.priority);
1193
+ if (wireOf(front).localDatagrams)
1194
+ legacy?.setPriority(update.priority);
1195
+ // Every update restates the wanted group. Past our largest it is a refresh, which
1196
+ // repeats the pending ask; at or below it the group already exists.
1197
+ const largest = hooks.peekLargest(track).largest?.group;
1198
+ if (update.wantedGroup !== undefined && (largest === undefined || update.wantedGroup > largest))
1199
+ hooks.askSubscriber(track, "refresh");
1200
+ if (!hasRanges(this.version)) {
1201
+ // An older update restates its one span, replacing every range: an absent start is
1202
+ // placed afresh within the new max age rather than retuned where the old one joined.
1203
+ const absent = legacyStart(this.version, update.maxDelay);
1204
+ const restated = { ranges: requestedRanges(update, absent) };
1205
+ const placed = requestedPlaced(update, absent);
1206
+ if (placed.size > 0)
1207
+ restated.placed = placed;
1208
+ hooks.restateSubscriber(track, restated);
1209
+ return;
1210
+ }
1211
+ // Lite-07 hands the model the edit by Range ID, so it costs the ranges it names
1212
+ // whatever else is live. A pinned or retuned range is replaced in place, keeping its
1213
+ // Range ID. A retune changes only a range's policy and a live join's max: it keeps the
1214
+ // range as it resolved, pinned in this same edit or before, so a time start is never
1215
+ // looked up again. Mirrors the Rust `TrackRun::edit`.
1216
+ for (const id of retired)
1217
+ unpinned.remove(id);
1218
+ const pinned = new Map(pinDue());
1219
+ const tuned = [];
1220
+ for (const [id, asked] of retuned) {
1221
+ const current = pinned.get(id) ?? requested.get(id);
1222
+ if (current === undefined)
1223
+ continue;
1224
+ pinned.delete(id);
1225
+ tuned.push([id, retunedRange(current, asked)]);
1226
+ }
1227
+ const replaced = [...pinned, ...tuned];
1228
+ for (const id of retired)
1229
+ requested.remove(id);
1230
+ for (const [id, range] of [...replaced, ...added])
1231
+ requested.insert(id, range);
1232
+ for (const [id, range] of added)
1233
+ unpinned.insert(id, due(range, false));
1234
+ for (const id of retired)
1235
+ positions.delete(id);
1236
+ for (const [id, range] of added)
1237
+ if (framed(range))
1238
+ positions.add(id);
1239
+ bounds.startsAfter.set(update, positions.size > 0 ? positionFrames([...requested.values()]) : new Map());
1240
+ for (const id of retired)
1241
+ stopping.delete(id);
1242
+ for (const [id, range] of added)
1243
+ if (range.end?.absolute !== undefined && range.end.frame)
1244
+ stopping.add(id);
1245
+ bounds.stopsAfter.set(update, stopping.size > 0 ? positionStops([...requested.values()]) : new Map());
1246
+ // Refused before the model moves, as one SUBSCRIBE asking for nothing is.
1247
+ Object.assign(update, spanBetween(this.version, requested.start(), requested.end()));
1248
+ const add = [...replaced, ...added].map(([id, range]) => [id, requestedRange(range)]);
1249
+ // A placed join or exact-group Position range stays placed where it was.
1250
+ const placed = new Map();
1251
+ for (const [id, range] of [...replaced, ...added]) {
1252
+ const at = range.start?.joined?.absolute ?? range.start?.absolute;
1253
+ if (at !== undefined)
1254
+ placed.set(id, at);
1255
+ }
1256
+ for (const id of retired)
1257
+ exact.delete(id);
1258
+ for (const [id, range] of added)
1259
+ exact.set(id, range);
1260
+ // An update editing no range leaves a fetch apart from the demand, as the Rust
1261
+ // `Preferences::edit` does.
1262
+ if (retired.length > 0 || add.length > 0)
1263
+ hooks.fetches(track, exact.fetches());
1264
+ hooks.editSubscriber(track, {
1265
+ retire: [...retired, ...replaced.map(([id]) => id)],
1266
+ add,
1267
+ placed,
479
1268
  });
480
1269
  },
481
1270
  });
482
- await this.#runTrack(track, stream.writer, controls, {
1271
+ const finished = await this.#runTrack(track, stream.writer, controls, {
483
1272
  sub: msg.id,
484
1273
  broadcast: msg.broadcast,
485
- timescale,
486
- bounds: {
487
- startGroup: msg.startGroup,
488
- startFrame: msg.startFrame,
489
- endGroup: msg.endGroup,
490
- endFrame: msg.endFrame,
491
- },
1274
+ stamp,
1275
+ publisher,
1276
+ compress,
1277
+ meta: msg.meta,
1278
+ named,
1279
+ floor,
1280
+ maxDelay: msg.maxDelay,
1281
+ bounds,
1282
+ initial: BigInt(asked.length),
1283
+ requested,
1284
+ maxAge: info.maxAge?.asMillis(),
1285
+ carried: legacy && { consumer: legacy, sent },
492
1286
  });
493
1287
  console.debug(`publish done: broadcast=${msg.broadcast} track=${track.name}`);
494
- stream.close();
1288
+ // A lite-05+ subscriber FINs once it has read the tail, so leave its half open and
1289
+ // wait for that: a receiver may drop unread bytes on close. Older versions stop it
1290
+ // here, which ends the decoder.
1291
+ if (waitsForSubscriberFin(this.version))
1292
+ stream.writer.close();
1293
+ else
1294
+ stream.close();
1295
+ // Ends both kinds carried by this old subscription.
495
1296
  track.close();
496
- // Closing the stream ends the decoder and track.close ends the datagram loop.
497
- await Promise.all([datagrams, controls.decoding]);
1297
+ legacy?.close();
1298
+ // A subscriber that left is owed nothing more, and its stream may already be reset.
1299
+ await Promise.all([datagrams, controls.decoding, finished && acknowledged(stream.writer)]);
498
1300
  }
499
1301
  catch (err) {
500
- const e = error(err);
501
- console.warn(`publish error: broadcast=${msg.broadcast} track=${track.name} error=${reason(e)}`);
1302
+ // The served track's error, such as a malformed group upstream, ends only this
1303
+ // subscription: its decoder (`SubscriptionControls`) closes the session for its own input.
1304
+ const e = servedError(error(err));
1305
+ if (e === cancel)
1306
+ console.debug(`publish cancelled: broadcast=${msg.broadcast} track=${track.name}`);
1307
+ else
1308
+ console.warn(`publish error: broadcast=${msg.broadcast} track=${track.name} error=${reason(e)}`);
502
1309
  track.close(e);
1310
+ legacy?.close(e);
503
1311
  stream.abort(e);
504
1312
  await Promise.all([datagrams, controls?.decoding]);
505
1313
  }
506
1314
  }
507
- /**
508
- * Handles a FETCH stream by serving one group as bare frame records (lite-05+).
509
- *
510
- * @internal
511
- */
512
- async runFetch(msg, stream) {
513
- if (!supportsTrackStream(this.version)) {
514
- stream.writer.reset(new Error("fetch requires moq-lite-05 or newer"));
515
- return;
516
- }
517
- let front;
518
- try {
519
- front =
520
- this.#publish &&
521
- (wireOf(this.#publish).local(msg.broadcast) ?? (await wireOf(this.#publish).demand(msg.broadcast)));
522
- }
523
- catch (err) {
524
- stream.writer.reset(error(err));
525
- return;
526
- }
527
- if (!front) {
528
- console.debug(`fetch unknown: broadcast=${msg.broadcast}`);
529
- stream.writer.reset(new NotFound(`broadcast ${msg.broadcast}`));
530
- return;
531
- }
532
- // The subscriber opened this stream, so its send order only ranked the request. Rank the
533
- // response here, on the same scale as the group streams it competes with.
534
- stream.writer.setPriority(sendOrder({ priority: msg.priority }));
535
- let group;
536
- try {
537
- // The timescale is immutable, so serve exactly what TRACK_INFO advertised. Both
538
- // come off the same front, so the metadata and the frames are one generation.
539
- const info = await this.#resolveTrackInfo(front, msg.track);
540
- group = await wireOf(front).fetchGroup(msg.track, msg.group, { priority: msg.priority });
541
- await this.#runFetchGroup(group, stream.writer, {
542
- timescale: Timescale(info.timescale),
543
- start: msg.startFrame,
544
- end: msg.endFrame,
545
- });
546
- console.debug(`fetch done: broadcast=${msg.broadcast} track=${msg.track} group=${msg.group}`);
547
- stream.close();
548
- group.close();
549
- }
550
- catch (err) {
551
- const e = error(err);
552
- console.warn(`fetch error: broadcast=${msg.broadcast} track=${msg.track} group=${msg.group} error=${reason(e)}`);
553
- group?.close(e);
554
- stream.abort(e);
555
- }
556
- }
557
1315
  /**
558
1316
  * Runs a track and sends its data to the stream.
559
1317
  * @param sub - The subscription ID
560
1318
  * @param broadcast - The broadcast name
561
1319
  * @param track - The track to run
562
1320
  * @param stream - The stream to write to
1321
+ * @returns Whether the track finished with every group stream done, rather than the
1322
+ * subscriber leaving
563
1323
  *
564
1324
  * @internal
565
1325
  */
566
1326
  async #runTrack(track, stream, controls, serving) {
567
- const { sub, broadcast, timescale, bounds } = serving;
1327
+ const { sub, broadcast, stamp, publisher, compress, meta, named, bounds, initial, requested } = serving;
1328
+ // What the wire was told of each key: served, or given up, and how. Kept in the
1329
+ // reader's own record, which its drops consult too. Undefined before lite-05.
1330
+ const record = named ? hooks.wire(track) : undefined;
1331
+ // The read cursor's floor; the subscription's ranges cap it.
1332
+ let floor = serving.floor;
1333
+ // Before lite-07: the one max age the subscription last asked, null for none.
1334
+ let maxDelay = serving.maxDelay;
1335
+ const moveCursor = () => track.withRange({ start: { included: floor } });
1336
+ // Raise the floor to `start`, keeping any higher floor already set.
1337
+ const raiseFloor = (start) => {
1338
+ if (start <= floor)
1339
+ return;
1340
+ floor = start;
1341
+ moveCursor();
1342
+ };
568
1343
  // Lite-05+ resolves the range on the subscribe stream: SUBSCRIBE_START once the
569
1344
  // first group is known, SUBSCRIBE_END when the track finishes.
570
- const emitRange = supportsTrackStream(this.version);
571
- let startSent = false;
1345
+ const emitRange = hasTrackStream(this.version);
1346
+ // Dispositions before delivery resolves refine its start; later ones are named as drops. Each
1347
+ // replaces the runs it covers, as a skip may go out over a drop, so they stay sorted and
1348
+ // disjoint. Where delivery resolved is lowered by an update that asks for groups below it.
1349
+ let answer = startAnswer(this.version);
1350
+ // Before lite-07: where delivery first started, once a lowered start owes the drops below it.
1351
+ // Mirrors the Rust `TrackRun::first_start`.
1352
+ let firstStart;
1353
+ // Before lite-07: the keys `nameOwed` has walked, untold or not, contiguous. Mirrors the Rust
1354
+ // `TrackRun::scanned`.
1355
+ let scanned = { start: 0n, end: 0n };
1356
+ // Before lite-07, for a subscription naming no start: where delivery starts, below which no drop
1357
+ // is owed. A budget change places its live join afresh, reaching back to the oldest group held,
1358
+ // so the scan judges the whole history again, or after a change that landed before the
1359
+ // SUBSCRIBE_START, everything the start left untold below it; a relay's front also learns of
1360
+ // history below its copy's feed start from upstream. Those drops stay untold until a start
1361
+ // lowered to them owes them, one per gap and stale group otherwise. Mirrors the Rust
1362
+ // `TrackRun::drop_floor`.
1363
+ const dropFloor = () => answer.kind === "started" && resolvesStart(this.version) && bounds.startGroup === undefined
1364
+ ? answer.from
1365
+ : undefined;
1366
+ // Lower where delivery starts to `start`, once resolved, owing the drops the track holds below
1367
+ // the old start from there up that settle the reader, within the ranges, which the scan left
1368
+ // untold (see `owed`). Mirrors the Rust `TrackRun::lower_from`.
1369
+ const lowerFrom = (start) => {
1370
+ if (answer.kind === "started" && start < answer.from)
1371
+ firstStart ??= answer.from;
1372
+ if (answer.kind === "started" || answer.kind === "withheld" || answer.kind === "answered")
1373
+ answer.from = min(answer.from, start);
1374
+ };
1375
+ // Before lite-07: the keys a lowered start owes the drops of now, which nothing stores: below
1376
+ // where delivery first started, from where it starts now, within the ranges' start and end.
1377
+ // Mirrors the Rust `TrackRun::owed`.
1378
+ const owed = () => {
1379
+ if (!record || firstStart === undefined || answer.kind !== "started")
1380
+ return { start: 0n, end: 0n };
1381
+ const end = bounds.endGroup === undefined ? firstStart : min(firstStart, bounds.endGroup + 1n);
1382
+ return { start: max(answer.from, floor), end };
1383
+ };
1384
+ // The next drop a lowered start owes, told already: its untold runs, or none when the step found
1385
+ // nothing to name; undefined once nothing is owed. Walks `owed` from where it left off, seeking
1386
+ // past what the wire was told through the record, so history told already costs nothing. A walk
1387
+ // below where the last one began starts over there, rejoining it once it reaches it. Mirrors the
1388
+ // Rust `TrackRun::name_owed`.
1389
+ const nameOwed = () => {
1390
+ const window = owed();
1391
+ if (!record || window.start >= window.end)
1392
+ return undefined;
1393
+ const resumed = scanned.start <= window.start && window.start <= scanned.end;
1394
+ const from = resumed ? scanned.end : window.start;
1395
+ const gap = from < window.end ? record.firstUntold(from, window.end) : undefined;
1396
+ const run = gap && hooks.nextSettledDrop(track, gap.start, gap.end);
1397
+ // A front whose serving route has yet to answer knows no verdict there yet: the walk waits
1398
+ // on it rather than passing the gap by.
1399
+ if (run === "pending")
1400
+ return undefined;
1401
+ // Nothing untold is left, so no step goes here until the window moves.
1402
+ const walked = !gap
1403
+ ? max(window.end, from)
1404
+ : !run
1405
+ ? gap.end
1406
+ : run.reason === "skip"
1407
+ ? run.end
1408
+ : reach(run.end);
1409
+ const start = resumed ? scanned.start : window.start;
1410
+ const rejoined = start <= scanned.start && scanned.start <= walked;
1411
+ scanned = { start, end: rejoined ? max(walked, scanned.end) : walked };
1412
+ if (!gap)
1413
+ return undefined;
1414
+ if (!run)
1415
+ return [];
1416
+ const gaps = record.untold(run.start, walked);
1417
+ for (const told of gaps)
1418
+ record.tell(told.start, told.end);
1419
+ return gaps.map((told) => ({ ...run, ...told }));
1420
+ };
1421
+ // What this hop knows of the largest position, `position` the newest it saw: nothing on a
1422
+ // relay's copy its upstream has yet to answer, whatever its cache holds. Mirrors the Rust
1423
+ // `TrackRun::largest`.
1424
+ const edge = (position) => {
1425
+ if (!hooks.knowsEdge(track))
1426
+ return "unknown";
1427
+ return position ? { position, ended: hooks.largestFinished(track, position) } : "empty";
1428
+ };
1429
+ const newest = () => newer(hooks.bufferedLargest(track), hooks.peekLargest(track).largest);
572
1430
  let endSent = false;
573
- // Lite-07+ counts the group streams in SUBSCRIBE_END, so it goes out only once every
574
- // served group has opened its stream or given up, and a cap holding groups back
575
- // delays it until they are released.
576
- const countStreams = hasStreamCount(this.version);
577
- let streams = 0;
578
- const opening = new Set();
1431
+ // Lite-07: the ranges no SUBSCRIBE_START answered yet, by Range ID, each as it was asked.
1432
+ const unstarted = new Map();
1433
+ if (hasRanges(this.version)) {
1434
+ for (let id = 0n; id < initial; id++) {
1435
+ const range = controls.range(id);
1436
+ if (range)
1437
+ unstarted.set(id, asked(range));
1438
+ }
1439
+ }
1440
+ // Lite-07: the narrowest Max Age as each outcome was given up before the first START. A held
1441
+ // OLD keeps it even once queued behind the START write; any other unjudged OLD is capped by it
1442
+ // only until the held drops go out (`pendingNarrowest`), as the Rust `Ranges::held_narrowest`.
1443
+ let heldNarrowest;
1444
+ let pendingNarrowest;
1445
+ const holdMaxAge = (maxAge) => {
1446
+ heldNarrowest = narrower(heldNarrowest, maxAge);
1447
+ pendingNarrowest = narrower(pendingNarrowest, maxAge);
1448
+ };
1449
+ // Use the budget when the outcome is accepted (`asked`, if captured earlier), before a control
1450
+ // update can retune it. Every outcome held before the first START contributes to its shared minimum.
1451
+ const snapshotHole = (hole, asked) => {
1452
+ if (!hasRanges(this.version))
1453
+ return hole;
1454
+ const held = answer.kind === "unresolved" || answer.kind === "withheld";
1455
+ const unjudged = hole.reason === "old" && hole.maxAge === undefined;
1456
+ if (!held && !unjudged)
1457
+ return hole;
1458
+ const maxAge = asked ? asked.maxAge : requested.narrowest();
1459
+ if (held)
1460
+ holdMaxAge(maxAge);
1461
+ if (!unjudged)
1462
+ return hole;
1463
+ if (maxAge === undefined)
1464
+ return dropHole();
1465
+ return held ? { reason: "held-old" } : staleHole(maxAge);
1466
+ };
1467
+ // Hold `[start, end)` given up before delivery resolved, which the start names. Mirrors the Rust
1468
+ // `TrackRun::hold_hole`.
1469
+ const holdSkipped = (skipped, start, end, run) => {
1470
+ if (hasRanges(this.version))
1471
+ holdMaxAge(requested.narrowest());
1472
+ skipped.set(start, end, run);
1473
+ };
1474
+ // Send a range's SUBSCRIBE_START, then whatever was withheld for the first one.
1475
+ const sendStart = async (start) => {
1476
+ if (!(await controls.response(encodeSubscribeResponse(stream, { start }, this.version))))
1477
+ return false;
1478
+ if (answer.kind !== "withheld")
1479
+ return true;
1480
+ const { from, held } = answer;
1481
+ answer = { kind: "answered", from };
1482
+ // Empty while delivery resolves, whose own held drops go out after its starts.
1483
+ if (held.length === 0)
1484
+ return true;
1485
+ for (const [low, high, hole] of held) {
1486
+ const msg = holeMessage(low, high, hole);
1487
+ if (!(await controls.response(encodeSubscribeResponse(stream, msg, this.version))))
1488
+ return false;
1489
+ }
1490
+ pendingNarrowest = undefined;
1491
+ return true;
1492
+ };
1493
+ // Send `[start, end)` given up as `hole`, or hold it until a lite-07 subscription's first
1494
+ // SUBSCRIBE_START: one given up before delivery resolved, such as a group served meanwhile whose
1495
+ // stream failed, is named once it does.
1496
+ const sendHole = (start, end, hole) => {
1497
+ if (answer.kind === "unresolved")
1498
+ holdSkipped(answer.skipped, start, end, { ...hole, start, end });
1499
+ else if (answer.kind === "withheld") {
1500
+ holdMaxAge(requested.narrowest());
1501
+ answer.held.push([start, end, hole]);
1502
+ }
1503
+ else
1504
+ return controls.response(encodeSubscribeResponse(stream, holeMessage(start, end, hole), this.version));
1505
+ return Promise.resolve(true);
1506
+ };
1507
+ // Lite-07: whether the track is a relay's copy that places each range only where its upstream
1508
+ // would, from that upstream's answer for it or groups proving it, so a range it placed waits
1509
+ // on no other. A copy that places ranges from whatever groups it holds, or a local track,
1510
+ // waits for where its whole feed starts. Mirrors the Rust `TrackRun::per_range`.
1511
+ const perRange = () => hasRanges(this.version) && hooks.placesAsUpstream(track);
1512
+ // A time range reaching back before the first group held names drops from its time: start
1513
+ // there when a drop is recorded at the time or between it and that group, so the subscriber
1514
+ // does not pass over it. Mirrors the Rust `TrackState::source_start`.
1515
+ const historyStart = (ask, range, from) => {
1516
+ const start = max(range.start, from);
1517
+ const time = ask?.time;
1518
+ if (time !== undefined && !range.floored && !perRange() && (range.end === undefined || time < range.end)) {
1519
+ const reach = max(start, time + 1n);
1520
+ const until = range.end === undefined ? reach : min(reach, range.end);
1521
+ for (let at = time; at < until;) {
1522
+ const run = hooks.nextSettledDrop(track, at, until);
1523
+ if (!run || run === "pending")
1524
+ break;
1525
+ if (run.reason !== "skip")
1526
+ return time;
1527
+ at = run.end;
1528
+ }
1529
+ }
1530
+ return start;
1531
+ };
1532
+ // Resolve delivery at `from`, `position` the newest this hop saw, then name the groups given up
1533
+ // above it while it was held back. Before lite-07 the one start answers the subscription. On
1534
+ // lite-07 each of the SUBSCRIBE's ranges resolved there is answered now; one still waiting, or
1535
+ // one following the live edge before this hop knows where it is, is answered later by
1536
+ // `reportStarted`, and the drops given up meanwhile wait for the first answer. The only way out
1537
+ // of an unresolved answer, so none leaves its held drops unsent. Mirrors the Rust
1538
+ // `TrackRun::resolve`.
1539
+ const resolveStart = async (from, position) => {
1540
+ if (answer.kind === "waiting") {
1541
+ const { skipped } = answer;
1542
+ answer = { kind: "started", from };
1543
+ if (!(await sendStart(new SubscribeStart({ id: 0n, start: from, largest: "unknown" }))))
1544
+ return false;
1545
+ return nameSkipped(from, skipped);
1546
+ }
1547
+ if (answer.kind !== "unresolved")
1548
+ throw new Error(`delivery resolves once, not when ${answer.kind}`);
1549
+ const { skipped } = answer;
1550
+ answer = { kind: "withheld", from, held: [] };
1551
+ const largest = edge(position);
1552
+ const ids = [...unstarted.keys()].filter((id) => id < initial && controls.holds(id));
1553
+ const resolution = hooks.servingResolvedKeys(track, ids);
1554
+ // A range reaching back to the oldest group, on a copy placing each range as its upstream
1555
+ // answered it, starts where the copy's feed does, which it may not know yet.
1556
+ const reaches = perRange() && hooks.sourceStart(track) === "pending";
1557
+ for (const [index, id] of ids.entries()) {
1558
+ const range = resolution[index];
1559
+ // An update taken while an earlier start went out may have retired it.
1560
+ if (!range || !controls.holds(id) || (unstarted.get(id)?.live && largest === "unknown"))
1561
+ continue;
1562
+ // A live join starts at the history this hop vouches for from where it was placed, whatever
1563
+ // its max, which may be below where delivery starts: a relay serves first the groups it
1564
+ // holds, before those the join is owed arrive. It moves delivery down to it. Any other
1565
+ // range starts no earlier than delivery.
1566
+ const ask = unstarted.get(id);
1567
+ const joins = ask?.joins === true;
1568
+ if (!joins && reaches && !range.floored)
1569
+ continue;
1570
+ const start = joins
1571
+ ? hooks.joinStart(track, range.start, NO_MAX_DELAY)
1572
+ : historyStart(ask, range, from);
1573
+ unstarted.delete(id);
1574
+ const at = range.end === undefined || range.end > start ? start : undefined;
1575
+ if (at !== undefined)
1576
+ lowerFrom(at);
1577
+ if (!(await sendStart(new SubscribeStart({ id, start: at, largest }))))
1578
+ return false;
1579
+ }
1580
+ // A range an update added before this start is answered with it, before the drops held
1581
+ // for it, which a subscriber reads only once a range has started.
1582
+ if (!(await reportStarted(false)))
1583
+ return false;
1584
+ const resolved = answerFrom(answer);
1585
+ if (resolved !== undefined && !(await nameSkipped(resolved, skipped)))
1586
+ return false;
1587
+ // Sent now unless still withheld for the first START, which releases them then.
1588
+ if (answer.kind !== "withheld" || answer.held.length === 0)
1589
+ pendingNarrowest = undefined;
1590
+ return true;
1591
+ };
1592
+ // Name the runs in `skipped`, given up before delivery resolved at `start`, as they would have
1593
+ // been after it. Nothing below the start is owed. The final runs reaching up to it unbroken are
1594
+ // named all the same, so a reader filling below the start (a relay whose reader reaches lower)
1595
+ // learns nothing there exists. The rest, past a stale run, a group still held, or a key nothing
1596
+ // gave up, stay untold: naming them would send every gap in the track's history, as a lite-06
1597
+ // track keyed by timestamp holds one per group. An update that asks below the start names them
1598
+ // then, and a wider budget may still serve a stale one. On lite-07, whose ranges bound what a
1599
+ // stale verdict was judged within, a run stale under the track's own max age is final all the
1600
+ // same, since no budget reaches past it: a relay reading from the oldest group would otherwise
1601
+ // wait on it forever. Earlier drafts name a drop with no range, which a capped read could still
1602
+ // serve, so they stop there. Mirrors the Rust `TrackRun::name_skipped`, whose bound also takes in
1603
+ // the hop's cache ceiling, which a TypeScript publisher does not have.
1604
+ const nameSkipped = async (start, skipped) => {
1605
+ if (skipped.size === 0)
1606
+ return true;
1607
+ const bound = hasRanges(this.version) ? serving.maxAge : undefined;
1608
+ const finalStale = (stale) => bound !== undefined && stale >= bound;
1609
+ let reach = start;
1610
+ for (let i = skipped.size - 1; i >= 0; i--) {
1611
+ const range = skipped.all[i];
1612
+ if (range.start >= reach)
1613
+ continue;
1614
+ if (range.end < reach ||
1615
+ (range.reason !== "held-old" && range.maxAge !== undefined && !finalStale(range.maxAge)))
1616
+ break;
1617
+ reach = range.start;
1618
+ }
1619
+ // On lite-07, a subscription can also name disjoint history ranges below `reach` whose groups
1620
+ // were already given up before delivery resolved: forward their drops too.
1621
+ const send = [];
1622
+ const maxEnd = 1n << 64n;
1623
+ insertRun(send, reach, maxEnd);
1624
+ if (hasRanges(this.version)) {
1625
+ for (const askedRange of requested.values()) {
1626
+ const model = requestedRange(askedRange);
1627
+ if (typeof model.start !== "bigint")
1628
+ continue;
1629
+ const to = model.end !== undefined ? model.end + 1n : maxEnd;
1630
+ if (model.start < to)
1631
+ insertRun(send, model.start, to);
1632
+ }
1633
+ }
1634
+ // Below reach they stay untold: a start lowered to them owes them (see `lowerFrom`), and
1635
+ // otherwise only a rescan names them again.
1636
+ for (const range of skipped.all) {
1637
+ for (const gap of runGaps(send, range.start, range.end))
1638
+ record?.untell(gap.start, gap.end);
1639
+ for (const part of send) {
1640
+ const from = max(part.start, range.start);
1641
+ const to = min(part.end, range.end);
1642
+ if (from < to && !(await forward(from, to, range)))
1643
+ return false;
1644
+ }
1645
+ }
1646
+ return true;
1647
+ };
1648
+ // While the source has yet to say where its whole feed starts, `position` the newest this hop
1649
+ // saw: whether a range still unanswered, one the SUBSCRIBE carried or an update added since,
1650
+ // names a group the copy placed as its upstream answered (see `perRange`), so `resolveStart`
1651
+ // answers it now rather than wait on a live join or older history upstream still places.
1652
+ // Mirrors the Rust `TrackRun::places_any`.
1653
+ const placesAny = (position) => {
1654
+ if (!perRange())
1655
+ return false;
1656
+ const known = edge(position) !== "unknown";
1657
+ const ids = [...unstarted.keys()].filter((id) => controls.holds(id));
1658
+ const resolution = hooks.servingResolvedKeys(track, ids);
1659
+ return ids.some((id, index) => resolution[index]?.floored && (known || !unstarted.get(id)?.live));
1660
+ };
1661
+ // Lite-07: resolve delivery from the lowest group served while unresolved, `position` the newest
1662
+ // this hop saw, once the source says where its feed starts, or once one of the SUBSCRIBE's
1663
+ // ranges is placed, with delivery at the floor, at or below where any range still unplaced
1664
+ // starts, so its answer later is never raised past its own start. Undefined while neither
1665
+ // holds. Mirrors the Rust `TrackRun::start`.
1666
+ const resolveServed = async (position) => {
1667
+ if (answer.kind !== "unresolved" || answer.served === undefined)
1668
+ return undefined;
1669
+ let source = hooks.sourceStart(track);
1670
+ if (source === "pending" && placesAny(position))
1671
+ source = floor;
1672
+ if (source === "pending")
1673
+ return undefined;
1674
+ const from = hooks.deliveryStart(track, { first: answer.served, source, givenUp: answer.skipped });
1675
+ return resolveStart(from, position);
1676
+ };
1677
+ // Lite-07: whether a range still unanswered waits on this copy's upstream to place it, which
1678
+ // answers every range once the track ends: only while the copy's source has yet to say where
1679
+ // its feed starts. Mirrors the Rust `TrackRun::awaits_upstream`.
1680
+ const awaitsUpstream = () => {
1681
+ if (!perRange())
1682
+ return false;
1683
+ const held = [...unstarted.keys()].filter((id) => controls.holds(id));
1684
+ if (hooks.servingResolvedKeys(track, held).every((range) => range !== undefined))
1685
+ return false;
1686
+ return hooks.sourceStart(track) === "pending";
1687
+ };
1688
+ // `edge(newest())`, or once `finished` with the edge unknown, what this hop holds: nothing more
1689
+ // arrives to tell it, so a range following the edge is answered with what it has. Mirrors the
1690
+ // Rust `TrackRun::settled_largest`.
1691
+ const settledLargest = (finished) => {
1692
+ const position = newest();
1693
+ const largest = edge(position);
1694
+ if (largest !== "unknown" || !finished || position === undefined)
1695
+ return largest;
1696
+ return { position, ended: hooks.largestFinished(track, position) };
1697
+ };
1698
+ // Answer each range still waiting for its SUBSCRIBE_START once it resolves, or with no start
1699
+ // once nothing can resolve it (`finished`). One following the live edge also waits until this
1700
+ // hop knows where it is, unless the track finished, after which nothing more tells it. Waits
1701
+ // for delivery to resolve, which `resolveStart` does. Mirrors the Rust
1702
+ // `TrackRun::report_started`.
1703
+ const reportStarted = async (finished) => {
1704
+ const resolved = answerFrom(answer);
1705
+ if (resolved === undefined || unstarted.size === 0)
1706
+ return true;
1707
+ const largest = settledLargest(finished);
1708
+ // An update not taken yet retired one, and taking that update forgets it. In Range ID
1709
+ // order, as the Rust `TrackRun::report_started` reports them.
1710
+ const held = [...unstarted.keys()]
1711
+ .filter((id) => controls.holds(id))
1712
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
1713
+ // Every range clamps against where delivery started before this batch, so one reported
1714
+ // later isn't clamped against a start an earlier join in the batch lowered.
1715
+ const from = resolved;
1716
+ const per = perRange();
1717
+ const resolution = hooks.servingResolvedKeys(track, held);
1718
+ for (const [index, id] of held.entries()) {
1719
+ // Or one taken while an earlier start went out.
1720
+ if (!controls.holds(id))
1721
+ continue;
1722
+ const ask = unstarted.get(id);
1723
+ // Never answered without the largest, even once nothing else can resolve it: this hop's
1724
+ // feed answering or ending tells it.
1725
+ if (ask?.live && largest === "unknown")
1726
+ continue;
1727
+ const range = resolution[index];
1728
+ if (!range && !finished)
1729
+ continue;
1730
+ let start;
1731
+ if (range) {
1732
+ // A live join placed behind where delivery started, further from the live edge than
1733
+ // the first ranges, starts at the history this hop vouches for from where it was
1734
+ // placed, even past groups its max expired, which delivery names as old, so a wider max
1735
+ // reads them later: the subscriber reads its answer as the join's start, so its groups
1736
+ // from there are owed, and delivery now starts there too. So does a range naming a
1737
+ // group on a copy that places it as its upstream answered. One reaching back there starts where the copy's
1738
+ // feed does, once the copy knows. Any other range starts no earlier than delivery.
1739
+ if (ask?.joins)
1740
+ start = hooks.joinStart(track, range.start, NO_MAX_DELAY);
1741
+ else if (per && range.floored)
1742
+ start = range.start;
1743
+ else if (per) {
1744
+ const source = hooks.sourceStart(track);
1745
+ if (source === "pending" && !finished)
1746
+ continue;
1747
+ start = max(range.start, source === "pending" ? from : (source ?? from));
1748
+ }
1749
+ else
1750
+ start = historyStart(ask, range, from);
1751
+ if (range.end !== undefined && range.end <= start)
1752
+ start = undefined;
1753
+ else
1754
+ lowerFrom(start);
1755
+ }
1756
+ unstarted.delete(id);
1757
+ if (!(await sendStart(new SubscribeStart({ id, start, largest }))))
1758
+ return false;
1759
+ }
1760
+ return true;
1761
+ };
1762
+ // Lite-07, on a track this hop knows has no group yet: answer each range starting at the
1763
+ // oldest group at once, since every group the track produces is owed, so the subscriber
1764
+ // learns the track is empty rather than wait on a group. A time start above the floor, or a
1765
+ // live join, waits for a group to place it; one at or below the floor starts where delivery
1766
+ // does. Mirrors the Rust `TrackRun::resolve_empty`.
1767
+ const resolveEmpty = async () => {
1768
+ if (!hasRanges(this.version) || ![...unstarted.values()].some((ask) => ask.oldest))
1769
+ return undefined;
1770
+ if (newest() !== undefined || !hooks.knowsEdge(track) || hooks.subscriberEnd(track) !== undefined)
1771
+ return undefined;
1772
+ if (!(await resolveStart(0n, undefined)))
1773
+ return false;
1774
+ for (const [id, ask] of [...unstarted]) {
1775
+ if (!ask.oldest || !controls.holds(id))
1776
+ continue;
1777
+ unstarted.delete(id);
1778
+ if (!(await sendStart(new SubscribeStart({ id, start: 0n, largest: "empty" }))))
1779
+ return false;
1780
+ }
1781
+ return true;
1782
+ };
1783
+ // Lite-07, on a track that ended before its first group: its SUBSCRIBE_END at group 0 answers
1784
+ // every range, so none waits for a start, and nothing given up is owed. Mirrors the Rust
1785
+ // `TrackRun::answer_empty`.
1786
+ const answerEmpty = () => {
1787
+ unstarted.clear();
1788
+ answer = { kind: "answered", from: 0n };
1789
+ };
1790
+ // An unjudged OLD names the narrowest live budget, capped while drops are held. A held OLD had a
1791
+ // finite Max Age when queued and shares the pre-START minimum. Mirrors the Rust `TrackRun::hole`.
1792
+ const holeMessage = (start, end, hole) => {
1793
+ if (hole.reason !== "held-old")
1794
+ return givenUp(start, end, hole, narrower(requested.narrowest(), pendingNarrowest), this.version);
1795
+ return givenUp(start, end, { reason: "old" }, narrower(heldNarrowest, requested.narrowest()), this.version);
1796
+ };
1797
+ // A drop of a group held whole names its span, `[start, max(End, start + 1))`, so the
1798
+ // subscriber accounts for the starts inside it too: no other group starts there. The
1799
+ // group is the highest one below `end`, starting at `end - 1n` or holding it in its span,
1800
+ // as the Rust `TrackState::span_end` takes it.
1801
+ const reach = (end) => max(end, hooks.wholeEnd(track, end - 1n) ?? hooks.wholeAround(track, end - 1n)?.end ?? end);
1802
+ // The starts of the groups whose stream is still serving, which may yet send GROUP_END.
1803
+ const streaming = new Set();
1804
+ // Give up, as `hole` says, whatever part of `[start, end)` this subscription has not been
1805
+ // served or given up yet.
1806
+ const drop = async (start, end, hole) => {
1807
+ if (!record)
1808
+ return true;
1809
+ for (const gap of record.untold(start, end)) {
1810
+ // The starts inside a whole group whose stream is still serving are its GROUP_END's to
1811
+ // account for, which may still be on its way, or its drop's, which names its span. A
1812
+ // stream that already ended without one left them untold, so they are named here.
1813
+ const around = hooks.wholeAround(track, gap.start);
1814
+ const from = around && streaming.has(around.start) ? min(around.end, gap.end) : gap.start;
1815
+ if (from >= gap.end)
1816
+ continue;
1817
+ record.tell(from, gap.end);
1818
+ if (!(await sendHole(from, gap.end, hole)))
1819
+ return false;
1820
+ }
1821
+ return true;
1822
+ };
1823
+ // Forward a verdict the reader reached on `[start, end)`, which its record already took in, so
1824
+ // nothing went out over it. A drop of a group held whole names its span.
1825
+ const forward = async (start, end, hole) => {
1826
+ if (!record || start >= end)
1827
+ return true;
1828
+ if (hole.reason !== "skip")
1829
+ end = reach(end);
1830
+ record.tell(start, end);
1831
+ return sendHole(start, end, hole);
1832
+ };
579
1833
  // The track's exclusive final boundary. A Rust subscriber feeds SUBSCRIBE_END
580
1834
  // straight into finish_at, so it must name the track's boundary (which counts
581
1835
  // datagram sequences too), not the delivered range: a subscription cap can hold
582
1836
  // produced groups back. The latest() fallback covers a subscription torn down
583
1837
  // before the producer declared it.
584
- const boundary = () => track.final() ?? (track.latest() ?? -1) + 1;
585
- // Before lite-07, SUBSCRIBE_END names that boundary, which a cap can hold groups back
586
- // from, so it goes out as soon as the producer finishes and the subscription keeps
587
- // serving whatever a later cap raise releases (see the Rust publisher's Recv::Boundary).
1838
+ // Lite cannot name a frame, so a mid-group end rounds up past its group, whose own
1839
+ // stream FIN says where it stops.
1840
+ const boundary = () => {
1841
+ const end = hooks.subscriberEnd(track);
1842
+ return end ? finalKey(end) : (hooks.latestKey(track) ?? -1n) + 1n;
1843
+ };
1844
+ // Declare the boundary immediately; groups below it can still be in flight.
588
1845
  const sendEnd = async () => {
589
1846
  endSent = true;
590
1847
  if (!emitRange)
591
1848
  return true;
592
- return controls.response((async () => {
593
- // A group that gives up before its stream opens is never counted.
594
- if (countStreams)
595
- while (opening.size > 0)
596
- await Promise.all(opening);
597
- const end = new SubscribeEnd(boundary(), streams);
598
- await encodeSubscribeResponse(stream, { end }, this.version);
599
- })());
1849
+ // Lite-05/06 carry the name's datagrams on this subscription, keyed in the groups' space:
1850
+ // the end covers the highest datagram sent, everything above the stream's own end is
1851
+ // dropped, and no later datagram goes out. Keys below the stream's own end stay open,
1852
+ // since its groups may be in flight.
1853
+ let end = boundary();
1854
+ const { carried } = serving;
1855
+ if (carried) {
1856
+ const settled = carried.sent.settle(end);
1857
+ carried.consumer.close();
1858
+ end = settled.end;
1859
+ if (settled.span) {
1860
+ const [from, to] = settled.span;
1861
+ if (!(await drop(from, to, dropHole())))
1862
+ return false;
1863
+ }
1864
+ }
1865
+ return controls.response(encodeSubscribeResponse(stream, { end: new SubscribeEnd(end) }, this.version));
1866
+ };
1867
+ // The FIN tells the subscriber every group is accounted for, so it waits until each group
1868
+ // stream finished or reset. False once the subscriber left instead, which cancels whatever
1869
+ // is still queued. `race`, since this repeats per batch of drops against the subscription's end.
1870
+ const drained = async () => {
1871
+ const done = Symbol("drained");
1872
+ const end = await race([Promise.all(groups).then(() => done), controls.ended]);
1873
+ if (end instanceof Error)
1874
+ throw end;
1875
+ return end === done;
1876
+ };
1877
+ // Lite-07: true once every group settled, or `undefined` once a control is there to take,
1878
+ // its FIN or failure included. An update may move a stop a group is parked at, which only
1879
+ // the loop applies, so the drain waits for it no longer. Each wait is disposed once it
1880
+ // wakes, so updates that leave a group parked leave nothing behind.
1881
+ const drainedOrControl = async () => {
1882
+ for (;;) {
1883
+ if (controls.pending())
1884
+ return undefined;
1885
+ if (groups.size === 0)
1886
+ return true;
1887
+ const dispose = [];
1888
+ await new Promise((resolve) => {
1889
+ dispose.push(controls.changed(resolve), groupEnded.changed(() => resolve()));
1890
+ });
1891
+ for (const close of dispose)
1892
+ close();
1893
+ }
600
1894
  };
601
1895
  // One ranking for the whole subscription, shared by every group it serves.
602
- const priority = new Priority(track);
1896
+ const priority = new Priority(track, publisher);
1897
+ // Lite-07: the policy and budget of the live range with Range ID `id`, as the latest update
1898
+ // left it, so a retuned max moves a group already going out. Mirrors the Rust `Steering::of`.
1899
+ const rangeSteering = (id) => {
1900
+ const range = controls.range(id);
1901
+ if (!range)
1902
+ return undefined;
1903
+ const max = range.start?.live?.max ?? range.start?.joined?.max;
1904
+ return { policy: policyOf(range), budget: typeof max === "number" ? max : NO_MAX_DELAY };
1905
+ };
1906
+ // Lite-07: a group goes out at the top of the live ranges still wanting it, falling as it ages
1907
+ // past the ones above, so its stream ranks by its own policy. The ranges covering it are read
1908
+ // again each time it is ranked, so an update that adds a range over it, or re-adds its span
1909
+ // under a new Range ID, moves it, as the Rust `Steer::inflight` does.
1910
+ const rankingOf = (group) => {
1911
+ if (!hasRanges(this.version))
1912
+ return undefined;
1913
+ const expiry = hooks.groupExpiry(group);
1914
+ // The widest budget the group is known to have aged past, which only grows.
1915
+ let aged;
1916
+ return {
1917
+ policy: (whole) => {
1918
+ const covers = hooks.servingCovering(track, group.start).map(([id]) => id);
1919
+ for (;;) {
1920
+ const { policy, lasts } = groupPolicy({ whole, steering: rangeSteering }, covers, aged);
1921
+ if (lasts === undefined || !expiry?.aged?.(lasts))
1922
+ return policy;
1923
+ aged = lasts;
1924
+ }
1925
+ },
1926
+ changed: expiry?.changed ?? [],
1927
+ };
1928
+ };
603
1929
  // Every group this subscription started serving, until its stream finishes or resets.
604
1930
  const groups = new Set();
1931
+ // Bumped each time one of `groups` ends.
1932
+ const groupEnded = new Signal(0);
1933
+ const drops = new Signal(0);
1934
+ // Groups whose stream failed, with why, for the control stream to name, as runs: a group held
1935
+ // whole names its span.
1936
+ const pendingDrops = [];
1937
+ // Lite-07: the starts inside whole groups' spans whose GROUP_END a reset may have cut, to name
1938
+ // again as a skip. Mirrors the Rust `GroupOutcomes::cut`.
1939
+ const pendingCuts = [];
605
1940
  // Cancels groups still queued for a stream slot. Only the subscriber leaving counts:
606
1941
  // a track that ran out of groups still has to flush the ones already queued, and the
607
1942
  // caller FINs the subscribe stream to say so.
608
1943
  let finished = false;
1944
+ // Lite-07: the subscriber cleanly FIN'd its send half (no further updates).
1945
+ let peerFin = false;
1946
+ let armed;
1947
+ // Park until the subscription changes, from the wait armed this pass if any.
1948
+ const park = () => armed?.woke ?? waitForSubscription(controls, track, drops);
609
1949
  let unsubscribe;
610
1950
  const unsubscribed = new Promise((resolve) => {
611
1951
  unsubscribe = resolve;
612
1952
  });
1953
+ // Unlike `unsubscribed`, settles however the run ends: a group parked at a stop waits on an
1954
+ // update, which no longer comes.
1955
+ let end;
1956
+ const ended = new Promise((resolve) => {
1957
+ end = resolve;
1958
+ });
613
1959
  try {
614
1960
  for (;;) {
1961
+ for (const { start, end } of pendingCuts.splice(0)) {
1962
+ record?.tell(start, end);
1963
+ if (!(await sendHole(start, end, skipHole())))
1964
+ return false;
1965
+ }
1966
+ if (pendingDrops.length > 0) {
1967
+ for (const { start, end, hole } of pendingDrops.splice(0)) {
1968
+ // The rest of the span is told with it; the served start keeps its record.
1969
+ for (const gap of record?.untold(start, end) ?? [])
1970
+ record?.tell(gap.start, gap.end);
1971
+ if (!(await sendHole(start, end, hole)))
1972
+ return false;
1973
+ }
1974
+ }
1975
+ // While a range waits for its START, the wait below is armed before `reportStarted` reads
1976
+ // what this hop knows, so an answer landing while this pass awaits still wakes it.
1977
+ armed?.dispose();
1978
+ armed = unstarted.size > 0 ? armSubscription(controls, track, drops) : undefined;
1979
+ if (!(await reportStarted(false)))
1980
+ return false;
615
1981
  // Control before data, matching the Rust publisher: every control decoded while
616
1982
  // the loop was parked applies to the next pop, never to one already made. This
617
1983
  // drain is synchronous, so nothing the decoder holds can land between the pop
@@ -619,300 +1985,944 @@ export class Publisher {
619
1985
  const control = controls.take();
620
1986
  if (control) {
621
1987
  switch (control.kind) {
1988
+ case "fin":
1989
+ peerFin = true;
1990
+ // Already finished and waiting for updates or FIN: close cleanly now.
1991
+ if (finished)
1992
+ return true;
1993
+ continue;
622
1994
  case "done":
623
1995
  // The subscriber left. Its queued groups are pointless now, which
624
- // the finally below acts on since `finished` stays false.
625
- return;
1996
+ // the finally below acts on since `finished` stays false. On lite-07 it
1997
+ // also FINs once it read a finished track's tail, which ends the
1998
+ // subscription as finished.
1999
+ return finished;
626
2000
  case "error":
627
2001
  throw control.error;
628
2002
  case "update": {
2003
+ // An update may reach the finished track's history, so it is served again.
2004
+ finished = false;
629
2005
  const update = control.update;
2006
+ if (hasRanges(this.version)) {
2007
+ // A range retired before its start resolved is owed no SUBSCRIBE_START.
2008
+ for (const id of control.applied.retired)
2009
+ unstarted.delete(id);
2010
+ for (const [id, range] of control.applied.added)
2011
+ unstarted.set(id, asked(range));
2012
+ }
630
2013
  console.debug(`subscribe update: broadcast=${broadcast} track=${track.name}`);
631
- // `positionCursor` pins an unfloored pre-06 SUBSCRIBE to the latest
2014
+ // `cursorFloor` pins an unfloored pre-06 SUBSCRIBE to the latest
632
2015
  // group, so an update that drops a named floor re-pins there too. On
633
- // an empty track the next group is the latest, whatever its sequence.
634
- const start = update.startGroup === undefined &&
635
- bounds.startGroup !== undefined &&
636
- !resolvesStart(this.version)
637
- ? (track.latest() ?? 0)
638
- : update.startGroup;
639
- hooks.replaceGroups(track, {
640
- start: start === undefined ? undefined : { included: start },
641
- end: update.endGroup === undefined ? undefined : { included: update.endGroup },
642
- });
2016
+ // an empty track the next group is the latest, whatever its key.
2017
+ // Lite-06 encodes an absent start as no floor, so one that had a floor above
2018
+ // 0 drops back to 0: the cursor only rises on its own, and a finished group
2019
+ // below the old floor (a quiet catalog) is never served otherwise. One at 0
2020
+ // already keeps where delivery started, as the Rust `lower_floor` does.
2021
+ const requested = bounds.startGroup;
2022
+ const start = hasRanges(this.version)
2023
+ ? 0n
2024
+ : update.startGroup === undefined &&
2025
+ requested !== undefined &&
2026
+ !resolvesStart(this.version)
2027
+ ? (hooks.latestKey(track) ?? 0n)
2028
+ : (update.startGroup ??
2029
+ (resolvesStart(this.version) && requested !== undefined && requested > 0n
2030
+ ? 0n
2031
+ : undefined));
2032
+ if (start !== undefined) {
2033
+ floor = start;
2034
+ // Before SUBSCRIBE_START nothing is owed yet; the start accounts for it.
2035
+ // A lowered floor owes the groups it newly asks for, so the end sweep
2036
+ // covers them. A raised one sends no early drop: the subscriber already
2037
+ // stops owing below its floor, and a later update may lower it again to
2038
+ // ask for the groups the wire was told nothing of.
2039
+ lowerFrom(start);
2040
+ }
2041
+ // An update starts the walk of what is owed over: moving the cursor may leave keys
2042
+ // the walk passed untold again. The walk seeks past what is told, so going over it
2043
+ // again costs nothing there.
2044
+ scanned = { start: 0n, end: 0n };
2045
+ // Before lite-07, an update that names no start and changes the budget places delivery
2046
+ // afresh, which judges the history again. A rescan would name it gap by gap and group by
2047
+ // group, though the subscriber is owed none of it: a lite-06 track keyed by timestamp
2048
+ // holds a gap per group, thousands a minute. So the history below the first group the
2049
+ // budget reaches, and below where delivery started, goes out as one stale drop: only
2050
+ // what this copy vouches for, from where a join with no budget would start, since a
2051
+ // relay's copy below where its own feed starts may still receive the groups a wider
2052
+ // budget re-offers upstream, and the upstream's drops of the rest. Each group re-offered
2053
+ // lowers the start as it is served, owing the gaps between them. Mirrors the Rust
2054
+ // `TrackRun::name_history`.
2055
+ if (answer.kind === "started" &&
2056
+ resolvesStart(this.version) &&
2057
+ update.startGroup === undefined &&
2058
+ update.maxDelay !== maxDelay) {
2059
+ const budget = update.maxDelay ?? NO_MAX_DELAY;
2060
+ const cap = update.endGroup === undefined ? undefined : update.endGroup + 1n;
2061
+ // Nor at or past the first key a relay's copy has yet to account for, which its
2062
+ // upstream may still deliver (`joinStart` stops there).
2063
+ const placed = min(min(hooks.freshStart(track, floor, budget, cap), hooks.joinStart(track, floor, budget, true)), answer.from);
2064
+ const vouched = hooks.joinStart(track, floor, NO_MAX_DELAY, true);
2065
+ if (vouched < placed) {
2066
+ // The scan leaves what it reached below the start untold, so it is named with
2067
+ // the rest and the drop is one run per stretch untold. The wire is told, so these
2068
+ // keys stay settled, as every drop leaves them.
2069
+ const hole = staleHole(budget);
2070
+ for (const gap of record?.untold(vouched, placed) ?? []) {
2071
+ record?.tell(gap.start, gap.end);
2072
+ if (!(await sendHole(gap.start, gap.end, hole)))
2073
+ return false;
2074
+ }
2075
+ }
2076
+ }
2077
+ maxDelay = update.maxDelay;
643
2078
  bounds.startGroup = update.startGroup;
644
2079
  bounds.startFrame = update.startFrame;
645
2080
  bounds.endGroup = update.endGroup;
646
2081
  bounds.endFrame = update.endFrame;
647
- await yieldToControls();
2082
+ bounds.starts = bounds.startsAfter.get(update) ?? new Map();
2083
+ const stops = bounds.stopsAfter.get(update);
2084
+ if (stops && !sameStops(stops, bounds.stops.peek()))
2085
+ bounds.stops.set(stops);
2086
+ moveCursor();
2087
+ // A microtask is too short: decoding one framed update crosses several
2088
+ // awaits, each of which can requeue behind the serving continuation. A
2089
+ // task boundary usually lets the decoder finish whatever the transport
2090
+ // already delivered before the next group pop. It orders nothing: an update
2091
+ // decoded later applies from the pop after it. Updates are rare, so groups
2092
+ // do not pay this scheduling cost on the normal path.
2093
+ await yieldNow();
648
2094
  continue;
649
2095
  }
650
2096
  }
651
2097
  }
2098
+ // One step of what a lowered start owes per pass, after the controls, as the Rust
2099
+ // `poll_step` takes it: an update raising the start or moving the end applies before the
2100
+ // next step.
2101
+ const owedRuns = nameOwed();
2102
+ if (owedRuns) {
2103
+ for (const run of owedRuns)
2104
+ if (!(await sendHole(run.start, run.end, run)))
2105
+ return false;
2106
+ // A long walk over history with nothing to name lets the host's other work run.
2107
+ const yielded = replayBudget.poll();
2108
+ if (yielded !== undefined)
2109
+ await yielded;
2110
+ continue;
2111
+ }
652
2112
  // Exactly-once arrival-order serving. This synchronous package-internal pop
653
2113
  // and frameRange call are the operation's linearization point.
654
- const recv = hooks.tryRecvGroup(track);
2114
+ // Popping or filtering a group removes the subscriber's view of its edge.
2115
+ // A relay can hold just the first group of a backlog its source already
2116
+ // answered past, so the source's largest says where the live feed is.
2117
+ const held = answer.kind === "waiting" ? answer.first : undefined;
2118
+ const largest = (answer.kind === "waiting" || answer.kind === "unresolved") && hasLargest(this.version)
2119
+ ? newer(held?.largest, newest())
2120
+ : undefined;
2121
+ // Lite-05/06 hold their first group until the source says where its feed starts (below);
2122
+ // lite-07 serves its groups meanwhile, so a range waiting on its start holds back no
2123
+ // other's, and resolves from the lowest it served once it can.
2124
+ if (answer.kind === "unresolved" && answer.served !== undefined) {
2125
+ const resolved = await resolveServed(largest);
2126
+ if (resolved === false)
2127
+ return false;
2128
+ if (resolved)
2129
+ continue;
2130
+ }
2131
+ if (answer.kind === "waiting")
2132
+ answer.first = undefined;
2133
+ const recv = held
2134
+ ? { kind: "group", group: held.group }
2135
+ : hooks.tryRecvGroup(track, emitRange);
655
2136
  switch (recv.kind) {
656
2137
  case "error":
657
2138
  throw recv.error;
2139
+ case "drop": {
2140
+ // Below where delivery starts, only a final run reaching up to it is named, as at the
2141
+ // join: one learned after the start resolved still tells the subscriber the start's
2142
+ // group has nothing before it. The rest stays untold until a start lowered to it owes
2143
+ // it, a stale one too, which a wider budget may still serve. Mirrors the Rust
2144
+ // `TrackRun::poll_forward_drop`.
2145
+ const floor = dropFloor();
2146
+ let start = recv.start;
2147
+ if (floor !== undefined && start < floor && (recv.end < floor || recv.maxAge !== undefined)) {
2148
+ record?.untell(start, min(recv.end, floor));
2149
+ start = min(floor, recv.end);
2150
+ }
2151
+ if (start >= recv.end)
2152
+ continue;
2153
+ const hole = snapshotHole(recv);
2154
+ if (answer.kind === "waiting" || answer.kind === "unresolved")
2155
+ holdSkipped(answer.skipped, start, recv.end, { ...hole, start, end: recv.end });
2156
+ else if (answer.kind !== "legacy" && !(await forward(start, recv.end, hole)))
2157
+ return false;
2158
+ continue;
2159
+ }
658
2160
  case "idle":
659
- // Before lite-07, an end declared ahead of the live edge goes out as
660
- // soon as it is known, while the remaining groups are still being
661
- // produced. The lite-07 count is not final until those groups open.
662
- if (!endSent && !countStreams && track.final() !== undefined) {
2161
+ // A lite-07 window whose bounded ranges all resolved empty owes nothing: say so at
2162
+ // once, and the subscription ends as covered below. No group would ever answer it.
2163
+ if (answer.kind === "unresolved") {
2164
+ const end = hooks.servingEnd(track);
2165
+ if (end !== undefined && hooks.servingRuns(track, 0n, end).length === 0) {
2166
+ if (!(await resolveStart(end, largest)))
2167
+ return false;
2168
+ continue;
2169
+ }
2170
+ }
2171
+ // A declared end goes out while lower groups are still being produced.
2172
+ if (!endSent && hooks.subscriberEnd(track) !== undefined) {
663
2173
  if (!(await sendEnd()))
664
- return;
2174
+ return false;
665
2175
  continue;
666
2176
  }
667
- await waitForSubscription(controls, track);
2177
+ // Lite-07 keeps a covered subscription open for an update. One none of whose groups
2178
+ // can be served has no group to resolve its start: answer it now, as the Rust
2179
+ // publisher does, and the loop then names what it held back.
2180
+ if (answer.kind === "unresolved" && answer.served === undefined) {
2181
+ const end = hooks.servingEnd(track);
2182
+ const runs = end === undefined ? [] : hooks.servingRuns(track, 0n, end);
2183
+ const given = [];
2184
+ for (const range of answer.skipped.all)
2185
+ insertRun(given, range.start, range.end);
2186
+ if (runs.length > 0 &&
2187
+ runs.every((run) => runGaps(given, run.start, run.end).length === 0)) {
2188
+ if (!(await resolveStart(runs[0].start, largest)))
2189
+ return false;
2190
+ continue;
2191
+ }
2192
+ }
2193
+ if (answer.kind === "unresolved" && answer.served === undefined) {
2194
+ const empty = await resolveEmpty();
2195
+ if (empty === false)
2196
+ return false;
2197
+ if (empty)
2198
+ continue;
2199
+ }
2200
+ // Lite-07 SUBSCRIBE + FIN: once every bounded range is resolved,
2201
+ // accounted for, and every group stream has finished, close cleanly.
2202
+ if (keepsSubscribeOpen(this.version) &&
2203
+ peerFin &&
2204
+ requested.end() !== undefined &&
2205
+ answer.kind === "answered" &&
2206
+ unstarted.size === 0 &&
2207
+ groups.size === 0 &&
2208
+ pendingDrops.length === 0 &&
2209
+ pendingCuts.length === 0 &&
2210
+ record) {
2211
+ const end = hooks.servingEnd(track);
2212
+ if (end !== undefined &&
2213
+ hooks
2214
+ .servingRuns(track, 0n, end)
2215
+ .every((run) => record.untold(run.start, run.end).length === 0)) {
2216
+ finished = true;
2217
+ return true;
2218
+ }
2219
+ }
2220
+ await park();
668
2221
  continue;
669
2222
  case "boundary":
670
2223
  // The producer finished but is still holding groups above the cap.
671
2224
  // Declare the boundary, then wait for an update to release them.
672
- if (!endSent && !countStreams) {
2225
+ if (!endSent) {
673
2226
  if (!(await sendEnd()))
674
- return;
2227
+ return false;
675
2228
  continue;
676
2229
  }
677
- await waitForSubscription(controls, track);
2230
+ if (keepsSubscribeOpen(this.version) &&
2231
+ peerFin &&
2232
+ requested.end() !== undefined &&
2233
+ answer.kind === "answered" &&
2234
+ unstarted.size === 0 &&
2235
+ groups.size === 0 &&
2236
+ pendingDrops.length === 0 &&
2237
+ pendingCuts.length === 0 &&
2238
+ record) {
2239
+ const end = hooks.servingEnd(track);
2240
+ if (end !== undefined &&
2241
+ hooks
2242
+ .servingRuns(track, 0n, end)
2243
+ .every((run) => record.untold(run.start, run.end).length === 0)) {
2244
+ finished = true;
2245
+ return true;
2246
+ }
2247
+ }
2248
+ await park();
678
2249
  continue;
679
2250
  case "done": {
2251
+ // A relay's copy places a range only as its upstream would, so one its upstream has yet
2252
+ // to answer may start below every group held: nothing it owes is final until then.
2253
+ if (awaitsUpstream()) {
2254
+ await park();
2255
+ continue;
2256
+ }
2257
+ // Lite-07 sends no FIN to say nothing was served, so a track that ended before
2258
+ // delivery resolved still says where it starts, at or below any group served; the
2259
+ // drops below then account for the rest. One that ended before its first group is
2260
+ // answered by its SUBSCRIBE_END at 0 alone.
2261
+ if (answer.kind === "unresolved") {
2262
+ const fin = boundary();
2263
+ if (fin === 0n)
2264
+ answerEmpty();
2265
+ else {
2266
+ const first = hooks.servingRuns(track, 0n, fin)[0]?.start ?? fin;
2267
+ const from = answer.served === undefined ? first : min(first, answer.served);
2268
+ if (!(await resolveStart(from, largest)))
2269
+ return false;
2270
+ continue;
2271
+ }
2272
+ }
2273
+ // Nothing arrives to resolve a range still waiting on the live feed.
2274
+ if (!(await reportStarted(true)))
2275
+ return false;
2276
+ // Name every key from the start to the end this subscription never
2277
+ // got. A cap below the end bounds what the subscriber is owed, as on its side.
2278
+ const from = answerFrom(answer);
2279
+ if (from !== undefined) {
2280
+ // A key the publisher declared skipped went out as a skip already; one
2281
+ // it never declared might have existed, so it is not found.
2282
+ const unserved = dropHole();
2283
+ // Only the groups inside the ranges are owed.
2284
+ for (const run of hooks.servingRuns(track, from, boundary())) {
2285
+ if (!(await drop(run.start, run.end, unserved)))
2286
+ return false;
2287
+ }
2288
+ }
680
2289
  if (!endSent) {
681
2290
  if (!(await sendEnd()))
682
- return;
2291
+ return false;
2292
+ continue;
2293
+ }
2294
+ const drain = keepsSubscribeOpen(this.version) ? await drainedOrControl() : await drained();
2295
+ if (drain === undefined)
2296
+ continue;
2297
+ if (!drain)
2298
+ return false;
2299
+ if (pendingDrops.length > 0 || pendingCuts.length > 0)
2300
+ continue;
2301
+ // Lite-07 keeps the stream open past SUBSCRIBE_END until the subscriber FINs
2302
+ // (unless the subscriber already FIN'd a bounded SUBSCRIBE).
2303
+ if (keepsSubscribeOpen(this.version) && !peerFin) {
2304
+ finished = true;
2305
+ if (!controls.pending())
2306
+ await waitForControl(controls);
683
2307
  continue;
684
2308
  }
685
- // The FIN tells the subscriber every group is accounted for, so it waits
686
- // until each group stream finished or reset. The subscriber leaving
687
- // instead cancels whatever is still queued.
688
- const drained = Symbol("drained");
689
- const end = await Promise.race([Promise.all(groups).then(() => drained), controls.ended]);
690
- if (end instanceof Error)
691
- throw end;
692
- if (end !== drained)
693
- return;
694
2309
  finished = true;
695
- return;
2310
+ return true;
696
2311
  }
697
2312
  }
698
2313
  const group = recv.group;
699
- const range = frameRange(bounds, group.sequence);
700
- if (emitRange && !startSent) {
701
- startSent = true;
702
- // SUBSCRIBE_START names the first group served now. A later group at or
703
- // above an explicit floor is still delivered, so the cursor stays put.
2314
+ // Never a second stream for a key this subscription already accounted for (served,
2315
+ // sent as a datagram, or dropped, stale or not): a subscriber settles every drop for good,
2316
+ // and a reader wider than a stale one asks for the group with a request of its own.
2317
+ if (record?.told(group.start)) {
2318
+ group.close();
2319
+ continue;
2320
+ }
2321
+ const range = frameRange(bounds, group.start);
2322
+ if (answer.kind === "waiting") {
2323
+ // A group stream can beat the upstream START on its own stream, and resolving
2324
+ // from the group alone would give up the backlog that START still promises.
2325
+ const source = hooks.sourceStart(track);
2326
+ if (source === "pending") {
2327
+ answer.first = { group, largest };
2328
+ await park();
2329
+ continue;
2330
+ }
2331
+ // A group given up, or held and not servable, cannot be where the feed starts. A
2332
+ // lite-06 live join with a bounded budget owes nothing that budget does not still
2333
+ // read, so it starts at the lowest group held unread, never where a relay's copy
2334
+ // started its feed, which would owe every drop above. An unbounded join reads all
2335
+ // the copy vouches for, so the feed start stands. Mirrors the Rust `TrackRun::start`.
2336
+ const boundedJoin = resolvesStart(this.version) && bounds.startGroup === undefined && maxDelay !== null;
2337
+ const from = hooks.deliveryStart(track, {
2338
+ first: group.start,
2339
+ source: boundedJoin ? undefined : source,
2340
+ givenUp: answer.skipped,
2341
+ });
2342
+ // A later group above an explicit floor is still delivered, so the cursor stays put.
704
2343
  // A pre-06 subscribe that named no group is the exception: an absent
705
- // Group Start is the latest group, and this sequence becomes the floor.
2344
+ // Group Start is the latest group, and this key becomes the floor.
706
2345
  // Lite-06 encodes a floor of group 0 as 0, so an omitted start is not pinned.
707
- if (bounds.startGroup === undefined && !resolvesStart(this.version)) {
708
- hooks.replaceGroups(track, {
709
- start: { included: group.sequence },
710
- end: bounds.endGroup === undefined ? undefined : { included: bounds.endGroup },
711
- });
712
- }
713
- if (!(await controls.response(encodeSubscribeResponse(stream, { start: new SubscribeStart(group.sequence) }, this.version))))
714
- return;
2346
+ if (bounds.startGroup === undefined && !resolvesStart(this.version))
2347
+ raiseFloor(from);
2348
+ if (!(await resolveStart(from, largest)))
2349
+ return false;
2350
+ }
2351
+ else if (answer.kind === "unresolved") {
2352
+ answer.served = answer.served === undefined ? group.start : min(answer.served, group.start);
2353
+ // Resolved before the group goes out when the source already answered, so its START
2354
+ // leads the group's stream.
2355
+ if ((await resolveServed(largest)) === false)
2356
+ return false;
715
2357
  }
2358
+ // A group a wider budget re-offers below the start starts delivery there.
2359
+ if (dropFloor() !== undefined)
2360
+ lowerFrom(group.start);
2361
+ record?.tell(group.start, group.start + 1n);
2362
+ streaming.add(group.start);
2363
+ let atReset;
716
2364
  const options = {
717
2365
  sub,
718
2366
  group,
719
- timescale,
2367
+ givenUp: new GivenUp(group),
2368
+ stamp,
2369
+ compress,
2370
+ meta,
720
2371
  priority,
2372
+ ranking: rankingOf(group),
721
2373
  unsubscribed,
722
2374
  start: range.start,
723
2375
  end: range.end,
2376
+ stops: hasRanges(this.version) ? { at: bounds.stops, ended } : undefined,
2377
+ // The starts inside a group sent whole are accounted for by its GROUP_END, so the
2378
+ // end-of-track scan never drops them.
2379
+ ended: (end) => {
2380
+ if (end > group.start + 1n)
2381
+ record?.tell(group.start + 1n, end);
2382
+ },
2383
+ cut: (start, end) => {
2384
+ if (answer.kind === "unresolved" || answer.kind === "withheld")
2385
+ holdMaxAge(requested.narrowest());
2386
+ pendingCuts.push({ start, end });
2387
+ drops.update((revision) => revision + 1);
2388
+ },
2389
+ resetting: () => {
2390
+ atReset ??= { maxAge: requested.narrowest() };
2391
+ },
724
2392
  };
725
- // `opening` settles when the stream opens so the lite-07 count can be sent.
726
- // `groups` covers the serve too, so the FIN still waits for every stream to
727
- // finish or reset, including one that has not opened yet.
728
- const opened = this.#openGroup(options);
729
- const task = opened.then(async (writer) => {
730
- if (!writer)
731
- return;
732
- streams += 1;
733
- await this.#serveGroup(writer, options);
734
- });
2393
+ // The FIN waits for every stream to finish or reset, including one that has not opened yet.
2394
+ // A stream reset to make room fails the group like any other reset, so it is dropped,
2395
+ // unless a lite-07 reset delivered its header, which accounts for the group.
2396
+ const task = (async () => {
2397
+ const writer = await this.#openGroup(options);
2398
+ let failed;
2399
+ try {
2400
+ failed = writer instanceof Error ? writer : await this.#serveGroup(writer, options);
2401
+ }
2402
+ finally {
2403
+ options.givenUp.close();
2404
+ streaming.delete(group.start);
2405
+ }
2406
+ if (failed && emitRange) {
2407
+ const end = max(group.end ?? group.start, group.start + 1n);
2408
+ // A group that went stale names the budget it was judged under, a superseded or skipped
2409
+ // one says so, and any other failure is dropped for this subscription alone.
2410
+ const budget = group.staleUnder;
2411
+ const hole = snapshotHole(budget === undefined ? holeOf(failed) : staleHole(budget), atReset);
2412
+ pendingDrops.push({ start: group.start, end, hole });
2413
+ drops.update((revision) => revision + 1);
2414
+ }
2415
+ })();
735
2416
  groups.add(task);
736
- void task.finally(() => groups.delete(task));
737
- opening.add(opened);
738
- void opened.finally(() => opening.delete(opened));
2417
+ void task.finally(() => {
2418
+ groups.delete(task);
2419
+ groupEnded.update((ended) => ended + 1);
2420
+ if (groups.size === 0)
2421
+ drops.update((revision) => revision + 1);
2422
+ });
739
2423
  }
740
2424
  }
741
2425
  finally {
2426
+ armed?.dispose();
2427
+ // A group held for the upstream START has no one left to read it.
2428
+ if (answer.kind === "waiting")
2429
+ answer.first?.group.close();
742
2430
  if (!finished)
743
2431
  unsubscribe();
2432
+ end();
2433
+ // A lite-07 subscriber FINs once it read the finished track's tail, or once it wants
2434
+ // nothing more, even while a reply is still being written. Either way the groups still
2435
+ // waiting for a slot are cancelled, but an opened stream may be a final group whose FIN
2436
+ // is still being acknowledged, so a draining close still waits for it; a reader that
2437
+ // wants none of it resets it.
2438
+ if (keepsSubscribeOpen(this.version) && groups.size > 0)
2439
+ void this.owe(Promise.allSettled(groups).then(() => undefined));
744
2440
  priority.close();
745
2441
  }
746
2442
  }
747
2443
  /**
748
2444
  * Answers a TRACK stream (0x6) with a single TRACK_INFO, then FINs.
749
2445
  *
2446
+ * The open stream is interest in the track, held until the requester closes its side,
2447
+ * so demand holds while the requester moves on to SUBSCRIBE. Only the reply is owed.
2448
+ *
750
2449
  * @internal
751
2450
  */
752
2451
  async runTrackInfo(msg, stream) {
2452
+ const hold = new AbortController();
2453
+ // Armed before the first check and held until the answer is acknowledged, so a grant
2454
+ // that shrinks while the answer is blocked on flow control resets it, never sends it.
2455
+ const watch = this.#gate.watch(msg.broadcast, () => {
2456
+ console.debug(`track info revoked: broadcast=${msg.broadcast} track=${msg.track}`);
2457
+ hold.abort();
2458
+ stream.writer.reset(unauthorized(msg.broadcast));
2459
+ });
2460
+ if (watch.revoked()) {
2461
+ watch.dispose();
2462
+ hold.abort();
2463
+ stream.writer.reset(unauthorized(msg.broadcast));
2464
+ return;
2465
+ }
2466
+ // Watched from the start, so a requester leaving while the reply is still blocked on
2467
+ // flow control lets go of the track too.
2468
+ void stream.reader.done().then((fin) => {
2469
+ hold.abort();
2470
+ if (fin)
2471
+ return;
2472
+ // TRACK is the requester's only message, so more breaks the session, as in Rust.
2473
+ const violation = new ProtocolViolation("data after TRACK");
2474
+ closeViolation(this.#quic, violation);
2475
+ stream.abort(violation);
2476
+ }, () => hold.abort());
753
2477
  try {
754
- const front = this.#publish &&
755
- (wireOf(this.#publish).local(msg.broadcast) ?? (await wireOf(this.#publish).demand(msg.broadcast)));
2478
+ const front = await this.#resolve(msg, hold.signal);
756
2479
  if (!front)
757
2480
  throw new NotFound(`broadcast ${msg.broadcast}`);
758
- const info = await this.#resolveTrackInfo(front, msg.track);
2481
+ let info;
2482
+ let datagrams;
2483
+ try {
2484
+ info = await this.#resolveTrackInfo(front, msg.track, hold.signal);
2485
+ }
2486
+ catch (err) {
2487
+ if (!hasDatagrams(this.version) ||
2488
+ hasDatagramTracks(this.version) ||
2489
+ toStreamCode(error(err)) !== StreamCode.NotFound)
2490
+ throw err;
2491
+ const asked = front.datagrams(msg.track);
2492
+ try {
2493
+ info = trackInfoMessage(datagramTrackInfo(await untilAborted(asked.info(), hold.signal)), this.version);
2494
+ }
2495
+ catch (err) {
2496
+ asked.close();
2497
+ throw err;
2498
+ }
2499
+ datagrams = asked;
2500
+ }
2501
+ // Lite-05/06: the name's datagram track, read from this answer on, held for the
2502
+ // SUBSCRIBE alongside, beside a stream track too.
2503
+ if (hasDatagrams(this.version) && !hasDatagramTracks(this.version)) {
2504
+ datagrams ??= wireOf(front).liveDatagrams(msg.track);
2505
+ }
2506
+ if (datagrams)
2507
+ this.#holdDatagrams(datagrams, hold.signal);
2508
+ if (watch.revoked())
2509
+ throw unauthorized(msg.broadcast);
759
2510
  await info.encode(stream.writer, this.version);
760
2511
  console.debug(`track info: broadcast=${msg.broadcast} track=${msg.track}`);
761
- stream.close();
2512
+ stream.writer.close();
2513
+ await acknowledged(stream.writer);
762
2514
  }
763
2515
  catch (err) {
2516
+ hold.abort();
764
2517
  console.debug(`track unknown: broadcast=${msg.broadcast} track=${msg.track}`);
765
- stream.writer.reset(error(err));
2518
+ stream.writer.reset(servedError(error(err)));
2519
+ }
2520
+ finally {
2521
+ watch.dispose();
766
2522
  }
767
2523
  }
2524
+ /**
2525
+ * Answers a TRACKS stream (0x8): the broadcast's listed tracks, SYNCED, then each change,
2526
+ * until the broadcast ends (FIN) or a newer listing of it on this session replaces this one.
2527
+ *
2528
+ * Each listing queues the broadcast's whole listed set, so the session lists each broadcast
2529
+ * once: a newer listing replaces the older rather than being refused, since a subscriber
2530
+ * that stops listing and lists again can open the new stream before we see the old one
2531
+ * close. The requester's FIN or reset cancels it. Not owed: it lasts as long as the broadcast.
2532
+ *
2533
+ * @internal
2534
+ */
2535
+ async runTracks(msg, stream) {
2536
+ const cancel = new AbortController();
2537
+ const watch = this.#gate.watch(msg.broadcast, () => {
2538
+ console.debug(`tracks revoked: broadcast=${msg.broadcast}`);
2539
+ cancel.abort(unauthorized(msg.broadcast));
2540
+ });
2541
+ // TRACKS is the requester's only message: its FIN or reset ends the listing.
2542
+ void stream.reader.done().then((fin) => {
2543
+ if (fin) {
2544
+ cancel.abort(new StreamError(StreamCode.Cancel, { message: "listing cancelled" }));
2545
+ return;
2546
+ }
2547
+ const violation = new ProtocolViolation("data after TRACKS");
2548
+ closeViolation(this.#quic, violation);
2549
+ cancel.abort(violation);
2550
+ }, (err) => cancel.abort(error(err)));
2551
+ let tracks;
2552
+ try {
2553
+ if (watch.revoked())
2554
+ throw unauthorized(msg.broadcast);
2555
+ const front = await this.#resolve(msg, cancel.signal);
2556
+ if (!front)
2557
+ throw new NotFound(`broadcast ${msg.broadcast}`);
2558
+ tracks = wireOf(front).tracks(this);
2559
+ console.debug(`tracks: broadcast=${msg.broadcast}`);
2560
+ for (;;) {
2561
+ // Pull an event only once the last is written, so a stalled requester's changes
2562
+ // collapse in the listing's queue rather than pile up here.
2563
+ const event = await untilAborted(tracks.next(), cancel.signal);
2564
+ if (!event)
2565
+ break;
2566
+ await untilAborted(encodeTracksEvent(stream.writer, tracksEvent(event, this.version), this.version), cancel.signal);
2567
+ }
2568
+ stream.writer.close();
2569
+ }
2570
+ catch (err) {
2571
+ const e = cancel.signal.aborted ? error(cancel.signal.reason) : error(err);
2572
+ console.debug(`tracks end: broadcast=${msg.broadcast} error=${reason(e)}`);
2573
+ stream.writer.reset(servedError(e));
2574
+ }
2575
+ finally {
2576
+ tracks?.close();
2577
+ watch.dispose();
2578
+ }
2579
+ }
2580
+ // Hold `consumer`'s track from its position for the SUBSCRIBE alongside until `hold`
2581
+ // aborts, as a passive observer in place of `consumer`.
2582
+ #holdDatagrams(consumer, hold) {
2583
+ const held = hooks.observeDatagramConsumer(consumer);
2584
+ consumer.close();
2585
+ this.#heldDatagrams.add(held);
2586
+ const release = () => {
2587
+ this.#heldDatagrams.delete(held);
2588
+ held.close();
2589
+ };
2590
+ if (hold.aborted)
2591
+ release();
2592
+ else
2593
+ hold.addEventListener("abort", release, { once: true });
2594
+ }
2595
+ // `consumer`, or a clone of the oldest hold of the same track, read from that hold's answer on.
2596
+ // Several TRACKs of one track may be open, and the SUBSCRIBE could follow any of them, so it
2597
+ // reads from the earliest answer: a replay only duplicates, a later one would lose.
2598
+ #adopt(consumer) {
2599
+ for (const held of this.#heldDatagrams) {
2600
+ if (!hooks.datagramSameTrack(held, consumer))
2601
+ continue;
2602
+ consumer.close();
2603
+ return held.clone();
2604
+ }
2605
+ return consumer;
2606
+ }
768
2607
  // Resolve (and cache) a track's immutable TRACK_INFO by asking the application.
769
2608
  // `resolveTrackInfo` triggers a TrackRequest the app answers with accept(TrackInfo);
770
2609
  // only the immutable properties are needed (not the groups). Cached because they're
771
- // fixed for the track's lifetime. Rejects if the track is unavailable.
772
- #resolveTrackInfo(front, track) {
2610
+ // fixed for the track's lifetime. Rejects if the track is unavailable, or once `hold`
2611
+ // aborts. Each requester holds the lookup until `hold` aborts, and the lookup ends with
2612
+ // its last holder, answered or not, so the next requester asks again.
2613
+ #resolveTrackInfo(front, track, hold) {
2614
+ hold.throwIfAborted();
773
2615
  let tracks = this.#trackInfo.get(front);
774
2616
  if (!tracks) {
775
2617
  tracks = new Map();
776
2618
  this.#trackInfo.set(front, tracks);
777
2619
  }
778
- const cached = tracks.get(track);
779
- if (cached !== undefined)
780
- return cached;
781
- const pending = (async () => {
782
- const info = await wireOf(front).resolveTrackInfo(track);
783
- return new TrackInfoMessage({
784
- priority: info.priority,
785
- // Publisher Max Age: the publisher's retention bound, advertised so
786
- // relays re-serve with the same window.
787
- maxAge: info.maxAge,
788
- // Lite05 mandates per-frame timestamps. Advertise the track's timescale;
789
- // `#serveGroup` emits each frame converted to it.
790
- timescale: info.timescale,
2620
+ let entry = tracks.get(track);
2621
+ if (!entry) {
2622
+ const release = new AbortController();
2623
+ const info = (async () => trackInfoMessage(await wireOf(front).resolveTrackInfo(track, release.signal), this.version))();
2624
+ const created = { info, holders: 0, release };
2625
+ // Don't poison the cache on failure: a later request may succeed.
2626
+ info.catch(() => {
2627
+ if (tracks.get(track) === created)
2628
+ tracks.delete(track);
791
2629
  });
2630
+ tracks.set(track, created);
2631
+ entry = created;
2632
+ }
2633
+ const held = entry;
2634
+ held.holders++;
2635
+ hold.addEventListener("abort", () => {
2636
+ if (--held.holders > 0)
2637
+ return;
2638
+ if (tracks.get(track) === held)
2639
+ tracks.delete(track);
2640
+ held.release.abort();
2641
+ }, { once: true });
2642
+ return untilAborted(held.info, hold);
2643
+ }
2644
+ /** Serve a lite-07 datagram-track request until its publisher or subscriber ends it. */
2645
+ async runDatagrams(msg, stream) {
2646
+ const cancel = new AbortController();
2647
+ let track;
2648
+ const watch = this.#gate.watch(msg.broadcast, () => cancel.abort(unauthorized(msg.broadcast)));
2649
+ let updates;
2650
+ try {
2651
+ if (watch.revoked())
2652
+ throw unauthorized(msg.broadcast);
2653
+ if (!this.#datagramWriter)
2654
+ throw new Error("transport does not support datagrams");
2655
+ // Read updates from dispatch so a requester leaving releases even an unanswered lookup.
2656
+ updates = (async () => {
2657
+ let next = msg.priority;
2658
+ for (;;) {
2659
+ const yielded = datagramBudget.poll();
2660
+ if (yielded !== undefined)
2661
+ await yielded;
2662
+ const update = await DatagramsUpdate.decodeMaybe(stream.reader, this.version);
2663
+ if (!update)
2664
+ return;
2665
+ next = update.priority;
2666
+ msg.priority = next;
2667
+ track?.setPriority(next);
2668
+ }
2669
+ })();
2670
+ void updates.then(() => cancel.abort(new StreamError(StreamCode.Cancel)), (err) => {
2671
+ closeViolation(this.#quic, err);
2672
+ cancel.abort(error(err));
2673
+ });
2674
+ const front = await this.#resolve(msg, cancel.signal);
2675
+ if (!front)
2676
+ throw new NotFound(`broadcast ${msg.broadcast}`);
2677
+ track = front.datagrams(msg.track);
2678
+ track.setPriority(msg.priority);
2679
+ const info = await untilAborted(track.info(), cancel.signal);
2680
+ await untilAborted(new DatagramsInfo(info).encode(stream.writer, this.version), cancel.signal);
2681
+ await untilAborted(this.#runDatagrams(track, { sub: msg.id, stamp: stamping(this.version, info) }), cancel.signal);
2682
+ stream.writer.close();
2683
+ await updates;
2684
+ }
2685
+ catch (err) {
2686
+ // Only the update reader's own errors close the session, above; the track's end here.
2687
+ stream.abort(error(err));
2688
+ }
2689
+ finally {
2690
+ track?.close();
2691
+ watch.dispose();
2692
+ stream.reader.stop(StreamCode.Cancel);
2693
+ await updates?.catch(() => { });
2694
+ }
2695
+ }
2696
+ // Lite-05/06: a name with no stream track serves its datagram track alone.
2697
+ async #serveLegacyDatagrams(front, msg, stream, signal) {
2698
+ const track = this.#adopt(front.datagrams(msg.track));
2699
+ track.setPriority(msg.priority);
2700
+ const sent = new DatagramEnd();
2701
+ const updates = (async () => {
2702
+ for (;;) {
2703
+ const yielded = datagramBudget.poll();
2704
+ if (yielded !== undefined)
2705
+ await yielded;
2706
+ const update = await SubscribeUpdate.decodeMaybe(stream.reader, this.version);
2707
+ if (!update)
2708
+ return;
2709
+ track.setPriority(update.priority);
2710
+ }
792
2711
  })();
793
- // Don't poison the cache on failure: a later request may succeed.
794
- pending.catch(() => tracks.delete(track));
795
- tracks.set(track, pending);
796
- return pending;
2712
+ void updates.then(() => track.close(), (err) => {
2713
+ closeViolation(this.#quic, err);
2714
+ track.close(error(err));
2715
+ });
2716
+ try {
2717
+ const info = await untilAborted(track.info(), signal);
2718
+ await encodeSubscribeResponse(stream.writer, { start: new SubscribeStart({ id: 0n, start: 0n, largest: "unknown" }) }, this.version);
2719
+ await untilAborted(this.#runDatagrams(track, { sub: msg.id, stamp: stamping(this.version, info), sent }), signal);
2720
+ // No stream track holds groups below the end, so every key is dropped, and the subscriber
2721
+ // settles without its tail grace.
2722
+ const settled = sent.settle(0n);
2723
+ if (settled.span) {
2724
+ const [from, to] = settled.span;
2725
+ const drop = new SubscribeDrop({ start: from, end: to });
2726
+ await encodeSubscribeResponse(stream.writer, { drop }, this.version);
2727
+ }
2728
+ await encodeSubscribeResponse(stream.writer, { end: new SubscribeEnd(settled.end) }, this.version);
2729
+ stream.writer.close();
2730
+ await updates;
2731
+ }
2732
+ finally {
2733
+ track.close();
2734
+ stream.reader.stop(StreamCode.Cancel);
2735
+ await updates.catch(() => { });
2736
+ }
797
2737
  }
798
- /**
799
- * Forwards a track's datagrams best-effort over QUIC datagrams (lite-05 §6.4), parallel to
800
- * its groups. Each datagram is dropped (there is no group fallback) if the encoded body
801
- * doesn't fit the transport's datagram limit or the send fails. Returns once the track
802
- * finishes; a failure never tears down the subscription.
803
- *
804
- * @internal
805
- */
806
- async #runDatagrams(sub, track, timescale) {
807
- const writer = this.#datagramWriter;
808
- if (!writer)
809
- return; // Only reached with a writer (see the #datagramWriter gate).
810
- const maxSize = DatagramStream.maxDatagramSize(this.#quic);
2738
+ // Shared by dedicated lite-07 requests and the old SUBSCRIBE carry-both mapping.
2739
+ async #runDatagrams(track, options) {
2740
+ if (!this.#datagramWriter)
2741
+ throw new Error("transport does not support datagrams");
2742
+ const info = await track.info();
2743
+ const priority = options.priority ?? hooks.datagramPriority(track);
2744
+ const rank = () => sendOrder({ priority: priority.peek(), publisher: info.priority });
2745
+ const sender = this.#datagramWriter.open(rank());
2746
+ const dispose = priority.subscribe(() => sender.setPriority(rank()));
2747
+ const left = hooks.datagramClosed(track);
2748
+ const { writer } = sender;
2749
+ const maxSize = Math.min(DatagramMessage.MAX_SIZE, DatagramStream.maxDatagramSize(this.#quic));
811
2750
  try {
812
2751
  for (;;) {
813
- const datagram = await track.recvDatagram();
814
- if (!datagram)
815
- return; // Track finished; #runTrack tears the subscription down.
816
- // Convert the timestamp to the track's advertised timescale, matching #serveGroup.
817
- const ts = Math.round(datagram.timestamp.as(timescale));
818
- const body = new DatagramMessage(sub, datagram.sequence, ts, datagram.payload).encode(this.version);
819
- // No group fallback: drop anything that doesn't fit a single datagram.
2752
+ const next = await hooks.recvDatagramWire(track);
2753
+ if (!next)
2754
+ return;
2755
+ const { datagram, wire } = next;
2756
+ // The key before any rescaling, so datagrams a microsecond apart keep distinct
2757
+ // sequences on a version that carries one.
2758
+ const sequence = wire ?? BigInt(datagram.timestamp.value);
2759
+ // An old subscription uses its stream track's timescale for both kinds. Without one
2760
+ // the track is a scale-less lite-07 one, whose timestamp goes out bare.
2761
+ const timestamp = wireTime(datagram.timestamp, options.stamp ?? {});
2762
+ const body = new DatagramMessage(options.sub, hasDatagramTracks(this.version) ? undefined : sequence, timestamp, datagram.payload).encode(this.version);
820
2763
  if (body.byteLength > maxSize) {
821
- console.debug(`dropping oversize datagram: sub=${sub} size=${body.byteLength} max=${maxSize}`);
2764
+ console.debug(`dropping oversize datagram: sub=${options.sub} size=${body.byteLength} max=${maxSize}`);
822
2765
  continue;
823
2766
  }
824
- await writer.ready;
2767
+ // The legacy writer is shared, so another request's write can hold back this one:
2768
+ // stop waiting once this request ends, and send nothing after it does.
2769
+ // Raced directly, so a ready writer drops its close listener rather than keep one per send.
2770
+ await race([writer.ready, left]);
2771
+ // As recv() does: a clean close ends the request, an error close fails it.
2772
+ const reason = left.peek();
2773
+ if (reason !== undefined) {
2774
+ if (reason)
2775
+ throw reason;
2776
+ return;
2777
+ }
2778
+ // Counted as it is handed over, since the end may settle while the write is pending.
2779
+ if (!hasDatagramTracks(this.version))
2780
+ options.sent?.record(sequence);
825
2781
  await writer.write(body);
826
2782
  }
827
2783
  }
828
- catch (err) {
829
- // Best-effort: a datagram send failure stops sending but never fails the subscription.
830
- console.debug(`datagram send stopped: sub=${sub} error=${reason(err)}`);
831
- }
832
- }
833
- // Serialize a fetched group's frames onto the FETCH stream as bare records: each a
834
- // zigzag-delta timestamp (at the track's advertised timescale) followed by size + bytes.
835
- async #runFetchGroup(group, stream, { timescale, start: startFrame, end: endFrame }) {
836
- // The response carries no header, so the receiver numbers the first frame it gets
837
- // as `startFrame`. Skipping the head here is the only thing keeping those numbers
838
- // honest; a group that ends before we reach it can't be served at all.
839
- for (let i = 0; i < startFrame; i++) {
840
- if (!(await race([group.readFrame(), stream.closed]))) {
841
- throw new Error(`fetch group ended at frame ${i}, before the requested start ${startFrame}`);
842
- }
843
- }
844
- let prevTs = 0n;
845
- for (let index = startFrame; endFrame === undefined || index <= endFrame; index++) {
846
- const frame = await race([group.readFrame(), stream.closed]);
847
- if (!frame)
848
- break;
849
- const ts = BigInt(Math.round(frame.timestamp.as(timescale)));
850
- await stream.u62(zigzag(ts - prevTs));
851
- prevTs = ts;
852
- await stream.u53(frame.payload.byteLength);
853
- await stream.write(frame.payload);
2784
+ finally {
2785
+ dispose();
2786
+ await sender.close();
854
2787
  }
855
2788
  }
856
2789
  /**
857
2790
  * Opens the unidirectional stream for one group, or closes the group and resolves
858
- * `undefined` when it cannot get one.
2791
+ * an error when it cannot get one.
859
2792
  *
860
2793
  * @internal
861
2794
  */
862
2795
  async #openGroup(options) {
863
- const { group, priority, unsubscribed } = options;
2796
+ const { group, givenUp, priority, ranking, unsubscribed, start } = options;
864
2797
  try {
865
- // The transport drains streams by send order, so this is what makes a high-priority
866
- // track (and a newer group within it) win the link when there isn't room for both.
867
- //
868
- // One stream per group is faster than a peer at its limit can retire them, so this
869
- // is the one path that doesn't wait for a slot: the transport would serve the opens
870
- // in the order we asked, which is oldest-first, exactly backwards for live media.
871
- // Failing here drops the group and lets the next one compete for the next slot.
872
- const stream = await Writer.tryOpen(this.#quic, {
873
- version: this.version,
874
- sendOrder: priority.rank(group.sequence),
875
- cancel: unsubscribed,
876
- waitUntilAvailable: false,
2798
+ // The transport drains streams by send order, and opens wait for stream credit in
2799
+ // it, so this is what makes a high-priority track (and a newer group within it) win
2800
+ // the link and the peer's credit when there isn't room for both. The place ranks the
2801
+ // open against the subscription's other groups while it waits.
2802
+ // Watch the group while the open waits, and release that watch once it settles.
2803
+ const place = priority.reserve(group.start, start, ranking);
2804
+ const opened = Promise.withResolvers();
2805
+ let failure;
2806
+ const abandoned = givenUp
2807
+ .write(() => opened.promise)
2808
+ .then((stop) => {
2809
+ failure = stop;
877
2810
  });
878
- if (!stream)
879
- group.close(new Error("no stream slot"));
2811
+ let stream;
2812
+ try {
2813
+ stream = await Writer.tryOpen(this.#quic, {
2814
+ version: this.version,
2815
+ sendOrder: place.rank,
2816
+ cancel: race([unsubscribed, abandoned]),
2817
+ group: true,
2818
+ });
2819
+ }
2820
+ finally {
2821
+ opened.resolve();
2822
+ place.release();
2823
+ }
2824
+ if (!stream) {
2825
+ const failed = failure ?? new Error("unsubscribed while waiting for a stream");
2826
+ hooks.releaseGroupReader(group, failed);
2827
+ return failed;
2828
+ }
880
2829
  return stream;
881
2830
  }
882
2831
  catch (err) {
883
- group.close(error(err));
884
- return undefined;
2832
+ const failed = error(err);
2833
+ hooks.releaseGroupReader(group, failed);
2834
+ return failed;
885
2835
  }
886
2836
  }
887
2837
  /**
888
- * Serves one group on the stream {@link #openGroup} opened for it.
2838
+ * Serves one group on the stream {@link #openGroup} opened for it, resolving the error a
2839
+ * SUBSCRIBE_DROP names it with, or undefined when the stream accounts for the group.
889
2840
  *
890
2841
  * @internal
891
2842
  */
892
2843
  async #serveGroup(stream, options) {
893
- const { sub, group, timescale, priority, start: startFrame, end: endFrame } = options;
894
- // This model holds whole groups, so frame `startFrame` is always reachable unless
895
- // the group ends first. Declaring it up front keeps the stream self-describing.
896
- const msg = new GroupMessage({ subscribe: sub, sequence: group.sequence, frameStart: startFrame });
2844
+ const { sub, group, givenUp, stamp, compress, priority, ranking, start: startFrame, end: endFrame, stops, } = options;
2845
+ // The header names the requested position, so a copy missing it must be refused.
2846
+ const msg = new GroupMessage({ subscribe: sub, key: group.start, frameStart: startFrame });
2847
+ // The subscription's budget, or an eviction of what is left to read, may give up on the
2848
+ // group mid-write, which abandons the stream. A group already given up never starts the write.
2849
+ const write = async (op) => {
2850
+ const stop = await givenUp.write(op);
2851
+ if (stop)
2852
+ throw stop;
2853
+ };
2854
+ // Lite-07: the transport took the whole GROUP header, which every later reset still delivers.
2855
+ let held = false;
2856
+ // Lite-07: the end of the span a buffered GROUP_END accounted for.
2857
+ let spanEnd;
897
2858
  // Everything past this point runs inside the cleanup scope, so a failure never leaves
898
2859
  // a finished group's stream being ranked.
899
2860
  try {
2861
+ if (hooks.groupIndex(group) > startFrame)
2862
+ throw new Error(`group lacks frame ${startFrame}`);
900
2863
  // A SUBSCRIBE_UPDATE re-ranks the subscription, so a group already on the wire
901
2864
  // follows it too rather than keeping a stale rank until it finishes.
902
- priority.add(stream, group.sequence);
903
- await hooks.guardGroup(group, async () => {
2865
+ priority.add(stream, group.start, startFrame, ranking);
2866
+ await write(async () => {
904
2867
  await stream.u53(0); // stream type
905
2868
  await msg.encode(stream, this.version);
906
2869
  });
907
- // Lite05+ prefixes every frame with a zigzag-delta timestamp at the track's
908
- // advertised timescale; older drafts omit it.
909
- const timestamps = supportsTrackStream(this.version);
910
- let prevTs = 0n;
2870
+ if (hasReliableReset(this.version))
2871
+ held = stream.hold();
2872
+ // Lite-07 omits frame 0's delta, since the group starts at it, counts a later stream's first
2873
+ // delta from the group's start, and GROUP_END from the last timestamp sent.
2874
+ let prevTs = hasGroupEnd(this.version) ? group.start : 0n;
2875
+ let implicit = startFrame === 0;
911
2876
  // Whether the cursor ever reached the requested start, which decides how the
912
- // end of the group is read below.
913
- let reached = startFrame === 0;
2877
+ // end of the group is read below. A received tail may already begin there.
2878
+ let reached = hooks.groupIndex(group) === startFrame;
2879
+ // Whether every frame went out, which a finished group's GROUP_END then claims.
2880
+ let whole = false;
2881
+ // Kept across loop iterations so waking on a Position End change never starts a
2882
+ // second concurrent readGroupFrame(), and stream.closed is derived lazily once
2883
+ // the first read starts (avoiding unhandled rejections if a cap breaks early).
2884
+ let pendingRead;
2885
+ let closed;
2886
+ const stopWake = Symbol("stop-wake");
2887
+ // Track the next unsent frame index separately from `hooks.groupIndex(group)`,
2888
+ // which an in-flight `pendingRead` may advance before its frame is consumed.
2889
+ let nextUnsent = Math.max(hooks.groupIndex(group), startFrame);
914
2890
  for (;;) {
915
- const read = await race([hooks.readGroupFrame(group), stream.closed]);
2891
+ // Lite-07: reaching a Position end closes the stream cleanly without GROUP_END
2892
+ // (a slice, not the whole group) instead of parking open. If the group itself
2893
+ // already finished at or before `nextUnsent`, let the read below observe EOF so
2894
+ // GROUP_END is still sent.
2895
+ const stopBefore = stops?.at.peek().get(group.start);
2896
+ const settled = hooks.groupSettledFrames(group);
2897
+ if (((stopBefore !== undefined && nextUnsent >= stopBefore) ||
2898
+ (endFrame !== undefined && nextUnsent > endFrame)) &&
2899
+ (settled === undefined || settled > nextUnsent)) {
2900
+ pendingRead?.catch(() => { });
2901
+ closed?.catch(() => { });
2902
+ break;
2903
+ }
2904
+ pendingRead ??= hooks.readGroupFrame(group, compress, 0, options.meta);
2905
+ closed ??= stream.closed.then(() => undefined);
2906
+ let disposeStop;
2907
+ let outcome;
2908
+ try {
2909
+ if (stops) {
2910
+ const moved = new Promise((resolve) => {
2911
+ disposeStop = stops.at.changed(() => resolve(stopWake));
2912
+ });
2913
+ outcome = await race([pendingRead, closed, moved]);
2914
+ }
2915
+ else {
2916
+ outcome = await race([pendingRead, closed]);
2917
+ }
2918
+ }
2919
+ finally {
2920
+ disposeStop?.();
2921
+ }
2922
+ if (outcome === stopWake)
2923
+ continue;
2924
+ pendingRead = undefined;
2925
+ const read = outcome;
916
2926
  if (!read) {
917
2927
  // The group ended before the frame the subscriber asked to start
918
2928
  // at, so this publisher can't serve the range at all. FINning here
@@ -920,38 +2930,76 @@ export class Publisher {
920
2930
  // as the gap it is.
921
2931
  if (!reached)
922
2932
  throw new Error(`group ended before frame ${startFrame}`);
2933
+ whole = true;
923
2934
  break;
924
2935
  }
925
- try {
926
- // A group that ends exactly at the start is a valid, empty range.
927
- if (read.sequence + 1 >= startFrame)
928
- reached = true;
929
- // Frames below the requested start were excluded, and the receiver
930
- // numbers what it gets from `startFrame`.
931
- if (read.sequence < startFrame)
932
- continue;
933
- if (endFrame !== undefined && read.sequence > endFrame)
934
- break;
935
- if (timestamps) {
936
- // Convert each frame to the track's advertised timescale.
937
- const ts = BigInt(Math.round(read.frame.timestamp.as(timescale)));
938
- await hooks.guardGroup(group, () => stream.u62(zigzag(ts - prevTs)));
939
- prevTs = ts;
940
- }
941
- await hooks.guardGroup(group, () => stream.u53(read.frame.payload.byteLength));
942
- await hooks.guardGroup(group, () => stream.write(read.frame.payload));
2936
+ // A group that ends exactly at the start is a valid, empty range.
2937
+ if (read.index + 1 >= startFrame)
2938
+ reached = true;
2939
+ // Frames below the requested start were excluded, and the receiver
2940
+ // numbers what it gets from `startFrame`.
2941
+ if (read.index < startFrame) {
2942
+ nextUnsent = Math.max(nextUnsent, read.index + 1);
2943
+ continue;
943
2944
  }
944
- finally {
945
- read.complete();
2945
+ const stop = stops?.at.peek().get(group.start);
2946
+ if ((endFrame !== undefined && read.index > endFrame) || (stop !== undefined && read.index >= stop)) {
2947
+ break;
2948
+ }
2949
+ nextUnsent = read.index + 1;
2950
+ let delta;
2951
+ if (stamp !== undefined) {
2952
+ // Convert each frame to the track's wire timescale.
2953
+ const ts = wireTime(read.frame.timestamp, stamp);
2954
+ delta = ts - prevTs;
2955
+ prevTs = ts;
946
2956
  }
2957
+ const header = options.meta
2958
+ ? frameHeader(stream.version, delta, undefined, read.inflated ?? readSize(read), true, implicit)
2959
+ : frameHeader(stream.version, delta, read.inflated, readSize(read), hasLengthFirst(this.version), implicit);
2960
+ implicit = false;
2961
+ // A metadata FRAME is its header: the frame's bytes are never read, so nothing waits for them.
2962
+ const chunks = options.meta ? undefined : read.chunks;
2963
+ const payload = options.meta || chunks ? undefined : read.frame.payload;
2964
+ // One budget race covers the frame's header and payload.
2965
+ await write(async () => {
2966
+ await stream.write(header);
2967
+ if (chunks)
2968
+ await sendPayload(chunks, (chunk) => stream.write(chunk), stream.closed);
2969
+ else if (payload && payload.length > 0)
2970
+ await stream.write(payload);
2971
+ });
2972
+ }
2973
+ // Lite-07 ends a finished group with GROUP_END, after one frame at least on a stream from
2974
+ // frame 0, since a group starts at its first frame.
2975
+ const end = hasGroupEnd(this.version) && whole && !(implicit && startFrame === 0) ? group.end : undefined;
2976
+ if (end !== undefined) {
2977
+ options.ended?.(end);
2978
+ spanEnd = end;
2979
+ await write(() => stream.write(groupEnd(stream.version, end, prevTs)));
947
2980
  }
948
2981
  stream.close();
949
2982
  group.close();
2983
+ // A stream that fails after its FIN may have lost its header, so report it for a DROP,
2984
+ // unless a lite-07 reset still delivers it. Its bytes still hold the connection until
2985
+ // acknowledged, so a group gone stale meanwhile is reset like one still serving, as the
2986
+ // Rust `GroupServe` does: stale bytes must not fill the send window ahead of the streams
2987
+ // behind them.
2988
+ await write(() => stream.closed);
2989
+ return undefined;
950
2990
  }
951
2991
  catch (err) {
952
- const e = error(err);
2992
+ const e = servedError(error(err));
2993
+ options.resetting?.();
953
2994
  stream.reset(e);
954
- group.close(e);
2995
+ hooks.releaseGroupReader(group, e);
2996
+ if (hasReliableReset(this.version) && (await accounts(stream, held))) {
2997
+ // The reset may cut the GROUP_END, so the starts it accounted for are named again.
2998
+ if (spanEnd !== undefined && spanEnd > group.start + 1n)
2999
+ options.cut?.(group.start + 1n, spanEnd);
3000
+ return undefined;
3001
+ }
3002
+ return e;
955
3003
  }
956
3004
  finally {
957
3005
  priority.remove(stream);
@@ -964,9 +3012,8 @@ export class Publisher {
964
3012
  * @internal
965
3013
  */
966
3014
  async runProbe(stream) {
967
- // getStats is not yet in the TypeScript WebTransport type definitions.
968
- const quic = this.#quic;
969
- if (!quic.getStats) {
3015
+ const getStats = statsOf(this.#quic);
3016
+ if (!getStats) {
970
3017
  // Best-effort: we can't supply bandwidth estimates, so close the
971
3018
  // whole bidi (FIN + STOP_SENDING) to let the peer release its end.
972
3019
  stream.close();
@@ -985,23 +3032,40 @@ export class Publisher {
985
3032
  return next !== 0;
986
3033
  return Math.abs(next - prev) / prev >= threshold;
987
3034
  };
3035
+ const ended = new Once();
3036
+ const reading = (async () => {
3037
+ // Report ignores target values, but must consume them to observe the FIN.
3038
+ while (await Probe.decodeMaybe(stream.reader, this.version)) { }
3039
+ })().then(() => ended.set(null), (err) => {
3040
+ closeViolation(this.#quic, err);
3041
+ ended.set(error(err));
3042
+ });
988
3043
  try {
989
3044
  for (;;) {
990
- const timeout = new Promise((resolve) => setTimeout(() => resolve("timeout"), PROBE_INTERVAL));
991
- const result = await race([timeout, stream.reader.closed]);
3045
+ const timer = new AbortController();
3046
+ const timeout = sleep(Duration.millis(PROBE_INTERVAL), { signal: timer.signal }).then(() => "timeout", () => "timeout");
3047
+ let result;
3048
+ try {
3049
+ result = await race([timeout, ended]);
3050
+ }
3051
+ finally {
3052
+ timer.abort();
3053
+ }
3054
+ if (result instanceof Error)
3055
+ throw result;
992
3056
  if (result !== "timeout")
993
3057
  break;
994
3058
  // The two fields are independent on the wire, each using 0 for
995
3059
  // unknown, so a transport exposing only one still has something to
996
3060
  // report. Anything this version can't carry is dropped here rather
997
3061
  // than by the encoder, so it reads as unknown to every check below.
998
- const stats = await quic.getStats();
3062
+ const stats = await getStats();
999
3063
  // `smoothedRtt` is a DOMHighResTimeStamp, i.e. a double, but the wire
1000
3064
  // carries whole milliseconds and the varint encoder throws on a
1001
3065
  // fractional value. Round before it ever reaches `Probe`.
1002
3066
  const rtt = stats.smoothedRtt != null ? Math.round(stats.smoothedRtt) : undefined;
1003
3067
  const report = new Probe({
1004
- bitrate: stats.estimatedSendRate ?? undefined,
3068
+ bitrate: probeBitrate(stats.estimatedSendRate),
1005
3069
  rtt: hasProbeRtt(this.version) ? rtt : undefined,
1006
3070
  });
1007
3071
  // Nothing left to report. Say so once if it retracts a value the peer
@@ -1017,7 +3081,7 @@ export class Publisher {
1017
3081
  shouldSend = true;
1018
3082
  }
1019
3083
  else {
1020
- const elapsed = performance.now() - lastSentTime;
3084
+ const elapsed = now().since(lastSentTime).asMillis();
1021
3085
  // The bitrate threshold decays to zero as the last report ages: a
1022
3086
  // stale estimate is worth refreshing for a smaller move.
1023
3087
  const t = Math.max(PROBE_INTERVAL, Math.min(PROBE_MAX_AGE, elapsed));
@@ -1031,20 +3095,67 @@ export class Publisher {
1031
3095
  if (shouldSend) {
1032
3096
  await report.encode(stream.writer, this.version);
1033
3097
  lastSent = report;
1034
- lastSentTime = performance.now();
3098
+ lastSentTime = now();
1035
3099
  }
1036
3100
  }
1037
3101
  }
1038
3102
  catch (err) {
3103
+ closeViolation(this.#quic, err);
1039
3104
  console.warn("probe stream error", err);
3105
+ }
3106
+ finally {
1040
3107
  stream.close();
3108
+ await reading;
1041
3109
  }
1042
3110
  }
3111
+ /**
3112
+ * Close the session when our origin publishes a broadcast our grant does not cover;
3113
+ * see {@link enforceGrant}.
3114
+ *
3115
+ * @internal
3116
+ */
3117
+ async runEnforce(setupAnswered, auth) {
3118
+ if (!this.#grant)
3119
+ return;
3120
+ await enforceGrant({ quic: this.#quic, advertised: this.#advertised, grant: this.#grant, setupAnswered, auth });
3121
+ }
3122
+ /**
3123
+ * Owes the peer `task`, a served SUBSCRIBE, DATAGRAMS, or TRACK request, until it ends.
3124
+ *
3125
+ * @internal
3126
+ */
3127
+ owe(task) {
3128
+ const tracked = task.finally(() => this.#owed.delete(tracked));
3129
+ this.#owed.add(tracked);
3130
+ return tracked;
3131
+ }
3132
+ /**
3133
+ * Withdraws announcements and waits for every owed request to end, including any that
3134
+ * arrive meanwhile. Rejects if a withdrawal failed; an owed request ends either way.
3135
+ *
3136
+ * @internal
3137
+ */
3138
+ async drain() {
3139
+ const [withdrawn] = await Promise.allSettled([
3140
+ // Lite-07: the stream finishes once every route on it is ended, which says this side is leaving.
3141
+ this.#withdrawal.close().then(async () => {
3142
+ if (hasRoutes(this.version))
3143
+ await AnnounceStream.of(this.#quic, this.version).finish();
3144
+ }),
3145
+ ]);
3146
+ // Only after the withdrawals, so a request that arrived while they were in flight is
3147
+ // waited for too. Owed requests run on their own meanwhile, so this adds no delay.
3148
+ while (this.#owed.size > 0)
3149
+ await Promise.allSettled(this.#owed);
3150
+ if (withdrawn.status === "rejected")
3151
+ throw withdrawn.reason;
3152
+ }
1043
3153
  close() {
1044
3154
  // The broadcasts belong to the origin, which outlives this session; closing here
1045
3155
  // only drops the borrow. The peer sees the unannounce when the streams die.
3156
+ this.#answer?.close();
1046
3157
  // Release the datagram writer's lock so the stream can be torn down.
1047
- this.#datagramWriter?.releaseLock();
3158
+ this.#datagramWriter?.close();
1048
3159
  this.#datagramWriter = undefined;
1049
3160
  }
1050
3161
  }