@moq/net 0.3.5 → 0.4.1

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 (244) hide show
  1. package/announce.d.ts +7 -0
  2. package/announce.d.ts.map +1 -0
  3. package/announce.js +8 -0
  4. package/announce.js.map +1 -0
  5. package/announced.d.ts +49 -91
  6. package/announced.d.ts.map +1 -1
  7. package/announced.js +21 -156
  8. package/announced.js.map +1 -1
  9. package/bandwidth.d.ts +163 -0
  10. package/bandwidth.d.ts.map +1 -0
  11. package/bandwidth.js +304 -0
  12. package/bandwidth.js.map +1 -0
  13. package/bandwidth_api.d.ts +7 -0
  14. package/bandwidth_api.d.ts.map +1 -0
  15. package/bandwidth_api.js +8 -0
  16. package/bandwidth_api.js.map +1 -0
  17. package/broadcast.d.ts +23 -28
  18. package/broadcast.d.ts.map +1 -1
  19. package/broadcast.js +61 -40
  20. package/broadcast.js.map +1 -1
  21. package/connection/accept.d.ts +16 -1
  22. package/connection/accept.d.ts.map +1 -1
  23. package/connection/accept.js +48 -25
  24. package/connection/accept.js.map +1 -1
  25. package/connection/browser.d.ts.map +1 -1
  26. package/connection/browser.js +9 -7
  27. package/connection/browser.js.map +1 -1
  28. package/connection/connect.d.ts +30 -6
  29. package/connection/connect.d.ts.map +1 -1
  30. package/connection/connect.js +95 -46
  31. package/connection/connect.js.map +1 -1
  32. package/connection/established.d.ts +17 -21
  33. package/connection/established.d.ts.map +1 -1
  34. package/connection/established.js.map +1 -1
  35. package/connection/forward.d.ts +2 -0
  36. package/connection/forward.d.ts.map +1 -0
  37. package/connection/forward.js +166 -0
  38. package/connection/forward.js.map +1 -0
  39. package/connection/handshake.d.ts +1 -0
  40. package/connection/handshake.d.ts.map +1 -1
  41. package/connection/handshake.js +5 -2
  42. package/connection/handshake.js.map +1 -1
  43. package/connection/index.d.ts +5 -5
  44. package/connection/index.d.ts.map +1 -1
  45. package/connection/index.js +4 -5
  46. package/connection/index.js.map +1 -1
  47. package/connection/pool.d.ts +186 -0
  48. package/connection/pool.d.ts.map +1 -0
  49. package/connection/pool.js +361 -0
  50. package/connection/pool.js.map +1 -0
  51. package/connection/reload.d.ts +14 -93
  52. package/connection/reload.d.ts.map +1 -1
  53. package/connection/reload.js +217 -81
  54. package/connection/reload.js.map +1 -1
  55. package/connection/stats.d.ts +3 -26
  56. package/connection/stats.d.ts.map +1 -1
  57. package/connection/stats.js.map +1 -1
  58. package/connection/transport.d.ts +0 -7
  59. package/connection/transport.d.ts.map +1 -1
  60. package/consume.d.ts +1 -43
  61. package/consume.d.ts.map +1 -1
  62. package/consume.js +1 -1
  63. package/consume.js.map +1 -1
  64. package/error.d.ts +180 -29
  65. package/error.d.ts.map +1 -1
  66. package/error.js +331 -16
  67. package/error.js.map +1 -1
  68. package/errors.d.ts +7 -0
  69. package/errors.d.ts.map +1 -0
  70. package/errors.js +8 -0
  71. package/errors.js.map +1 -0
  72. package/group.d.ts +9 -43
  73. package/group.d.ts.map +1 -1
  74. package/group.js +283 -69
  75. package/group.js.map +1 -1
  76. package/hop.d.ts +107 -0
  77. package/hop.d.ts.map +1 -0
  78. package/hop.js +103 -0
  79. package/hop.js.map +1 -0
  80. package/ietf/adapter.d.ts +5 -1
  81. package/ietf/adapter.d.ts.map +1 -1
  82. package/ietf/adapter.js +27 -9
  83. package/ietf/adapter.js.map +1 -1
  84. package/ietf/aliases.d.ts +1 -78
  85. package/ietf/aliases.d.ts.map +1 -1
  86. package/ietf/cluster.d.ts +6 -120
  87. package/ietf/cluster.d.ts.map +1 -1
  88. package/ietf/cluster.js +81 -41
  89. package/ietf/cluster.js.map +1 -1
  90. package/ietf/connection.d.ts +6 -72
  91. package/ietf/connection.d.ts.map +1 -1
  92. package/ietf/connection.js +17 -49
  93. package/ietf/connection.js.map +1 -1
  94. package/ietf/error.d.ts +11 -0
  95. package/ietf/error.d.ts.map +1 -0
  96. package/ietf/error.js +193 -0
  97. package/ietf/error.js.map +1 -0
  98. package/ietf/filter.d.ts.map +1 -1
  99. package/ietf/filter.js +6 -1
  100. package/ietf/filter.js.map +1 -1
  101. package/ietf/goaway.d.ts.map +1 -1
  102. package/ietf/goaway.js +22 -5
  103. package/ietf/goaway.js.map +1 -1
  104. package/ietf/hidden.d.ts +2 -0
  105. package/ietf/hidden.d.ts.map +1 -0
  106. package/ietf/hidden.js +30 -0
  107. package/ietf/hidden.js.map +1 -0
  108. package/ietf/index.d.ts +1 -0
  109. package/ietf/index.d.ts.map +1 -1
  110. package/ietf/index.js +1 -0
  111. package/ietf/index.js.map +1 -1
  112. package/ietf/object.d.ts +8 -2
  113. package/ietf/object.d.ts.map +1 -1
  114. package/ietf/object.js +17 -3
  115. package/ietf/object.js.map +1 -1
  116. package/ietf/parameters.d.ts +7 -2
  117. package/ietf/parameters.d.ts.map +1 -1
  118. package/ietf/parameters.js +35 -17
  119. package/ietf/parameters.js.map +1 -1
  120. package/ietf/properties.d.ts +1 -0
  121. package/ietf/properties.d.ts.map +1 -1
  122. package/ietf/properties.js +14 -0
  123. package/ietf/properties.js.map +1 -1
  124. package/ietf/publish.d.ts +19 -2
  125. package/ietf/publish.d.ts.map +1 -1
  126. package/ietf/publish.js +40 -6
  127. package/ietf/publish.js.map +1 -1
  128. package/ietf/publish_namespace.d.ts +25 -0
  129. package/ietf/publish_namespace.d.ts.map +1 -1
  130. package/ietf/publish_namespace.js +63 -0
  131. package/ietf/publish_namespace.js.map +1 -1
  132. package/ietf/publisher.d.ts +1 -82
  133. package/ietf/publisher.d.ts.map +1 -1
  134. package/ietf/publisher.js +302 -181
  135. package/ietf/publisher.js.map +1 -1
  136. package/ietf/solicit.d.ts +1 -40
  137. package/ietf/solicit.d.ts.map +1 -1
  138. package/ietf/subscribe.d.ts +1 -5
  139. package/ietf/subscribe.d.ts.map +1 -1
  140. package/ietf/subscribe.js +11 -13
  141. package/ietf/subscribe.js.map +1 -1
  142. package/ietf/subscribe_namespace.d.ts +8 -2
  143. package/ietf/subscribe_namespace.d.ts.map +1 -1
  144. package/ietf/subscribe_namespace.js +18 -8
  145. package/ietf/subscribe_namespace.js.map +1 -1
  146. package/ietf/subscriber.d.ts +1 -65
  147. package/ietf/subscriber.d.ts.map +1 -1
  148. package/ietf/subscriber.js +325 -121
  149. package/ietf/subscriber.js.map +1 -1
  150. package/ietf/version.d.ts +12 -1
  151. package/ietf/version.d.ts.map +1 -1
  152. package/ietf/version.js +13 -0
  153. package/ietf/version.js.map +1 -1
  154. package/index.d.ts +11 -6
  155. package/index.d.ts.map +1 -1
  156. package/index.js +10 -5
  157. package/index.js.map +1 -1
  158. package/internal.d.ts +104 -1
  159. package/internal.d.ts.map +1 -1
  160. package/internal.js +76 -0
  161. package/internal.js.map +1 -1
  162. package/lite/announce.d.ts +60 -10
  163. package/lite/announce.d.ts.map +1 -1
  164. package/lite/announce.js +173 -31
  165. package/lite/announce.js.map +1 -1
  166. package/lite/connection.d.ts +9 -59
  167. package/lite/connection.d.ts.map +1 -1
  168. package/lite/connection.js +26 -32
  169. package/lite/connection.js.map +1 -1
  170. package/lite/fetch.d.ts +15 -1
  171. package/lite/fetch.d.ts.map +1 -1
  172. package/lite/fetch.js +39 -7
  173. package/lite/fetch.js.map +1 -1
  174. package/lite/goaway.d.ts.map +1 -1
  175. package/lite/goaway.js +7 -1
  176. package/lite/goaway.js.map +1 -1
  177. package/lite/group.d.ts +18 -4
  178. package/lite/group.d.ts.map +1 -1
  179. package/lite/group.js +31 -10
  180. package/lite/group.js.map +1 -1
  181. package/lite/priority.d.ts +1 -61
  182. package/lite/priority.d.ts.map +1 -1
  183. package/lite/priority.js +4 -5
  184. package/lite/priority.js.map +1 -1
  185. package/lite/publisher.d.ts +1 -69
  186. package/lite/publisher.d.ts.map +1 -1
  187. package/lite/publisher.js +593 -227
  188. package/lite/publisher.js.map +1 -1
  189. package/lite/setup.d.ts +7 -7
  190. package/lite/setup.d.ts.map +1 -1
  191. package/lite/setup.js +13 -13
  192. package/lite/setup.js.map +1 -1
  193. package/lite/subscribe.d.ts +71 -17
  194. package/lite/subscribe.d.ts.map +1 -1
  195. package/lite/subscribe.js +205 -53
  196. package/lite/subscribe.js.map +1 -1
  197. package/lite/subscriber.d.ts +15 -56
  198. package/lite/subscriber.d.ts.map +1 -1
  199. package/lite/subscriber.js +316 -188
  200. package/lite/subscriber.js.map +1 -1
  201. package/lite/track.d.ts +4 -10
  202. package/lite/track.d.ts.map +1 -1
  203. package/lite/track.js +34 -29
  204. package/lite/track.js.map +1 -1
  205. package/lite/version.d.ts +42 -6
  206. package/lite/version.d.ts.map +1 -1
  207. package/lite/version.js +126 -10
  208. package/lite/version.js.map +1 -1
  209. package/origin.d.ts +248 -29
  210. package/origin.d.ts.map +1 -1
  211. package/origin.js +1232 -37
  212. package/origin.js.map +1 -1
  213. package/package.json +8 -3
  214. package/path.d.ts +25 -7
  215. package/path.d.ts.map +1 -1
  216. package/path.js +5 -3
  217. package/path.js.map +1 -1
  218. package/stream.d.ts +2 -2
  219. package/stream.d.ts.map +1 -1
  220. package/stream.js +39 -25
  221. package/stream.js.map +1 -1
  222. package/tail.d.ts +11 -0
  223. package/tail.d.ts.map +1 -0
  224. package/tail.js +121 -0
  225. package/tail.js.map +1 -0
  226. package/time.d.ts +15 -2
  227. package/time.d.ts.map +1 -1
  228. package/time.js +28 -9
  229. package/time.js.map +1 -1
  230. package/track.d.ts +195 -84
  231. package/track.d.ts.map +1 -1
  232. package/track.js +694 -196
  233. package/track.js.map +1 -1
  234. package/wire.d.ts +69 -0
  235. package/wire.d.ts.map +1 -0
  236. package/wire.js +32 -0
  237. package/wire.js.map +1 -0
  238. package/zod.d.ts +1 -1
  239. package/zod.d.ts.map +1 -1
  240. package/zod.js.map +1 -1
  241. package/mock.d.ts +0 -66
  242. package/mock.d.ts.map +0 -1
  243. package/mock.js +0 -243
  244. package/mock.js.map +0 -1
