From 47d2773e12a7110e3409aa0a79387b79da3e8745 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 15 Oct 2026 10:31:22 -0700 Subject: [PATCH 1/2] chore: claim subscribe-close release backport Co-Authored-By: GPT-6 From c62e3dddab6087968e33642979a82af02e0c6b9e Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 15 Oct 2026 10:43:01 -0700 Subject: [PATCH 2/2] fix(net): backport subscribe-close error handling Co-Authored-By: GPT-6 --- js/net/src/lite/subscriber.test.ts | 159 +++++++++++++++++++++++++++-- js/net/src/lite/subscriber.ts | 8 +- js/signals/src/index.test.ts | 26 +++++ js/signals/src/index.ts | 18 +++- 4 files changed, 193 insertions(+), 18 deletions(-) diff --git a/js/net/src/lite/subscriber.test.ts b/js/net/src/lite/subscriber.test.ts index 0fbdb8140e7..63b38f9d68b 100644 --- a/js/net/src/lite/subscriber.test.ts +++ b/js/net/src/lite/subscriber.test.ts @@ -1,12 +1,13 @@ import { expect, spyOn, test } from "bun:test"; import { Signal } from "@moq/signals"; import type { Probe as ProbeStats } from "../connection/stats.ts"; -import { error, fromTransport, reason, StreamCode, StreamError } from "../error.ts"; +import { error, fromTransport, ProtocolViolation, reason, StreamCode, StreamError } from "../error.ts"; import { HopSchema, isAnonymous, MAX_HOPS, Route, UNKNOWN_HOP } from "../hop.ts"; import * as Path from "../path.ts"; -import { Writer } from "../stream.ts"; +import { Reader, Writer } from "../stream.ts"; import * as Time from "../time.ts"; import { type AnnounceBroadcast, AnnounceInit, AnnounceOk, encodeAnnounceBroadcast } from "./announce.ts"; +import { Group } from "./group.ts"; import { Probe } from "./probe.ts"; import { Subscriber } from "./subscriber.ts"; import { TrackInfo } from "./track.ts"; @@ -737,22 +738,38 @@ interface FakeStream { // Resolves once the subscriber waits on a read the test has not answered. reading: Promise; aborted: Promise; + // Resolves once the subscriber FINs its side. + finished: Promise; + // Resolves on the first write, even if it stalls. + writing: Promise; + // Every chunk the subscriber wrote. + written: Uint8Array[]; // Hands the stream to the subscriber, for an open the session was told to park. release: () => void; } // A session whose streams the test answers by hand and that never fails them on its own, so // only Subscriber.close() can end a wait. Opens numbered in `park` wait for `release()`. -function fakeSession(park: number[] = []) { +// Delayed writes model transport credit arriving outside the microtask queue. +function fakeSession(park: number[] = [], delayedWrites = false) { const streams: FakeStream[] = []; + const count = new Signal(0); + async function opened(index: number): Promise { + while (streams.length <= index) await count.changed(); + return streams[index]; + } const quic = { createBidirectionalStream: () => { let inbound!: ReadableStreamDefaultController; let onRead!: () => void; let onAbort!: (reason: unknown) => void; + let onFinish!: () => void; + let onWrite!: () => void; let release!: () => void; const reading = new Promise((resolve) => (onRead = resolve)); const aborted = new Promise((resolve) => (onAbort = resolve)); + const finished = new Promise((resolve) => (onFinish = resolve)); + const writing = new Promise((resolve) => (onWrite = resolve)); // No high water mark, so pull() means the subscriber is blocked on a read. const readable = new ReadableStream( { @@ -763,23 +780,43 @@ function fakeSession(park: number[] = []) { }, { highWaterMark: 0 }, ); - const writable = new WritableStream({ abort: (reason) => void onAbort(reason) }); + const written: Uint8Array[] = []; + const writable = new WritableStream({ + write: (chunk) => { + written.push(new Uint8Array(chunk)); + onWrite(); + if (!delayedWrites) return; + return new Promise((resolve) => { + // Transport credit can arrive in a task, outside the microtask queue. + const channel = new MessageChannel(); + channel.port1.onmessage = () => { + channel.port1.close(); + channel.port2.close(); + resolve(); + }; + channel.port2.postMessage(null); + }); + }, + close: () => onFinish(), + abort: (reason) => void onAbort(reason), + }); const opened = new Promise((resolve) => (release = () => resolve({ readable, writable }))); if (!park.includes(streams.length)) release(); - streams.push({ inbound, reading, aborted, release }); + streams.push({ inbound, reading, aborted, finished, writing, written, release }); + count.set(streams.length); return opened; }, } as unknown as WebTransport; - return { quic, streams }; + return { quic, streams, opened }; } -async function answerTrackInfo(stream: FakeStream): Promise { +async function answerTrackInfo(stream: FakeStream, version: Version = Version.DRAFT_05): Promise { const chunks: Uint8Array[] = []; const writer = new Writer( new WritableStream({ write: (chunk) => void chunks.push(new Uint8Array(chunk)) }), - Version.DRAFT_05, + version, ); - await new TrackInfo({}).encode(writer, Version.DRAFT_05); + await new TrackInfo({}).encode(writer, version); for (const chunk of chunks) stream.inbound.enqueue(chunk); stream.inbound.close(); } @@ -949,3 +986,107 @@ test("the last reader leaving mid-response cancels the fetch", async () => { subscriber.close(); }); + +// Let all queued reactions finish without relying on host timers. +function drainReactions(): Promise { + return new Promise((resolve) => { + const channel = new MessageChannel(); + channel.port1.onmessage = () => { + channel.port1.close(); + channel.port2.close(); + resolve(); + }; + channel.port2.postMessage(null); + }); +} + +test("a local unsubscribe owes no SUBSCRIBE_END", async () => { + const { quic, streams, opened } = fakeSession([], true); + const subscriber = new Subscriber(quic, Version.DRAFT_07, HopSchema.parse(1n)); + const responseTask = Promise.withResolvers(); + const outcome = responseTask.promise.then( + () => undefined, + (err: unknown) => err, + ); + // TypeScript-private so tests can observe the task without exporting a test hook. + const internal = subscriber as unknown as { runResponses: (...args: unknown[]) => Promise }; + const runResponses = internal.runResponses.bind(internal); + const responses = spyOn(internal, "runResponses").mockImplementation((...args) => { + const task = runResponses(...args); + responseTask.resolve(task); + return task; + }); + const broadcast = subscriber.consume(Path.from("room")); + const track = broadcast.track("video").subscribe(); + const ordered = track.ordered(); + try { + await opened(0); + await answerTrackInfo(streams[0], Version.DRAFT_07); + await (await opened(1)).reading; + const next = ordered.nextGroup(); + await subscriber.runGroup( + new Group({ subscribe: 0n, sequence: 0 }), + new Reader( + new ReadableStream({ + start: (controller) => controller.close(), + }), + undefined, + Version.DRAFT_07, + ), + ); + (await next)?.close(); + ordered.close(); + track.close(); + await streams[1].finished; + await drainReactions(); + expect(await outcome).toBeUndefined(); + } finally { + responses.mockRestore(); + ordered.close(); + track.close(); + broadcast.close(); + subscriber.close(); + } +}); + +test("a publisher FIN without SUBSCRIBE_END still violates an open subscription", async () => { + const { quic, streams, opened } = fakeSession([], true); + const subscriber = new Subscriber(quic, Version.DRAFT_07, HopSchema.parse(1n)); + const broadcast = subscriber.consume(Path.from("room")); + const track = broadcast.track("video").subscribe(); + try { + await opened(0); + await answerTrackInfo(streams[0], Version.DRAFT_07); + await (await opened(1)).reading; + streams[1].inbound.close(); + expect(await track.closed).toBeInstanceOf(ProtocolViolation); + expect((track.closed.peek() as Error).message).toBe("subscribe stream ended without SUBSCRIBE_END"); + } finally { + track.close(); + broadcast.close(); + subscriber.close(); + } +}); + +test("closing a broadcast while TRACK_INFO is pending leaves no unhandled rejection", async () => { + const { quic, streams, opened } = fakeSession([], true); + const subscriber = new Subscriber(quic, Version.DRAFT_07, HopSchema.parse(1n)); + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => unhandled.push(reason); + const broadcast = subscriber.consume(Path.from("room")); + const track = broadcast.track("video").subscribe(); + process.on("unhandledRejection", onUnhandled); + try { + await opened(0); + await streams[0].reading; + broadcast.close(); + track.close(); + await answerTrackInfo(streams[0], Version.DRAFT_07); + await (await opened(1)).finished; + await drainReactions(); + expect(unhandled).toEqual([]); + } finally { + process.off("unhandledRejection", onUnhandled); + subscriber.close(); + } +}); diff --git a/js/net/src/lite/subscriber.ts b/js/net/src/lite/subscriber.ts index c007208eb98..b5096c8a36c 100644 --- a/js/net/src/lite/subscriber.ts +++ b/js/net/src/lite/subscriber.ts @@ -575,7 +575,7 @@ export class Subscriber { // flight, so the track ends only once the tail is accounted for. A reset rejects // instead, so the track ends with that error rather than a clean tail. const responses = supportsTrackStream(this.version) - ? this.#runResponses(stream, entry) + ? this.runResponses(stream, entry) : stream.reader.closed; const closed = responses.then(() => this.#settleTail(entry)); // A reset that lands after the race below settled is moot; the race observes one before. @@ -881,12 +881,12 @@ export class Subscriber { // Reads SUBSCRIBE_START/END/DROP on the subscribe stream until FIN (lite-05+), recording // the range the tail is accounted against. SUBSCRIBE_END declares the track's end right // away, so a consumer learns it before the last groups arrive. The publisher must declare - // the end before FIN; resets and malformed responses reject with their failure. - async #runResponses(stream: Stream, entry: SubscribeEntry): Promise { + // the end before FIN unless we cancelled locally; resets and malformed responses reject. + private async runResponses(stream: Stream, entry: SubscribeEntry): Promise { for (;;) { const resp = await decodeSubscribeResponseMaybe(stream.reader, this.version); if (!resp) { - if (entry.end === undefined) + if (entry.end === undefined && entry.track.closed.peek() === undefined) throw new ProtocolViolation("subscribe stream ended without SUBSCRIBE_END"); return; } diff --git a/js/signals/src/index.test.ts b/js/signals/src/index.test.ts index 71c5b190d69..526531ee2d1 100644 --- a/js/signals/src/index.test.ts +++ b/js/signals/src/index.test.ts @@ -1107,6 +1107,32 @@ describe("race", () => { expect(await race([Promise.resolve("promise"), once])).toBe("done"); }); + test("a loser after an already settled winner is still observed", async () => { + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => unhandled.push(reason); + process.on("unhandledRejection", onUnhandled); + try { + const once = new Once(); + once.set("done"); + let fail!: (err: Error) => void; + const later = new Promise((_, reject) => (fail = reject)); + expect(await race([once, later])).toBe("done"); + fail(new Error("late")); + await new Promise((resolve) => { + const channel = new MessageChannel(); + channel.port1.onmessage = () => { + channel.port1.close(); + channel.port2.close(); + resolve(); + }; + channel.port2.postMessage(null); + }); + expect(unhandled).toEqual([]); + } finally { + process.off("unhandledRejection", onUnhandled); + } + }); + test("resolves when a pending Once settles", async () => { const once = new Once(); const result = race([new Promise(() => {}), once]); diff --git a/js/signals/src/index.ts b/js/signals/src/index.ts index 5b4681faf99..6aaed924f0e 100644 --- a/js/signals/src/index.ts +++ b/js/signals/src/index.ts @@ -357,17 +357,24 @@ function raceUntil(values: readonly unknown[], abort?: AbortSignal): Promise< else reject(settled.error); }; - if (abort) { - if (abort.aborted) return finish({ ok: true, value: undefined }); + if (abort?.aborted) { + finish({ ok: true, value: undefined }); + } else if (abort) { const stop = () => finish({ ok: true, value: undefined }); abort.addEventListener("abort", stop); disposes.push(() => abort.removeEventListener("abort", stop)); } for (const value of values) { + // Observe a loser even once the race is decided, as Promise.race does, so its later + // rejection is not reported as unhandled. A thenable keeps one shared reaction. + if (done) { + listen(value, noop)(); + continue; + } const dispose = listen(value, finish); - if (done) return dispose(); - disposes.push(dispose); + if (done) dispose(); + else disposes.push(dispose); } }); } @@ -379,7 +386,8 @@ function raceUntil(values: readonly unknown[], abort?: AbortSignal): Promise< * Accepts promises and {@link GetPromise} values such as a {@link Once}. Racing a value that * outlives the call (a `closed` pending for the whole track) once per frame therefore leaks nothing, * where `Promise.race` would leave a listener or reaction behind on every call. An already settled - * value wins at once. + * value wins at once. Like `Promise.race`, every value is observed, so a loser that rejects later + * is not an unhandled rejection. */ export function race(values: T): Promise> { return raceUntil(values);