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
21 changes: 20 additions & 1 deletion js/web-transport/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const session = new Session("https://example.com:4443/path", {
});
```

QUIC uses the smaller of both peers' idle timeouts, so disabling one endpoint's timeout leaves the peer's in effect. To keep an otherwise idle session open, set `keepAliveInterval` below the effective idle timeout on either endpoint.
QUIC uses the smaller of both peers' idle timeouts, so disabling one endpoint's timeout leaves the peer's in effect. To keep an otherwise idle session open, set `keepAliveInterval` below the effective idle timeout on either endpoint. An expired idle timeout is a connection failure, so it rejects `session.closed` with a session `WebTransportError`.

### Polyfill

Expand Down Expand Up @@ -170,10 +170,29 @@ import { WebTransportError } from "@moq/web-transport";
await writer.abort(new WebTransportError("cancelled", { streamErrorCode: 7 }));
```

### Releasing readers

Call `reader.cancel()` when you stop reading a receive stream. Cancellation is the
release boundary: it interrupts a pending `read()`, sends STOP_SENDING with the reason's
`streamErrorCode` (0 otherwise), and releases the native stream.

A pending `read()` keeps its stream alive until data, the stream's end, a session
close, or cancellation settles it. Garbage collection does not cancel an abandoned
reader with a pending read, so an abandoned reader keeps its stream open and the
peer never sees STOP_SENDING. This matches Web Streams, where an awaited `read()`
or `pipeTo()` must not fail because only its promise remains reachable.

### Closing

Always call `session.close()` when finished and await `session.closed`. The Node wrapper retains native Session handles while its close promise and incoming stream operations are pending. Garbage collecting the JavaScript Session does not close those handles, so it does not provide the Rust Session's final-handle cleanup contract.

`session.closed` resolves with the application code and reason after a local or peer close,
including nonzero application codes. An orderly HTTP/3 connection shutdown (H3_NO_ERROR)
without application details resolves with code 0 and an empty reason. A failed connection or an underlying connection
failure rejects it with a `WebTransportError` whose `source` is `"session"` and
`streamErrorCode` is `null`. `session.ready` rejects with the same error if connecting fails.
Backend teardown without an application `session.close()` also rejects `closed`.