package/ietf/publisher.js CHANGED
@@ -1,31 +1,44 @@
1
1
  /* @ts-self-types="./publisher.d.ts" */
2
- import { Signal } from "@moq/signals";
3
- import { error, reason } from "../error.js";
2
+ import { race, Signal } from "@moq/signals";
3
+ import { controlTimeout, error, reason, StreamCode, StreamError } from "../error.js";
4
+ import { routesEqual } from "../hop.js";
5
+ import { hiddenBelow, hooks } from "../internal.js";
4
6
  import * as Path from "../path.js";
5
7
  import { Writer } from "../stream.js";
6
- import { withTimeout } from "../util/timeout.js";
8
+ import { Milli, Timescale } from "../time.js";
9
+ import { TimeoutError, withTimeout } from "../util/timeout.js";
10
+ import * as Varint from "../varint.js";
11
+ import { wireOf } from "../wire.js";
7
12
  import * as Cluster from "./cluster.js";
13
+ import { requestReason, toRequestCode } from "./error.js";
8
14
  import { FetchHeader } from "./fetch.js";
9
15
  import * as Filter from "./filter.js";
10
16
  import { FetchFrame, Frame, Group as GroupMessage } from "./object.js";
11
- import { fromWire } from "./priority.js";
17
+ import { fromWire, toWire } from "./priority.js";
12
18
  import * as Properties from "./properties.js";
