Skip to content
Merged
42 changes: 35 additions & 7 deletions js/net/src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* @module
*/

import { sharedStreamCode } from "./ietf/error.ts";
import type { IetfVersion } from "./ietf/version.ts";
import { TimeoutError } from "./util/timeout.ts";

Expand Down Expand Up @@ -269,16 +270,20 @@ interface TransportErrorOptions {
* rather than inventing one. A {@link SessionError} lands there too: the two registries are
* disjoint, so forwarding its code onto a stream would mistranslate it.
*
* On IETF streams only cancellation is mapped; other failures use INTERNAL_ERROR.
* On an IETF stream the code has to be one the negotiated draft assigns the same meaning to,
* so a condition it does not register degrades to INTERNAL_ERROR as well. See
* {@link sharedStreamCode}.
*
* @internal
*/
export function toStreamCode(err: unknown, options?: TransportErrorOptions): StreamCode {
if (options?.version !== undefined) {
// Match Rust's IETF mapping: a local timeout is not a negotiated delivery timeout,
// and losing one group does not establish that the subscription is terminating.
return err instanceof StreamError && err.code === StreamCode.Cancel ? StreamCode.Cancel : StreamCode.Internal;
}
const code = localStreamCode(err);
if (options?.version === undefined) return code;
return sharedStreamCode(code, options.version) ? code : StreamCode.Internal;
}

/** The moq-lite code for a local failure, before any draft has a say. */
function localStreamCode(err: unknown): StreamCode {
if (err instanceof StreamError) return err.code;
if (err instanceof TimeoutError) return StreamCode.DeliveryTimeout;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep generic timeouts out of DELIVERY_TIMEOUT

This maps every TimeoutError to the IETF DELIVERY_TIMEOUT reset even when the timeout is unrelated to media delivery. For example, the SUBSCRIBE_OK timer in ietf/subscriber.ts and the PUBLISH_NAMESPACE response timer in ietf/publisher.ts both abort their request streams with that error, so a silent peer is told that content missed a delivery deadline although only a control response timed out. Keep generic IETF timeouts as INTERNAL_ERROR, or introduce a distinct error used only when an actual delivery deadline expires.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The observation is right, but the fix is not this PR's.

toStreamCode mapped every TimeoutError to DeliveryTimeout before this branch, and Rust does the same through From<&Error> for StreamError (Error::Timeout => StreamError::DeliveryTimeout). Making the IETF branch alone say INTERNAL_ERROR would leave the two languages and the two wires disagreeing about the same condition, which is exactly what this PR set out to stop.

The real question is whether "you never answered" deserves a condition separate from "your content was late", in both languages, on both wires. Filed as quest/m1/control-timeout-code.md in 104d644, including the option of dropping the code rather than adding one.

(written by claude-opus-5)

// Session-scoped: the peer learns which rule it broke from the session close, not from here.
Expand All @@ -298,15 +303,38 @@ export function toStreamCode(err: unknown, options?: TransportErrorOptions): Str
* the same `instanceof` as one raised here. Only the registered codes do: the reserved 32-63
* placeholders carry no meaning the draft assigns, so they stay a plain {@link StreamError}.
*
* On an IETF stream a code keeps its value unless moq-lite claims that number for something
* the draft does not: `0x4` is GOING_AWAY here but UNKNOWN_OBJECT_STATUS on draft-16 and 17,
* and reading one back as the other would retire a session that is not going anywhere. Those
* read as {@link StreamCode.Internal} with the wire value kept in the message, since
* {@link StreamCode} is one numeric space and cannot hold a foreign code without lying about
* it. A code moq-lite names nothing for survives intact: nothing can misread it.
*
* @internal Called at the transport boundary so the raw error never reaches an application.
*/
export function fromTransport(err: unknown, options?: TransportErrorOptions): Error {
const code = streamCode(err);
if (code === undefined) return error(err);
if (options?.version === undefined && code === StreamCode.TooFarBehind) return new Lagged({ cause: err });
if (options?.version !== undefined && !sharedStreamCode(code, options.version) && claimedLocally(code)) {
return new StreamError(StreamCode.Internal, { cause: err, message: `remote error: ${code}` });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve unknown IETF reset codes

When an IETF peer sends a registered code that has no matching moq-lite meaning, such as UNKNOWN_OBJECT_STATUS (0x4) on draft-16/17, this branch replaces the observable StreamError.code with INTERNAL_ERROR (0). That discards the machine-readable wire value and makes the peer's condition indistinguishable from an actual internal failure, unlike Rust's from_stream_code, which retains it as Unknown(code). Keep the received code on the plain StreamError; only avoid assigning a misleading typed subclass.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, and taken partway.

A code moq-lite names nothing for now keeps its value: UNKNOWN_OBJECT_STATUS (0x6 from draft-18), EXPIRED_AUTH_TOKEN (0x7) and EXCESSIVE_LOAD (0x9) reach the caller as a plain StreamError carrying the wire number, since nothing can misread them.

The flattening stays only where moq-lite claims the number for something the draft does not, which is the case you named: StreamCode is one numeric space, so a draft-16/17 UNKNOWN_OBJECT_STATUS kept as 0x4 would compare equal to StreamCode.GoingAway and retire a session that is not going anywhere. Same for 0x5 and 0x12 on the drafts that predate their registration, and for the reserved 32-63 placeholders. Rust avoids this with a separate StreamError::Unknown(code) variant that cannot collide; JS has no second space, so those codes report Internal with the wire value kept in the message.

8980206

(written by claude-opus-5)

}
if (code === StreamCode.TooFarBehind) return new Lagged({ cause: err });
return new StreamError(code, { cause: err });
}

/** The codes moq-lite names, which a foreign one must not borrow. */
const NAMED_CODES: ReadonlySet<number> = new Set(Object.values(StreamCode));

/**
* Whether moq-lite could give `code` a meaning of its own: one of its named codes, or
* anywhere in the 64+ range, where `StreamCode(code)` mints an application code and an
* application compares against its own. moq-transport registers nothing above 0x12 and has
* no application range at all, so a foreign code landing there is never what it looks like.
*/
function claimedLocally(code: number): boolean {
return code >= 64 || NAMED_CODES.has(code);
}

const legacyWebTransportErrors = new WeakSet<object>();

/**
Expand Down
11 changes: 6 additions & 5 deletions js/net/src/ietf/adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createMockTransportPair } from "../mock.ts";
import * as Path from "../path.ts";
import { Stream } from "../stream.ts";
import { ControlStreamAdapter } from "./adapter.ts";
import { toRequestCode } from "./error.ts";
import { PublishNamespace, PublishNamespaceCancel, PublishNamespaceDone } from "./publish_namespace.ts";
import { RequestError } from "./request.ts";
import { ALPN, Version } from "./version.ts";
Expand Down Expand Up @@ -85,10 +86,10 @@ async function closed(stream: Stream): Promise<boolean> {

/**
* Draft-14/15 withdrawals name a namespace, so the adapter resolves them through a map it
* keeps while decoding. A duplicate announcement is refused with 409, but the mapping is
* written before the subscriber ever sees it: overwriting there would point the first
* request's DONE at the refused one, which has no stream left, and the announcement would
* stay up for the rest of the session.
* keeps while decoding. A duplicate announcement is refused, but the mapping is written
* before the subscriber ever sees it: overwriting there would point the first request's DONE
* at the refused one, which has no stream left, and the announcement would stay up for the
* rest of the session.
*/
test("a refused duplicate does not strand the first announcement", async () => {
const { adapter, peer } = await connect();
Expand All @@ -105,7 +106,7 @@ test("a refused duplicate does not strand the first announcement", async () => {
await second.writer.u53(RequestError.id);
await new RequestError({
requestId: 3n,
errorCode: 409,
errorCode: toRequestCode("internal", "publish_namespace", VERSION),
reasonPhrase: "duplicate namespace",
retryInterval: 0n,
}).encode(second.writer, VERSION);
Expand Down
168 changes: 168 additions & 0 deletions js/net/src/ietf/error.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
import { expect, test } from "bun:test";
import { StreamCode } from "../error.ts";
import { fromRequestCode, type RequestCondition, type RequestKind, sharedStreamCode, toRequestCode } from "./error.ts";
import { type IetfVersion, Version } from "./version.ts";

const ALL: IetfVersion[] = [
Version.DRAFT_14,
Version.DRAFT_15,
Version.DRAFT_16,
Version.DRAFT_17,
Version.DRAFT_18,
Version.DRAFT_19,
Version.DRAFT_20,
];

const KINDS: RequestKind[] = ["subscribe", "fetch", "publish", "publish_namespace", "subscribe_namespace"];

/** Every condition a rejection can carry. A new one belongs here. */
const CONDITIONS: RequestCondition[] = [
"internal",
"unauthorized",
"timeout",
"not_supported",
"does_not_exist",
"uninterested",
"malformed_track",
"going_away",
];

/**
* Every code we put in a rejection has to be one the negotiated draft registers for that
* request. The table is transcribed from the drafts (draft-14 section 13.1 through draft-20
* section 15.11.2), not derived from the mapping, so a mistake in the mapping cannot talk
* the assertion into agreeing with it.
*/
function registered(kind: RequestKind, version: IetfVersion): number[] {
if (version === Version.DRAFT_14) {
switch (kind) {
case "subscribe":
return [0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x10, 0x12];
case "fetch":
return [0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x10, 0x12];
case "publish":
return [0x0, 0x1, 0x2, 0x3, 0x4];
case "publish_namespace":
return [0x0, 0x1, 0x2, 0x3, 0x4, 0x10, 0x12];
case "subscribe_namespace":
return [0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x10, 0x12];
}
}
if (version === Version.DRAFT_15) return [0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x10, 0x11, 0x12, 0x20, 0x30, 0x32, 0x33];
if (version === Version.DRAFT_16) return [0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x10, 0x11, 0x12, 0x19, 0x20, 0x30, 0x32];
if (version === Version.DRAFT_17) {
return [0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x9, 0x10, 0x11, 0x12, 0x19, 0x20, 0x30, 0x31, 0x32];
}
return [
0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x9, 0x10, 0x11, 0x12, 0x19, 0x20, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36,
];
}

test("only registered codes reach the wire", () => {
for (const version of ALL) {
for (const kind of KINDS) {
for (const condition of CONDITIONS) {
const code = toRequestCode(condition, kind, version);
expect(registered(kind, version)).toContain(code);
}
}
}
});

test("every emitted code round trips", () => {
for (const version of ALL) {
for (const kind of KINDS) {
for (const condition of CONDITIONS) {
const code = toRequestCode(condition, kind, version);
const decoded = fromRequestCode(code, kind, version) ?? "internal";
expect(toRequestCode(decoded, kind, version)).toBe(code);
}
}
}
});

/**
* Draft-14 numbers a missing track 0x4 and draft-15 moved it to 0x10, which is draft-14's
* MALFORMED_AUTH_TOKEN. Getting this backwards tells a peer its token is broken when the
* broadcast simply is not here, so it re-authenticates instead of waiting.
*/
test("a missing broadcast uses the draft's own number", () => {
for (const kind of ["subscribe", "fetch"] as const) {
expect(toRequestCode("does_not_exist", kind, Version.DRAFT_14)).toBe(0x4);
expect(fromRequestCode(0x4, kind, Version.DRAFT_14)).toBe("does_not_exist");

for (const version of ALL.slice(1)) {
expect(toRequestCode("does_not_exist", kind, version)).toBe(0x10);
expect(fromRequestCode(0x10, kind, version)).toBe("does_not_exist");
// 0x4 is MALFORMED_AUTH_TOKEN from draft-15 on, which is not ours to claim.
expect(fromRequestCode(0x4, kind, version)).toBeUndefined();
}
}
});

/**
* Draft-14 gives 0x4 to UNINTERESTED on the requests that offer content and to
* TRACK_DOES_NOT_EXIST on the ones that ask for it, so the same integer on the same draft
* says two different things.
*/
test("draft-14 reads 0x4 per request", () => {
for (const kind of ["publish", "publish_namespace"] as const) {
expect(toRequestCode("uninterested", kind, Version.DRAFT_14)).toBe(0x4);
expect(fromRequestCode(0x4, kind, Version.DRAFT_14)).toBe("uninterested");
// Those requests offer content, so "it is not here" is not a rejection they carry.
expect(toRequestCode("does_not_exist", kind, Version.DRAFT_14)).toBe(0x0);
}

expect(fromRequestCode(0x4, "subscribe_namespace", Version.DRAFT_14)).toBeUndefined();
});

/** GOING_AWAY arrived in draft-17; an earlier peer is told INTERNAL_ERROR instead. */
test("going away only exists from draft-17", () => {
for (const kind of KINDS) {
for (const version of [Version.DRAFT_14, Version.DRAFT_15, Version.DRAFT_16] as const) {
expect(toRequestCode("going_away", kind, version)).toBe(0x0);
expect(fromRequestCode(0x6, kind, version)).toBeUndefined();
}

for (const version of [Version.DRAFT_17, Version.DRAFT_18, Version.DRAFT_19, Version.DRAFT_20] as const) {
expect(toRequestCode("going_away", kind, version)).toBe(0x6);
expect(fromRequestCode(0x6, kind, version)).toBe("going_away");
}
}
});

/**
* Draft-18 took 0x4 for GOING_AWAY from UNKNOWN_OBJECT_STATUS, so the same integer means
* different things on two drafts we both negotiate. Sending it to draft-17 would claim the
* next object's status is unknowable; reading theirs as GOING_AWAY would start draining a
* session that is not going anywhere.
*/
test("stream reset codes are shared only where the draft agrees", () => {
for (const version of ALL) {
for (const code of [
StreamCode.Internal,
StreamCode.Cancel,
StreamCode.DeliveryTimeout,
StreamCode.SessionClosed,
]) {
expect(sharedStreamCode(code, version)).toBe(true);
}

// moq-lite's reserved 32-63 placeholders are not in this registry at all.
for (const code of [StreamCode.NotFound, StreamCode.Old, StreamCode.Evicted, StreamCode.FrameTooLarge]) {
expect(sharedStreamCode(code, version)).toBe(false);
}
}

for (const version of [Version.DRAFT_14, Version.DRAFT_15, Version.DRAFT_16, Version.DRAFT_17] as const) {
expect(sharedStreamCode(StreamCode.GoingAway, version)).toBe(false);
}
for (const version of [Version.DRAFT_18, Version.DRAFT_19, Version.DRAFT_20] as const) {
expect(sharedStreamCode(StreamCode.GoingAway, version)).toBe(true);
}

expect(sharedStreamCode(StreamCode.TooFarBehind, Version.DRAFT_16)).toBe(false);
expect(sharedStreamCode(StreamCode.TooFarBehind, Version.DRAFT_17)).toBe(true);
expect(sharedStreamCode(StreamCode.MalformedTrack, Version.DRAFT_15)).toBe(false);
expect(sharedStreamCode(StreamCode.MalformedTrack, Version.DRAFT_16)).toBe(true);
});
Loading
Loading