Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion js/hang/src/container/consumer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1496,12 +1496,12 @@ test("Consumer duration-skips a stalled group once it is covered", async () => {
g1.finish();

track.finish();
track.close();

const frames = await drainFrames(consumer, 200);
expect(frames.map((f) => f.timestamp as number)).toEqual([0, 33_000]);
expect(frames.map((f) => f.group)).toEqual([0, 1]);
consumer.close();
track.close();
});

test("Consumer does not duration-skip when the gap is not covered", async () => {
Expand Down
2 changes: 1 addition & 1 deletion js/net/api/index.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -631,7 +631,7 @@ export namespace Track {
demand(): Track.Demand;
readonly name: string;
get priority(): number;
reject(err?: Error): void;
reject(err: Error): void;
get subscription(): Readonly<Track.Subscription>;
}
export class Subscriber {
Expand Down
10 changes: 5 additions & 5 deletions js/net/src/broadcast.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect, setSystemTime, test } from "bun:test";
import { Milli } from "@moq/clock";
import { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts";
import { GroupTooLarge, NotFound } from "./error.ts";
import { GroupTooLarge, NotFound, StreamCode } from "./error.ts";
import { MAX_GROUP_FRAMES } from "./group.ts";
import { hooks } from "./internal.ts";
import { textFrame } from "./mock.ts";
Expand Down Expand Up @@ -161,7 +161,7 @@ test("createTrack does not take over a request a handler already pulled", async

// The handler holds it, so the name stays duplicate until it answers, as in Rust.
expect(() => broadcast.createTrack("media")).toThrow("duplicate track");
request.reject();
request.reject(new Error("request refused"));
broadcast.close();
});

Expand Down Expand Up @@ -340,11 +340,11 @@ test("closing a broadcast rejects a dequeued request", async () => {
const request = await pulled;
if (!request) throw new Error("expected request");
broadcast.close();
await expect(subscriber.info()).rejects.toThrow("track closed before info was known");
await expect(subscriber.info()).rejects.toMatchObject({ code: StreamCode.Internal });

const producer = request.accept({ timescale: Timescale.MILLI });
expect(() => producer.appendGroup()).toThrow("track is closed");
await expect(subscriber.info()).rejects.toThrow("track closed before info was known");
await expect(subscriber.info()).rejects.toMatchObject({ code: StreamCode.Internal });
subscriber.close();
producer.finish();
producer.close();
Expand Down Expand Up @@ -735,7 +735,7 @@ test("broadcast demand watches static and pending tracks rather than broadcast h
await unwanted(requested);
await demand.unused();
expect(demand.used.peek()).toBe(false);
request.reject();
request.reject(new Error("request refused"));
video.finish();
video.close();
broadcast.close();
Expand Down
9 changes: 7 additions & 2 deletions js/net/src/broadcast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/
import { type Dispose, type GetPromise, type Getter, Once, Signal } from "@moq/signals";
import type * as Epoch from "./epoch.ts";
import { NotFound } from "./error.ts";
import { NotFound, StreamCode, StreamError } from "./error.ts";
import type { Consumer as GroupConsumer } from "./group.ts";
import type { Route } from "./hop.ts";
import { hooks } from "./internal.ts";
Expand Down Expand Up @@ -149,7 +149,12 @@ function closeState(state: BroadcastState) {
state.closed.set(null);
state.listing.close();
for (const cleanup of state.demands.values()) cleanup();
for (const request of state.pending) request.reject();
for (const request of state.pending)
request.reject(
new StreamError(StreamCode.Internal, {
message: `track request ${request.name} dropped before acceptance`,
}),
);
state.requested.mutate((requests) => {
requests.length = 0;
});
Expand Down
19 changes: 14 additions & 5 deletions js/net/src/lite/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ export class Connection implements Established {
this.#auth.violated.subscribe((err) => {
if (!err) return;
closeViolation(this.#quic, err);
this.abort();
this.#fail(err);
});

this.#publisher = new Publisher(this.#quic, this.#version, this.hop, publish, {
Expand Down Expand Up @@ -273,6 +273,12 @@ export class Connection implements Established {
}
}

// Set the received tracks' terminal cause before abort's deliberate local teardown.
#fail(err: Error): void {
this.#subscriber.close(err);
this.abort();
}

async #run(): Promise<void> {
const tasks: Promise<void>[] = [this.#runSession(), this.#runBidis(), this.#runUnis()];

Expand Down Expand Up @@ -312,8 +318,7 @@ export class Connection implements Established {
this.#peerImplementation.resolve(undefined);
// The session died under every track it was receiving, so they end with its
// error. A deliberate close() already ended them cleanly, which makes this a no-op.
this.#subscriber.close(fatal ?? (await closeError(this.#quic)));
this.abort();
this.#fail(fatal ?? (await closeError(this.#quic)));
}
}

Expand Down Expand Up @@ -370,7 +375,8 @@ export class Connection implements Established {
stream.writer.reset(err);
// A protocol violation on one stream is the peer breaking the session.
// Resetting that stream would leave it free to repeat malformed input.
if (closeViolation(this.#quic, err)) this.abort();
const violation = closeViolation(this.#quic, err);
if (violation) this.#fail(violation);
})
.finally(() => {
stream.writer.close();
Expand Down Expand Up @@ -448,7 +454,10 @@ export class Connection implements Established {
})
.catch((err: unknown) => {
stream.stop(err);
if (err instanceof ProtocolViolation) closeViolation(this.#quic, err);
if (err instanceof ProtocolViolation) {
closeViolation(this.#quic, err);
this.#fail(err);
}
});
}
}
Expand Down
6 changes: 3 additions & 3 deletions js/net/src/lite/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { closeReason, ProtocolViolation } from "../error.ts";
import { isDecodeError } from "../util/decode_error.ts";

// Control handlers share AUTH's session-close policy; data readers never call this.
export function closeViolation(quic: WebTransport, cause: unknown): boolean {
export function closeViolation(quic: WebTransport, cause: unknown): ProtocolViolation | undefined {
const err =
isDecodeError(cause) && !(cause instanceof ProtocolViolation)
? new ProtocolViolation("invalid control encoding", { cause })
: cause;
if (!(err instanceof ProtocolViolation)) return false;
if (!(err instanceof ProtocolViolation)) return undefined;
quic.close({ closeCode: err.code, reason: closeReason(err.message) });
return true;
return err;
}
2 changes: 1 addition & 1 deletion js/net/src/lite/track_stream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver
pair.server.close();
expect(await settlesWithin(demand.unused(), 1000)).toBe(true);

request.reject();
request.reject(new Error("request refused"));
publisher.close();
broadcast.close();
origin.close();
Expand Down
92 changes: 92 additions & 0 deletions js/net/src/terminal.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { expect, test } from "bun:test";
import { Producer as BroadcastProducer } from "./broadcast.ts";
import { ProtocolViolation, SessionCode, StreamCode } from "./error.ts";
import { hooks } from "./internal.ts";
import { Connection } from "./lite/connection.ts";
import { StreamId } from "./lite/stream.ts";
import { ALPN_06, Version } from "./lite/version.ts";
import { createMockTransportPair, textFrame } from "./mock.ts";
import { Producer as OriginProducer } from "./origin.ts";
import * as Path from "./path.ts";
import { Stream } from "./stream.ts";
import { Timescale } from "./time.ts";
import { Producer as TrackProducer } from "./track.ts";
import { wireOf } from "./wire.ts";

for (const release of [false, true]) {
test(`${release ? "releasing" : "closing"} a track preserves finished groups and aborts its unfinished tail`, async () => {
const producer = new TrackProducer("video").accept({ timescale: Timescale.MILLI });
const complete = producer.appendGroup();
complete.writeFrame(textFrame("complete"));
complete.finish();
const tail = producer.appendGroup();
tail.writeFrame(textFrame("prefix"));
const finished = complete.consume();
const unfinished = tail.consume();
producer.finish();
try {
if (release) hooks.releaseTrack(producer);
else producer.close();
expect(await finished.readString()).toBe("complete");
expect(await finished.readFrame()).toBeUndefined();
expect(await unfinished.readString()).toBe("prefix");
await expect(unfinished.readFrame()).rejects.toMatchObject({ code: StreamCode.Cancel });
} finally {
finished.close();
unfinished.close();
producer.close();
}
});
}

test("an unanswered track request is refused with the dropped producer's error", async () => {
const broadcast = new BroadcastProducer();
const requested = wireOf(broadcast).requested();
const track = broadcast.track("absent").subscribe();
await requested;
const info = track.info();
broadcast.close();
try {
await expect(info).rejects.toMatchObject({ code: StreamCode.Internal });
expect(await track.closed).toMatchObject({ code: StreamCode.Internal });
} finally {
track.close();
}
});

test("a lite protocol violation reaches the subscribed track and its open group", async () => {
const pair = createMockTransportPair(ALPN_06);
const origin = new OriginProducer();
const publication = origin.createBroadcast(Path.from("room"));
publication.announce();
const producer = publication.broadcast.createTrack("video", { timescale: Timescale.MILLI });
producer.appendGroup().writeFrame(textFrame("prefix"));
const url = new URL("https://example.com");
const client = new Connection({ url, quic: pair.client, version: Version.DRAFT_06 });
const server = new Connection({
url,
quic: pair.server,
version: Version.DRAFT_06,
publish: origin.consume(),
client: false,
});
const broadcast = wireOf(client).consume(Path.from("room"));
const track = broadcast.track("video").subscribe();
const group = await track.recvGroup();
try {
expect(await group?.readString()).toBe("prefix");
const duplicate = await Stream.open(pair.server, { version: Version.DRAFT_06 });
await duplicate.writer.u53(StreamId.Session);
expect((await pair.client.closed).closeCode).toBe(SessionCode.ProtocolViolation);
expect(await track.closed).toBeInstanceOf(ProtocolViolation);
await expect(group?.readFrame()).rejects.toBeInstanceOf(ProtocolViolation);
} finally {
group?.close();
track.close();
broadcast.close();
client.abort();
server.abort();
publication.broadcast.close();
origin.close();
}
});
7 changes: 4 additions & 3 deletions js/net/src/track.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1857,7 +1857,7 @@ test("withRange parks recvGroup beyond the cap and a raised cap re-offers", asyn
const producer = new TrackProducer("test");
const track = producer.subscribe({ maxDelay: Milli(5000) });

for (let sequence = 0; sequence < 3; sequence++) producer.createGroup(sequence);
for (let sequence = 0; sequence < 3; sequence++) producer.createGroup(sequence).finish();

track.withRange({ end: { excluded: 2 } });
expect((await track.recvGroup())?.sequence).toBe(0);
Expand Down Expand Up @@ -2450,7 +2450,7 @@ test("a lowered range re-offers a cached cut with its error", async () => {
test("a lowered range still re-offers after the producer closes", () => {
const producer = new TrackProducer("test");
const track = producer.subscribe({ maxDelay: Milli(5000), groups: { start: { included: 1 } } });
for (const sequence of [0, 1]) producer.createGroup(sequence);
for (const sequence of [0, 1]) producer.createGroup(sequence).finish();
expect(track.tryRecvGroup()?.sequence).toBe(1);
producer.finish();
producer.close();
Expand Down Expand Up @@ -3485,7 +3485,8 @@ test("an evicted group still bounds, and a late group below it is unverified", a
// the group and it is accepted without being trusted to time anything.
const track = producer.subscribe({ maxDelay: Milli(60_000) });
expect(() => stampGroup(producer, 1, 4000)).toThrow(TimestampMismatch);
stampGroup(producer, 1, 500);
stampGroup(producer, 1, 500).finish();
edge.finish();
producer.finish();
producer.close();

Expand Down
22 changes: 10 additions & 12 deletions js/net/src/track.ts
Original file line number Diff line number Diff line change
Expand Up @@ -386,14 +386,10 @@ export class Request {
};
}

/** Reject the request, closing the track optionally with an error. */
reject(err?: Error): void {
/** Reject the request with the error its subscribers receive. */
reject(err: Error): void {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
this.#pending.delete(this);
if (err) this.#producer.abort(err);
else {
this.#producer.finish();
this.#producer.close();
}
this.#producer.abort(err);
}
}

Expand Down Expand Up @@ -1698,13 +1694,15 @@ export class Producer {
if (abort && (this.#state.outcome.peek() === null || this.#settled())) abort = undefined;
// Nobody will finish these, so a subscriber that has not taken one yet never sees it.
// Not evicted: a reader already holding one keeps its frames and sees the abort.
const open = abort ? this.#cache.filter((entry) => entry.group.closed.peek() === undefined) : [];
const open = this.#cache.filter((entry) => entry.group.closed.peek() === undefined);
closeTrackState(this.#state, abort);
if (this.#state.outcome.peek() === undefined) this.#state.outcome.set(abort ?? null);
for (const { group } of this.#cache) {
if (abort) group.abort(abort);
else group.finish();
}
// Closing a copy never supplies the missing tail of a group. Already finished groups
// ignore the abort and stay readable; unfinished ones retain their truncation cause.
const groupError =
abort ??
new StreamError(StreamCode.Cancel, { message: `track ${this.name} closed with unfinished groups` });
for (const { group } of this.#cache) group.abort(groupError);
for (const entry of open) {
this.#unlink(entry);
this.#uncache(entry);
Expand Down
2 changes: 1 addition & 1 deletion quest/m1/cut-audit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ leaving JS-only redesigns of `js/net` to [rs2ts](/quest/m2/rs2ts/README.md).

- [Counted field-less `trun` entries](/quest/m1/cut-audit/fmp4-sample-resolver.md) - a moof of field-less runs cannot materialize millions of sample entries
- [A reserved group survives a route returning](/quest/m1/cut-audit/reserved-route-return.md) - a route flip A to B to A no longer panics a peeked reader
- [JS tracks end clean only on a deliberate finish](/quest/m1/cut-audit/js-close-cause.md) - local close, violations, and unanswered requests end with errors
- [Settle received-track termination on a local session close](/quest/m1/cut-audit/js-close-cause.md) - choose the received track's local-close outcome after the prepared teardown error fixes
- [A description-less AAC rendition means one thing](/quest/m1/cut-audit/aac-description-less.md) - every player and exporter agrees on the frame format
- [RTMP sessions follow one strict path](/quest/m1/cut-audit/rtmp-session-strict.md) - idle sockets, repeated requests, rewinds, and stalled servers are handled
- [The export jitter buffer admits only frames due within its window](/quest/m1/cut-audit/jitter-admission.md) - a fast track is backpressured, not buffered without bound
Expand Down
Loading
Loading