13
- import { PublishDone } from "./publish.js";
19
+ import { PublishDone, PublishDoneStatus } from "./publish.js";
14
20
  import { PublishNamespace, PublishNamespaceDone, PublishNamespaceOk } from "./publish_namespace.js";
15
21
  import { RequestError, RequestOk } from "./request.js";
16
22
  import { SubscribeError, SubscribeOk } from "./subscribe.js";
17
23
  import { SubscribeNamespaceEntry, SubscribeNamespaceEntryDone, SubscribeNamespaceOk, } from "./subscribe_namespace.js";
18
- import { TrackStatus } from "./track.js";
19
24
  import { Version } from "./version.js";
20
25
  /** First wait before re-offering a namespace the peer refused or we couldn't open for. */
21
26
  const RETRY_BASE = 100;
22
27
  /** Ceiling on that wait. The loop retries for the life of the session, so it must not spin. */
23
28
  const RETRY_MAX = 5000;
24
- /** PUBLISH_DONE statuses this implementation emits. Stable across drafts 14 through 19. */
25
- const PUBLISH_DONE_STATUS = {
26
- INTERNAL_ERROR: 0x0,
27
- TRACK_ENDED: 0x2,
28
- };
29
+ /** Cluster parameters for one snapshot: the advertised hops, then our own id last. */
30
+ function clusterFor(base, route) {
31
+ if (!base)
32
+ return undefined;
33
+ const self = base.hops.at(-1);
34
+ if (self === undefined)
35
+ return undefined;
36
+ const hops = route.hops.at(-1) === self ? [...route.hops] : [...route.hops, self];
37
+ return { hops, cost: route.cost.warm };
38
+ }
39
+ function sameAdvert(a, b) {
40
+ return a !== undefined && b !== undefined && a.identity === b.identity && routesEqual(a.route, b.route);
41
+ }
29
42
  /**
30
43
  * How long one advertisement may take to be answered. Matches the Rust publisher, and the
31
44
  * peer accepting the stream is only half the exchange: one it never answers on holds the
@@ -46,44 +59,30 @@ export class Publisher {
46
59
  #quic;
47
60
  #session;
48
61
  #requiresSolicitation;
62
+ // The origin this session serves, borrowed: it outlives the session, and closing the
63
+ // session leaves its broadcasts alone. The namespaces are advertised with an unsolicited
64
+ // PUBLISH_NAMESPACE (see {@link runPublishNamespaces}), or on request if the peer asked
65
+ // for that (see {@link runSubscribeNamespace}).
66
+ #advertised;
67
+ #publish;
49
68
  // What every advertisement carries on a session that negotiated the MoQ Cluster
50
69
  // extension: a hop path holding our own id, so the peer can tell that what it hears
51
70
  // back came from us. `undefined` when nothing negotiated it.
52
71
  #advert;
53
- // Our published broadcasts.
54
- // It's a signal so we can live update any subscribe_namespace streams.
55
- #broadcasts = new Signal(new Map());
56
72
  /**
57
73
  * Creates a new Publisher instance.
58
74
  *
59
75
  * @internal
60
76
  */