```ts
// Close gracefully
session.close({ closeCode: 0, reason: "done" });
Expand Down
6 changes: 3 additions & 3 deletions js/web-transport/napi.d.cts
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ export declare class NapiClient {
export declare class NapiRecvStream {
/**
* Read up to `max_size` bytes from the stream. Returns null on FIN, or the error if the
* peer reset the stream or the session failed.
* peer reset the stream or the session failed. Local cancellation rejects the read.
*/
read(maxSize: number): Promise<Buffer | NapiStreamError | null>;
/** Tell the peer to stop sending with the given error code. */
/** Tell the peer to stop sending with the given code; an already terminal stream is a no-op. */
stop(code: number): Promise<void>;
}

Expand Down Expand Up @@ -110,7 +110,7 @@ export declare class NapiSession {
maxDatagramSize(): number;
/** Close the session with a code and reason. */
close(code: number, reason: string): void;
/** Wait for the session to close, returning close info matching W3C WebTransportCloseInfo. */
/** Wait for normal closure with its application details, or reject on a connection failure. */
closed(): Promise<NapiCloseInfo>;
}

Expand Down
2 changes: 1 addition & 1 deletion js/web-transport/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"scripts": {
"build": "bun run build:native && bun run build:js",
"check": "tsc --project tsconfig.tests.json --noEmit",
"test": "bun test tests",
"test": "cargo build -p web-transport-node --example session-peer && bun test tests",
"test:runtime": "bun scripts/test-runtime.ts",
"release": "bun scripts/release.ts",
"build:native": "napi build --platform --release --manifest-path ../../rs/web-transport-node/Cargo.toml --output-dir . --js napi.cjs --dts napi.d.cts && biome check --write napi.cjs napi.d.cts",
Expand Down
37 changes: 20 additions & 17 deletions js/web-transport/src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,18 @@ import { fromNapi, resetCode, sessionError } from "./error.ts";
const { NapiClient } = napi;

function wrapRecvStream(recv: NapiRecvStream): ReadableStream<Uint8Array> {
let cancelled = false;
return new ReadableStream({
async pull(controller) {
const chunk = await recv.read(65536);
if (chunk === null) {
controller.close();
} else if (chunk instanceof Uint8Array) {
controller.enqueue(new Uint8Array(chunk));
} else {
controller.error(fromNapi(chunk));
}
if (cancelled) return;
if (chunk === null) controller.close();
else if (chunk instanceof Uint8Array) controller.enqueue(new Uint8Array(chunk));
else controller.error(fromNapi(chunk));
},
cancel(reason) {
recv.stop(resetCode(reason)).catch(() => {});
cancelled = true;
return recv.stop(resetCode(reason));
},
});
}
Expand Down Expand Up @@ -93,6 +92,13 @@ export default class Session implements WebTransport {
const closed = Promise.withResolvers<WebTransportCloseInfo>();
this.ready = ready.promise;
this.closed = closed.promise;
// The spec marks lifecycle promises handled; callers can still await their rejections.
void this.ready.catch(() => {});
void this.closed.catch(() => {});

const watchSession = (session: NapiSession) => {
void session.closed().then(closed.resolve, (err: unknown) => closed.reject(sessionError(err)));
};

// Check if we got an existing NapiSession (server-side path)
if (typeof urlOrSession === "object" && !(urlOrSession instanceof URL)) {
Expand All @@ -101,9 +107,7 @@ export default class Session implements WebTransport {

ready.resolve();

urlOrSession.closed().then((info) => {
closed.resolve({ closeCode: info.closeCode, reason: info.reason });
});
watchSession(urlOrSession);
} else {
// Client-side: create NapiClient and connect
const url = typeof urlOrSession === "string" ? urlOrSession : urlOrSession.toString();
Expand Down Expand Up @@ -147,14 +151,13 @@ export default class Session implements WebTransport {
(this.datagrams as DeferredDatagrams).bind(session);
ready.resolve();

session.closed().then((info) => {
closed.resolve({ closeCode: info.closeCode, reason: info.reason });
});
watchSession(session);
})
.catch((err) => {
(this.datagrams as DeferredDatagrams).fail(err instanceof Error ? err : new Error(String(err)));
ready.reject(err instanceof Error ? err : new Error(String(err)));
closed.resolve({ closeCode: 0, reason: String(err) });
const error = sessionError(err);
(this.datagrams as DeferredDatagrams).fail(error);
ready.reject(error);
closed.reject(error);
});
}
}
Expand Down
45 changes: 45 additions & 0 deletions js/web-transport/tests/fixtures/active-reader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import assert from "node:assert/strict";
import { setImmediate } from "node:timers/promises";
import Session from "../../src/session.ts";

const url = process.argv[2];
if (!url || !globalThis.gc) throw new Error("requires a peer URL and --expose-gc");
const session = new Session(url, { serverCertificateDisableVerify: true });
await session.ready;
const incoming = session.incomingUnidirectionalStreams.getReader();
const trigger = session.datagrams.writable.getWriter();

for (const pipe of [false, true]) {
const started = Promise.withResolvers<void>();
const result = (async () => {
const { value: readable } = await incoming.read();
if (!readable) throw new Error("no stream");
if (pipe) {
const observed = readable.pipeThrough(
new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
started.resolve();
controller.enqueue(chunk);
},
}),
);
return new Response(observed).arrayBuffer();
}
const reader = readable.getReader();
await reader.read();
started.resolve();
return reader.read();
})();
// Wait for the first byte, then collect while only the consumer's result is retained.
await started.promise;
await setImmediate();
globalThis.gc();
await setImmediate();
await trigger.write(new Uint8Array([1]));
const value = await result;
if (pipe) assert.deepEqual(new Uint8Array(value as ArrayBuffer), new Uint8Array([1, 2]));
else assert.deepEqual((value as ReadableStreamReadResult<Uint8Array>).value, new Uint8Array([2]));
}

session.close();
await session.closed;
8 changes: 5 additions & 3 deletions js/web-transport/tests/fixtures/idle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { createSocket } from "node:dgram";
import { setTimeout as sleep } from "node:timers/promises";
import Session, { Server, type ServerOptions, type SessionOptions } from "../../src/index.ts";
import Session, { Server, type ServerOptions, type SessionOptions, WebTransportError } from "../../src/index.ts";

const pem = execFileSync("openssl", [
"req",
Expand Down Expand Up @@ -47,8 +47,10 @@ const EXPIRY_BOUND_MS = 10_000;
async function expectExpiry(serverOptions: ServerOptions | undefined, clientOptions: SessionOptions) {
const { client, peer } = await connect(serverOptions, clientOptions);
const start = performance.now();
const [info] = await Promise.all([client.closed, peer.closed]);
assert.match(info.reason ?? "", /timed out/);
// An idle timeout is a connection failure, so both sides reject with a session error.
const timedOut = (err: unknown) =>
err instanceof WebTransportError && err.source === "session" && /timed out/.test(err.message);
await Promise.all([assert.rejects(client.closed, timedOut), assert.rejects(peer.closed, timedOut)]);
assert(performance.now() - start < EXPIRY_BOUND_MS);
}

Expand Down
2 changes: 1 addition & 1 deletion js/web-transport/tests/fixtures/server-close.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ holding = false;
assert(remoteClient);
for (const flight of flights) proxy.send(flight, remoteClient.port, remoteClient.address);
await rejected;
await stalled.closed;
await assert.rejects(stalled.closed);
await new Promise<void>((resolve) => proxy.close(resolve));

// Stopping the listener must not close sessions it already accepted.
Expand Down
Loading
Loading