Skip to content
43 changes: 25 additions & 18 deletions js/net/src/ietf/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,16 @@ function handed(task: Promise<void>): Promise<void> {
return task.catch((err: unknown) => console.error("error processing bidi stream", err));
}

/** Where a session is: open, delivering what it owes before it closes, or closed. */
type Phase = { kind: "open" } | { kind: "closing"; done: Promise<void> } | { kind: "closed" };

/**
* Represents a connection to a MoQ server using moq-transport protocol.
*
* @internal
*/
export class Connection implements Established {
#closing?: Promise<void>;
#phase: Phase = { kind: "open" };
// The URL of the connection.
readonly url: URL;

Expand Down Expand Up @@ -95,9 +98,6 @@ export class Connection implements Established {
// The peer's GOAWAY, read off its SETUP stream.
#goaway = new Once<Drain>();

// Just to avoid logging when `close()` is called.
#closed = false;

/** The implementation the peer advertised; see {@link Established.peerImplementation}. */
readonly peerImplementation: Promise<string | undefined>;

Expand Down Expand Up @@ -189,7 +189,7 @@ export class Connection implements Established {
subscribe: new Path.Patterns(publish ? [Path.Pattern.all()] : []),
},
handle,
draining: () => this.#goaway.peek() !== undefined || this.#closing !== undefined,
draining: () => this.#goaway.peek() !== undefined || this.#phase.kind !== "open",
});
// Left before anything observes the close, so a successor on the same handle never
// finds this session still active.
Expand Down Expand Up @@ -245,25 +245,32 @@ export class Connection implements Established {

/** Withdraw announcements and wait up to one second for delivery before closing. */
close(): Promise<void> {
this.#closing ??= withTimeout(
this.#publisher.withdraw(),
Nano.fromSecond(Second(1)),
"session close timed out",
).finally(() => this.abort());
return this.#closing;
switch (this.#phase.kind) {
case "open": {
const done = withTimeout(
this.#publisher.withdraw(),
Nano.fromSecond(Second(1)),
"session close timed out",
).finally(() => this.abort());
this.#phase = { kind: "closing", done };
return done;
}
case "closing":
return this.#phase.done;
case "closed":
return Promise.resolve();
}
}

/** End the session immediately without waiting for delivery. */
abort(): void {
if (this.#closed) return;
this.#close();
}

// Close with the session code the peer should see, a clean close by default.
#close(info?: WebTransportCloseInfo) {
if (this.#closed) return;

this.#closed = true;
if (this.#phase.kind === "closed") return;
this.#phase = { kind: "closed" };

this.#publisher.close();
this.#auth.close();
Expand Down Expand Up @@ -301,15 +308,15 @@ export class Connection implements Established {
if (this.#client) tasks.push(this.#publisher.runEnforce(this.#auth.setupAnswered(), this.#auth));
await Promise.all(tasks);
} catch (err) {
if (!this.#closed) {
if (this.#phase.kind !== "closed") {
console.error("fatal error running connection", err);
}
} finally {
// A graceful close owns the teardown while it drains. runPublishNamespaces is
// a tracked withdrawal, so a failure in it ends this driver while close() is
// still waiting on the sibling loops; closing here would drop their
// withdrawals. close() aborts once its barrier settles or the deadline hits.
if (!this.#closing) this.#close();
if (this.#phase.kind !== "closing") this.#close();
}
}

Expand Down Expand Up @@ -573,7 +580,7 @@ export class Connection implements Established {
});
await race([read(), stopped]);
} catch (err) {
if (!this.#closed && !sessionClosed(err))
if (this.#phase.kind !== "closed" && !sessionClosed(err))
this.#violated(
err instanceof ProtocolViolation
? err
Expand Down
50 changes: 50 additions & 0 deletions js/net/src/ietf/publisher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4580,6 +4580,56 @@ test("draft-22: narrowing gives up an excluded group's open stream", async () =>
}
});

test("draft-22: an update reopening a drained subscription serves its tail", async () => {
const fx = fixture();
// The SUBSCRIBE's fill waits for stream credit, holding the request open past the track's end.
const credit = Promise.withResolvers<void>();
const createUni = fx.pair.server.createUnidirectionalStream.bind(fx.pair.server);
spyOn(fx.pair.server, "createUnidirectionalStream").mockImplementationOnce(async (options) => {
await credit.promise;
return createUni(options);
});
const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI });
const open = track.appendGroup();
open.writeFrame({ payload: new TextEncoder().encode("head"), timestamp: Timestamp.now() });
const { client } = await runSubscribe(
fx,
new Subscribe({
requestId: 0n,
trackNamespace: Path.from("test"),
trackName: "video",
subscriberPriority: 0,
filter: { kind: "absolute", startGroup: 5n, startObject: 0n },
fill: { filter: { kind: "absolute", startGroup: 0n, startObject: 0n }, rangeFilters: false },
}),
);
try {
// The open group stays open: the end falls after it.
track.finish();
const parameters = new Parameters();
parameters.subscriptionFilter = { kind: "absolute", startGroup: 0n, startObject: 0n };
parameters.fillParameters = Filter.encodeFill({ rangeFilters: false }, fx.version);
await client.writer.u53(SubscribeUpdate.id);
await new SubscribeUpdate({ requestId: 2n, parameters }).encode(client.writer, fx.version);
credit.resolve();
expect(await client.reader.u53()).toBe(RequestOk.id);
await RequestOk.decode(client.reader, fx.version);
open.writeFrame({ payload: new TextEncoder().encode("tail"), timestamp: Timestamp.now() });
open.finish();
expect(await client.reader.u53()).toBe(PublishDone.id);
const done = await PublishDone.decode(client.reader, fx.version);
// Both fills, the tail's group, then END_OF_TRACK once they closed.
expect(done.streamCount).toBe(4n);
expect((await readServed(fx.uni, 3)).sort()).toEqual(["head", "head", "tail"]);
expect(await readEndOfTrack(await nextUni(fx.uni))).toBe(1n);
} finally {
open.finish();
client.close();
track.close();
fx.close();
}
});

test("draft-22: widening with a fill keeps the open live group", async () => {
using clock = manual();
const fx = fixture();
Expand Down
Loading
Loading