61
- constructor({ quic, session, requiresSolicitation, cluster, }) {
77
+ constructor({ quic, session, publish, requiresSolicitation, cluster, }) {
62
78
  this.#quic = quic;
63
79
  this.#session = session;
80
+ const origin = publish && wireOf(publish);
81
+ this.#advertised = origin?.advertised ?? new Signal(new Map());
82
+ this.#publish = publish;
64
83
  this.#requiresSolicitation = requiresSolicitation;
65
84
  this.#advert = Cluster.advertise(cluster);
66
85
  }
67
- /**
68
- * Publishes a broadcast with any associated tracks.
69
- * The namespace is advertised with an unsolicited PUBLISH_NAMESPACE, or on request
70
- * if the peer asked for that (see {@link runPublishNamespaces}).
71
- */
72
- publish(path, broadcast) {
73
- this.#broadcasts.mutate((broadcasts) => {
74
- if (!broadcasts)
75
- throw new Error("closed");
76
- broadcasts.set(path, broadcast);
77
- });
78
- // Remove the broadcast from the lookup when it's closed, unless the path was republished.
79
- void broadcast.closed.then(() => {
80
- this.#broadcasts.mutate((broadcasts) => {
81
- if (broadcasts?.get(path) === broadcast) {
82
- broadcasts.delete(path);
83
- }
84
- });
85
- });
86
- }
87
86
  /**
88
87
  * Handles an incoming SUBSCRIBE request on a bidi stream.
89
88
  * Owns the full lifecycle: sends response, serves track data, waits for close.
@@ -93,15 +92,30 @@ export class Publisher {
93
92
  async runSubscribe(msg, stream) {
94
93
  const version = this.#session.version;
95
94
  const name = msg.trackNamespace;
96
- const broadcast = this.#broadcasts.peek()?.get(name);
97
- if (!broadcast) {
98
- // Write error response
95
+ let broadcast;
96
+ let refusal;
97
+ try {
98
+ broadcast =
99
+ this.#publish && (wireOf(this.#publish).local(name) ?? (await wireOf(this.#publish).demand(name)));
100
+ if (!broadcast) {
101
+ refusal = {
102
+ errorCode: toRequestCode("does_not_exist", "subscribe", version),
103
+ reasonPhrase: "broadcast not found",
104
+ };
105
+ }
106
+ }
107
+ catch (err) {
108
+ const e = error(err);
109
+ const condition = e instanceof StreamError && e.code === StreamCode.NotFound ? "does_not_exist" : "internal";
110
+ refusal = { errorCode: toRequestCode(condition, "subscribe", version), reasonPhrase: reason(e) };
111
+ }
112
+ if (refusal) {
99
113
  if (version === Version.DRAFT_14) {
100
114
  await stream.writer.u53(SubscribeError.id);
101
115
  const err = new SubscribeError({
102
116
  requestId: msg.requestId,
103
- errorCode: 404,
104
- reasonPhrase: "Broadcast not found",
117
+ errorCode: refusal.errorCode,
118
+ reasonPhrase: refusal.reasonPhrase,
105
119
  });
106
120
  await err.encode(stream.writer, version);
107
121
  }
@@ -109,21 +123,36 @@ export class Publisher {
109
123
  await stream.writer.u53(RequestError.id);
110
124
  const err = new RequestError({
111
125
  requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined,
112
- errorCode: 404,
113
- reasonPhrase: "Broadcast not found",
126
+ errorCode: refusal.errorCode,
127
+ reasonPhrase: refusal.reasonPhrase,
114
128
  });
115
129
  await err.encode(stream.writer, version);
116
130
  }
117
131
  stream.close();
118
132
  return;
119
133
  }
134
+ if (!broadcast)
135
+ return;
120
136
  const priority = fromWire(msg.subscriberPriority);
121
- const track = broadcast.subscribe(msg.trackName, { priority });
122
- // Hoisted so the cleanup below reaches it: the fork happens before SUBSCRIBE_OK is
123
- // written, and a write that throws must not strand the sink it attached.
137
+ const track = wireOf(broadcast).subscribe(msg.trackName, {
138
+ priority,
139
+ // moq-transport has no subscriber latency parameter. Keep everything the
140
+ // producer retained and let the receiving subscriber enforce its own budget.
141
+ // Keep the sentinel encodable if this demand crosses a Lite hop before the
142
+ // producer's retention bound is known.
143
+ maxAge: Milli(Varint.MAX_U53),
144
+ });
124
145
  let cache;
125
146
  try {
126
- const timescale = (await track.info()).timescale;
147
+ // Declaring the timescale is what opts the track into timestamps; every object
148
+ // Timestamp below is in these units.
149
+ const info = await track.info();
150
+ const timescale = info.timescale;
151
+ // The model ranks higher-first, the IETF wire lower-first. Every group this
152
+ // subscription serves carries the same publisher priority, which is what lets a
153
+ // relay prefer catalog and audio over video when it has no subscriber preference
154
+ // to go on.
155
+ const publisherPriority = toWire(info.priority);
127
156
  // The filter and any fill are relative to the live edge, so snapshot it once: the
128
157
  // fill ends exactly where a Next Object subscription begins, which is what lets
129
158
  // the draft's current-group join (Next Object plus a StartGroup=1 fill) cover the
@@ -133,21 +162,25 @@ export class Publisher {
133
162
  // The wire request tells an upstream what we need; the cursor is what actually
134
163
  // trims this subscriber, since the producer fans every cached group out to every
135
164
  // sink regardless. An absent start joins at the latest group, which is what
136
- // moq-lite means by joining a live track.
165
+ // moq-lite means by joining a live track. The range's end is the inclusive last
166
+ // group; the model's `endGroup` is exclusive.
137
167
  track.update({
138
168
  priority,
139
- startGroup: range.start && Number(range.start.group),
140
- endGroup: range.end && Number(range.end.group),
169
+ maxAge: Milli(Varint.MAX_U53),
170
+ groups: {
171
+ start: range.start ? { included: Number(range.start.group) } : undefined,
172
+ end: range.end ? { included: Number(range.end.group) } : undefined,
173
+ },
141
174
  });
142
175
  const startGroup = range.start ? Number(range.start.group) : track.latest();
143
176
  if (startGroup !== undefined)
144
- track.startAt(startGroup);
177
+ track.setGroups({ start: { included: startGroup } });
145
178
  // A fill reads the group cache through its own consumer, independent of the
146
179
  // subscription's cursor. Forked from this subscriber rather than resolved through
147
180
  // the broadcast again: a dynamic serve is one request per peer subscription, so
148
181
  // asking the broadcast would mint a second producer nobody has accepted.
149
182
  const fill = msg.fill && Filter.isDraft20(version) ? fillRange(msg.fill, msg.filter, edge.largest) : undefined;
150
- cache = fill && fill.kind !== "empty" ? track.fork({ priority }) : undefined;
183
+ cache = fill && fill.kind !== "empty" ? track.fork({ priority, maxAge: Milli(Varint.MAX_U53) }) : undefined;
151
184
  // Send SUBSCRIBE_OK
152
185
  await stream.writer.u53(SubscribeOk.id);
153
186
  const ok = new SubscribeOk({
@@ -156,13 +189,20 @@ export class Publisher {
156
189
  : undefined,
157
190
  trackAlias: msg.requestId,
158
191
  // Required once the track has content; a fill-requesting subscriber sizes its
159
- // backfill against this.
160
- largest: edge.largest && { groupId: edge.largest.group, objectId: edge.largest.object },
192
+ // backfill against this. Below draft-20 round it down to the start of its
193
+ // group, matching what the subscription serves there: a draft-20 subscriber
194
+ // recovers a group's head with a FILL, which we serve, while older drafts
195
+ // recover it with a joining FETCH, which we do not, so naming a mid-group
196
+ // start would strand them.
197
+ largest: edge.largest &&
198
+ (Filter.isDraft20(version)
199
+ ? { groupId: edge.largest.group, objectId: edge.largest.object }
200
+ : { groupId: edge.largest.group, objectId: 0n }),
161
201
  properties: msg.propertiesWanted
162
202
  ? // Declaring the timescale is what opts the track into timestamps; every
163
203
  // object Timestamp below is in these units. We serve the newest group
164
204
  // first, matching moq-lite.
165
- { timescale, groupOrder: Properties.DESCENDING }
205
+ { timescale, priority: publisherPriority, groupOrder: Properties.DESCENDING }
166
206
  : // INCLUDE_PROPERTIES=0. The block stays present but empty, which also means
167
207
  // the track opts out of timestamps for this subscriber.
168
208
  {},
@@ -183,13 +223,17 @@ export class Publisher {
183
223
  },
184
224
  // A reset is always the peer.
185
225
  () => unsubscribe());
226
+ // Every group started, until its stream finishes or resets, and the data streams
227
+ // opened for PUBLISH_DONE to report.
228
+ const groups = new Set();
229
+ const streams = { opened: 0 };
186
230
  // Serve track groups, racing with stream close (= Unsubscribe)
187
231
  const serving = (async () => {
188
232
  for (;;) {
189
233
  const group = await track.recvGroup();
190
234
  if (!group)
191
235
  return;
192
- // Past the filter's end. Dropped here rather than through `endAt`, which
236
+ // Past the filter's end. Dropped here rather than through `setGroups`, which
193
237
  // parks a capped group instead: this range is fixed for the life of the
194
238
  // subscription, so a group above it is never coming back in, and holding
195
239
  // one keeps the loop from ever ending. A producer that publishes beyond
@@ -198,14 +242,18 @@ export class Publisher {
198
242
  group.close();
199
243
  continue;
200
244
  }
201
- void this.#runGroup({
245
+ const task = this.#runGroup({
202
246
  requestId: msg.requestId,
203
247
  group,
204
248
  timescale,
249
+ publisherPriority,
205
250
  stamped: msg.propertiesWanted,
206
251
  slice: groupSlice(range, group.sequence),
207
252
  unsubscribed,
253
+ streams,
208
254
  });
255
+ groups.add(task);
256
+ void task.finally(() => groups.delete(task));
209
257
  }
210
258
  })();
211
259
  // The fill (when one was requested) runs alongside on its own fetch stream; its
@@ -219,15 +267,35 @@ export class Publisher {
219
267
  timescale,
220
268
  stamped: msg.propertiesWanted,
221
269
  unsubscribed,
270
+ streams,
222
271
  })
223
272
  : Promise.resolve();
224
273
  let publishError;
274
+ let ended = false;
225
275
  try {
226
- await Promise.race([Promise.all([serving, filling]), stream.reader.closed]);
276
+ const served = Symbol("served");
277
+ ended =
278
+ (await race([Promise.all([serving, filling]).then(() => served), stream.reader.closed])) === served;
227
279
  }
228
280
  catch (err) {
229
281
  publishError = error(err);
230
282
  }
283
+ // PUBLISH_DONE waits until every stream this subscription will open is closed, as
284
+ // the draft requires, so its count is final. The subscriber leaving cancels the
285
+ // ones still queued instead.
286
+ await race([Promise.all(groups), unsubscribed]);
287
+ // Draft 14 on has no end location in PUBLISH_DONE: an END_OF_TRACK object is what
288
+ // tells the subscriber where the track ended.
289
+ const final = track.final();
290
+ if (ended && !publishError && final !== undefined) {
291
+ await this.#runEndOfTrack({
292
+ requestId: msg.requestId,
293
+ final,
294
+ publisherPriority,
295
+ unsubscribed,
296
+ streams,
297
+ });
298
+ }
231
299
  console.debug(`publish done: broadcast=${name} track=${track.name}`);
232
300
  if (publishError) {
233
301
  console.warn(`publish error: broadcast=${name} track=${track.name} error=${reason(publishError)}`);
@@ -240,7 +308,8 @@ export class Publisher {
240
308
  requestId: version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16
241
309
  ? msg.requestId
242
310
  : undefined,
243
- statusCode: publishError ? PUBLISH_DONE_STATUS.INTERNAL_ERROR : PUBLISH_DONE_STATUS.TRACK_ENDED,
311
+ statusCode: publishError ? PublishDoneStatus.INTERNAL_ERROR : PublishDoneStatus.TRACK_ENDED,
312
+ streamCount: BigInt(streams.opened),
244
313
  reasonPhrase: publishError ? "internal error" : "track ended",
245
314
  });
246
315
  await done.encode(stream.writer, version);
@@ -270,7 +339,7 @@ export class Publisher {
270
339
  * Runs a group and sends its frames using ObjectStream (Subgroup delivery mode).
271
340
  */
