diff --git a/js/net/src/ietf/connection.ts b/js/net/src/ietf/connection.ts index e5b28abc080..a758b226819 100644 --- a/js/net/src/ietf/connection.ts +++ b/js/net/src/ietf/connection.ts @@ -42,6 +42,12 @@ import { type IetfVersion, Version, versionName } from "./version.ts"; // The PADDING stream type (draft-18+): bytes a peer sends to probe for bandwidth. const PADDING = 0x132b3e28n; +// A handler owns its request stream, and ending the request (closing the session over a +// violation) is its job: closing again here could only send a competing code. +function handed(task: Promise): Promise { + return task.catch((err: unknown) => console.error("error processing bidi stream", err)); +} + /** * Represents a connection to a MoQ server using moq-transport protocol. * @@ -373,7 +379,7 @@ export class Connection implements Established { case BigInt(SubscribeNamespace.id): { const decoded = SubscribeNamespace.decode(stream.reader, this.#session.version); const msg = await this.#request(stream, "subscribe_namespace", decoded); - if (msg) await this.#publisher.runSubscribeNamespace(msg, stream); + if (msg) await handed(this.#publisher.runSubscribeNamespace(msg, stream)); break; } case BigInt(SubscribeNamespaceLegacy.id): { @@ -403,14 +409,14 @@ export class Connection implements Established { this.#spend(legacy.requestId); try { if (legacy.subscribeOptions === SubscribeOptions.PUBLISH) { - await this.#publisher.refuseSubscribeNamespace(legacy.requestId, stream); + await handed(this.#publisher.refuseSubscribeNamespace(legacy.requestId, stream)); } else { const msg = new SubscribeNamespace({ requestId: legacy.requestId, namespace: legacy.namespace, hidden: legacy.hidden, }); - await this.#publisher.runSubscribeNamespace(msg, stream); + await handed(this.#publisher.runSubscribeNamespace(msg, stream)); } } finally { adapter?.releaseRequest(legacy.requestId); @@ -426,7 +432,7 @@ export class Connection implements Established { case BigInt(Subscribe.id): { const decoded = Subscribe.decode(stream.reader, this.#session.version); const msg = await this.#request(stream, "subscribe", decoded); - if (msg) await this.#publisher.runSubscribe(msg, stream); + if (msg) await handed(this.#publisher.runSubscribe(msg, stream)); break; } case BigInt(SUBSCRIBE_TRACKS_ID): { @@ -443,19 +449,19 @@ export class Connection implements Established { throw malformed(err, "subscribe_tracks"); }); this.#session.spendRequest(request.requestId); - await this.#publisher.runSubscribeTracks(stream, request.namespace); + await handed(this.#publisher.runSubscribeTracks(stream, request.namespace)); break; } case BigInt(TrackStatusRequest.id): { const decoded = TrackStatusRequest.decode(stream.reader, this.#session.version); const msg = await this.#request(stream, "track_status", decoded); - if (msg) await this.#publisher.runTrackStatusRequest(msg, stream); + if (msg) await handed(this.#publisher.runTrackStatusRequest(msg, stream)); break; } case BigInt(Fetch.id): { const decoded = Fetch.decode(stream.reader, this.#session.version); const msg = await this.#request(stream, "fetch", decoded); - if (msg) await this.#publisher.runFetch(msg, stream); + if (msg) await handed(this.#publisher.runFetch(msg, stream)); break; } @@ -488,7 +494,7 @@ export class Connection implements Established { break; } - await this.#subscriber.runPublishNamespace(msg, stream); + await handed(this.#subscriber.runPublishNamespace(msg, stream)); break; } case BigInt(AuthMessage.id): { @@ -500,7 +506,7 @@ export class Connection implements Established { case BigInt(Publish.id): { const decoded = Publish.decode(stream.reader, this.#session.version); const msg = await this.#request(stream, "publish", decoded); - if (msg) await this.#subscriber.runPublish(msg, stream); + if (msg) await handed(this.#subscriber.runPublish(msg, stream)); break; } diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index f33eed8c224..8c7d801b580 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -200,6 +200,7 @@ function requestStream(version: IetfVersion) { stream, written, wire: () => new Reader(undefined, Uint8Array.from(written), version), + send: (bytes: Uint8Array) => input.enqueue(bytes), cancel: () => input.error(new Error("request cancelled")), }; } @@ -319,6 +320,42 @@ test("TRACK_STATUS outside the grant is refused on every draft", async () => { } }); +// Nothing answers a SUBSCRIBE while its broadcast resolves, yet the request stream is still +// read: a second GOAWAY then closes the session at once, not once an answer goes out. +test("a second GOAWAY on an unanswered SUBSCRIBE closes the session", async () => { + for (const version of [Version.DRAFT_18, Version.DRAFT_21]) { + const pair = createMockTransportPair(ALPNS[version]); + const session = new NativeSession(pair.server, version, true); + const { pub, origin } = publisher(pair.server, { session }); + const requests = origin.dynamic(Path.from("room")).requested(); + + const held = requestStream(version); + const task = pub.runSubscribe( + new Subscribe({ + requestId: 0n, + trackNamespace: Path.from("room"), + trackName: "video", + subscriberPriority: 0, + }), + held.stream, + ); + expect((await requests.next()).value?.path).toBe(Path.from("room")); + // GOAWAY with no new session and no timeout, twice. + held.send(Uint8Array.of(0x10, 0, 2, 0, 0, 0x10, 0, 2, 0, 0)); + + const closed = await Promise.race([ + pair.server.closed, + new Promise((_resolve, reject) => setTimeout(() => reject(new Error("session stayed up")), 500)), + ]); + expect(closed.closeCode).toBe(SessionCode.ProtocolViolation); + await task; + expect(held.written).toEqual([]); + + await requests.return?.(); + origin.close(); + } +}); + test("TRACK_STATUS for a missing broadcast or track is refused DOES_NOT_EXIST", async () => { for (const version of IETF_VERSIONS) { const missing = toRequestCode("does_not_exist", "track_status", version); diff --git a/js/net/src/ietf/publisher.ts b/js/net/src/ietf/publisher.ts index 2d48c91f4da..41d41bf2c78 100644 --- a/js/net/src/ietf/publisher.ts +++ b/js/net/src/ietf/publisher.ts @@ -59,14 +59,11 @@ import { } from "./publish_namespace.ts"; import { RequestError, RequestOk } from "./request.ts"; import { - cancelled, - ended, - finCancels, + type Framed, malformed, namespaceUpdate, - nextMessage, type Refusal, - refuse, + RequestStream, refuseReserved, refuseUpdate, } from "./request_stream.ts"; @@ -170,9 +167,9 @@ type Answer = "held" | "dropped" | Refused; type NamespaceRequest = { path: Path.Valid; requestId: bigint; - stream: Stream; + stream: RequestStream; auth?: Auth; - reply?: Promise; + reply?: Promise; updating?: boolean; }; @@ -437,10 +434,15 @@ export class Publisher { * * @internal */ - async runSubscribe(msg: Subscribe, stream: Stream) { + runSubscribe(msg: Subscribe, stream: Stream): Promise { + const request = new RequestStream(stream, this.#session, this.#quic); + return request.serve(this.#runSubscribe(msg, request)); + } + + async #runSubscribe(msg: Subscribe, request: RequestStream) { this.#pinned(msg.epoch); if (Namespace.reserved(msg.trackNamespace, this.#session.version)) { - await refuseReserved(stream, this.#session.version); + await refuseReserved(request); return; } // Only a subscription we would serve holds a slot, as in Rust: a refused one ends at @@ -448,13 +450,13 @@ export class Publisher { const charged = msg.forward && !msg.rangeFilters && this.#gate.allows(msg.trackNamespace); if (charged) this.#subscriptions.acquire(); try { - await this.#serveSubscribe(msg, stream); + await this.#serveSubscribe(msg, request); } finally { if (charged) this.#subscriptions.release(); } } - async #serveSubscribe(msg: Subscribe, stream: Stream) { + async #serveSubscribe(msg: Subscribe, request: RequestStream) { const version = this.#session.version; const name = msg.trackNamespace; let broadcast: broadcast.Consumer | undefined; @@ -465,7 +467,7 @@ export class Publisher { // is answered, which may be never. const left = new AbortController(); const cancel = new StreamError(StreamCode.Cancel, { message: "cancel" }); - void cancelled(stream, version).then(() => left.abort(cancel)); + void request.ended.then(() => left.abort(cancel)); // Legal requests we can't honor are refused one at a time. A subscription that // forwards nothing is only useful to a subscriber that later turns forwarding on, @@ -495,7 +497,7 @@ export class Publisher { } catch (err: unknown) { // Nobody is left to refuse. if (left.signal.aborted) { - stream.abort(cancel); + request.abort(cancel); return; } refusal = this.#failed(err, rendezvous); @@ -503,7 +505,7 @@ export class Publisher { } if (refusal) { - await refuse(stream, version, "subscribe", { ...refusal, requestId: msg.requestId }); + await request.refuse("subscribe", { ...refusal, requestId: msg.requestId }); return; } if (!broadcast) return; @@ -537,7 +539,7 @@ export class Publisher { throw err; // The broadcast resolved, so only a vanished route still means a missing publisher; // a missing track is the publisher's answer. - await refuse(stream, version, "subscribe", { + await request.refuse("subscribe", { ...this.#failed(err, rendezvous && failed.code === StreamCode.Unroutable), requestId: msg.requestId, }); @@ -586,7 +588,7 @@ export class Publisher { : undefined; // Send SUBSCRIBE_OK - await stream.writer.u53(SubscribeOk.id); + await request.writer.u53(SubscribeOk.id); const ok = new SubscribeOk({ requestId: version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16 @@ -623,7 +625,7 @@ export class Publisher { // the track opts out of timestamps for this subscriber. {}, }); - await ok.encode(stream.writer, version); + await ok.encode(request.writer, version); console.debug(`publish ok: broadcast=${name} track=${track.name}`); // Cancels groups still queued for a stream slot. Only the subscriber leaving counts: @@ -637,24 +639,24 @@ export class Publisher { const legacy = version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16; const updates = (async () => { for (;;) { - const type = await nextMessage(stream.reader, version, this.#session.client).catch( - (err: unknown) => { - throw malformed(err, "subscription message"); - }, - ); - if (type === undefined) { - if (legacy || finCancels(version)) return; - return stream.writer.closed; - } - if (type !== 0x02) - throw new ProtocolViolation(`unexpected message on a subscription: 0x${type.toString(16)}`); + const framed = await request.next(); + // The requester sent its last message, which ends the request only where FIN cancels. + if (framed === undefined) return request.ended; + if (framed.type !== 0x02) + throw new ProtocolViolation( + `unexpected message on a subscription: 0x${framed.type.toString(16)}`, + ); // Drafts 15 and 16 name the update's own Request ID. const refused = async ( condition: "not_supported" | "malformed_auth_token", reasonPhrase: string, requestId: bigint | undefined, ) => { - await refuseUpdate(stream.writer, version, "subscribe", { requestId, condition, reasonPhrase }); + await refuseUpdate(request.writer, version, "subscribe", { + requestId, + condition, + reasonPhrase, + }); return new UpdateFailed(); }; let ownRequestId: bigint | undefined; @@ -662,11 +664,11 @@ export class Publisher { try { if (legacy) { // The adapter already spent the update's own Request ID. - const update = await SubscribeUpdate.decode(stream.reader, version); + const update = await SubscribeUpdate.decode(framed.reader, version); ownRequestId = update.ownRequestId; params = update.parameters; } else { - params = await Message.decode(stream.reader, async (r) => { + params = await Message.decode(framed.reader, async (r) => { this.#session.spendRequest(await r.u62()); if (version === Version.DRAFT_17) await r.u62(); return Parameters.decode(r, version, "request-update"); @@ -703,11 +705,11 @@ export class Publisher { if (params.maxAge !== undefined) track.update({ ...track.subscription.peek(), maxDelay: Milli(params.maxAge) }); if (version === Version.DRAFT_14) continue; - await stream.writer.u53(RequestOk.id); - await new RequestOk({ requestId: ownRequestId }).encode(stream.writer, version); + await request.writer.u53(RequestOk.id); + await new RequestOk({ requestId: ownRequestId }).encode(request.writer, version); } })(); - const requestEnded = legacy ? updates : race([updates, stream.writer.closed]); + const requestEnded = race([updates, request.ended]); void requestEnded.then( () => { if (!finished) unsubscribe(); @@ -845,7 +847,7 @@ export class Publisher { // Draft 14 registers no UPDATE_FAILED, so a failed update ends there as any error does. const updateFailed = publishError instanceof UpdateFailed && version !== Version.DRAFT_14; try { - await stream.writer.u53(PublishDone.id); + await request.writer.u53(PublishDone.id); const done = new PublishDone({ requestId: version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16 @@ -867,20 +869,20 @@ export class Publisher { ? "internal error" : "track ended", }); - await done.encode(stream.writer, version); + await done.encode(request.writer, version); } catch { // Stream might already be closed by peer. } // Our close follows PUBLISH_DONE; it must not cancel data still queued for delivery. finished = true; - stream.close(); + request.close(); } catch (err: unknown) { if (err instanceof ProtocolViolation) throw err; const e = error(err); if (e === cancel) console.debug(`publish cancelled: broadcast=${name} track=${track.name}`); else console.warn(`publish error: broadcast=${name} track=${track.name} error=${reason(e)}`); - stream.abort(e); + request.abort(e); } finally { // Groups still draining keep being ranked until they finish. ranking?.close(); @@ -1226,12 +1228,13 @@ export class Publisher { * @internal */ runSubscribeNamespace(msg: SubscribeNamespace, stream: Stream): Promise { - return this.#withdrawal.track(this.#runSubscribeNamespace(msg, stream)); + const request = new RequestStream(stream, this.#session, this.#quic); + return this.#withdrawal.track(request.serve(this.#runSubscribeNamespace(msg, request))); } - async #runSubscribeNamespace(msg: SubscribeNamespace, stream: Stream) { + async #runSubscribeNamespace(msg: SubscribeNamespace, request: RequestStream) { if (Namespace.reserved(msg.namespace, this.#session.version)) { - await refuseReserved(stream, this.#session.version); + await refuseReserved(request); return; } if (this.#withdrawal.closing.peek()) return; @@ -1248,30 +1251,30 @@ export class Publisher { } }; - const ending = cancelled(stream, version); + const ending = request.ended; const readUpdate = () => - namespaceUpdate(stream.reader, version, this.#session.client).then( - (update) => ({ update }), - (err) => ({ error: error(err) }), - ); + (async () => { + const framed = await request.next(); + return { update: framed && (await namespaceUpdate(framed, version)) }; + })().catch((err: unknown) => ({ error: error(err) })); // Drafts 14-16 route an update onto the stream too, which stays open behind one left unread. let updating = version !== Version.DRAFT_17 ? readUpdate() : undefined; try { const answer = async (activeCount?: number) => { if (version === Version.DRAFT_14) { - await stream.writer.u53(SubscribeNamespaceOk.id); + await request.writer.u53(SubscribeNamespaceOk.id); const ok = new SubscribeNamespaceOk({ requestId: msg.requestId }); - await ok.encode(stream.writer, version); + await ok.encode(request.writer, version); return; } const parameters = new Parameters(); parameters.activeCount = activeCount; - await stream.writer.u53(RequestOk.id); + await request.writer.u53(RequestOk.id); const ok = new RequestOk({ requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined, parameters, }); - await ok.encode(stream.writer, version); + await ok.encode(request.writer, version); }; // MoQ Active Count: the OK counts what the first pass below sends, so it waits for @@ -1296,10 +1299,10 @@ export class Publisher { // publisher included, as Rust does. Only a legacy PUBLISH_NAMESPACE request can // be declined. const namespace = async (suffix: Path.Valid, snap: Advertised): Promise => { - await stream.writer.u53(SubscribeNamespaceEntry.id); + await request.writer.u53(SubscribeNamespaceEntry.id); // Either extension puts the Parameters field on NAMESPACE, even an empty one. const params = this.#advert !== undefined || this.#epoch ? this.#params(snap.route) : undefined; - await new SubscribeNamespaceEntry({ suffix, params }).encode(stream.writer, version); + await new SubscribeNamespaceEntry({ suffix, params }).encode(request.writer, version); return "held"; }; const target: Target = legacy @@ -1319,8 +1322,8 @@ export class Publisher { held: () => undefined, carry: () => undefined, withdraw: async (suffix) => { - await stream.writer.u53(SubscribeNamespaceEntryDone.id); - await new SubscribeNamespaceEntryDone({ suffix }).encode(stream.writer, version); + await request.writer.u53(SubscribeNamespaceEntryDone.id); + await new SubscribeNamespaceEntryDone({ suffix }).encode(request.writer, version); }, }; @@ -1387,7 +1390,7 @@ export class Publisher { const keyed = version <= Version.DRAFT_16; if (!keyed) this.#session.spendRequest(update.requestId); if (update.refused || (update.prefix !== undefined && Namespace.reserved(update.prefix, version))) { - await refuseUpdate(stream.writer, version, "subscribe_namespace", { + await refuseUpdate(request.writer, version, "subscribe_namespace", { requestId: update.requestId, condition: update.refused ?? "does_not_exist", reasonPhrase: "namespace update refused", @@ -1405,8 +1408,8 @@ export class Publisher { // A new cursor starts its backoff fresh, as in Rust. retry = 0; } - await stream.writer.u53(RequestOk.id); - await new RequestOk({ requestId: undefined }).encode(stream.writer, version); + await request.writer.u53(RequestOk.id); + await new RequestOk({ requestId: undefined }).encode(request.writer, version); updating = readUpdate(); } } @@ -1414,20 +1417,18 @@ export class Publisher { // Withdraw before the ask stream FINs, as Rust does: a peer that reads that // FIN as the subscription ending can drop the DONEs still in flight. await withdrawAll(); - stream.close(); - await stream.writer.closed; + request.close(); + await request.writer.closed; } catch (err: unknown) { const e = error(err); console.debug(`subscribe_namespace stream error: ${reason(e)}`); - stream.abort(e); + request.abort(e); if (e instanceof ProtocolViolation || this.#withdrawal.closing.peek()) throw e; } finally { // This subscription's advertisements die with it. await withdrawAll(); - if (updating !== undefined) { - stream.reader.stop(new Error("namespace subscription ended")); - await updating; - } + // Closing stopped the read, which settles it. + await updating; } } @@ -1748,23 +1749,27 @@ export class Publisher { // a peer out of stream credit rejects here, and letting that escape would unwind // the announce loop and take discovery down for the whole session, rather than // leaving this one namespace unadvertised. - let request: Stream | undefined; + let request: RequestStream | undefined; try { const deadline = new Deadline(); const answer = await deadline.wait( (async (): Promise => { - request = await deadline.open(this.#session.openBi(requestOptions)); - const stream = request; - await stream.writer.u53(PublishNamespace.id); + const opened = new RequestStream( + await deadline.open(this.#session.openBi(requestOptions)), + this.#session, + this.#quic, + ); + request = opened; + await opened.writer.u53(PublishNamespace.id); const token = this.#auth?.carried(auth); const msg = new PublishNamespace({ requestId, trackNamespace: path, params, token }); - await msg.encode(stream.writer, this.#session.version); + await msg.encode(opened.writer, this.#session.version); // Read response (RequestOk and PublishNamespaceOk share 0x07) - const respTypeId = await nextMessage(stream.reader, this.#session.version, this.#session.client); - if (respTypeId === undefined) throw new Error("advertisement ended before its response"); - if (respTypeId === RequestError.id) { - const err = await RequestError.decode(stream.reader, this.#session.version); + const response = await opened.next(); + if (response === undefined) throw new Error("advertisement ended before its response"); + if (response.type === RequestError.id) { + const err = await RequestError.decode(response.reader, this.#session.version); const why = requestReason( err.errorCode, err.reasonPhrase, @@ -1772,17 +1777,17 @@ export class Publisher { this.#session.version, ); console.warn(`announce refused: broadcast=${path} error=${why}`); - stream.abort(new Error(`PublishNamespace rejected: ${why}`)); + opened.abort(new Error(`PublishNamespace rejected: ${why}`)); return this.#refusal(err); } - if (respTypeId !== RequestOk.id) { - throw new Error(`PublishNamespace rejected: typeId=0x${respTypeId.toString(16)}`); + if (response.type !== RequestOk.id) { + throw new Error(`PublishNamespace rejected: typeId=0x${response.type.toString(16)}`); } // Draft-14 sends PublishNamespaceOk (requestId only, no parameters) if (this.#session.version === Version.DRAFT_14) { - await PublishNamespaceOk.decode(stream.reader, this.#session.version); + await PublishNamespaceOk.decode(response.reader, this.#session.version); } else { - this.#answered(await RequestOk.decode(stream.reader, this.#session.version)); + this.#answered(await RequestOk.decode(response.reader, this.#session.version)); } return "held"; })(), @@ -1797,10 +1802,6 @@ export class Publisher { } catch (err: unknown) { // The peer never answered the advertisement: a control timeout, not late content. const e = err instanceof TimeoutError ? controlTimeout(err) : error(err); - if (e instanceof ProtocolViolation) { - this.#quic.close({ closeCode: e.code, reason: e.message }); - this.#session.close(); - } console.warn(`announce failed: broadcast=${path} error=${reason(e)}`); request?.abort(e); return e instanceof NoStreamCredit || (e instanceof StreamError && e.code === StreamCode.ControlTimeout) @@ -1814,24 +1815,19 @@ export class Publisher { * update. A stream that ends while idle drops the request, and the announce loop re-offers it * after a backoff. */ - #readAdvertisement(request: NamespaceRequest, requests: Requests): Promise { - const reply = nextMessage(request.stream.reader, this.#session.version, this.#session.client) - .then((type) => { - if (type !== undefined && !request.updating) - throw new ProtocolViolation("unexpected message on an idle advertisement"); - return type; - }) - .catch((err: unknown) => { - if (err instanceof ProtocolViolation) { - this.#quic.close({ closeCode: err.code, reason: err.message }); - this.#session.close(); - } - throw err; - }); + #readAdvertisement(request: NamespaceRequest, requests: Requests): Promise { + const reply = request.stream.next().then((framed) => { + if (framed !== undefined && !request.updating) + throw new ProtocolViolation("unexpected message on an idle advertisement"); + return framed; + }); // A later update consumes an answer; an end is acted on as soon as it arrives. void reply.then( - (type) => type === undefined && this.#lapse(request, requests), - () => this.#lapse(request, requests), + (framed) => framed === undefined && this.#lapse(request, requests), + (err: unknown) => { + if (err instanceof ProtocolViolation) request.stream.abort(err); + this.#lapse(request, requests); + }, ); return reply; } @@ -1846,21 +1842,12 @@ export class Publisher { /** * Check a REQUEST_OK answering a PUBLISH_NAMESPACE. ACTIVE_COUNT only answers - * SUBSCRIBE_NAMESPACE (MoQ Active Count), and the session closes over it here, with the - * violation's code, since the caller only drops the advertisement. + * SUBSCRIBE_NAMESPACE (MoQ Active Count), and reading one too large to hold throws the + * same violation. */ #answered(ok: RequestOk) { - try { - // Reading it throws on a count too large to hold, a violation all the same. - if (ok.parameters.activeCount === undefined) return; + if (ok.parameters.activeCount !== undefined) throw new ProtocolViolation("ACTIVE_COUNT on a PUBLISH_NAMESPACE answer"); - } catch (err) { - if (err instanceof ProtocolViolation) { - this.#quic.close({ closeCode: err.code, reason: err.message }); - this.#session.close(); - } - throw err; - } } /** @@ -1895,7 +1882,7 @@ export class Publisher { answer = await withTimeout( (async (): Promise => { - const { writer, reader } = request.stream; + const writer = request.stream.writer; request.updating = true; await writer.u53(PublishNamespaceUpdate.id); const namespaceRequestId = version === Version.DRAFT_16 ? request.requestId : undefined; @@ -1904,22 +1891,23 @@ export class Publisher { version, ); - // Draft 16's adapter ends the stream on the peer's PUBLISH_NAMESPACE_CANCEL, which - // can beat the answer. - if (version === Version.DRAFT_16 && (await reader.done())) return "dropped"; - - const typeId = await (request.reply ?? nextMessage(reader, version, this.#session.client)); - if (typeId === undefined) throw new Error("advertisement ended before its update response"); - if (typeId === RequestError.id) { - const err = await RequestError.decode(reader, version); + const response = await (request.reply ?? request.stream.next()); + if (response === undefined) { + // Draft 16's adapter ends the stream on the peer's PUBLISH_NAMESPACE_CANCEL, + // which can beat the answer. + if (version === Version.DRAFT_16) return "dropped"; + throw new Error("advertisement ended before its update response"); + } + if (response.type === RequestError.id) { + const err = await RequestError.decode(response.reader, version); const why = requestReason(err.errorCode, err.reasonPhrase, "publish_namespace", version); console.warn(`publish_namespace update refused: broadcast=${path} error=${why}`); return this.#refusal(err); } - if (typeId !== RequestOk.id) { - throw new Error(`unexpected answer to the update: typeId=0x${typeId.toString(16)}`); + if (response.type !== RequestOk.id) { + throw new Error(`unexpected answer to the update: typeId=0x${response.type.toString(16)}`); } - this.#answered(await RequestOk.decode(reader, version)); + this.#answered(await RequestOk.decode(response.reader, version)); request.updating = false; if (version >= Version.DRAFT_18) request.reply = this.#readAdvertisement(request, requests); return "held"; @@ -1929,15 +1917,12 @@ export class Publisher { ); } catch (err: unknown) { const e = err instanceof TimeoutError ? controlTimeout(err) : error(err); - if (e instanceof ProtocolViolation) { - this.#quic.close({ closeCode: e.code, reason: e.message }); - this.#session.close(); - } console.warn(`publish_namespace update failed: broadcast=${path} error=${reason(e)}`); requests.delete(path); // Aborting a request riding the control stream tells the peer nothing, so it would - // hold the namespace beside the one advertised next. - if (version === Version.DRAFT_16) await this.#end(request).catch(() => undefined); + // hold the namespace beside the one advertised next. A violation ends the session. + if (version === Version.DRAFT_16 && !(e instanceof ProtocolViolation)) + await this.#end(request).catch(() => undefined); else request.stream.abort(e); return "dropped"; } @@ -2014,10 +1999,15 @@ export class Publisher { * * @internal */ - async runTrackStatusRequest(msg: TrackStatusRequest, stream: Stream) { + runTrackStatusRequest(msg: TrackStatusRequest, stream: Stream): Promise { + const request = new RequestStream(stream, this.#session, this.#quic); + return request.serve(this.#runTrackStatusRequest(msg, request)); + } + + async #runTrackStatusRequest(msg: TrackStatusRequest, request: RequestStream) { this.#pinned(msg.epoch); if (Namespace.reserved(msg.trackNamespace, this.#session.version)) { - await refuseReserved(stream, this.#session.version); + await refuseReserved(request); return; } const version = this.#session.version; @@ -2027,7 +2017,7 @@ export class Publisher { // Answer only for what our grant lets us publish. Checked before the track resolves, // so a denied request never reaches the origin. if (!this.#gate.allows(name)) { - await refuse(stream, version, "track_status", denied); + await request.refuse("track_status", denied); return; } @@ -2035,23 +2025,21 @@ export class Publisher { // nothing, and lets go of the broadcast and track lookups. const hold = new AbortController(); const cancel = new StreamError(StreamCode.Cancel, { message: "cancel" }); - void ended(stream, version, this.#session.client).then( - () => hold.abort(cancel), - (err) => { - if (err instanceof ProtocolViolation) { - this.#quic.close({ closeCode: err.code, reason: err.message }); - this.#session.close(); - } - hold.abort(cancel); - }, - ); + void request.ended.then(() => hold.abort(cancel)); + // Nothing may follow the request. Drafts 14-16 route only their own follow-ups here. + if (version > Version.DRAFT_16) + void request.next().then( + (framed) => framed && request.abort(new ProtocolViolation("unexpected request stream message")), + // The request ended, which the hold already heard. + () => undefined, + ); // A grant that narrows abandons the lookup, and resets an answer the transport has // not taken yet rather than delivering it. let answering = false; const watch = this.#gate.watch(name, () => { hold.abort(); - if (answering) stream.abort(unauthorized(name)); + if (answering) request.abort(unauthorized(name)); }); try { @@ -2077,20 +2065,20 @@ export class Publisher { }); } catch (err: unknown) { if (hold.signal.reason === cancel) { - stream.abort(cancel); + request.abort(cancel); return; } const refusal = !this.#gate.allows(name) ? denied : { ...this.#failed(err), requestId: msg.requestId }; - await refuse(stream, version, "track_status", refusal); + await request.refuse("track_status", refusal); return; } answering = true; - await stream.writer.u53(TrackStatusOk.id(version)); - await answer.encode(stream.writer, version); + await request.writer.u53(TrackStatusOk.id(version)); + await answer.encode(request.writer, version); // The answer is all this stream carries. - stream.close(); - await stream.writer.closed.catch(() => undefined); + request.close(); + await request.writer.closed.catch(() => undefined); } finally { watch.dispose(); hold.abort(); @@ -2102,12 +2090,15 @@ export class Publisher { * * @internal */ - async refuseSubscribeNamespace(requestId: bigint, stream: Stream) { - await refuse(stream, this.#session.version, "subscribe_namespace", { - requestId, - condition: "not_supported", - reasonPhrase: "SUBSCRIBE_NAMESPACE for PUBLISH is not supported", - }); + refuseSubscribeNamespace(requestId: bigint, stream: Stream): Promise { + const request = new RequestStream(stream, this.#session, this.#quic); + return request.serve( + request.refuse("subscribe_namespace", { + requestId, + condition: "not_supported", + reasonPhrase: "SUBSCRIBE_NAMESPACE for PUBLISH is not supported", + }), + ); } /** @@ -2116,15 +2107,16 @@ export class Publisher { * * @internal */ - async runSubscribeTracks(stream: Stream, namespace?: Path.Valid) { - if (namespace !== undefined && Namespace.reserved(namespace, this.#session.version)) { - await refuseReserved(stream, this.#session.version); - return; - } - await refuse(stream, this.#session.version, "subscribe_namespace", { - condition: "not_supported", - reasonPhrase: "SUBSCRIBE_TRACKS is not supported", - }); + runSubscribeTracks(stream: Stream, namespace?: Path.Valid): Promise { + const request = new RequestStream(stream, this.#session, this.#quic); + return request.serve( + namespace !== undefined && Namespace.reserved(namespace, this.#session.version) + ? refuseReserved(request) + : request.refuse("subscribe_namespace", { + condition: "not_supported", + reasonPhrase: "SUBSCRIBE_TRACKS is not supported", + }), + ); } /** @@ -2132,15 +2124,20 @@ export class Publisher { * * @internal */ - async runFetch(msg: Fetch, stream: Stream) { + runFetch(msg: Fetch, stream: Stream): Promise { + const request = new RequestStream(stream, this.#session, this.#quic); + return request.serve(this.#runFetch(msg, request)); + } + + async #runFetch(msg: Fetch, request: RequestStream) { this.#pinned(msg.epoch); this.#fetches.acquire(); try { if (msg.trackNamespace !== undefined && Namespace.reserved(msg.trackNamespace, this.#session.version)) { - await refuseReserved(stream, this.#session.version); + await refuseReserved(request); return; } - await refuse(stream, this.#session.version, "fetch", { + await request.refuse("fetch", { requestId: msg.requestId, condition: msg.rangeFilters ? "invalid_filter" : "not_supported", reasonPhrase: msg.rangeFilters ? "Range Filters exceed MAX_FILTER_RANGES=0" : "FETCH is not supported", diff --git a/js/net/src/ietf/request_stream.test.ts b/js/net/src/ietf/request_stream.test.ts index 510dca53600..ac45e473ad1 100644 --- a/js/net/src/ietf/request_stream.test.ts +++ b/js/net/src/ietf/request_stream.test.ts @@ -1,27 +1,59 @@ import { expect, test } from "bun:test"; -import { ProtocolViolation } from "../error.ts"; +import { ProtocolViolation, SessionCode } from "../error.ts"; import { Reader, Stream } from "../stream.ts"; import * as Varint from "../varint.ts"; +import type { Session } from "./adapter.ts"; import { type RequestKind, toRequestCode } from "./error.ts"; import { FetchError } from "./fetch.ts"; import { PublishError } from "./publish.ts"; import { PublishNamespaceError } from "./publish_namespace.ts"; import { RequestError } from "./request.ts"; -import { namespaceUpdate, nextMessage, refuse, refuseUpdate } from "./request_stream.ts"; +import { namespaceUpdate, nextMessage, RequestStream, refuse, refuseUpdate } from "./request_stream.ts"; import { SubscribeError } from "./subscribe.ts"; import { SubscribeNamespaceError } from "./subscribe_namespace.ts"; import { TRACK_STATUS_ERROR_14 } from "./track.ts"; import { type IetfVersion, Version, versionName } from "./version.ts"; -test("an oversized or truncated namespace update type is a protocol violation", async () => { +/** + * A request stream the peer wrote `bytes` on, then optionally ended once they were read, + * recording how the session was closed. + */ +function requested(version: IetfVersion, bytes: Uint8Array, end?: "fin" | "reset") { + const closes: (WebTransportCloseInfo | undefined)[] = []; + const quic = { close: (info?: WebTransportCloseInfo) => closes.push(info) } as unknown as WebTransport; + const session = { version, client: true, close: () => closes.push(undefined) } as unknown as Session; + const stream = new Stream({ + readable: new ReadableStream({ + start(c) { + c.enqueue(bytes); + }, + // Pulled once the bytes are read, whether or not anyone reads further. + pull(c) { + if (end === "fin") c.close(); + // Shaped like the WebTransportError a peer's RESET_STREAM fails the read with. + if (end === "reset") + c.error(Object.assign(new Error("reset"), { source: "stream", streamErrorCode: null })); + }, + }), + writable: new WritableStream(), + version, + }); + return { request: new RequestStream(stream, session, quic), closes }; +} + +// GOAWAY with no new session and no timeout. +const GOAWAY = [0x10, 0, 2, 0, 0]; + +test("an oversized or truncated request stream message type is a protocol violation", async () => { // Both drafts use leading-ones varints. for (const version of [Version.DRAFT_18, Version.DRAFT_21]) { const oversized = Varint.encodeLeadingOnes(2n ** 53n); // A two-byte varint prefix with its second byte missing. const truncated = Uint8Array.of(0x80); for (const bytes of [oversized, truncated]) { - const reader = new Reader(undefined, bytes, version); - await expect(namespaceUpdate(reader, version, false)).rejects.toBeInstanceOf(ProtocolViolation); + const { request, closes } = requested(version, bytes, "fin"); + await expect(request.next()).rejects.toBeInstanceOf(ProtocolViolation); + expect(closes[0]?.closeCode).toBe(SessionCode.ProtocolViolation); } } }); @@ -29,22 +61,61 @@ test("an oversized or truncated namespace update type is a protocol violation", test("namespace update framing refuses duplicate prefix parameters", async () => { for (const version of [Version.DRAFT_18, Version.DRAFT_21]) { const body = [2, 2, 0x34, 1, 1, 97, 0, 1, 1, 98]; - const reader = new Reader(undefined, Uint8Array.from([2, 0, body.length, ...body]), version); - await expect(namespaceUpdate(reader, version, false)).rejects.toBeInstanceOf(ProtocolViolation); + const reader = new Reader(undefined, Uint8Array.from([0, body.length, ...body]), version); + await expect(namespaceUpdate({ type: 2, reader }, version)).rejects.toBeInstanceOf(ProtocolViolation); } }); test("a repeated namespace update token is a request refusal", async () => { for (const version of [Version.DRAFT_18, Version.DRAFT_21]) { const body = [2, 2, 3, 3, 3, 0, 170, 0, 3, 3, 0, 170]; - const reader = new Reader(undefined, Uint8Array.from([2, 0, body.length, ...body]), version); - expect(await namespaceUpdate(reader, version, false)).toEqual({ + const reader = new Reader(undefined, Uint8Array.from([0, body.length, ...body]), version); + expect(await namespaceUpdate({ type: 2, reader }, version)).toEqual({ requestId: 2n, refused: "malformed_auth_token", }); } }); +for (const version of [Version.DRAFT_18, Version.DRAFT_21]) { + test(`${versionName(version)} a request nobody reads yet still refuses a second GOAWAY`, async () => { + const { request, closes } = requested(version, Uint8Array.of(...GOAWAY, ...GOAWAY)); + await request.ended; + expect(closes).toEqual([ + { closeCode: SessionCode.ProtocolViolation, reason: "second GOAWAY on a request stream" }, + undefined, + ]); + // Ending it again closes nothing more. + request.abort(new ProtocolViolation("again")); + request.close(); + expect(closes).toHaveLength(2); + }); + + test(`${versionName(version)} a request stream's messages are taken whole, around a GOAWAY`, async () => { + // An empty REQUEST_OK, then FIN. + const { request, closes } = requested(version, Uint8Array.of(...GOAWAY, 7, 0, 0), "fin"); + const framed = await request.next(); + expect(framed?.type).toBe(7); + expect(await framed?.reader.u16()).toBe(0); + expect(await request.next()).toBeUndefined(); + // FIN cancels a draft-18 request; a draft-21 one lasts until reset. + const ended = await Promise.race([request.ended.then(() => true), Bun.sleep(10).then(() => false)]); + expect(ended).toBe(version === Version.DRAFT_18); + expect(closes).toEqual([]); + }); + + test(`${versionName(version)} a request ends behind a message nobody took`, async () => { + // FIN cancels only a draft-18 request; a reset cancels on every draft. + const ends = version === Version.DRAFT_18 ? (["fin", "reset"] as const) : (["reset"] as const); + for (const end of ends) { + // An empty REQUEST_UPDATE, then the peer's end. + const { request, closes } = requested(version, Uint8Array.of(2, 0, 0), end); + await request.ended; + expect(closes).toEqual([]); + } + }); +} + for (const version of [Version.DRAFT_18, Version.DRAFT_19, Version.DRAFT_21, Version.DRAFT_22]) { test(`${versionName(version)} keeps GOAWAY state across request response phases`, async () => { // GOAWAY, an empty REQUEST_OK, and another GOAWAY on the same stream. diff --git a/js/net/src/ietf/request_stream.ts b/js/net/src/ietf/request_stream.ts index 5184f364aa9..0bec16b6c47 100644 --- a/js/net/src/ietf/request_stream.ts +++ b/js/net/src/ietf/request_stream.ts @@ -1,7 +1,7 @@ -import { race } from "@moq/signals"; -import { ProtocolViolation, StreamError } from "../error.ts"; +import { error, ProtocolViolation, StreamError } from "../error.ts"; import type * as Path from "../path.ts"; -import type { Reader, Stream, Writer } from "../stream.ts"; +import { Reader, type Stream, type Writer } from "../stream.ts"; +import type { Session } from "./adapter.ts"; import { type RequestCondition, type RequestKind, toRequestCode } from "./error.ts"; import { FetchError } from "./fetch.ts"; import { GoAway } from "./goaway.ts"; @@ -27,15 +27,6 @@ export function finCancels(version: IetfVersion): boolean { ); } -/** Wait for request cancellation, including STOP_SENDING after a clean requester FIN. */ -export async function cancelled(stream: Stream, version: IetfVersion): Promise { - const read = stream.reader.closed.then(() => (finCancels(version) ? undefined : stream.writer.closed)); - // Legacy virtual response writers finish while the adapted control request lives. - if (version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16) - return read.catch(() => undefined); - await race([read, stream.writer.closed]).catch(() => undefined); -} - /** * Why a request is refused, and which one: only drafts 14-16 name the Request ID. * @internal @@ -88,8 +79,8 @@ export async function refuseUpdate( } /** Refuse an unrecognized reserved namespace before it reaches the application. */ -export async function refuseReserved(stream: Stream, version: IetfVersion): Promise { - await refuse(stream, version, "subscribe", { +export async function refuseReserved(request: RequestStream): Promise { + await request.refuse("subscribe", { condition: "does_not_exist", reasonPhrase: "reserved namespace does not exist", }); @@ -135,32 +126,17 @@ export async function nextMessage(reader: Reader, version: IetfVersion, client: } } -/** Wait for a request's FIN or reset while still validating its GOAWAY messages. @internal */ -export async function ended(stream: Stream, version: IetfVersion, client: boolean): Promise { - if (version <= Version.DRAFT_16) return cancelled(stream, version); - const read = (async () => { - if ((await nextMessage(stream.reader, version, client)) !== undefined) - throw new ProtocolViolation("unexpected request stream message"); - if (!finCancels(version)) await stream.writer.closed; - })(); - await race([read, stream.writer.closed]); -} - /** - * Read one whole namespace update without abandoning a partial frame. + * Decode a namespace update the peer sent on its SUBSCRIBE_NAMESPACE. * @internal */ export async function namespaceUpdate( - reader: Reader, + framed: Framed, version: IetfVersion, - client: boolean, -): Promise<{ requestId: bigint; prefix?: Path.Valid; refused?: RequestCondition } | undefined> { +): Promise<{ requestId: bigint; prefix?: Path.Valid; refused?: RequestCondition }> { + if (framed.type !== 0x02) throw new ProtocolViolation("expected namespace REQUEST_UPDATE"); try { - // Inside the normalization, so an oversized or truncated type is malformed too. - const type = await nextMessage(reader, version, client); - if (type === undefined) return undefined; - if (type !== 0x02) throw new ProtocolViolation("expected namespace REQUEST_UPDATE"); - return await Message.decode(reader, async (body) => { + return await Message.decode(framed.reader, async (body) => { const requestId = await body.u62(); // Drafts 14-16 define no namespace update. The update's own Request ID is all its // refusal names; the target is what the adapter routed it by. @@ -182,6 +158,175 @@ export async function namespaceUpdate( } } +/** + * One message off a request stream, read whole so a taker that stops partway consumes nothing. + * @internal + */ +export interface Framed { + type: number; + /** The length-prefixed body, for the message's own `decode`. */ + reader: Reader; +} + +/** + * The single owner of one request stream, after its request message. + * + * Every read goes through it. From the first wait on it keeps reading, consuming GOAWAYs and + * acting on the end as they arrive, with the next message held in one slot until taken, so no + * reader is left detached. Every close goes through it once, and a protocol violation closes + * the session with its code once. + * @internal + */ +export class RequestStream { + /** Where answers to the request go. */ + readonly writer: Writer; + readonly #stream: Stream; + readonly #session: Session; + readonly #quic?: WebTransport; + // The next message, read ahead of whoever takes it. Unset until someone first waits. + #ahead?: Promise; + #taking = false; + #closed = false; + #violated = false; + readonly #ended: Promise; + #end!: () => void; + + /** Own `stream` for a request on `session`, closing `quic` over the peer's violations. */ + constructor(stream: Stream, session: Session, quic?: WebTransport) { + this.#stream = stream; + this.writer = stream.writer; + this.#session = session; + this.#quic = quic; + this.#ended = new Promise((resolve) => { + this.#end = resolve; + }); + } + + /** + * Settles once the peer ends the request, by FIN where that cancels or by resetting either + * direction, or once it closes here or over a violation. Never rejects. + */ + get ended(): Promise { + void this.#read(); + return this.#ended; + } + + /** Take the next message, or undefined once the peer finishes. One taker at a time. */ + async next(): Promise { + if (this.#taking) throw new Error("request stream already being read"); + this.#taking = true; + try { + const framed = await this.#read(); + if (framed !== undefined) this.#ahead = this.#readAhead(); + return framed; + } finally { + this.#taking = false; + } + } + + /** Refuse the request and end it. */ + async refuse(kind: RequestKind, refusal: Refusal): Promise { + await writeRefusal(this.writer, this.#session.version, kind, refusal); + this.close(); + } + + /** End the request cleanly: FIN, and stop reading. Only the first close counts. */ + close(): void { + if (this.#closed) return; + this.#closed = true; + this.#stream.close(); + this.#end(); + } + + /** + * Reset the request with `err`. A protocol violation closes the session with its code + * first, even after the request ended. Only the first close of each counts. + */ + abort(err: unknown): void { + const e = error(err); + if (e instanceof ProtocolViolation && !this.#violated) { + this.#violated = true; + // Before the session's own close, which would send a clean code. + try { + this.#quic?.close({ closeCode: e.code, reason: e.message }); + } catch { + // Already closed. + } + this.#session.close(); + } + if (this.#closed) return; + this.#closed = true; + this.#stream.abort(e); + this.#end(); + } + + /** Await `task`, which owns the request: whatever it throws ends the request, and so does returning. */ + async serve(task: Promise): Promise { + try { + await task; + } catch (err) { + this.abort(err); + throw err; + } + this.close(); + } + + // Start reading on the first wait. + #read(): Promise { + if (this.#ahead === undefined) { + const version = this.#session.version; + this.#ahead = this.#readAhead(); + // The read ahead stops at an untaken message, so watch for the peer's end apart from it. + this.#stream.reader.closed.then( + () => { + if (finCancels(version)) this.#end(); + }, + () => this.#end(), + ); + // Drafts 14-16 adapt the request onto the control stream, whose virtual writer + // finishes while the request lives. + if (version > Version.DRAFT_16) + this.writer.closed.then( + () => this.#end(), + () => this.#end(), + ); + } + return this.#ahead; + } + + // Act on the end as soon as it arrives, even while the message before it waits untaken. + #readAhead(): Promise { + const read = this.#readFramed(); + read.then( + (framed) => { + if (framed === undefined && finCancels(this.#session.version)) this.#end(); + }, + (err: unknown) => { + if (err instanceof ProtocolViolation) this.abort(err); + this.#end(); + }, + ); + return read; + } + + async #readFramed(): Promise { + const reader = this.#stream.reader; + const version = this.#session.version; + const type = await nextMessage(reader, version, this.#session.client); + if (type === undefined) return undefined; + try { + const size = await reader.u16(); + const framed = new Uint8Array(2 + size); + framed[0] = size >> 8; + framed[1] = size & 0xff; + framed.set(await reader.read(size), 2); + return { type, reader: new Reader(undefined, framed, version) }; + } catch (err) { + throw malformed(err, "request stream message"); + } + } +} + /** * A request message the peer sent that does not decode, including one cut short by FIN, * breaks the protocol. A reset stream does not. @@ -191,7 +336,11 @@ export function malformed(err: unknown, what: string): unknown { if ( err instanceof ProtocolViolation || err instanceof StreamError || - (typeof err === "object" && err !== null && "source" in err && err.source === "session") + // A transport failure, including a reset whose code the browser did not report. + (typeof err === "object" && + err !== null && + "source" in err && + (err.source === "session" || err.source === "stream")) ) return err; return new ProtocolViolation(`malformed ${what}`, { cause: err }); diff --git a/js/net/src/ietf/subscriber.test.ts b/js/net/src/ietf/subscriber.test.ts index d18e12dc1cb..3301ee2cc07 100644 --- a/js/net/src/ietf/subscriber.test.ts +++ b/js/net/src/ietf/subscriber.test.ts @@ -874,7 +874,7 @@ test("a PUBLISH_NAMESPACE update that changes the publisher applies in place", a test("a repeated PUBLISH_NAMESPACE is a protocol violation", async () => { const pair = createMockTransportPair(ALPN.DRAFT_19); const session = new NativeSession(pair.server, VERSION, true); - const subscriber = new Subscriber({ session, cluster: { self: SELF, peer: PEER } }); + const subscriber = new Subscriber({ session, quic: pair.server, cluster: { self: SELF, peer: PEER } }); const announced = subscriber.announced(); await acceptSubscribeNamespace(pair.client); @@ -906,7 +906,9 @@ test("a repeated PUBLISH_NAMESPACE is a protocol violation", async () => { channel.port2.postMessage(null); }); await expect(handler).rejects.toThrow(ProtocolViolation); - expect(await announced.next()).toMatchObject({ prefix: Path.from("theirs"), kind: "end" }); + // The request closes the session itself, which takes the namespace subscription down too. + await violationClosed(pair); + await expect(announced.next()).rejects.toThrow(); }); /** @@ -2248,6 +2250,22 @@ test("an ACTIVE_COUNT that does not match the negotiation closes the session", a } }); +/** A violation on a namespace subscription closes the session through its request, once. */ +test("a namespace subscription closes the session once over a violation", async () => { + const pair = createMockTransportPair(ALPN.DRAFT_19); + const session = new NativeSession(pair.server, VERSION, true); + const subscriber = new Subscriber({ session, quic: pair.server, activeCount: true }); + const warn = spyOn(console, "warn").mockImplementation(() => void 0); + onTestFinished(() => warn.mockRestore()); + const close = spyOn(pair.server, "close"); + + subscriber.announced(); + await answerCounted(pair.client, undefined); + await violationClosed(pair); + await yieldTask(); + expect(close.mock.calls.filter(([info]) => info?.closeCode !== undefined)).toHaveLength(1); +}); + /** A counted set cut short, by a NAMESPACE_DONE or the stream ending, is the peer's fault. */ test.each(["done", "fin"] as const)("a counted set cut short by %s closes the session", async (cut) => { { diff --git a/js/net/src/ietf/subscriber.ts b/js/net/src/ietf/subscriber.ts index bf621937bc1..ce472b2678c 100644 --- a/js/net/src/ietf/subscriber.ts +++ b/js/net/src/ietf/subscriber.ts @@ -65,7 +65,7 @@ import { PublishNamespaceUpdate, } from "./publish_namespace.ts"; import { RequestError, RequestOk } from "./request.ts"; -import { finCancels, nextMessage, refuse, refuseReserved, refuseUpdate } from "./request_stream.ts"; +import { type Framed, RequestStream, refuseReserved, refuseUpdate } from "./request_stream.ts"; import { joinFilter, Subscribe, SubscribeError, SubscribeOk, SubscribeUpdate, Unsubscribe } from "./subscribe.ts"; import { PublishBlocked, @@ -99,7 +99,7 @@ type Subscription = { // (stream opened, trackAlias registered) so it can clean up on timeout even // before the setup promise settles. type SubscribeSetupState = { - stream?: Stream; + stream?: RequestStream; registeredAlias?: bigint; /** * Whether the caller has given up. Setup checks this once the stream exists so a request @@ -524,15 +524,19 @@ export class Subscriber { try { // v16: use a real bidi stream (not virtual control stream) const deadline = new Deadline(); - const stream = await deadline.wait( - deadline.open( - version === Version.DRAFT_16 && this.#session.openNativeBi - ? this.#session.openNativeBi(requestOptions) - : this.#session.openBi(requestOptions), + const request = new RequestStream( + await deadline.wait( + deadline.open( + version === Version.DRAFT_16 && this.#session.openNativeBi + ? this.#session.openNativeBi(requestOptions) + : this.#session.openBi(requestOptions), + ), ), + this.#session, + this.#quic, ); - try { + const run = async () => { // Draft-18+ uses SUBSCRIBE_NAMESPACE (0x50); earlier drafts use the // legacy 0x11 message with a Subscribe Options field. if ( @@ -541,15 +545,15 @@ export class Subscriber { version === Version.DRAFT_16 || version === Version.DRAFT_17 ) { - await stream.writer.u53(SubscribeNamespaceLegacy.id); + await request.writer.u53(SubscribeNamespaceLegacy.id); await new SubscribeNamespaceLegacy({ namespace: prefix, requestId, hidden }).encode( - stream.writer, + request.writer, version, ); } else { - await stream.writer.u53(SubscribeNamespace.id); + await request.writer.u53(SubscribeNamespace.id); await new SubscribeNamespace({ namespace: prefix, requestId, hidden }).encode( - stream.writer, + request.writer, version, ); } @@ -559,22 +563,22 @@ export class Subscriber { // For v14/v15: send UnsubscribeNamespace before closing if (version === Version.DRAFT_14 || version === Version.DRAFT_15) { try { - await stream.writer.u53(UnsubscribeNamespace.id); + await request.writer.u53(UnsubscribeNamespace.id); const unsub = new UnsubscribeNamespace({ requestId }); - await unsub.encode(stream.writer, version); + await unsub.encode(request.writer, version); } catch { // Stream might already be closed } } - stream.close(); + request.close(); }; // Resolves to how many NAMESPACEs make up the initial set (MoQ Active Count). const response = (async () => { - const respTypeId = await nextMessage(stream.reader, version, this.#session.client); - if (respTypeId === undefined) throw new Error("namespace stream ended before its response"); - if (respTypeId === RequestOk.id) { - const ok = await RequestOk.decode(stream.reader, version); + const framed = await request.next(); + if (framed === undefined) throw new Error("namespace stream ended before its response"); + if (framed.type === RequestOk.id) { + const ok = await RequestOk.decode(framed.reader, version); // A count the negotiation did not promise, or a missing one it did, is // the peer breaking the extension. Without it, the answer is the best // boundary there is. @@ -584,13 +588,9 @@ export class Subscriber { } return count ?? 0; } - if (respTypeId === SubscribeNamespaceOk.id) { - // v14: SubscribeNamespaceOk - const size = await stream.reader.u16(); - await stream.reader.read(size); - return 0; - } - throw new Error(`SubscribeNamespace rejected: typeId=0x${respTypeId.toString(16)}`); + // v14: SubscribeNamespaceOk, whose body says nothing more. + if (framed.type === SubscribeNamespaceOk.id) return 0; + throw new Error(`SubscribeNamespace rejected: typeId=0x${framed.type.toString(16)}`); })(); // A consumer that leaves before the peer answers ends the request now, not on the answer. const answered = await race([response, announced.closed.then(() => undefined)]); @@ -605,19 +605,20 @@ export class Subscriber { for (;;) { if (initial === 0) announced.synced(); - const msgType = await nextMessage(stream.reader, version, this.#session.client); - if (msgType === undefined) { + const framed = await request.next(); + if (framed === undefined) { if (initial > 0) throw new ProtocolViolation("namespace stream ended inside the initial set"); break; } + const msgType = framed.type; // The counted initial set is NAMESPACEs only, so anything else cuts it short. if (initial > 0 && msgType !== SubscribeNamespaceEntry.id) { throw new ProtocolViolation(`message 0x${msgType.toString(16)} inside the initial set`); } if (msgType === SubscribeNamespaceEntry.id) { - const entry = await SubscribeNamespaceEntry.decode(stream.reader, version, { + const entry = await SubscribeNamespaceEntry.decode(framed.reader, version, { cluster: Cluster.negotiated(this.#cluster), epoch: this.#epoch, }); @@ -656,7 +657,7 @@ export class Subscriber { live.set(path, { id: this.#attachAnnounce(path, route), epoch: params.epoch }); } } else if (msgType === SubscribeNamespaceEntryDone.id) { - const entry = await SubscribeNamespaceEntryDone.decode(stream.reader, version); + const entry = await SubscribeNamespaceEntryDone.decode(framed.reader, version); if (released) break; const path = Path.join(prefix, entry.suffix); @@ -664,7 +665,7 @@ export class Subscriber { live.delete(path); if (held?.id !== undefined) this.#detachAnnounce(path, held.id); } else if (msgType === PublishBlocked.id && version === Version.DRAFT_17) { - const blocked = await PublishBlocked.decode(stream.reader, version); + const blocked = await PublishBlocked.decode(framed.reader, version); console.debug(`publish_blocked: suffix=${blocked.suffix} track=${blocked.trackName}`); } else { throw new Error( @@ -676,31 +677,22 @@ export class Subscriber { // The race below can end through the consumer's close while a message that // already arrived is still decoding, which leaves the loop with nothing - // awaiting it: a violation decoded after that would land nowhere, and its - // rejection would go unhandled. Idempotent with the catch below, which is - // what runs when the loop is the one that ends the race. - readLoop.catch((err: unknown) => { - if (err instanceof ProtocolViolation) this.#violated(err); - }); + // awaiting it: a violation decoded after that still closes the session. + // An advertisement is decoded here rather than in the session dispatch, so + // this is the only place a malformed one surfaces, and the cluster draft + // requires closing the session over it: the peer would just repeat it on the + // next SUBSCRIBE_NAMESPACE. + readLoop.catch((err: unknown) => request.abort(err)); // Wait for either the read loop or the announced to close await race([readLoop, announced.closed]); await end(); - } catch (err) { - stream.abort(error(err)); - throw err; - } + }; + await request.serve(run()); } catch (err: unknown) { - if (err instanceof ProtocolViolation) this.#violated(err); const e = error(err); console.warn(`subscribe_namespace error: ${reason(e)}`); - // An advertisement is decoded here rather than in the session dispatch, so this - // is the only place a malformed one surfaces. The cluster draft requires closing - // the session over those, and the stream alone is not enough: the peer would - // just repeat it on the next SUBSCRIBE_NAMESPACE. - if (e instanceof ProtocolViolation) this.#violated(e); - // Abort the stream rather than letting the caller's `finally` close it cleanly. // A rejected namespace subscription is a failure, and a consumer that can't tell // it from "nothing is published under this prefix" waits forever on a broadcast @@ -820,7 +812,7 @@ export class Subscriber { return null; }; - let stream: Stream; + let stream: RequestStream; let trackAlias: bigint; // The SUBSCRIBER_PRIORITY the request went out with. let priority: number; @@ -843,7 +835,7 @@ export class Subscriber { } console.debug(`subscribe ok: id=${requestId} broadcast=${broadcast} track=${request.name}`); } catch (err) { - if (err instanceof ProtocolViolation) this.#violated(err); + // A violation on the stream already closed the session through it. // A control request that timed out is not late content, so it carries its own code. // Local abandonment must commit without yielding after the demand check. const e = err === abandoned ? abandoned : await sessionCause(this.#quic, err); @@ -959,10 +951,9 @@ export class Subscriber { stream.close(); console.debug(`subscribe close: id=${requestId} broadcast=${broadcast} track=${request.name}`); } catch (err) { - if (err instanceof ProtocolViolation) this.#violated(err); + stream.abort(err); const e = await sessionCause(this.#quic, err); producer.close(this.#localClose ? undefined : e); - stream.abort(e); console.warn( `subscribe error: id=${requestId} broadcast=${broadcast} track=${request.name} error=${reason(e)}`, ); @@ -984,7 +975,7 @@ export class Subscriber { * stream that FINs without PUBLISH_DONE is a protocol violation. */ async #runPublishDone( - stream: Stream, + stream: RequestStream, subscription: Subscription, broadcast: Path.Valid, unanswered: Signal, @@ -993,22 +984,24 @@ export class Subscriber { // A refused update is followed by PUBLISH_DONE, which ends the subscription, so no // further answer is owed. let refused = false; + let framed: Framed | undefined; for (;;) { - const typeId = await nextMessage(stream.reader, version, this.#session.client); - if (typeId === undefined) throw new ProtocolViolation("subscribe stream ended without PUBLISH_DONE"); - if (typeId === PublishDone.id) break; - const answer = (typeId === RequestOk.id || typeId === RequestError.id) && !refused && unanswered.peek() > 0; - if (!answer) throw new ProtocolViolation(`unexpected message on a subscription: 0x${typeId.toString(16)}`); - if (typeId === RequestOk.id) { - await RequestOk.decode(stream.reader, version); + framed = await stream.next(); + if (framed === undefined) throw new ProtocolViolation("subscribe stream ended without PUBLISH_DONE"); + const { type } = framed; + if (type === PublishDone.id) break; + const answer = (type === RequestOk.id || type === RequestError.id) && !refused && unanswered.peek() > 0; + if (!answer) throw new ProtocolViolation(`unexpected message on a subscription: 0x${type.toString(16)}`); + if (type === RequestOk.id) { + await RequestOk.decode(framed.reader, version); unanswered.update((count) => count - 1); } else { - const err = await RequestError.decode(stream.reader, version); + const err = await RequestError.decode(framed.reader, version); console.debug(`subscription update refused: ${err.reasonPhrase}`); refused = true; } } - const done = await PublishDone.decode(stream.reader, version); + const done = await PublishDone.decode(framed.reader, version); // A revocation reads the same as one from a moq-lite peer. if (done.statusCode === PublishDoneStatus.UNAUTHORIZED) throw unauthorized(broadcast); if (!publishDoneClean(done.statusCode, version)) { @@ -1029,7 +1022,7 @@ export class Subscriber { * group order, so it stays as asked. */ async #runUpdates( - stream: Stream, + stream: RequestStream, requestId: bigint, producer: track.Producer, sent: number, @@ -1104,7 +1097,7 @@ export class Subscriber { * subscription goes through here, because those versions carry the request over a * virtual stream whose reset never reaches the peer. */ - async #cancelSubscribe(stream: Stream, requestId: bigint) { + async #cancelSubscribe(stream: RequestStream, requestId: bigint) { const version = this.#session.version; if (version !== Version.DRAFT_14 && version !== Version.DRAFT_15 && version !== Version.DRAFT_16) return; @@ -1128,15 +1121,17 @@ export class Subscriber { requestId: bigint, deadline: Deadline, epoch: Epoch.Valid | undefined, - ): Promise<{ stream: Stream; alias: bigint; priority: number; maxAge?: number }> { + ): Promise<{ stream: RequestStream; alias: bigint; priority: number; maxAge?: number }> { const version = this.#session.version; const legacy = version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16; // Virtual streams use no transport credit. Their owner must send UNSUBSCRIBE before // resetting them, including on a deadline, so they stay out of the real-stream guard. - state.stream = legacy - ? await this.#session.openBi() - : await deadline.open(this.#session.openBi(requestOptions)); + state.stream = new RequestStream( + legacy ? await this.#session.openBi() : await deadline.open(this.#session.openBi(requestOptions)), + this.#session, + this.#quic, + ); // The timeout can fire while the open is still in flight, in which case cleanup ran // with nothing to release. Bail now that the stream is recorded, so settling this @@ -1174,16 +1169,16 @@ export class Subscriber { if (state.cancelled) throw new Error("subscribe cancelled while it was being sent"); console.debug(`subscribe written: id=${requestId} broadcast=${broadcast} track=${request.name}`); - const respTypeId = await nextMessage(state.stream.reader, version, this.#session.client); - if (respTypeId === undefined) throw new Error("subscription ended before its response"); - if (respTypeId !== SubscribeOk.id) { + const response = await state.stream.next(); + if (response === undefined) throw new Error("subscription ended before its response"); + if (response.type !== SubscribeOk.id) { let reasonPhrase = "unknown error"; try { - if (respTypeId === RequestError.id) { + if (response.type === RequestError.id) { const err = version === Version.DRAFT_14 - ? await SubscribeError.decode(state.stream.reader, version) - : await RequestError.decode(state.stream.reader, version); + ? await SubscribeError.decode(response.reader, version) + : await RequestError.decode(response.reader, version); reasonPhrase = requestReason(err.errorCode, err.reasonPhrase, "subscribe", version); } } catch { @@ -1193,7 +1188,7 @@ export class Subscriber { throw new Error(`SUBSCRIBE error: ${reasonPhrase}`); } - const ok = await SubscribeOk.decode(state.stream.reader, version); + const ok = await SubscribeOk.decode(response.reader, version); if (state.cancelled) throw new Error("subscribe cancelled before acceptance"); const maxCacheDuration = ok.properties.maxCacheDuration; if (maxCacheDuration !== undefined && maxCacheDuration > BigInt(Number.MAX_SAFE_INTEGER)) { @@ -1246,9 +1241,14 @@ export class Subscriber { * * @internal */ - async runPublishNamespace(msg: PublishNamespace, stream: Stream) { + runPublishNamespace(msg: PublishNamespace, stream: Stream): Promise { + const request = new RequestStream(stream, this.#session, this.#quic); + return request.serve(this.#runPublishNamespace(msg, request)); + } + + async #runPublishNamespace(msg: PublishNamespace, request: RequestStream) { if (Namespace.reserved(msg.trackNamespace, this.#session.version)) { - await refuseReserved(stream, this.#session.version); + await refuseReserved(request); return; } const version = this.#session.version; @@ -1259,7 +1259,7 @@ export class Subscriber { // conforming one never offers it; 0 as the retry interval says not to come back. if (this.#reflected(msg.params.cluster)) { console.debug(`dropping reflected publish_namespace: broadcast=${path}`); - await refuse(stream, version, "publish_namespace", { + await request.refuse("publish_namespace", { requestId: msg.requestId, condition: "uninterested", reasonPhrase: "route loops back", @@ -1278,7 +1278,7 @@ export class Subscriber { console.warn("duplicate PublishNamespace"); // No draft registers a code for a duplicate, and this refusal is a draft-14/15 // implementation limit, which is what INTERNAL_ERROR describes. - await refuse(stream, version, "publish_namespace", { + await request.refuse("publish_namespace", { requestId: msg.requestId, condition: "internal", reasonPhrase: "duplicate namespace", @@ -1300,15 +1300,15 @@ export class Subscriber { // because consumers may trigger Subscribe writes that would // interleave with our OK on the control stream. if (version === Version.DRAFT_14) { - await stream.writer.u53(PublishNamespaceOk.id); + await request.writer.u53(PublishNamespaceOk.id); const ok = new PublishNamespaceOk({ requestId: msg.requestId }); - await ok.encode(stream.writer, version); + await ok.encode(request.writer, version); } else { - await stream.writer.u53(RequestOk.id); + await request.writer.u53(RequestOk.id); const ok = new RequestOk({ requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined, }); - await ok.encode(stream.writer, version); + await ok.encode(request.writer, version); } // Only now is the advertisement ours to announce, for the reason above: a @@ -1321,29 +1321,21 @@ export class Subscriber { // is kept current, since an update carries only what changed. let held = msg.params.cluster; const done = version === Version.DRAFT_16 || legacy; - const stopped = !done - ? stream.writer.closed.then( - () => true, - () => true, - ) - : undefined; for (;;) { - const typeId = await (stopped !== undefined - ? race([nextMessage(stream.reader, version, this.#session.client), stopped.then(() => undefined)]) - : nextMessage(stream.reader, version, this.#session.client)); - if (typeId === undefined) { - if (!finCancels(version)) await stopped; - stream.reader.stop(new StreamError(StreamCode.Cancel)); + const framed = await race([request.next(), request.ended.then(() => undefined)]); + if (framed === undefined) { + // FIN cancels only on some drafts; on the rest the request lasts until reset. + await request.ended; break; } // Drafts 14-15 have no update for an advertisement, so a SUBSCRIBE_UPDATE the // adapter routed here is refused and changes nothing. Draft 14 answers no update; // draft 15 names the update's own Request ID, which the adapter already spent. - if (legacy && typeId === SubscribeUpdate.id) { - const body = await stream.reader.read(await stream.reader.u16()); + if (legacy && framed.type === SubscribeUpdate.id) { + const body = await framed.reader.read(await framed.reader.u16()); if (version === Version.DRAFT_15) { - await refuseUpdate(stream.writer, version, "publish_namespace", { + await refuseUpdate(request.writer, version, "publish_namespace", { requestId: await new Reader(undefined, body, version).u62(), condition: "not_supported", reasonPhrase: "update not supported", @@ -1351,15 +1343,15 @@ export class Subscriber { } continue; } - if (done && typeId === PublishNamespaceDone.id) { - await PublishNamespaceDone.decode(stream.reader, version); + if (done && framed.type === PublishNamespaceDone.id) { + await PublishNamespaceDone.decode(framed.reader, version); break; } // A repeated PUBLISH_NAMESPACE lands here too: a second request on the // stream is the base draft's duplicate request ID. - if (typeId !== PublishNamespaceUpdate.id) { + if (framed.type !== PublishNamespaceUpdate.id) { throw new ProtocolViolation( - `unexpected message on publish_namespace stream: 0x${typeId.toString(16)}`, + `unexpected message on publish_namespace stream: 0x${framed.type.toString(16)}`, ); } @@ -1368,28 +1360,28 @@ export class Subscriber { const keyed = version === Version.DRAFT_16; let update: PublishNamespaceUpdate; try { - update = await PublishNamespaceUpdate.decode(stream.reader, version); + update = await PublishNamespaceUpdate.decode(framed.reader, version); } catch (err) { if (!(err instanceof MalformedAuthToken)) throw err; // A refused update still spends its own request ID. if (!keyed && err.requestId !== undefined) this.#session.spendRequest(err.requestId); // Section 8.9 rejects the update, which withdraws the advertisement as any // refused update does. - await refuseUpdate(stream.writer, version, "publish_namespace", { + await refuseUpdate(request.writer, version, "publish_namespace", { requestId: err.requestId, condition: "malformed_auth_token", reasonPhrase: err.message, }); // Draft-16's advertisement outlives its stream, so withdraw it explicitly. if (keyed) { - await stream.writer.u53(PublishNamespaceCancel.id); + await request.writer.u53(PublishNamespaceCancel.id); await new PublishNamespaceCancel({ requestId: msg.requestId, errorCode: toRequestCode("malformed_auth_token", "publish_namespace", version), reasonPhrase: err.message, - }).encode(stream.writer, version); + }).encode(request.writer, version); } - stream.close(); + request.close(); break; } if (!keyed) this.#session.spendRequest(update.requestId); @@ -1425,8 +1417,11 @@ export class Subscriber { // Nothing here can fail to apply, so every update is acknowledged. A leaf // routes nothing, so a repricing changes nothing it holds; consumers still // hear the new route so a forwarder can reprice. - await stream.writer.u53(RequestOk.id); - await new RequestOk({ requestId: keyed ? update.requestId : undefined }).encode(stream.writer, version); + await request.writer.u53(RequestOk.id); + await new RequestOk({ requestId: keyed ? update.requestId : undefined }).encode( + request.writer, + version, + ); } } finally { if (legacy) this.#legacyRequests.delete(path); @@ -1445,21 +1440,22 @@ export class Subscriber { * * @internal */ - async runPublish(msg: Publish, stream: Stream) { - if (Namespace.reserved(msg.trackNamespace, this.#session.version)) { - await refuseReserved(stream, this.#session.version); - return; - } + runPublish(msg: Publish, stream: Stream): Promise { + const request = new RequestStream(stream, this.#session, this.#quic); // We decline the method itself rather than this particular track, which would be // UNINTERESTED. // // The alias the message carries is deliberately not recorded. Nothing will ever bind // it, and a rejected request has no lifetime of ours to hang the cleanup on. - await refuse(stream, this.#session.version, "publish", { - requestId: msg.requestId, - condition: "not_supported", - reasonPhrase: "publish not supported", - }); + return request.serve( + Namespace.reserved(msg.trackNamespace, this.#session.version) + ? refuseReserved(request) + : request.refuse("publish", { + requestId: msg.requestId, + condition: "not_supported", + reasonPhrase: "publish not supported", + }), + ); } /** diff --git a/js/net/src/session-limits.test.ts b/js/net/src/session-limits.test.ts index 32faccb792a..513f3a383c4 100644 --- a/js/net/src/session-limits.test.ts +++ b/js/net/src/session-limits.test.ts @@ -57,6 +57,8 @@ function pendingPublisher(protocol: "lite" | "ietf", options: { track?: boolean const pending: Promise[] = []; let draining = false; const writes: (() => void)[] = []; + // Shaped like the WebTransportError a requester's RESET_STREAM fails the read with. + const reset = Object.assign(new Error("cancelled"), { source: "stream", streamErrorCode: null }); // Subscribe once, returning a cancel that resets the requester's half. const subscribe = (id: number): (() => void) => { @@ -86,7 +88,7 @@ function pendingPublisher(protocol: "lite" | "ietf", options: { track?: boolean stream, ); pending.push(request.catch(() => {})); - return () => requester.error(new Error("cancelled")); + return () => requester.error(reset); }; // Each wire request has its own slot even when its track and group are identical. diff --git a/quest/m1/README.md b/quest/m1/README.md index 19cd0cc438e..6c49cff0429 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -94,7 +94,6 @@ lands before the cut. - [Restart reset](/quest/m1/stateless-reset-key.md) - a relay restarted with the same `listen.reset_key` stateless-resets its predecessor's connections, so clients reconnect within an RTT instead of the idle timeout - [Drain cleanup](/quest/m1/drain-cleanup.md) - sessions force-closed at the drain deadline record their lease end and bytes before the relay or CLI exits, while unfinished handshakes stay bounded - [Rust redirect loops](/quest/m1/tokio-redirect-loop.md) - moq-tokio escalates its backoff when GOAWAY redirects bounce between peers, as JS does -- [JS request owner](/quest/m1/js-request-owner.md) - every JS IETF request stream has one owning handle with an `ended` promise and one closer - [Container reads drop backfill](/quest/m1/read-backfill.md) - the JS container consumer drops groups below its read cursor like Rust - [Rust request credit](/quest/m1/rs-request-credit.md) - a moq-net request fails at once without stream credit instead of waiting - [A stalled subscriber holds bounded state](/quest/m1/egress-held-state.md) - group machines and bytes a credit-withholding downstream makes a publisher hold plateau at what its credit and the latency budget allow, on lite and moq-transport diff --git a/quest/m1/js-request-owner.md b/quest/m1/js-request-owner.md deleted file mode 100644 index f8fb7bb4f34..00000000000 --- a/quest/m1/js-request-owner.md +++ /dev/null @@ -1,26 +0,0 @@ -# [S] Every JS request stream has one owner and one closer - -## Goal - -In `js/net`'s IETF adapter, each request stream has a single handle that -owns its reader and exposes a terminal `ended` promise every consumer races, -so no request reader can be left detached, and each request closes through a -single per-request closer, so request tasks stop closing a session or stream -twice with competing codes. - -## Plan - -Follow-ups of [#5998](https://github.com/moq-dev/moq/pull/5998). Today no -reader is detached, but nothing prevents it: each request type wires its own -read loop and close path, and #5998's unit harness has to assert that every -close carries one code because the transport keeps the first. - -- Add the handle internally in `js/net/src/ietf/` and move SUBSCRIBE, FETCH, - TRACK_STATUS, SUBSCRIBE_NAMESPACE, SUBSCRIBE_TRACKS and PUBLISH_NAMESPACE - (both sides) onto it. -- Check whether the Rust request tasks close twice the same way and give - them the same single closer if so; mirror the shape in both languages. -- Internal refactor: deleting the per-request read and close code it - replaces is the measure of success. - -Public API: none. Wire: none.