272
341
  async #runGroup(options) {
273
- const { requestId, group, timescale, stamped, slice, unsubscribed } = options;
342
+ const { requestId, group, timescale, publisherPriority, stamped, slice, unsubscribed, streams } = options;
274
343
  try {
275
344
  // One stream per group is faster than a peer at its limit can retire them, so this
276
345
  // is the one path that doesn't wait for a slot: the transport would serve the opens
@@ -285,11 +354,12 @@ export class Publisher {
285
354
  group.close(new Error("no stream slot"));
286
355
  return;
287
356
  }
357
+ streams.opened += 1;
288
358
  const header = new GroupMessage({
289
359
  trackAlias: requestId,
290
360
  groupId: group.sequence,
291
361
  subGroupId: 0,
292
- publisherPriority: 0,
362
+ publisherPriority,
293
363
  flags: {
294
364
  // The object properties carry the timestamp, so there is nothing to write
295
365
  // when the track declared no units to read one in.
@@ -303,8 +373,8 @@ export class Publisher {
303
373
  firstObject: slice.skip === 0,
304
374
  },
305
375
  });
306
- await header.encode(stream, this.#session.version);
307
376
  try {
377
+ await hooks.guardGroup(group, header.encode(stream, this.#session.version));
308
378
  // The first written object goes on the wire as its absolute id, so a trimmed
309
379
  // head shows the true numbering rather than a silently renumbered group.
310
380
  let first = true;
@@ -318,20 +388,25 @@ export class Publisher {
318
388
  // outside the requested range, so stop without waiting for the group's end.
319
389
  if (slice.until !== undefined && next >= slice.until)
320
390
  break;
321
- // Reading from the filter's start drops the objects below it, including any the
322
- // group's cache evicted: they are outside the requested range, so losing them is
323
- // not the gap that would otherwise reset this stream and forfeit the rest of the
324
- // group. An eviction at or above the start is a real gap and still throws.
325
- const frame = await Promise.race([group.readFrameSequence({ from: slice.skip }), stream.closed]);
326
- if (!frame)
391
+ // Reading from the filter's start drops the objects below it: they are outside
392
+ // the requested range, so skipping them is not a gap.
393
+ const read = await race([hooks.readGroupFrame(group, slice.skip), stream.closed]);
394
+ if (!read)
327
395
  break;
328
- next = frame.sequence + 1;
329
- if (slice.until !== undefined && frame.sequence >= slice.until)
396
+ next = read.sequence + 1;
397
+ if (slice.until !== undefined && read.sequence >= slice.until) {
398
+ read.complete();
330
399
  break;
331
- const obj = new Frame({ payload: frame.payload, timestamp: frame.timestamp });
332
- const delta = first ? frame.sequence : 0;
333
- first = false;
334
- await obj.encode(stream, header.flags, timescale, this.#session.version, delta);
400
+ }
401
+ try {
402
+ const obj = new Frame({ payload: read.frame.payload, timestamp: read.frame.timestamp });
403
+ const delta = first ? read.sequence : 0;
404
+ first = false;
405
+ await hooks.guardGroup(group, obj.encode(stream, header.flags, timescale, this.#session.version, delta));
406
+ }
407
+ finally {
408
+ read.complete();
409
+ }
335
410
  }
336
411
  stream.close();
337
412
  }
@@ -343,6 +418,43 @@ export class Publisher {
343
418
  group.close();
344
419
  }
345
420
  }
421
+ /**
422
+ * Mark the track's end with an END_OF_TRACK object on its own stream, at object 0 of the
423
+ * group that will never exist.
424
+ *
425
+ * The last group's stream has usually finished before the track ends, so the marker cannot
426
+ * ride on it. A failure only costs the subscriber the early boundary.
427
+ */
428
+ async #runEndOfTrack(options) {
429
+ const { requestId, final, publisherPriority, unsubscribed, streams } = options;
430
+ const version = this.#session.version;
431
+ const stream = await Writer.tryOpen(this.#quic, { cancel: unsubscribed, version }).catch(() => undefined);
432
+ if (!stream)
433
+ return;
434
+ streams.opened += 1;
435
+ try {
436
+ const header = new GroupMessage({
437
+ trackAlias: requestId,
438
+ groupId: final,
439
+ subGroupId: 0,
440
+ publisherPriority,
441
+ flags: {
442
+ hasExtensions: false,
443
+ hasSubgroup: false,
444
+ hasSubgroupObject: false,
445
+ hasEnd: false,
446
+ hasPriority: true,
447
+ firstObject: true,
448
+ },
449
+ });
450
+ await header.encode(stream, version);
451
+ await new Frame({ endOfTrack: true }).encode(stream, header.flags, Timescale.MILLI, version);
452
+ stream.close();
453
+ }
454
+ catch (err) {
455
+ stream.reset(error(err));
456
+ }
457
+ }
346
458
  /**
347
459
  * Serve a draft-20 fill on its own fetch stream: the requested range, read from the
348
460
  * group cache, capped at the Largest Object snapshot.
@@ -352,7 +464,7 @@ export class Publisher {
352
464
  * fill-failure signal. Nothing here touches the subscription either way.
353
465
  */
354
466
  async #runFill(options) {
355
- const { requestId, fill, cache, timescale, stamped, unsubscribed } = options;
467
+ const { requestId, fill, cache, timescale, stamped, unsubscribed, streams } = options;
356
468
  const version = this.#session.version;
357
469
  // Everything is inside the try so the cache fork is released on every path out,
358
470
  // including a transport failure while opening the stream.
@@ -365,6 +477,7 @@ export class Publisher {
365
477
  console.debug(`fill stream failed to open: fill=${requestId}`);
366
478
  return;
367
479
  }
480
+ streams.opened += 1;
368
481
  await stream.u53(FetchHeader.type);
369
482
  await new FetchHeader({ requestId }).encode(stream, version);
370
483
  if (fill.kind !== "group") {
@@ -413,13 +526,8 @@ export class Publisher {
413
526
  // subscription, so stop without waiting for the group's end.
414
527
  if (fill.until !== undefined && next >= fill.until)
415
528
  break;
416
- // Reading from the fill's start drops everything below it, evicted objects included;
417
- // see the same read in #runGroup.
418
- const frame = await Promise.race([
419
- group.readFrameSequence({ from: Number(fill.skip) }),
420
- stream.closed,
421
- cancelled,
422
- ]);
529
+ // Reading from the fill's start drops everything below it; see the same read in #runGroup.
530
+ const frame = await race([group.readFrameSequence({ from: Number(fill.skip) }), stream.closed, cancelled]);
423
531
  if (left)
424
532
  throw new Error("unsubscribed before the fill finished");
425
533
  if (!frame)
@@ -435,10 +543,10 @@ export class Publisher {
435
543
  /**
436
544
  * Handles an incoming SUBSCRIBE_NAMESPACE on a bidi stream.
437
545
  *
438
- * This carries the advertisements only when the peer asked to be told on request
439
- * (MoQ Solicit); otherwise {@link runPublishNamespaces} has already announced
440
- * everything and repeating it here would leave the peer holding two sources for one
441
- * broadcast. Draft-16+ streams Namespace entries inline; draft-14/15 predate those
546
+ * This carries the advertisements when the peer asked to be told on request (MoQ
547
+ * Solicit); otherwise {@link runPublishNamespaces} has already announced everything
548
+ * visible and repeating it here would leave the peer holding two sources for one
549
+ * broadcast, so only the hidden namespaces it may see ride here (MoQ Hidden). Draft-16+ streams Namespace entries inline; draft-14/15 predate those
442
550
  * messages, so each advertisement is a PUBLISH_NAMESPACE request of its own.
443
551
  *
444
552
  * @internal
@@ -463,20 +571,20 @@ export class Publisher {
463
571
  });
464
572
  await ok.encode(stream.writer, version);
465
573
  }
466
- if (!this.#requiresSolicitation) {
467
- // Already announced, unasked. Hold the stream open until the peer is done.
468
- await stream.reader.closed;
469
- stream.close();
470
- return;
471
- }
574
+ // Hidden namespaces are left out unless the peer opted in (MoQ Hidden). Unless the
575
+ // peer asked to be told only on request, it has already heard everything visible
576
+ // from the empty prefix unasked, so this stream carries only what that hid.
577
+ const carries = (covered) => (msg.hidden || !hiddenBelow(prefix, covered)) &&
578
+ (this.#requiresSolicitation || hiddenBelow(Path.empty(), covered));
472
579
  // Reports whether the peer now holds the namespace: an inline entry always
473
580
  // lands, but a PUBLISH_NAMESPACE request can be declined.
474
- const advertise = async (suffix) => {
581
+ const advertise = async (suffix, snap) => {
582
+ const cluster = clusterFor(this.#advert, snap.route);
475
583
  if (legacy) {
476
- return await this.#advertise(Path.join(prefix, suffix), requests, refused);
584
+ return await this.#advertise(Path.join(prefix, suffix), requests, refused, cluster);
477
585
  }
478
586
  await stream.writer.u53(SubscribeNamespaceEntry.id);
479
- await new SubscribeNamespaceEntry({ suffix, cluster: this.#advert }).encode(stream.writer, version);
587
+ await new SubscribeNamespaceEntry({ suffix, cluster }).encode(stream.writer, version);
480
588
  return true;
481
589
  };
482
590
  const withdraw = async (suffix) => {
@@ -488,13 +596,14 @@ export class Publisher {
488
596
  await new SubscribeNamespaceEntryDone({ suffix }).encode(stream.writer, version);
489
597
  }
490
598
  };
491
- // Which producer holds each advertised suffix. Keyed on the producer rather than
492
- // the path alone, so a path handed to a new producer is withdrawn and re-offered
493
- // instead of diffing away to nothing and leaving the peer on the dead generation.
599
+ // What the peer holds: keyed by suffix, valued by the routing front, so a republish
600
+ // diffs as withdraw-then-advertise rather than nothing.
494
601
  let active = new Map();
495
602
  let retry = 0;
496
603
  // What the peer refused, and whether coming back is worth anything.
497
604
  const refused = new Map();
605
+ // The identity each refusal was about, so a republish at the same path clears it.
606
+ const offered = new Map();
498
607
  for (;;) {
499
608
  // Subscribe BEFORE reconciling, for the same reason as
500
609
  // {@link runPublishNamespaces}: a publish landing while an advertisement
@@ -502,56 +611,64 @@ export class Publisher {
502
611
  // TODO Make a better helper within Signals.
503
612
  let dispose;
504
613
  const changed = new Promise((resolve) => {
505
- dispose = this.#broadcasts.changed(resolve);
614
+ dispose = this.#advertised.changed(resolve);
506
615
  });
507
- const broadcasts = this.#broadcasts.peek();
508
- if (!broadcasts) {
616
+ const advertised = this.#advertised.peek();
617
+ if (!advertised) {
509
618
  dispose();
510
619
  break;
511
620
  }
512
621
  const updated = new Map();
513
- for (const [name, producer] of broadcasts) {
514
- const suffix = Path.stripPrefix(prefix, name);
515
- if (suffix === null)
622
+ for (const [covered, snap] of advertised) {
623
+ const suffix = Path.stripPrefix(prefix, covered);
624
+ if (suffix === null || !carries(covered))
516
625
  continue;
517
- updated.set(suffix, producer);
626
+ updated.set(suffix, snap);
518
627
  }
519
- // A namespace that is gone takes its refusal with it, so re-announcing the
520
- // path offers it again.
521
- const live = new Set([...updated.keys()].map((suffix) => Path.join(prefix, suffix)));
628
+ // A namespace that is gone, or that a republish replaced, takes its refusal with
629
+ // it: the peer refused a broadcast, not a path forever, so a different one at
630
+ // the same path is offered again. The origin swaps the front in one mutation,
631
+ // so the path never leaves `updated` and only the front says they differ.
522
632
  for (const path of [...refused.keys()]) {
523
- if (!live.has(path))
633
+ const suffix = Path.stripPrefix(prefix, path);
634
+ const snap = suffix === null ? undefined : updated.get(suffix);
635
+ if (snap === undefined || offered.get(path) !== snap.identity) {
524
636
  refused.delete(path);
637
+ offered.delete(path);
638
+ }
525
639
  }
526
640
  // Track what the peer holds rather than what we attempted: a declined
527
641
  // advertisement stays out of `held`, so the next turn retries it instead of
528
642
  // believing the namespace is already up.
529
643
  const held = new Map(active);
530
- // Withdraw first, so a replacement reads as an end followed by a start.
531
- for (const [suffix, producer] of active) {
532
- if (updated.get(suffix) === producer)
644
+ // Withdraw first so a republish or re-price reads as withdraw-then-advertise
645
+ // (a restart). Identity change is a new broadcast; a route change is the
646
+ // same one at a new cost or hop chain.
647
+ for (const [removed, snap] of active) {
648
+ if (sameAdvert(updated.get(removed), snap))
533
649
  continue;
534
- await withdraw(suffix);
535
- held.delete(suffix);
650
+ await withdraw(removed);
651
+ held.delete(removed);
536
652
  }
537
- for (const [suffix, producer] of updated) {
538
- if (active.get(suffix) === producer)
653
+ for (const [added, snap] of updated) {
654
+ if (sameAdvert(held.get(added), snap))
539
655
  continue;
540
- if (this.#offerable(Path.join(prefix, suffix), refused)) {
541
- if (await advertise(suffix))
542
- held.set(suffix, producer);
543
- }
656
+ if (!this.#offerable(Path.join(prefix, added), refused))
657
+ continue;
658
+ offered.set(Path.join(prefix, added), snap.identity);
659
+ if (await advertise(added, snap))
660
+ held.set(added, snap);
544
661
  }
545
662
  active = held;
546
663
  // Whatever we wanted up and could not get up, as {@link runPublishNamespaces}
547
664
  // does: only a legacy request can be declined, and nothing about the peer
548
665
  // starting to answer raises a signal this loop is watching.
549
- const outstanding = [...updated].some(([suffix, producer]) => active.get(suffix) !== producer && this.#pending(Path.join(prefix, suffix), refused));
666
+ const outstanding = [...updated].some(([suffix, snap]) => !sameAdvert(active.get(suffix), snap) && this.#pending(Path.join(prefix, suffix), refused));
550
667
  retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
551
668
  // Wait for the next change, or for the peer to unsubscribe.
552
669
  const next = await (retry
553
- ? Promise.race([changed, stream.reader.closed, retryAfter(retry).then(() => broadcasts)])
554
- : Promise.race([changed, stream.reader.closed]));
670
+ ? race([changed, stream.reader.closed, retryAfter(retry).then(() => advertised)])
671
+ : race([changed, stream.reader.closed]));
555
672
  dispose();
556
673
  if (!next)
557
674
  break;
@@ -589,13 +706,22 @@ export class Publisher {
589
706
  }
590
707
  // The open PUBLISH_NAMESPACE request per advertised path.
591
708
  const requests = new Map();
709
+ // The origin outlives the session and its signal never ends, so this loop needs the
710
+ // session's own ending to stop: without it a closed connection leaves the loop parked
711
+ // on a shared origin forever, waking on someone else's publish to fail on a dead
712
+ // transport. `runSubscribeNamespace` gets this from the stream the peer asked on; an
713
+ // unsolicited loop has no stream of its own, so the session is what it watches.
714
+ const closed = this.#quic.closed.then(() => undefined, () => undefined);
592
715
  let dispose;
593
716
  try {
594
- // Which producer holds each advertised path; see {@link runSubscribeNamespace}.
717
+ // What the peer holds: keyed by path, valued by identity plus route, so a
718
+ // republish diffs as withdraw-then-advertise rather than nothing.
595
719
  let active = new Map();
596
720
  let retry = 0;
597
721
  // What the peer refused, and whether coming back is worth anything.
598
722
  const refused = new Map();
723
+ // The identity each refusal was about, so a republish at the same path clears it.
724
+ const offered = new Map();
599
725
  for (;;) {
600
726
  // Subscribe BEFORE reconciling. Each advertisement below waits a round trip
601
727
  // for the peer's reply, and a publish that lands in that window notifies
@@ -604,51 +730,60 @@ export class Publisher {
604
730
  // changed.
605
731
  // TODO Make a better helper within Signals.
606
732
  const changed = new Promise((resolve) => {
607
- dispose = this.#broadcasts.changed(resolve);
733
+ dispose = this.#advertised.changed(resolve);
608
734
  });
609
- const broadcasts = this.#broadcasts.peek();
610
- if (!broadcasts) {
735
+ const advertised = this.#advertised.peek();
736
+ if (!advertised) {
611
737
  dispose?.();
612
738
  break;
613
739
  }
614
- const updated = new Map(broadcasts);
615
- // A namespace that is gone takes its refusal with it, so re-announcing the
616
- // path offers it again. Rust gets this by rebuilding the watched entry.
740
+ const updated = new Map();
741
+ for (const [covered, snap] of advertised) {
742
+ // Unasked, a hidden namespace stays off the wire (MoQ Hidden).
743
+ if (hiddenBelow(Path.empty(), covered))
744
+ continue;
745
+ updated.set(covered, snap);
746
+ }
747
+ // A namespace that is gone, or that a republish replaced, takes its refusal with
748
+ // it: the peer refused a broadcast, not a path forever, so a different one at
749
+ // the same path is offered again. Rust gets this by rebuilding the watched entry.
617
750
  for (const path of [...refused.keys()]) {
618
- if (!updated.has(path))
751
+ const snap = updated.get(path);
752
+ if (snap === undefined || offered.get(path) !== snap.identity) {
619
753
  refused.delete(path);
754
+ offered.delete(path);
755
+ }
620
756
  }
621
- // Withdraw first, so a replacement reads as an end followed by a start.
622
- for (const [path, producer] of active) {
623
- if (updated.get(path) === producer)
757
+ // Withdraw first so a republish or re-price reads as withdraw-then-advertise
758
+ // (a restart) rather than nothing.
759
+ for (const [removed, snap] of active) {
760
+ if (sameAdvert(updated.get(removed), snap))
624
761
  continue;
625
- await this.#withdraw(path, requests);
762
+ await this.#withdraw(removed, requests);
626
763
  }
627
- for (const [path, producer] of updated) {
628
- if (active.get(path) === producer)
764
+ for (const [added, snap] of updated) {
765
+ if (sameAdvert(active.get(added), snap))
629
766
  continue;
630
- if (this.#offerable(path, refused)) {
631
- await this.#advertise(path, requests, refused);
632
- }
767
+ if (!this.#offerable(added, refused))
768
+ continue;
769
+ offered.set(added, snap.identity);
770
+ await this.#advertise(added, requests, refused, clusterFor(this.#advert, snap.route));
633
771
  }
634
772
  // What the peer holds, not what we attempted: a declined PUBLISH_NAMESPACE
635
773
  // leaves no request behind, so it stays outstanding below.
636
- const held = new Map();
637
- for (const path of requests.keys()) {
638
- const producer = updated.get(path);
639
- if (producer)
640
- held.set(path, producer);
641
- }
642
- active = held;
774
+ active = new Map([...requests.keys()].flatMap((path) => {
775
+ const snap = updated.get(path);
776
+ return snap ? [[path, snap]] : [];
777
+ }));
643
778
  // Whatever we wanted up and could not get up. Stream credit freeing, a
644
779
  // transient failure clearing, or the peer starting to answer raises no
645
780
  // signal of its own, so the only way back is to ask again on a timer.
646
- const outstanding = [...updated].some(([path, producer]) => active.get(path) !== producer && this.#pending(path, refused));
781
+ const outstanding = [...updated].some(([path, snap]) => !sameAdvert(active.get(path), snap) && this.#pending(path, refused));
647
782
  retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
648
783
  // Wait for the next change, which has already fired if one landed above.
649
784
  const next = await (retry
650
- ? Promise.race([changed, retryAfter(retry).then(() => broadcasts)])
651
- : changed);
785
+ ? race([changed, closed, retryAfter(retry).then(() => advertised)])
786
+ : race([changed, closed]));
652
787
  dispose?.();
653
788
  if (!next)
654
789
  break;
@@ -698,7 +833,7 @@ export class Publisher {
698
833
  * `refused` records what a refusal said about coming back, so a peer that asked not to
699
834
  * be offered a namespace again is not re-offered it by the retry above.
700
835
  */
701
- async #advertise(path, requests, refused) {
836
+ async #advertise(path, requests, refused, cluster = this.#advert) {
702
837
  const requestId = await this.#session.nextRequestId();
703
838
  if (requestId === undefined)
704
839
  return false;
@@ -716,7 +851,7 @@ export class Publisher {
716
851
  // turn and leaves it outstanding, which the retry above re-offers.
717
852
  await withTimeout((async () => {
718
853
  await stream.writer.u53(PublishNamespace.id);
719
- const msg = new PublishNamespace({ requestId, trackNamespace: path, cluster: this.#advert });
854
+ const msg = new PublishNamespace({ requestId, trackNamespace: path, cluster });
720
855
  await msg.encode(stream.writer, this.#session.version);
721
856
  // Read response (RequestOk and PublishNamespaceOk share 0x07)
722
857
  const respTypeId = await stream.reader.u53();
@@ -729,7 +864,7 @@ export class Publisher {
729
864
  if (!legacy) {
730
865
  refused.set(path, err.retryInterval === 0n ? "never" : Date.now() + Number(err.retryInterval));
731
866
  }
732
- throw new Error(`PublishNamespace rejected: ${err.errorCode} ${err.reasonPhrase}`);
867
+ throw new Error(`PublishNamespace rejected: ${requestReason(err.errorCode, err.reasonPhrase, "publish_namespace", this.#session.version)}`);
733
868
  }
734
869
  if (respTypeId !== RequestOk.id) {
735
870
  throw new Error(`PublishNamespace rejected: typeId=0x${respTypeId.toString(16)}`);
@@ -746,7 +881,8 @@ export class Publisher {
746
881
  return true;
747
882
  }
748
883
  catch (err) {
749
- const e = error(err);
884
+ // The peer never answered the advertisement: a control timeout, not late content.
885
+ const e = err instanceof TimeoutError ? controlTimeout(err) : error(err);
750
886
  console.warn(`announce failed: broadcast=${path} error=${reason(e)}`);
751
887
  request?.abort(e);
752
888
  return false;
@@ -790,41 +926,26 @@ export class Publisher {
790
926
  */
791
927
  async runTrackStatusRequest(msg, stream) {
792
928
  const version = this.#session.version;
929
+ const errorCode = toRequestCode("not_supported", "track_status", version);
793
930
  if (version === Version.DRAFT_14) {
794
- // v14: respond with TrackStatus (0x0E = TRACK_STATUS_OK)
795
- await stream.writer.u53(TrackStatus.id);
796
- const status = new TrackStatus({
797
- trackNamespace: msg.trackNamespace,
798
- trackName: msg.trackName,
799
- statusCode: TrackStatus.STATUS_NOT_FOUND,
800
- lastGroupId: 0n,
801
- lastObjectId: 0n,
802
- });
803
- await status.encode(stream.writer, version);
931
+ // TRACK_STATUS_ERROR shares the SUBSCRIBE_ERROR body on draft-14.
932
+ await stream.writer.u53(0x0f);
933
+ await new SubscribeError({
934
+ requestId: msg.requestId,
935
+ errorCode,
936
+ reasonPhrase: "TRACK_STATUS is not supported",
937
+ }).encode(stream.writer, version);
804
938
  }
805
939
  else {
806
- // v15+: respond with RequestOk (0x07)
807
- await stream.writer.u53(RequestOk.id);
808
- const ok = new RequestOk({
940
+ await stream.writer.u53(RequestError.id);
941
+ await new RequestError({
809
942
  requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined,
810
- });
811
- await ok.encode(stream.writer, version);
943
+ errorCode,
944
+ reasonPhrase: "TRACK_STATUS is not supported",
945
+ }).encode(stream.writer, version);
812
946
  }
813
947
  stream.close();
814
948
  }
815
- /**
816
- * Closes every published broadcast and stops accepting new ones.
817
- *
818
- * @internal
819
- */
820
- close() {
821
- this.#broadcasts.update((broadcasts) => {
822
- for (const broadcast of broadcasts?.values() ?? []) {
823
- broadcast.close();
824
- }
825
- return undefined;
826
- });
827
- }
828
949
  }
829
950
  /**
830
951
  * Take one group out of a cache view, without waiting.