From 5e6ec6a0310236bd6045a552f7a09ffae9027f71 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 7 Sep 2026 16:01:28 -0700 Subject: [PATCH 1/7] chore: claim quest/m0/ietf-error-codes From 6cbbad12e30ea599c6f9e25c7ade41f7c18910b3 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 8 Sep 2026 00:22:05 -0700 Subject: [PATCH 2/7] fix(moq-net): send registered moq-transport request error codes Every rejection moq-net and js/net put on a moq-transport request stream was an HTTP status: 404 for a missing broadcast, 500 for an unsupported FETCH, 400 and 409 on the announce path. None of those are in any draft's registry, so a peer read them as unregistered and fell back to a generic failure. The registry is per draft twice over. Draft-14 gives each error message its own table and they disagree about 0x4: TRACK_DOES_NOT_EXIST on SUBSCRIBE_ERROR and FETCH_ERROR, UNINTERESTED on PUBLISH_ERROR and ANNOUNCE_ERROR. Draft-15 folded all five into REQUEST_ERROR and renumbered, so a missing broadcast moved from 0x4 to 0x10, which is draft-14's MALFORMED_AUTH_TOKEN. Sending either number without the draft in hand tells the peer the opposite of what happened. `ietf::error::request` maps a named `Condition` to the value the negotiated draft registers for that request, and back, alongside the stream reset half already there. `js/net/src/ietf/error.ts` mirrors it. Both fall back to INTERNAL_ERROR for a condition the draft does not register, and neither decodes a code the draft leaves unassigned into a meaning it never carried. A subscribe rejection now reaches the track as the reason the publisher gave rather than a bare cancel, so a subscriber can tell a broadcast that is not there from one it may not have. js/net also gained the per-draft stream reset mapping Rust has: a delivery timeout, a session close, a lag past the window and a malformed track now travel where the draft registers them instead of degrading to INTERNAL_ERROR, and a received 0x4 is only read as GOING_AWAY from draft-18 on, where draft-16 and 17 give it to UNKNOWN_OBJECT_STATUS. Public API: unchanged. `ietf::error` is crate-private and the new js/net module is not exported from the package index. Wire: moq-transport request error codes and js/net stream reset codes change to the registered values; moq-lite is untouched. Closes #3359 Co-Authored-By: Claude Opus 5 --- js/net/src/error.ts | 26 +- js/net/src/ietf/adapter.test.ts | 11 +- js/net/src/ietf/error.test.ts | 168 +++++++++++++ js/net/src/ietf/error.ts | 211 ++++++++++++++++ js/net/src/ietf/publisher.test.ts | 3 +- js/net/src/ietf/publisher.ts | 20 +- js/net/src/ietf/subscriber.test.ts | 6 +- js/net/src/ietf/subscriber.ts | 22 +- js/net/src/stream.test.ts | 26 +- quest/m0/README.md | 1 - quest/m0/ietf-error-codes.md | 74 ------ quest/m1/group-overflow-abort.md | 8 +- quest/m1/hls-cache-miss-codes.md | 4 - quest/m1/ietf-uni-stream-types.md | 4 - rs/moq-net/src/ietf/error.rs | 391 ++++++++++++++++++++++++++++- rs/moq-net/src/ietf/publisher.rs | 140 +++++++++-- rs/moq-net/src/ietf/subscriber.rs | 213 ++++++++++------ 17 files changed, 1104 insertions(+), 224 deletions(-) create mode 100644 js/net/src/ietf/error.test.ts create mode 100644 js/net/src/ietf/error.ts delete mode 100644 quest/m0/ietf-error-codes.md diff --git a/js/net/src/error.ts b/js/net/src/error.ts index 9089bdbd282..1f15813c086 100644 --- a/js/net/src/error.ts +++ b/js/net/src/error.ts @@ -4,6 +4,7 @@ * @module */ +import { sharedStreamCode } from "./ietf/error.ts"; import type { IetfVersion } from "./ietf/version.ts"; import { TimeoutError } from "./util/timeout.ts"; @@ -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; // Session-scoped: the peer learns which rule it broke from the session close, not from here. @@ -298,12 +303,19 @@ 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 the same holds per draft: a code the negotiated draft gives a meaning + * moq-lite has no name for, or none at all, reads as {@link StreamCode.Internal} with the wire + * value kept in the message, rather than being read as whatever moq-lite assigns that number. + * * @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)) { + return new StreamError(StreamCode.Internal, { cause: err, message: `remote error: ${code}` }); + } + if (code === StreamCode.TooFarBehind) return new Lagged({ cause: err }); return new StreamError(code, { cause: err }); } diff --git a/js/net/src/ietf/adapter.test.ts b/js/net/src/ietf/adapter.test.ts index 6b60f8576be..5f7ea4c06b0 100644 --- a/js/net/src/ietf/adapter.test.ts +++ b/js/net/src/ietf/adapter.test.ts @@ -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"; @@ -85,10 +86,10 @@ async function closed(stream: Stream): Promise { /** * 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(); @@ -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); diff --git a/js/net/src/ietf/error.test.ts b/js/net/src/ietf/error.test.ts new file mode 100644 index 00000000000..47fb0f1b121 --- /dev/null +++ b/js/net/src/ietf/error.test.ts @@ -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); +}); diff --git a/js/net/src/ietf/error.ts b/js/net/src/ietf/error.ts new file mode 100644 index 00000000000..ae573c95d75 --- /dev/null +++ b/js/net/src/ietf/error.ts @@ -0,0 +1,211 @@ +/** + * The moq-transport error code registries, per negotiated draft. + * + * A code only means something once you know which draft carried it: the registries grew, + * moved values, and in draft-15 collapsed five per-message tables into one. Mirrors the + * Rust `moq_net::ietf::error` module, and the two have to agree value for value. + * + * @module + */ + +import { type IetfVersion, Version } from "./version.ts"; + +/** + * Whether `code` means the same thing in the negotiated draft's stream reset registry as it + * does in moq-lite's. + * + * The two registries agree on most of what they both assign, but this one grew across the + * drafts we negotiate and moved a value on the way: + * + * | Code | draft-14/15 | draft-16/17 | draft-18+ | + * |------|-------------|-------------|-----------| + * | 0x0 | INTERNAL_ERROR | INTERNAL_ERROR | INTERNAL_ERROR | + * | 0x1 | CANCELLED | CANCELLED | CANCELLED | + * | 0x2 | DELIVERY_TIMEOUT | DELIVERY_TIMEOUT | DELIVERY_TIMEOUT | + * | 0x3 | SESSION_CLOSED | SESSION_CLOSED | SESSION_CLOSED | + * | 0x4 | - | UNKNOWN_OBJECT_STATUS | GOING_AWAY | + * | 0x5 | - | TOO_FAR_BEHIND (17) | TOO_FAR_BEHIND | + * | 0x12 | - | MALFORMED_TRACK | MALFORMED_TRACK | + * + * So GOING_AWAY sent to a draft-17 peer reads as UNKNOWN_OBJECT_STATUS, and that peer's + * UNKNOWN_OBJECT_STATUS read as GOING_AWAY would retire a session that is not going + * anywhere. Anything this says `false` about is sent as, and read as, INTERNAL_ERROR: the + * codes moq-lite reserves in 32-63, and the ones the draft assigns that moq-lite has no + * name for (UNKNOWN_OBJECT_STATUS, EXPIRED_AUTH_TOKEN, EXCESSIVE_LOAD). + * + * @internal + */ +export function sharedStreamCode(code: number, version: IetfVersion): boolean { + switch (code) { + case 0x0: + case 0x1: + case 0x2: + case 0x3: + return true; + // Draft-16 and 17 give 0x4 to UNKNOWN_OBJECT_STATUS, which draft-18 moved to 0x6 when + // it took 0x4 for GOING_AWAY. Draft-14 and 15 assign it nothing. + case 0x4: + return version >= Version.DRAFT_18; + // TOO_FAR_BEHIND arrived in draft-17. + case 0x5: + return version >= Version.DRAFT_17; + // MALFORMED_TRACK arrived in draft-16. + case 0x12: + return version >= Version.DRAFT_16; + default: + return false; + } +} + +/** + * Which request a rejection answers, so draft-14 picks the right registry. + * + * Draft-14 gives each error message its own registry and they disagree about 0x4; draft-15 + * folded them all into REQUEST_ERROR with a single registry, so from there on the kind + * changes nothing. + * + * @internal + */ +export type RequestKind = "subscribe" | "fetch" | "publish" | "publish_namespace" | "subscribe_namespace"; + +/** + * What a rejection reports, before the draft picks the number for it. + * + * Named separately from the wire code because a rejection says less than a failure does: a + * dozen local errors are one INTERNAL_ERROR on the wire. + * + * @internal + */ +export type RequestCondition = + /** Something went wrong that the registry has no value for. */ + | "internal" + /** The peer's credentials do not cover the request. */ + | "unauthorized" + /** The request outlived an implementation-specific deadline. */ + | "timeout" + /** This endpoint does not implement the request at all. */ + | "not_supported" + /** The broadcast or track the peer asked for is not here. */ + | "does_not_exist" + /** The content the peer offered is not wanted here, so it should stop offering it. */ + | "uninterested" + /** The track's content could not be parsed. */ + | "malformed_track" + /** A GOAWAY is draining the session, so no new request is accepted. */ + | "going_away"; + +/** An implementation-specific error. Assigned by every draft, for every request. */ +const INTERNAL_ERROR = 0x0; +const UNAUTHORIZED = 0x1; +const TIMEOUT = 0x2; +const NOT_SUPPORTED = 0x3; + +/** A draining session. Draft-17 and later. */ +const GOING_AWAY = 0x6; + +/** Draft-14 calls it TRACK_DOES_NOT_EXIST; draft-15 renamed it and moved it off 0x4. */ +const DOES_NOT_EXIST_14 = 0x4; +const DOES_NOT_EXIST = 0x10; + +/** Draft-14 assigns UNINTERESTED only to the two requests that offer content. */ +const UNINTERESTED_14 = 0x4; +const UNINTERESTED = 0x20; + +/** Draft-14 assigns MALFORMED_TRACK to FETCH_ERROR only. */ +const MALFORMED_TRACK_14 = 0x9; +const MALFORMED_TRACK = 0x12; + +/** The value for "the thing you asked for is not here", or undefined where none is assigned. */ +function doesNotExist(kind: RequestKind, version: IetfVersion): number | undefined { + if (version !== Version.DRAFT_14) return DOES_NOT_EXIST; + return kind === "subscribe" || kind === "fetch" ? DOES_NOT_EXIST_14 : undefined; +} + +/** The value for "we do not want this", or undefined where none is assigned. */ +function uninterested(kind: RequestKind, version: IetfVersion): number | undefined { + if (version !== Version.DRAFT_14) return UNINTERESTED; + return kind === "publish" || kind === "publish_namespace" ? UNINTERESTED_14 : undefined; +} + +/** The value for a track we could not parse, or undefined where none is assigned. */ +function malformedTrack(kind: RequestKind, version: IetfVersion): number | undefined { + if (version !== Version.DRAFT_14) return MALFORMED_TRACK; + return kind === "fetch" ? MALFORMED_TRACK_14 : undefined; +} + +/** The value for a draining session, or undefined before draft-17 registered one. */ +function goingAway(version: IetfVersion): number | undefined { + return version >= Version.DRAFT_17 ? GOING_AWAY : undefined; +} + +/** + * The code to reject a request with, on the negotiated draft. + * + * A condition the draft does not register for this request falls back to INTERNAL_ERROR + * rather than borrowing a number from another draft, which would say something the peer's + * registry gives a different meaning. The renumbering is the trap: draft-14 SUBSCRIBE_ERROR + * gives 0x4 to TRACK_DOES_NOT_EXIST and 0x10 to MALFORMED_AUTH_TOKEN, and draft-15 swaps + * the two. + * + * @internal + */ +export function toRequestCode(condition: RequestCondition, kind: RequestKind, version: IetfVersion): number { + switch (condition) { + case "internal": + return INTERNAL_ERROR; + case "unauthorized": + return UNAUTHORIZED; + case "timeout": + return TIMEOUT; + case "not_supported": + return NOT_SUPPORTED; + case "does_not_exist": + return doesNotExist(kind, version) ?? INTERNAL_ERROR; + // A subscriber that asked for content cannot act on "we do not want it": what it needs + // to know is that we do not have it, which is the same refusal from its side. Only the + // requests that offer content say UNINTERESTED. + case "uninterested": + return kind === "subscribe" || kind === "fetch" + ? (doesNotExist(kind, version) ?? INTERNAL_ERROR) + : (uninterested(kind, version) ?? INTERNAL_ERROR); + case "malformed_track": + return malformedTrack(kind, version) ?? INTERNAL_ERROR; + case "going_away": + return goingAway(version) ?? INTERNAL_ERROR; + } +} + +/** + * Read a rejection code received on the negotiated draft. + * + * A code the draft does not assign for this request, INTERNAL_ERROR included, is + * `undefined`: an error, but never one given a meaning it did not carry. + * + * @internal + */ +export function fromRequestCode(code: number, kind: RequestKind, version: IetfVersion): RequestCondition | undefined { + switch (code) { + case UNAUTHORIZED: + return "unauthorized"; + case TIMEOUT: + return "timeout"; + case NOT_SUPPORTED: + return "not_supported"; + } + + if (code === doesNotExist(kind, version)) return "does_not_exist"; + if (code === uninterested(kind, version)) return "uninterested"; + if (code === malformedTrack(kind, version)) return "malformed_track"; + if (code === goingAway(version)) return "going_away"; + return undefined; +} + +/** + * Describe a rejection a peer sent, naming the condition when the draft registers one. + * + * @internal + */ +export function requestReason(code: number, reasonPhrase: string, kind: RequestKind, version: IetfVersion): string { + const condition = fromRequestCode(code, kind, version) ?? "unregistered"; + return `${condition} (code=${code}) ${reasonPhrase}`; +} diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index 2c8cf616d06..45650648a19 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -84,7 +84,8 @@ async function declinePublishNamespace(stream: Stream, retryInterval = 1n): Prom await stream.writer.u53(RequestError.id); await new RequestError({ requestId: undefined, - errorCode: 403, + // UNINTERESTED, draft-19 section 15.11.2. + errorCode: 0x20, reasonPhrase: "no", retryInterval, }).encode(stream.writer, VERSION); diff --git a/js/net/src/ietf/publisher.ts b/js/net/src/ietf/publisher.ts index 8af8bf742dd..e2f2c026e99 100644 --- a/js/net/src/ietf/publisher.ts +++ b/js/net/src/ietf/publisher.ts @@ -12,6 +12,7 @@ import { withTimeout } from "../util/timeout.ts"; import * as Varint from "../varint.ts"; import type { Session } from "./adapter.ts"; import * as Cluster from "./cluster.ts"; +import { requestReason, toRequestCode } from "./error.ts"; import { FetchHeader } from "./fetch.ts"; import * as Filter from "./filter.ts"; import { FetchFrame, Frame, Group as GroupMessage } from "./object.ts"; @@ -192,21 +193,21 @@ export class Publisher { const broadcast = this.#broadcasts.peek()?.get(name); if (!broadcast) { - // Write error response + const errorCode = toRequestCode("does_not_exist", "subscribe", version); if (version === Version.DRAFT_14) { await stream.writer.u53(SubscribeError.id); const err = new SubscribeError({ requestId: msg.requestId, - errorCode: 404, - reasonPhrase: "Broadcast not found", + errorCode, + reasonPhrase: "broadcast not found", }); await err.encode(stream.writer, version); } else { await stream.writer.u53(RequestError.id); const err = new RequestError({ requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined, - errorCode: 404, - reasonPhrase: "Broadcast not found", + errorCode, + reasonPhrase: "broadcast not found", }); await err.encode(stream.writer, version); } @@ -937,7 +938,14 @@ export class Publisher { err.retryInterval === 0n ? "never" : Date.now() + Number(err.retryInterval), ); } - throw new Error(`PublishNamespace rejected: ${err.errorCode} ${err.reasonPhrase}`); + throw new Error( + `PublishNamespace rejected: ${requestReason( + err.errorCode, + err.reasonPhrase, + "publish_namespace", + this.#session.version, + )}`, + ); } if (respTypeId !== RequestOk.id) { throw new Error(`PublishNamespace rejected: typeId=0x${respTypeId.toString(16)}`); diff --git a/js/net/src/ietf/subscriber.test.ts b/js/net/src/ietf/subscriber.test.ts index 0cbe02fd08c..f0bdb27892b 100644 --- a/js/net/src/ietf/subscriber.test.ts +++ b/js/net/src/ietf/subscriber.test.ts @@ -401,7 +401,8 @@ test("a PUBLISH_NAMESPACE that looped back through us is refused", async () => { if (!peer) throw new Error("no PUBLISH_NAMESPACE stream"); expect(await peer.reader.u53()).toBe(RequestError.id); const err = await RequestError.decode(peer.reader, VERSION); - expect(err.errorCode).toBe(400); + // UNINTERESTED, draft-19 section 15.11.2: stop offering us this namespace. + expect(err.errorCode).toBe(0x20); // Refused, so nothing was announced: the sentinel is the first thing a consumer hears. await syncInline(subscription, announced, { hops: [PEER], cost: 0n }); @@ -547,7 +548,8 @@ test("a rejected subscribe is not unsubscribed", async () => { await wire.writer.u53(RequestError.id); await new RequestError({ requestId: 0n, - errorCode: 404, + // DOES_NOT_EXIST, draft-16 section 13.4.2. + errorCode: 0x10, reasonPhrase: "not found", retryInterval: 0n, }).encode(wire.writer, LEGACY); diff --git a/js/net/src/ietf/subscriber.ts b/js/net/src/ietf/subscriber.ts index 29f41a7ba43..c3c53b9f6ea 100644 --- a/js/net/src/ietf/subscriber.ts +++ b/js/net/src/ietf/subscriber.ts @@ -11,6 +11,7 @@ import { withTimeout } from "../util/timeout.ts"; import type { Session } from "./adapter.ts"; import { DuplicateTrackAlias, RetiredTrackAlias, TrackAliases } from "./aliases.ts"; import * as Cluster from "./cluster.ts"; +import { requestReason, toRequestCode } from "./error.ts"; import { Frame, type Group as GroupMessage } from "./object.ts"; import { toWire } from "./priority.ts"; import { type Publish, PublishError } from "./publish.ts"; @@ -614,7 +615,7 @@ export class Subscriber { version === Version.DRAFT_14 ? await SubscribeError.decode(state.stream.reader, version) : await RequestError.decode(state.stream.reader, version); - reasonPhrase = `code=${err.errorCode} reason=${err.reasonPhrase}`; + reasonPhrase = requestReason(err.errorCode, err.reasonPhrase, "subscribe", version); } } catch { // Decoding error response failed, use default message @@ -660,7 +661,7 @@ export class Subscriber { await stream.writer.u53(RequestError.id); await new RequestError({ requestId: msg.requestId, - errorCode: 400, + errorCode: toRequestCode("uninterested", "publish_namespace", version), reasonPhrase: "route loops back", }).encode(stream.writer, version); stream.close(); @@ -676,18 +677,21 @@ export class Subscriber { const legacy = version === Version.DRAFT_14 || version === Version.DRAFT_15; if (legacy && (this.#announced.has(path) || this.#legacyRequests.has(path))) { console.warn("duplicate PublishNamespace"); + // No draft registers a code for a duplicate, and this refusal is a draft-14/15 + // implementation limit, which is what INTERNAL_ERROR describes. + const errorCode = toRequestCode("internal", "publish_namespace", version); if (version === Version.DRAFT_14) { await stream.writer.u53(PublishNamespaceError.id); await new PublishNamespaceError({ requestId: msg.requestId, - errorCode: 409, + errorCode, reasonPhrase: "duplicate namespace", }).encode(stream.writer, version); } else { await stream.writer.u53(RequestError.id); await new RequestError({ requestId: msg.requestId, - errorCode: 409, + errorCode, reasonPhrase: "duplicate namespace", }).encode(stream.writer, version); } @@ -788,18 +792,18 @@ export class Subscriber { async runPublish(msg: Publish, stream: Stream) { const version = this.#session.version; - // NOT_SUPPORTED, from the PUBLISH error codes in draft-19 section 10.10. We decline - // the method itself rather than this particular track, which is UNINTERESTED (0x4). + // We decline the method itself rather than this particular track, which would be + // UNINTERESTED. // // The alias the message carries is deliberately not recorded. Nothing will ever bind // it, and a rejected request has no lifetime of ours to hang the cleanup on. - const NOT_SUPPORTED = 0x3; + const errorCode = toRequestCode("not_supported", "publish", version); if (version === Version.DRAFT_14) { await stream.writer.u53(PublishError.id); const err = new PublishError({ requestId: msg.requestId, - errorCode: NOT_SUPPORTED, + errorCode, reasonPhrase: "publish not supported", }); await err.encode(stream.writer, version); @@ -807,7 +811,7 @@ export class Subscriber { await stream.writer.u53(RequestError.id); const err = new RequestError({ requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined, - errorCode: NOT_SUPPORTED, + errorCode, reasonPhrase: "publish not supported", }); await err.encode(stream.writer, version); diff --git a/js/net/src/stream.test.ts b/js/net/src/stream.test.ts index eb6eb469158..68f8e84406b 100644 --- a/js/net/src/stream.test.ts +++ b/js/net/src/stream.test.ts @@ -573,18 +573,26 @@ test("open waits for a stream slot instead of rejecting once the peer's limit is ]); }); -for (const version of [undefined, Version.DRAFT_14, Version.DRAFT_19, Version.DRAFT_20]) { +// A moq-transport code has to be one the negotiated draft assigns the same meaning to, so +// each row says what it costs on a draft that predates the registration. TOO_FAR_BEHIND +// arrived in draft-17, and moq-lite's reserved 32-63 placeholders are in no draft at all. +for (const [version, tooFarBehind] of [ + [undefined, StreamCode.TooFarBehind], + [Version.DRAFT_14, StreamCode.Internal], + [Version.DRAFT_19, StreamCode.TooFarBehind], + [Version.DRAFT_20, StreamCode.TooFarBehind], +] as const) { test(`stream resets select the negotiated registry (${version})`, async () => { - for (const [reason, liteCode] of [ - [new Lagged(), StreamCode.TooFarBehind], - [new Reset(5), StreamCode.TooFarBehind], - [new FrameTooLarge(), StreamCode.FrameTooLarge], - [new NotFound("broadcast"), StreamCode.NotFound], + for (const [reason, expected] of [ + [new Lagged(), tooFarBehind], + [new Reset(5), tooFarBehind], + [new FrameTooLarge(), version === undefined ? StreamCode.FrameTooLarge : StreamCode.Internal], + [new NotFound("broadcast"), version === undefined ? StreamCode.NotFound : StreamCode.Internal], + // Assigned by every draft, so these survive the translation intact. [new TimeoutError("open"), StreamCode.DeliveryTimeout], [new ProtocolViolation("bad message"), StreamCode.SessionClosed], [new StreamError(StreamCode.Cancel), StreamCode.Cancel], ] as const) { - const expected = version === undefined || liteCode === StreamCode.Cancel ? liteCode : StreamCode.Internal; const aborted = Promise.withResolvers(); const writer = new Writer(new WritableStream({ abort: aborted.resolve }), version); writer.reset(reason); @@ -611,6 +619,8 @@ for (const version of [undefined, Version.DRAFT_14, Version.DRAFT_19, Version.DR ); const err = await reader.closed.catch((err: unknown) => err); expect(err).toBeInstanceOf(StreamError); - expect(err instanceof Lagged).toBe(version === undefined); + // 0x5 is TOO_FAR_BEHIND only where the draft registers it; on draft-14 it means + // nothing, so reading it as a lag would invent a gap the peer never reported. + expect(err instanceof Lagged).toBe(tooFarBehind === StreamCode.TooFarBehind); }); } diff --git a/quest/m0/README.md b/quest/m0/README.md index 65492e7c1db..bb20fde4cda 100644 --- a/quest/m0/README.md +++ b/quest/m0/README.md @@ -18,7 +18,6 @@ regression test per Root Cause First. - [#3360](/quest/m0/3360-js-watch-broadcast-is-undefined-at-initialization.md) - js/watch: a framework binding the element reads `broadcast` before the custom element is upgraded - [Adapter namespace map](/quest/m0/rs-adapter-namespace-map.md) - moq-net: a duplicate PUBLISH_NAMESPACE on draft-14/15 strands the first request, and the map never shrinks - [Playout clock](/quest/m0/playout-clock.md) - moq play presents on a clock it controls, with a `--delay` offset and forward re-anchoring -- [IETF error codes](/quest/m0/ietf-error-codes.md) - every request error a moq-transport wire carries is a registered value for the negotiated draft, in Rust and js/net - [Resume info](/quest/m0/resume-info-newest.md) - moq-net: resume reports segment zero's track info, so a replaced broadcast rescales timestamps on the predecessor's timescale - [#3363](/quest/m0/3363-js-watch-a-broadcast-republished-on-one-session-keeps-resuming.md) - js/watch: a broadcast republished under its name on one session keeps resuming - [#3361](/quest/m0/3361-js-every-moq-package-a-package-imports-is-declared.md) - js: every @moq package a package imports is a declared dependency diff --git a/quest/m0/ietf-error-codes.md b/quest/m0/ietf-error-codes.md deleted file mode 100644 index d7519540430..00000000000 --- a/quest/m0/ietf-error-codes.md +++ /dev/null @@ -1,74 +0,0 @@ -# [M] IETF error codes come from the draft registry - -## Goal - -Every error code moq-net and js/net put on a moq-transport wire is a -registered value for the negotiated draft, in both directions: the -SUBSCRIBE_ERROR, FETCH_ERROR, and REQUEST_ERROR payloads, and the RESET_STREAM -and STOP_SENDING codes on data and request streams. A relay built on these -crates passes the interop runner's subscribe-error and subscribe-before-announce -cases without the peer's compatibility branch. - -Boundaries: moq-lite's own code spaces are untouched. js/net already carries a -code on a locally raised stream error, via the `toStreamCode` / `fromTransport` -pair in `js/net/src/error.ts`; that mapping is the moq-lite space, not this -registry. - -## Plan - -The Rust stream reset half is done: `rs/moq-net/src/ietf/error.rs` is the -per-draft `StreamError` <-> code mapping in both directions, and the -`coding::StreamCodes` trait picks a stream's registry from the version its -`Reader`/`Writer` already carries. What is left is the request errors in both -languages and the richer per-draft JS stream mappings. - -Current implementation paths (verify against the target branch before starting): - -- `rs/moq-net/src/ietf/publisher.rs` `run_subscribe` rejects with the literal - `404` at three sites and `run_fetch_stream` with `500`; - `rs/moq-net/src/ietf/subscriber.rs` `write_error` uses `400`. - `reject_subscribe`, `reject_fetch`, and `write_error` take a bare `u64`, and - `ietf::SubscribeError`, `ietf::FetchError`, and `ietf::RequestError` carry a - bare `error_code`. The only named request-error code type is - `TrackStatusCode` (`rs/moq-net/src/ietf/track.rs`), for a different registry, - plus a function-local `NOT_SUPPORTED: u64 = 0x3` in the subscriber. -- `js/net/src/ietf/publisher.ts` `runSubscribe` writes `errorCode: 404` on both - the draft-14 `SubscribeError` and the draft-15+ `RequestError` branch; - `js/net/src/ietf/subscriber.ts` uses `400` and `409`; `errorCode` is a plain - number everywhere. -- `js/net/src/ietf/subscriber.ts` `runPublish` writes a draft-14 `PublishError` - with the function-local `NOT_SUPPORTED` and a `RequestError` on later - drafts; the Rust subscriber's publish handling is the same shape. -- JS's `toStreamCode` with an IETF version sends CANCELLED (1) for cancellation - and INTERNAL_ERROR (0) otherwise. JS keeps received IETF resets opaque rather - than decoding them as moq-lite local error classes. Per-draft typed decoding - and richer mappings remain here. -- `Version::Draft14` through `Draft20` are all negotiated, straddling the - draft-19 consolidation into REQUEST_ERROR, so the values are per version. - -The work: - -- One named code type per registry (request errors, and the richer JS stream - error mappings), with `Encode` and - `Decode` in the `TrackStatusCode` style, that maps `Error` variants - to the registered value for the negotiated draft and back. An incoming code - with no named value decodes to the remote/opaque variant, never to a named - one. Cite the draft section each value comes from in the type's docs. -- Use it at every construction site above, in Rust and JS. Delete the literals - and the function-local constants. `Error::NotFound`'s IETF wire value comes - from the same mapping. `rs/moq-net/src/ietf/error.rs` is the shape to follow. -- Tests: encode/decode round-trips per version; a draft-14 PublishError and a - draft-15+ RequestError round-trip for the publish path; a subscribe for a - missing broadcast rejects with the not-found value of each draft; the two - interop runner cases pass without their COMPAT branch. - -The reporter of #3359 offered a PR and asked whether to prefer a version-aware -enum over a flat one: version-aware, per the above. - -## Closes - -- [#3359](https://github.com/moq-dev/moq/issues/3359) - close this issue when the quest finishes - -## Related - -- [#3187](/quest/m1/3187-preserve-structured-protocol-error-codes-across-ffi-and-c.md) - the same codes crossing the FFI diff --git a/quest/m1/group-overflow-abort.md b/quest/m1/group-overflow-abort.md index b2a49ac799d..a2e35b32140 100644 --- a/quest/m1/group-overflow-abort.md +++ b/quest/m1/group-overflow-abort.md @@ -52,10 +52,9 @@ evicted prefix. exactly 100,000 one-byte frames to assert there is no count cap; it is rewritten rather than deleted, since the byte-budget half of what it proves still holds. -- **The IETF wire keeps its own mapping.** Sending the new code on the - moq-transport wire belongs to - [IETF error codes](/quest/m0/ietf-error-codes.md), - which is fixing the whole registry confusion rather than one variant. +- **The IETF wire keeps its own mapping.** `rs/moq-net/src/ietf/error.rs` picks + the registered value for the negotiated draft, and it registers nothing for + this condition, so the moq-transport wire says INTERNAL_ERROR. ### What actually gets deleted @@ -124,4 +123,3 @@ already claims its top end "intentionally reaches the raised ## Related - [Group charge](/quest/m0/group-charge.md) - pool-level budget accounting, unaffected by this change -- [IETF error codes](/quest/m0/ietf-error-codes.md) - the moq-transport half of the code mapping diff --git a/quest/m1/hls-cache-miss-codes.md b/quest/m1/hls-cache-miss-codes.md index e70fd3d3da4..9519707c7b4 100644 --- a/quest/m1/hls-cache-miss-codes.md +++ b/quest/m1/hls-cache-miss-codes.md @@ -48,7 +48,3 @@ The work: - Rewrite the tests to build the remote shape from the wire registry (`StreamError::to_code`, `ietf::error::to_stream_code`) so they fail when the two drift again. - -## Related - -- [IETF error codes](/quest/m0/ietf-error-codes.md) - the registry work that this classification has to follow diff --git a/quest/m1/ietf-uni-stream-types.md b/quest/m1/ietf-uni-stream-types.md index 15cd0f762d5..8d1ccb970d2 100644 --- a/quest/m1/ietf-uni-stream-types.md +++ b/quest/m1/ietf-uni-stream-types.md @@ -11,7 +11,3 @@ Accept valid padding streams and close the session for genuinely unknown stream Classify stream types before spawning a group handler. Handle PADDING according to each supported draft, including draining it where required, and propagate genuinely unknown types to the session driver. Keep ordinary group failures scoped to their streams. Add regressions for padding, unknown types causing session shutdown, and group failures preserving the session. Consult [draft-19 section 3.4 and section 11.5.1](https://www.ietf.org/archive/id/draft-ietf-moq-transport-19.html) and [draft-20 section 11.5.1](https://www.ietf.org/archive/id/draft-ietf-moq-transport-20.html), which explicitly permits cancelling padding streams. Check the earlier supported drafts too. - -## Related - -- [IETF error codes](/quest/m0/ietf-error-codes.md) - request and session error registry follow-ups diff --git a/rs/moq-net/src/ietf/error.rs b/rs/moq-net/src/ietf/error.rs index fd8f59af593..a798a6dd394 100644 --- a/rs/moq-net/src/ietf/error.rs +++ b/rs/moq-net/src/ietf/error.rs @@ -1,4 +1,9 @@ -//! The moq-transport stream reset code registry, per negotiated draft. +//! The moq-transport error code registries, per negotiated draft. +//! +//! This module holds the stream reset registry; [`request`] holds the one for rejecting a +//! request. The two are disjoint, so the same integer means different things in each. +//! +//! # Stream reset codes //! //! Sent on RESET_STREAM and STOP_SENDING, and read back off both. The values are the //! draft's, not [`StreamError::to_code`]'s: the two registries agree on most of what they @@ -109,6 +114,390 @@ pub fn from_stream_code(code: u32, version: Version) -> StreamError { } } +/// The moq-transport request error registry, per negotiated draft. +/// +/// Sent in a rejection response to a request, and read back off one. Draft-14 gives each +/// error message its own registry and they disagree about 0x4; draft-15 folded them all +/// into REQUEST_ERROR with a single registry that renumbered almost everything. So a +/// request code only means something once you know both the draft and, on draft-14, which +/// request it answers. +/// +/// | Condition | 14 SUBSCRIBE | 14 FETCH | 14 PUBLISH | 14 ANNOUNCE | 14 SUB_NS | 15+ | +/// |-----------|--------------|----------|------------|-------------|-----------|-----| +/// | INTERNAL_ERROR | 0x0 | 0x0 | 0x0 | 0x0 | 0x0 | 0x0 | +/// | UNAUTHORIZED | 0x1 | 0x1 | 0x1 | 0x1 | 0x1 | 0x1 | +/// | TIMEOUT | 0x2 | 0x2 | 0x2 | 0x2 | 0x2 | 0x2 | +/// | NOT_SUPPORTED | 0x3 | 0x3 | 0x3 | 0x3 | 0x3 | 0x3 | +/// | DOES_NOT_EXIST | 0x4 | 0x4 | - | - | - | 0x10 | +/// | UNINTERESTED | - | - | 0x4 | 0x4 | - | 0x20 | +/// | MALFORMED_TRACK | - | 0x9 | - | - | - | 0x12 | +/// | GOING_AWAY | - | - | - | - | - | 0x6 (17+) | +/// +/// The renumbering is the trap: draft-14 SUBSCRIBE_ERROR gives 0x4 to TRACK_DOES_NOT_EXIST +/// and 0x10 to MALFORMED_AUTH_TOKEN, and draft-15 swaps the two. Sending either number +/// without the draft in hand tells the peer the opposite of what happened. +pub(crate) mod request { + use super::Version; + use crate::Error; + + /// Which request the error answers, so draft-14 picks the right registry. + /// + /// Draft-15 and later carry one REQUEST_ERROR registry for every request, so from there + /// on the kind changes nothing. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) enum Kind { + /// SUBSCRIBE_ERROR, draft-14 section 13.1.2. + Subscribe, + /// FETCH_ERROR, draft-14 section 13.1.5. + Fetch, + /// PUBLISH_ERROR, draft-14 section 13.1.4. + Publish, + /// ANNOUNCE_ERROR, draft-14 section 13.1.6. + PublishNamespace, + /// SUBSCRIBE_NAMESPACE_ERROR, draft-14 section 13.1.7. + SubscribeNamespace, + } + + /// An implementation-specific error, with no registry entry for why. Assigned by every + /// draft, for every request. + const INTERNAL_ERROR: u64 = 0x0; + + /// The peer's credentials do not cover the request. + const UNAUTHORIZED: u64 = 0x1; + + /// The request could not be answered before an implementation-specific deadline. + const TIMEOUT: u64 = 0x2; + + /// The endpoint does not implement this request at all, as opposed to refusing this one. + const NOT_SUPPORTED: u64 = 0x3; + + /// A GOAWAY is draining the session, so no new request is accepted. Draft-17 and later. + const GOING_AWAY: u64 = 0x6; + + /// The requested broadcast or track is not here, as draft-14 numbers it under the name + /// TRACK_DOES_NOT_EXIST. + const DOES_NOT_EXIST_14: u64 = 0x4; + + /// The same condition from draft-15 on, renamed DOES_NOT_EXIST and moved off 0x4. + const DOES_NOT_EXIST: u64 = 0x10; + + /// The offered content is not wanted here, as draft-14 numbers it. + const UNINTERESTED_14: u64 = 0x4; + + /// The same condition from draft-15 on. + const UNINTERESTED: u64 = 0x20; + + /// The track's content could not be parsed, as draft-14 numbers it on FETCH_ERROR. + const MALFORMED_TRACK_14: u64 = 0x9; + + /// The same condition from draft-15 on. + const MALFORMED_TRACK: u64 = 0x12; + + /// The value for "the thing you asked for is not here", or `None` where the draft and + /// request assign none. + fn does_not_exist(kind: Kind, version: Version) -> Option { + match version { + Version::Draft14 => match kind { + Kind::Subscribe | Kind::Fetch => Some(DOES_NOT_EXIST_14), + _ => None, + }, + _ => Some(DOES_NOT_EXIST), + } + } + + /// The value for "we do not want this", or `None` where the draft and request assign + /// none. Draft-14 registers it only on the two requests that offer content. + fn uninterested(kind: Kind, version: Version) -> Option { + match version { + Version::Draft14 => match kind { + Kind::Publish | Kind::PublishNamespace => Some(UNINTERESTED_14), + _ => None, + }, + _ => Some(UNINTERESTED), + } + } + + /// The value for a track we could not parse, or `None` where the draft and request + /// assign none. + fn malformed_track(kind: Kind, version: Version) -> Option { + match version { + Version::Draft14 => match kind { + Kind::Fetch => Some(MALFORMED_TRACK_14), + _ => None, + }, + _ => Some(MALFORMED_TRACK), + } + } + + /// The value for a draining session, or `None` before draft-17 registered one. + fn going_away(version: Version) -> Option { + match version { + Version::Draft14 | Version::Draft15 | Version::Draft16 => None, + _ => Some(GOING_AWAY), + } + } + + /// What a rejection reports, before the draft picks the number for it. + /// + /// Named separately from [`Error`] because a rejection says less than an error does: a + /// dozen local failures are one INTERNAL_ERROR on the wire, and the two conditions the + /// registry does distinguish (asking for something absent versus offering something + /// unwanted) are the same [`Error::Unroutable`] here. A caller that knows which it means + /// names it; one that only holds an error converts. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) enum Condition { + /// Something went wrong that the registry has no value for. + Internal, + /// The peer's credentials do not cover the request. + Unauthorized, + /// The request outlived an implementation-specific deadline. + Timeout, + /// This endpoint does not implement the request at all. + NotSupported, + /// The broadcast or track the peer asked for is not here. + DoesNotExist, + /// The content the peer offered is not wanted here, so it should stop offering it. + Uninterested, + /// The track's content could not be parsed. + MalformedTrack, + /// A GOAWAY is draining the session, so no new request is accepted. + GoingAway, + } + + impl From<&Error> for Condition { + fn from(err: &Error) -> Self { + match err { + Error::Unauthorized => Self::Unauthorized, + Error::Timeout => Self::Timeout, + Error::Unsupported | Error::Version => Self::NotSupported, + Error::NotFound => Self::DoesNotExist, + // A path with no route is one we will not carry. On a request that offers + // content that is UNINTERESTED; on one that asks for it, [`to_code`] reads + // it as the answer the asker can act on instead. + Error::Unroutable => Self::Uninterested, + // Our own parse failure is, from the peer's side, a malformed track. + Error::Decode(_) | Error::BoundsExceeded(_) | Error::MalformedTrack => Self::MalformedTrack, + Error::GoingAway => Self::GoingAway, + // Everything else, a duplicate included: no draft assigns it a value, and + // INTERNAL_ERROR is how a peer reads an unregistered code anyway. + _ => Self::Internal, + } + } + } + + /// The code to reject a request with, on the negotiated draft. + /// + /// A condition the draft does not register for this request falls back to + /// INTERNAL_ERROR rather than borrowing a number from another draft, which would say + /// something the peer's registry gives a different meaning. + pub(crate) fn to_code(condition: Condition, kind: Kind, version: Version) -> u64 { + let registered = match condition { + Condition::Internal => return INTERNAL_ERROR, + Condition::Unauthorized => return UNAUTHORIZED, + Condition::Timeout => return TIMEOUT, + Condition::NotSupported => return NOT_SUPPORTED, + Condition::DoesNotExist => does_not_exist(kind, version), + // A subscriber that asked for content cannot act on "we do not want it": what it + // needs to know is that we do not have it, which is the same refusal from its + // side. Only the requests that offer content say UNINTERESTED. + Condition::Uninterested => match kind { + Kind::Subscribe | Kind::Fetch => does_not_exist(kind, version), + _ => uninterested(kind, version), + }, + Condition::MalformedTrack => malformed_track(kind, version), + Condition::GoingAway => going_away(version), + }; + + registered.unwrap_or(INTERNAL_ERROR) + } + + /// Read a rejection code received on the negotiated draft. + /// + /// A code the draft does not assign for this request, INTERNAL_ERROR included, stays + /// [`Error::Remote`]: an error, but never one given a meaning it did not carry. + pub(crate) fn from_code(code: u64, kind: Kind, version: Version) -> Error { + match code { + UNAUTHORIZED => Error::Unauthorized, + TIMEOUT => Error::Timeout, + NOT_SUPPORTED => Error::Unsupported, + code if Some(code) == does_not_exist(kind, version) => Error::NotFound, + code if Some(code) == uninterested(kind, version) => Error::Unroutable, + code if Some(code) == malformed_track(kind, version) => Error::MalformedTrack, + code if Some(code) == going_away(version) => Error::GoingAway, + code => Error::Remote(u32::try_from(code).unwrap_or(u32::MAX)), + } + } + + #[cfg(test)] + mod tests { + use super::*; + + const ALL: [Version; 7] = [ + Version::Draft14, + Version::Draft15, + Version::Draft16, + Version::Draft17, + Version::Draft18, + Version::Draft19, + Version::Draft20, + ]; + + const KINDS: [Kind; 5] = [ + Kind::Subscribe, + Kind::Fetch, + Kind::Publish, + Kind::PublishNamespace, + Kind::SubscribeNamespace, + ]; + + /// Every condition a rejection can carry, so the checks below cover the whole space + /// rather than the variants someone remembered. A new variant belongs here. + const EVERY_CONDITION: [Condition; 8] = [ + Condition::Internal, + Condition::Unauthorized, + Condition::Timeout, + Condition::NotSupported, + Condition::DoesNotExist, + Condition::Uninterested, + Condition::MalformedTrack, + Condition::GoingAway, + ]; + + /// 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 for the announcement. + #[test] + fn a_missing_broadcast_uses_the_draft_s_own_number() { + for kind in [Kind::Subscribe, Kind::Fetch] { + assert_eq!(to_code(Condition::DoesNotExist, kind, Version::Draft14), 0x4); + assert!(matches!(from_code(0x4, kind, Version::Draft14), Error::NotFound)); + + for version in ALL.into_iter().skip(1) { + assert_eq!(to_code(Condition::DoesNotExist, kind, version), 0x10); + assert!(matches!(from_code(0x10, kind, version), Error::NotFound)); + // 0x4 is MALFORMED_AUTH_TOKEN from draft-15 on, which is not ours to claim. + assert!(matches!(from_code(0x4, kind, version), Error::Remote(0x4))); + } + } + + // And an error with no more specific meaning reaches the same value. + assert_eq!( + to_code(Condition::from(&Error::NotFound), Kind::Subscribe, Version::Draft20), + 0x10 + ); + } + + /// 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] + fn draft_14_reads_0x4_per_request() { + for kind in [Kind::Publish, Kind::PublishNamespace] { + assert_eq!(to_code(Condition::Uninterested, kind, Version::Draft14), 0x4); + assert!(matches!(from_code(0x4, kind, Version::Draft14), Error::Unroutable)); + // Those requests offer content, so "it is not here" is not a rejection they + // can carry. + assert_eq!(to_code(Condition::DoesNotExist, kind, Version::Draft14), INTERNAL_ERROR); + } + + // And neither meaning reaches a request draft-14 gives neither to. + assert!(matches!( + from_code(0x4, Kind::SubscribeNamespace, Version::Draft14), + Error::Remote(0x4) + )); + } + + /// GOING_AWAY arrived in draft-17. Sent to an earlier peer, 0x6 is unassigned there, + /// so say INTERNAL_ERROR outright rather than a number that means nothing. + #[test] + fn going_away_only_exists_from_draft_17() { + for kind in KINDS { + for version in [Version::Draft14, Version::Draft15, Version::Draft16] { + assert_eq!(to_code(Condition::GoingAway, kind, version), INTERNAL_ERROR); + assert!(matches!(from_code(GOING_AWAY, kind, version), Error::Remote(0x6))); + } + + for version in [Version::Draft17, Version::Draft18, Version::Draft19, Version::Draft20] { + assert_eq!(to_code(Condition::GoingAway, kind, version), GOING_AWAY); + assert!(matches!(from_code(GOING_AWAY, kind, version), Error::GoingAway)); + } + } + } + + /// Every code we send must decode back to what we meant on the same draft and + /// request, or two moq-net peers disagree about what a rejection said. + #[test] + fn every_emitted_code_round_trips() { + for version in ALL { + for kind in KINDS { + for condition in EVERY_CONDITION { + let code = to_code(condition, kind, version); + let decoded = Condition::from(&from_code(code, kind, version)); + assert_eq!( + to_code(decoded, kind, version), + code, + "{condition:?} on {version:?}/{kind:?} did not survive a round trip" + ); + } + } + } + } + + /// 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. + #[test] + fn only_registered_codes_reach_the_wire() { + fn registered(kind: Kind, version: Version) -> &'static [u64] { + match (version, kind) { + (Version::Draft14, Kind::Subscribe) => &[0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x10, 0x12], + (Version::Draft14, Kind::Fetch) => &[0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x10, 0x12], + (Version::Draft14, Kind::Publish) => &[0x0, 0x1, 0x2, 0x3, 0x4], + (Version::Draft14, Kind::PublishNamespace) => &[0x0, 0x1, 0x2, 0x3, 0x4, 0x10, 0x12], + (Version::Draft14, Kind::SubscribeNamespace) => &[0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x10, 0x12], + (Version::Draft15, _) => &[0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x10, 0x11, 0x12, 0x20, 0x30, 0x32, 0x33], + (Version::Draft16, _) => &[0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x10, 0x11, 0x12, 0x19, 0x20, 0x30, 0x32], + (Version::Draft17, _) => &[ + 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x9, 0x10, 0x11, 0x12, 0x19, 0x20, 0x30, 0x31, 0x32, + ], + _ => &[ + 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x9, 0x10, 0x11, 0x12, 0x19, 0x20, 0x30, 0x31, 0x32, 0x33, + 0x34, 0x35, 0x36, + ], + } + } + + for version in ALL { + for kind in KINDS { + for condition in EVERY_CONDITION { + let code = to_code(condition, kind, version); + assert!( + registered(kind, version).contains(&code), + "{condition:?} sends {code:#x}, which {version} does not register for {kind:?}" + ); + } + } + } + } + + /// The conditions a local error degrades to. A failure with no registered meaning + /// says INTERNAL_ERROR rather than borrowing a number that means something else. + #[test] + fn a_local_error_degrades_to_a_registered_condition() { + for err in [Error::Duplicate, Error::Cancel, Error::ProtocolViolation, Error::Closed] { + assert_eq!(Condition::from(&err), Condition::Internal, "{err} is not internal"); + } + + assert_eq!(Condition::from(&Error::Unsupported), Condition::NotSupported); + assert_eq!(Condition::from(&Error::Unauthorized), Condition::Unauthorized); + assert_eq!(Condition::from(&Error::Unroutable), Condition::Uninterested); + assert_eq!(Condition::from(&Error::GoingAway), Condition::GoingAway); + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index ae3ed1a22af..b448225b973 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -15,7 +15,7 @@ use crate::{ util::{MaybeBoxedExt, MaybeSendBox}, }; -use super::{Message, Version, cluster, peer}; +use super::{Message, Version, cluster, error::request, peer}; /// Largest millisecond duration every implementation can carry losslessly. const MAX_SAFE_AGE_MS: u64 = (1_u64 << 53) - 1; @@ -437,7 +437,12 @@ where Ok(broadcast) => broadcast, Err(_) => { return self - .reject_subscribe(stream, request_id, 404, "Broadcast not found") + .reject_subscribe( + stream, + request_id, + request::Condition::DoesNotExist, + "broadcast not found", + ) .await; } }; @@ -445,7 +450,9 @@ where let track = match broadcast.track(&msg.track_name) { Ok(track) => track, Err(err) => { - return self.reject_subscribe(stream, request_id, 404, &err.to_string()).await; + return self + .reject_subscribe(stream, request_id, (&err).into(), &err.to_string()) + .await; } }; @@ -460,7 +467,9 @@ where match track.subscribe(subscription.clone()).await { Ok(subscribed) => (track, subscribed), Err(err) => { - return self.reject_subscribe(stream, request_id, 404, &err.to_string()).await; + return self + .reject_subscribe(stream, request_id, (&err).into(), &err.to_string()) + .await; } } }; @@ -584,10 +593,10 @@ where &self, mut stream: Stream, request_id: RequestId, - error_code: u64, + condition: request::Condition, reason: &str, ) -> Result<(), Error> { - self.write_subscribe_error(&mut stream.writer, request_id, error_code, reason) + self.write_subscribe_error(&mut stream.writer, request_id, condition, reason) .await?; // The peer dropping the stream once it has the rejection is a normal end, not our failure. @@ -600,9 +609,11 @@ where &self, writer: &mut Writer, request_id: RequestId, - error_code: u64, + condition: request::Condition, reason: &str, ) -> Result<(), Error> { + let error_code = request::to_code(condition, request::Kind::Subscribe, self.version); + match self.version { Version::Draft14 => { writer.encode(&ietf::SubscribeError::ID).await?; @@ -893,19 +904,40 @@ where async fn run_fetch_stream(mut self, mut stream: Stream, msg: ietf::Fetch<'_>) -> Result<(), Error> { let _subscribe_id = match msg.fetch_type { FetchType::Standalone { .. } => { - return self.reject_fetch(stream, msg.request_id, 500, "not supported").await; + return self + .reject_fetch( + stream, + msg.request_id, + request::Condition::NotSupported, + "not supported", + ) + .await; } FetchType::RelativeJoining { subscriber_request_id, group_offset, } => { if group_offset != 0 { - return self.reject_fetch(stream, msg.request_id, 500, "not supported").await; + return self + .reject_fetch( + stream, + msg.request_id, + request::Condition::NotSupported, + "not supported", + ) + .await; } subscriber_request_id } FetchType::AbsoluteJoining { .. } => { - return self.reject_fetch(stream, msg.request_id, 500, "not supported").await; + return self + .reject_fetch( + stream, + msg.request_id, + request::Condition::NotSupported, + "not supported", + ) + .await; } }; @@ -965,10 +997,10 @@ where &self, mut stream: Stream, request_id: RequestId, - error_code: u64, + condition: request::Condition, reason: &str, ) -> Result<(), Error> { - self.write_fetch_error(&mut stream.writer, request_id, error_code, reason) + self.write_fetch_error(&mut stream.writer, request_id, condition, reason) .await?; let _ = stream.writer.close().await; @@ -979,9 +1011,11 @@ where &self, writer: &mut Writer, request_id: RequestId, - error_code: u64, + condition: request::Condition, reason: &str, ) -> Result<(), Error> { + let error_code = request::to_code(condition, request::Kind::Fetch, self.version); + match self.version { Version::Draft14 => { writer.encode(&ietf::FetchError::ID).await?; @@ -2328,6 +2362,83 @@ mod serve_tests { serve.await.unwrap(); } + /// A subscribe for a broadcast we do not serve is refused with the negotiated draft's own + /// "does not exist" value. + /// + /// Draft-14 numbers it 0x4 and draft-15 moved it to 0x10, which is draft-14's + /// MALFORMED_AUTH_TOKEN: a peer told the wrong one re-authenticates instead of waiting + /// for the announcement. The reply is encoded here rather than matched by code alone, so + /// a value slipping outside the draft's table cannot pass. + #[tokio::test] + async fn a_missing_broadcast_is_refused_with_the_draft_s_code() { + for version in [ + Version::Draft14, + Version::Draft15, + Version::Draft16, + Version::Draft17, + Version::Draft18, + Version::Draft19, + Version::Draft20, + ] { + let error_code = match version { + Version::Draft14 => 0x4, + _ => 0x10, + }; + + let h = serve(version); + let mut session = h.session.clone(); + let stream = Stream::open(&mut session, version).await.unwrap(); + + let mut msg = subscribe(Filter::NextObject, None); + msg.track_namespace = crate::Path::new("absent"); + + h.publisher.clone().run_subscribe_stream(stream, msg).await.unwrap(); + + let expected = { + let log = crate::lite::test_transport::Log::default(); + let mut writer = + crate::coding::Writer::new(crate::lite::test_transport::SinkSend::new(log.clone()), version); + + match version { + Version::Draft14 => { + writer.encode(&ietf::SubscribeError::ID).await.unwrap(); + writer + .encode(&ietf::SubscribeError { + request_id: RequestId(REQUEST_ID), + error_code, + reason_phrase: "broadcast not found".into(), + }) + .await + .unwrap(); + } + _ => { + writer.encode(&ietf::RequestError::ID).await.unwrap(); + writer + .encode(&ietf::RequestError { + request_id: match version { + Version::Draft15 | Version::Draft16 => Some(RequestId(REQUEST_ID)), + _ => None, + }, + error_code, + reason_phrase: "broadcast not found".into(), + retry_interval: 0, + }) + .await + .unwrap(); + } + } + + log.writes.lock().unwrap().clone() + }; + + assert_eq!( + occurrences(&h.log, &expected), + 1, + "{version} must refuse a missing broadcast with {error_code:#x}" + ); + } + } + /// The draft's canonical current-group join: a Next Object subscription plus a /// StartGroup=1 fill. The published head arrives exactly once, on a fetch stream, /// and the subscription starts past the snapshot, so nothing is duplicated and @@ -2806,7 +2917,8 @@ mod tests { writer .encode(&ietf::RequestError { request_id: matches!(version, Version::Draft15 | Version::Draft16).then_some(RequestId(1)), - error_code: 403, + // UNINTERESTED, draft-17 section 14.5.2. + error_code: 0x20, reason_phrase: "no".into(), retry_interval, }) diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index 7b66fdb71c1..eb749ead1bc 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -13,7 +13,7 @@ use crate::{ util::{MaybeBoxedExt, MaybeSendBox, TaskSet, Tasks}, }; -use super::{Message, Version, cluster, peer}; +use super::{Message, Version, cluster, error::request, peer}; use web_async::Lock; use web_transport_trait::{MaybeSend, MaybeSync}; @@ -640,13 +640,15 @@ where } ietf::SubscribeNamespaceError::ID if self.version == Version::Draft14 => { let msg = ietf::SubscribeNamespaceError::decode_msg(&mut data, self.version)?; - tracing::warn!(error_code = %msg.error_code, reason = %msg.reason_phrase, "subscribe_namespace error"); - return Err(Error::Cancel); + let err = request::from_code(msg.error_code, request::Kind::SubscribeNamespace, self.version); + tracing::warn!(%err, reason = %msg.reason_phrase, "subscribe_namespace error"); + return Err(err); } ietf::RequestError::ID => { let msg = ietf::RequestError::decode_msg(&mut data, self.version)?; - tracing::warn!(error_code = %msg.error_code, reason = %msg.reason_phrase, "subscribe_namespace error"); - return Err(Error::Cancel); + let err = request::from_code(msg.error_code, request::Kind::SubscribeNamespace, self.version); + tracing::warn!(%err, reason = %msg.reason_phrase, "subscribe_namespace error"); + return Err(err); } _ => return Err(Error::UnexpectedMessage), } @@ -856,8 +858,13 @@ where // than attaching a source we would then have to route around. let Some(advert) = self.route(msg.cluster.as_ref(), &peer) else { tracing::debug!(%path, "dropping reflected publish_namespace"); - self.write_error(&mut stream, request_id, 400, "route loops through this relay") - .await?; + self.write_error( + &mut stream, + request_id, + request::Condition::Uninterested, + "route loops through this relay", + ) + .await?; let _ = stream.writer.close().await; return Ok(()); }; @@ -871,7 +878,8 @@ where } } Err(err) => { - self.write_error(&mut stream, request_id, 400, &err.to_string()).await?; + self.write_error(&mut stream, request_id, (&err).into(), &err.to_string()) + .await?; let _ = stream.writer.close().await; return Ok(()); } @@ -1010,17 +1018,20 @@ where ) -> Result<(), Error> { tracing::debug!(broadcast = %msg.track_namespace, track = %msg.track_name, "rejecting publish"); - // NOT_SUPPORTED, from the PUBLISH error codes in draft-19 section 10.10. We decline - // the method itself rather than this particular track, which is UNINTERESTED (0x4). + // We decline the method itself rather than this particular track, which would be + // UNINTERESTED. // // The alias the message carries is deliberately not recorded. Nothing will ever bind // it, and a rejected request has no lifetime of ours to hang the cleanup on, so the // entry would have to be swept asynchronously. Any data streams the publisher opened // before reading this are dropped by the unknown-alias path instead. - const NOT_SUPPORTED: u64 = 0x3; - - self.write_publish_error(&mut stream, msg.request_id, NOT_SUPPORTED, "PUBLISH is not supported") - .await?; + self.write_publish_error( + &mut stream, + msg.request_id, + request::Condition::NotSupported, + "PUBLISH is not supported", + ) + .await?; // The rejection is the whole exchange, but it still has to arrive: a finish alone // leaves the drop-time reset free to discard it before the peer acknowledges it. let _ = stream.writer.close().await; @@ -1052,14 +1063,16 @@ where Ok(()) } - /// Send error on the bidi stream. + /// Refuse a PUBLISH_NAMESPACE on the bidi stream that carries it. async fn write_error( &self, stream: &mut Stream, request_id: RequestId, - error_code: u64, + condition: request::Condition, reason: &str, ) -> Result<(), Error> { + let error_code = request::to_code(condition, request::Kind::PublishNamespace, self.version); + match self.version { Version::Draft14 => { stream.writer.encode(&ietf::PublishNamespaceError::ID).await?; @@ -1100,13 +1113,16 @@ where Ok(()) } + /// Refuse a PUBLISH on the bidi stream that carries it. async fn write_publish_error( &self, stream: &mut Stream, request_id: RequestId, - error_code: u64, + condition: request::Condition, reason: &str, ) -> Result<(), Error> { + let error_code = request::to_code(condition, request::Kind::Publish, self.version); + match self.version { Version::Draft14 => { stream.writer.encode(&ietf::PublishError::ID).await?; @@ -1727,15 +1743,25 @@ where largest: msg.largest, })) } + // The rejection reaches the track as the reason the publisher gave, so a + // subscriber can tell a broadcast that is not there from one it may not have. ietf::SubscribeError::ID if self.version == Version::Draft14 => { let msg = ietf::SubscribeError::decode_msg(&mut data, self.version)?; tracing::warn!(message = ?msg, "subscribe error"); - Err(Error::Cancel) + Err(request::from_code( + msg.error_code, + request::Kind::Subscribe, + self.version, + )) } ietf::RequestError::ID => { let msg = ietf::RequestError::decode_msg(&mut data, self.version)?; tracing::warn!(message = ?msg, "request error"); - Err(Error::Cancel) + Err(request::from_code( + msg.error_code, + request::Kind::Subscribe, + self.version, + )) } _ => Err(Error::UnexpectedMessage), } @@ -2788,7 +2814,8 @@ mod tests { writer .encode(&ietf::RequestError { request_id: Some(RequestId(1)), - error_code: 404, + // DOES_NOT_EXIST, draft-16 section 13.4.2. + error_code: 0x10, reason_phrase: "not found".into(), retry_interval: 0, }) @@ -4181,78 +4208,98 @@ mod tests { /// PUBLISH offers one track, but a source attaches per namespace and serves every /// track under it. Rather than invent a namespace-level source from a track-level /// offer, decline the request and leave the session running. + /// + /// Draft-14 answers with PUBLISH_ERROR and its own registry; draft-15 folded the message + /// into REQUEST_ERROR, so both shapes have to carry NOT_SUPPORTED. #[tokio::test] async fn publish_is_rejected_without_announcing() { - // An open gate, so the rejection actually reaches the wire. - let gate = kio::Producer::new(true); - let session = crate::lite::test_transport::SinkSession::gated_bi(gate.consume()); - let origin = crate::origin::Info::new(crate::Hop::new(1).unwrap()).produce(); - let consumer = origin.consume(); - let (tasks, task_set) = crate::util::TaskSet::new(); - std::mem::forget(task_set); - - let mut subscriber = Subscriber::new( - TestRuntime::new(), - session.clone(), - origin, - Control::new(None, false), - None, - peer::PeerSetup::default(), - crate::Hop::new(1).unwrap(), - None, - Version::Draft19, - tasks, - Default::default(), - ); + for version in [Version::Draft14, Version::Draft19] { + // An open gate, so the rejection actually reaches the wire. + let gate = kio::Producer::new(true); + let session = crate::lite::test_transport::SinkSession::gated_bi(gate.consume()); + let origin = crate::origin::Info::new(crate::Hop::new(1).unwrap()).produce(); + let consumer = origin.consume(); + let (tasks, task_set) = crate::util::TaskSet::new(); + std::mem::forget(task_set); - let stream = Stream::open(&mut session.clone(), Version::Draft19).await.unwrap(); - let msg = ietf::Publish { - request_id: RequestId(1), - track_namespace: crate::Path::new("room/host"), - track_name: "video".into(), - track_alias: 7, - largest_location: None, - forward: true, - properties: ietf::Properties::default(), - }; + let mut subscriber = Subscriber::new( + TestRuntime::new(), + session.clone(), + origin, + Control::new(None, false), + None, + peer::PeerSetup::default(), + crate::Hop::new(1).unwrap(), + None, + version, + tasks, + Default::default(), + ); - // Errors are surfaced to the peer on the stream, not raised as a session error. - subscriber.run_publish_stream(stream, msg).await.unwrap(); - tokio::time::sleep(Duration::from_millis(1)).await; + let stream = Stream::open(&mut session.clone(), version).await.unwrap(); + let msg = ietf::Publish { + request_id: RequestId(1), + track_namespace: crate::Path::new("room/host"), + track_name: "video".into(), + track_alias: 7, + largest_location: None, + forward: true, + properties: ietf::Properties::default(), + }; - assert!( - routed_now(&consumer, "room/host").is_none(), - "a rejected PUBLISH must not announce a broadcast" - ); - // Encode the reply we expect rather than matching the reason alone, so the error code - // regressing to something outside draft-19 section 10.10's table cannot slip through. - let expected = { - const NOT_SUPPORTED: u64 = 0x3; + // Errors are surfaced to the peer on the stream, not raised as a session error. + subscriber.run_publish_stream(stream, msg).await.unwrap(); + tokio::time::sleep(Duration::from_millis(1)).await; - let log = crate::lite::test_transport::Log::default(); - let mut writer = crate::coding::Writer::new( - crate::lite::test_transport::SinkSend::new(log.clone()), - Version::Draft19, + assert!( + routed_now(&consumer, "room/host").is_none(), + "a rejected PUBLISH must not announce a broadcast" ); - writer.encode(&ietf::RequestError::ID).await.unwrap(); - writer - .encode(&ietf::RequestError { - request_id: None, - error_code: NOT_SUPPORTED, - reason_phrase: "PUBLISH is not supported".into(), - retry_interval: 0, - }) - .await - .unwrap(); + // Encode the reply we expect rather than matching the reason alone, so an error + // code regressing to something outside the draft's table cannot slip through. + // NOT_SUPPORTED is 0x3 in every registry, which is what makes it comparable here. + let expected = { + const NOT_SUPPORTED: u64 = 0x3; + + let log = crate::lite::test_transport::Log::default(); + let mut writer = + crate::coding::Writer::new(crate::lite::test_transport::SinkSend::new(log.clone()), version); + + match version { + Version::Draft14 => { + writer.encode(&ietf::PublishError::ID).await.unwrap(); + writer + .encode(&ietf::PublishError { + request_id: RequestId(1), + error_code: NOT_SUPPORTED, + reason_phrase: "PUBLISH is not supported".into(), + }) + .await + .unwrap(); + } + _ => { + writer.encode(&ietf::RequestError::ID).await.unwrap(); + writer + .encode(&ietf::RequestError { + request_id: None, + error_code: NOT_SUPPORTED, + reason_phrase: "PUBLISH is not supported".into(), + retry_interval: 0, + }) + .await + .unwrap(); + } + } - log.writes.lock().unwrap().clone() - }; + log.writes.lock().unwrap().clone() + }; - assert_eq!( - occurrences(&session.log, &expected), - 1, - "the decline reaches the peer as NOT_SUPPORTED" - ); + assert_eq!( + occurrences(&session.log, &expected), + 1, + "{version} must decline the PUBLISH as NOT_SUPPORTED" + ); + } } } From 8980206d8266e47279dd8bb5698d53df8f8b1acc Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 8 Sep 2026 00:52:32 -0700 Subject: [PATCH 3/7] fix(net): keep an IETF reset code moq-lite does not claim Flattening every unshared code to INTERNAL_ERROR discarded the wire value of codes that could not be misread: moq-lite names nothing for UNKNOWN_OBJECT_STATUS, EXPIRED_AUTH_TOKEN or EXCESSIVE_LOAD, so carrying their number costs nothing. Only a code moq-lite claims for something the draft does not still flattens, and the wire value goes in the message. StreamCode is one numeric space, so a draft-16 UNKNOWN_OBJECT_STATUS kept as 0x4 would test equal to StreamCode.GoingAway and retire a session that is not going anywhere. Co-Authored-By: Claude Opus 5 --- js/net/src/error.ts | 14 ++++++++++---- js/net/src/stream.test.ts | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/js/net/src/error.ts b/js/net/src/error.ts index 1f15813c086..35487a460d6 100644 --- a/js/net/src/error.ts +++ b/js/net/src/error.ts @@ -303,22 +303,28 @@ function localStreamCode(err: unknown): StreamCode { * 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 the same holds per draft: a code the negotiated draft gives a meaning - * moq-lite has no name for, or none at all, reads as {@link StreamCode.Internal} with the wire - * value kept in the message, rather than being read as whatever moq-lite assigns that number. + * 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 && !sharedStreamCode(code, options.version)) { + if (options?.version !== undefined && !sharedStreamCode(code, options.version) && LOCAL_CODES.has(code)) { return new StreamError(StreamCode.Internal, { cause: err, message: `remote error: ${code}` }); } if (code === StreamCode.TooFarBehind) return new Lagged({ cause: err }); return new StreamError(code, { cause: err }); } +/** The codes moq-lite gives a meaning of its own, which a foreign one must not borrow. */ +const LOCAL_CODES: ReadonlySet = new Set(Object.values(StreamCode)); + const legacyWebTransportErrors = new WeakSet(); /** diff --git a/js/net/src/stream.test.ts b/js/net/src/stream.test.ts index 68f8e84406b..12a9f207756 100644 --- a/js/net/src/stream.test.ts +++ b/js/net/src/stream.test.ts @@ -622,5 +622,23 @@ for (const [version, tooFarBehind] of [ // 0x5 is TOO_FAR_BEHIND only where the draft registers it; on draft-14 it means // nothing, so reading it as a lag would invent a gap the peer never reported. expect(err instanceof Lagged).toBe(tooFarBehind === StreamCode.TooFarBehind); + // Flattened where the draft does not register it, but the wire value still reaches a + // log rather than being lost. + if (tooFarBehind === StreamCode.Internal) expect((err as StreamError).message).toContain("5"); + }); + + // EXCESSIVE_LOAD, which moq-lite names nothing for, so nothing can misread the value + // and it survives intact. Only a code moq-lite claims for something else is flattened. + test(`a code moq-lite does not claim keeps its value (${version})`, async () => { + const reader = new Reader( + new ReadableStream({ + start: (controller) => controller.error(new Reset(0x9)), + }), + undefined, + version, + ); + const err = await reader.closed.catch((err: unknown) => err); + expect(err).toBeInstanceOf(StreamError); + expect((err as StreamError).code).toBe(0x9 as StreamCode); }); } From 900afbabba0c0ba9289ce4900de4501b5c693516 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 8 Sep 2026 01:17:41 -0700 Subject: [PATCH 4/7] fix(moq-net): keep the origin's reason when a subscribe is refused Hardcoding DOES_NOT_EXIST discarded what an origin::Dynamic handler said: an authorization refusal or a draining session reached the peer as missing content, which is a different recovery. Co-Authored-By: Claude Opus 5 --- rs/moq-net/src/ietf/publisher.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index b448225b973..566d426d1e1 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -435,14 +435,12 @@ where .await { Ok(broadcast) => broadcast, - Err(_) => { + // The reason is the origin's, not ours: a dynamic router refusing on + // authorization or a drain says so, and only an unroutable path means the + // broadcast is not here. + Err(err) => { return self - .reject_subscribe( - stream, - request_id, - request::Condition::DoesNotExist, - "broadcast not found", - ) + .reject_subscribe(stream, request_id, (&err).into(), &err.to_string()) .await; } }; @@ -2368,7 +2366,8 @@ mod serve_tests { /// Draft-14 numbers it 0x4 and draft-15 moved it to 0x10, which is draft-14's /// MALFORMED_AUTH_TOKEN: a peer told the wrong one re-authenticates instead of waiting /// for the announcement. The reply is encoded here rather than matched by code alone, so - /// a value slipping outside the draft's table cannot pass. + /// a value slipping outside the draft's table cannot pass, and the reason phrase is the + /// origin's own, which is what carries a refusal the registry has no value for. #[tokio::test] async fn a_missing_broadcast_is_refused_with_the_draft_s_code() { for version in [ @@ -2406,7 +2405,7 @@ mod serve_tests { .encode(&ietf::SubscribeError { request_id: RequestId(REQUEST_ID), error_code, - reason_phrase: "broadcast not found".into(), + reason_phrase: Error::Unroutable.to_string().into(), }) .await .unwrap(); @@ -2420,7 +2419,7 @@ mod serve_tests { _ => None, }, error_code, - reason_phrase: "broadcast not found".into(), + reason_phrase: Error::Unroutable.to_string().into(), retry_interval: 0, }) .await From 104d644616879ddc54435008e18f3bccc45af33e Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 8 Sep 2026 01:38:39 -0700 Subject: [PATCH 5/7] docs(quest): file the control-timeout reset code follow-up A request stream torn down because the peer never answered resets with DELIVERY_TIMEOUT, which describes content that missed its deadline. Both languages and both wires do it, so the fix is cross-cutting and out of scope here. Co-Authored-By: Claude Opus 5 --- quest/m1/README.md | 1 + quest/m1/control-timeout-code.md | 41 ++++++++++++++++++++++++++++++++ quest/m1/group-overflow-abort.md | 1 + 3 files changed, 43 insertions(+) create mode 100644 quest/m1/control-timeout-code.md diff --git a/quest/m1/README.md b/quest/m1/README.md index 2e270bd81fc..1bfb0e2813b 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -28,6 +28,7 @@ with the current dev tree before starting. - [Gap discontinuity](/quest/m1/gap-discontinuity.md) - a hole in the delivered group sequence is the discontinuity unless the boundary proves continuity; no marker has to arrive - [Monotonic timeline](/quest/m1/monotonic-timeline.md) - a track's timestamps never fall below its live edge; publishers declare a discontinuity and continue forward, consumers stop detecting rewinds - [Group overflow](/quest/m1/group-overflow-abort.md) - an oversized open group aborts for every reader instead of shedding its head +- [Control timeout code](/quest/m1/control-timeout-code.md) - a request stream the peer never answered stops claiming its content was late - [#2895](/quest/m1/2895-add-an-atomic-readiness-gate-for-origin-broadcasts.md) - Add an atomic readiness gate for Origin broadcasts - [#2991](/quest/m1/2991-net-coalesce-dynamic-tracks-and-preserve-sequences-across.md) - net: coalesce dynamic tracks and preserve sequences across replacements - [#3190](/quest/m1/3190-align-origin-broadcast-creation-naming-across-language.md) - every native binding exposes create_broadcast, announce/unannounce on the broadcast, and dynamic(prefix, route) with one meaning diff --git a/quest/m1/control-timeout-code.md b/quest/m1/control-timeout-code.md new file mode 100644 index 00000000000..79bbd5cb200 --- /dev/null +++ b/quest/m1/control-timeout-code.md @@ -0,0 +1,41 @@ +# [S] A control timeout is not a delivery timeout + +## Goal + +A request stream torn down because the peer never answered resets with a code +that says so, rather than DELIVERY_TIMEOUT. Both wires and both languages agree, +so a relay carrying the reset across a hop does not change what it says. + +## Plan + +`DELIVERY_TIMEOUT` describes content that missed its deadline (draft-20 section +3.3.4, and the same claim moq-lite makes with 0x2). Every local timeout uses it +today, including the ones that never touched content: + +- `js/net/src/ietf/subscriber.ts` aborts the request stream with the + `SUBSCRIBE_OK` timer's `TimeoutError`, and `js/net/src/ietf/publisher.ts` does + the same with the PUBLISH_NAMESPACE response timer. `toStreamCode` in + `js/net/src/error.ts` maps every `TimeoutError` to `StreamCode.DeliveryTimeout`. +- Rust does the same through `From<&Error> for StreamError` in + `rs/moq-net/src/error.rs`: `Error::Timeout` becomes + `StreamError::DeliveryTimeout`. + +So a peer that opens a stream and goes quiet is told its content was late. + +The fix is a condition of its own for "you did not answer", not a rename of the +existing one, since a real delivery deadline still needs DELIVERY_TIMEOUT. The +moq-transport stream registry has no value for it, so the IETF wire says +INTERNAL_ERROR; moq-lite can register one in its reserved range or say the same. +Whichever it says, `rs/moq-net/src/error.rs`, `js/net/src/error.ts` and +`rs/moq-net/src/ietf/error.rs` have to agree, and the moq-lite draft changes with +them if a value is registered. + +Decide first whether the distinction is worth a code at all: a caller that only +logs the reason gains nothing, and INTERNAL_ERROR is already what a peer does +with an unregistered value. If it is not, the fix is instead to stop putting a +control timeout through the delivery mapping and let it be INTERNAL_ERROR +outright, which is a smaller change than a new code. + +## Related + +- [Group overflow](/quest/m1/group-overflow-abort.md) - the other condition whose wire code is under review diff --git a/quest/m1/group-overflow-abort.md b/quest/m1/group-overflow-abort.md index a2e35b32140..24c17fa0962 100644 --- a/quest/m1/group-overflow-abort.md +++ b/quest/m1/group-overflow-abort.md @@ -123,3 +123,4 @@ already claims its top end "intentionally reaches the raised ## Related - [Group charge](/quest/m0/group-charge.md) - pool-level budget accounting, unaffected by this change +- [Control timeout code](/quest/m1/control-timeout-code.md) - the other condition whose wire code is under review From 1e474917d0e356becd33101d5b3b13b0d0909793 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 8 Sep 2026 02:03:58 -0700 Subject: [PATCH 6/7] fix(net): flatten a foreign reset code in the application range moq-lite mints an application code for anything 64 and up, so an application compares against its own. moq-transport registers nothing above 0x12 and has no application range, so an IETF code landing there is never the application code it would look like. Co-Authored-By: Claude Opus 5 --- js/net/src/error.ts | 16 +++++++++++++--- js/net/src/stream.test.ts | 17 +++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/js/net/src/error.ts b/js/net/src/error.ts index 35487a460d6..d30b806dde1 100644 --- a/js/net/src/error.ts +++ b/js/net/src/error.ts @@ -315,15 +315,25 @@ function localStreamCode(err: unknown): StreamCode { export function fromTransport(err: unknown, options?: TransportErrorOptions): Error { const code = streamCode(err); if (code === undefined) return error(err); - if (options?.version !== undefined && !sharedStreamCode(code, options.version) && LOCAL_CODES.has(code)) { + if (options?.version !== undefined && !sharedStreamCode(code, options.version) && claimedLocally(code)) { return new StreamError(StreamCode.Internal, { cause: err, message: `remote error: ${code}` }); } if (code === StreamCode.TooFarBehind) return new Lagged({ cause: err }); return new StreamError(code, { cause: err }); } -/** The codes moq-lite gives a meaning of its own, which a foreign one must not borrow. */ -const LOCAL_CODES: ReadonlySet = new Set(Object.values(StreamCode)); +/** The codes moq-lite names, which a foreign one must not borrow. */ +const NAMED_CODES: ReadonlySet = 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(); diff --git a/js/net/src/stream.test.ts b/js/net/src/stream.test.ts index 12a9f207756..43621ef646d 100644 --- a/js/net/src/stream.test.ts +++ b/js/net/src/stream.test.ts @@ -641,4 +641,21 @@ for (const [version, tooFarBehind] of [ expect(err).toBeInstanceOf(StreamError); expect((err as StreamError).code).toBe(0x9 as StreamCode); }); + + // moq-lite mints an application code for anything 64 and up, so an application compares + // against its own. moq-transport has no such range, so a code landing there from an IETF + // peer is never the application code it would look like. + test(`a foreign code in the application range is flattened (${version})`, async () => { + const reader = new Reader( + new ReadableStream({ + start: (controller) => controller.error(new Reset(70)), + }), + undefined, + version, + ); + const err = await reader.closed.catch((err: unknown) => err); + expect(err).toBeInstanceOf(StreamError); + expect((err as StreamError).code).toBe(version === undefined ? StreamCode(70) : StreamCode.Internal); + if (version !== undefined) expect((err as StreamError).message).toContain("70"); + }); } From 2a2bbd9a9c5c10ce4fda0e155cf5f7aa6c65d588 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 8 Sep 2026 13:55:41 -0700 Subject: [PATCH 7/7] refactor(moq-net): map a request rejection straight from Error Every Condition variant named an Error variant, so the enum was a second spelling of the same eight cases between the call site and the registry. to_code now takes the Error itself, mirroring the stream half, and Kind alone decides what a refused route says on each request. Co-Authored-By: Claude Fable 5.1 --- rs/moq-net/src/ietf/error.rs | 172 ++++++++++++------------------ rs/moq-net/src/ietf/publisher.rs | 49 +++------ rs/moq-net/src/ietf/subscriber.rs | 14 +-- 3 files changed, 89 insertions(+), 146 deletions(-) diff --git a/rs/moq-net/src/ietf/error.rs b/rs/moq-net/src/ietf/error.rs index a798a6dd394..3645d80ea89 100644 --- a/rs/moq-net/src/ietf/error.rs +++ b/rs/moq-net/src/ietf/error.rs @@ -143,7 +143,8 @@ pub(crate) mod request { /// Which request the error answers, so draft-14 picks the right registry. /// /// Draft-15 and later carry one REQUEST_ERROR registry for every request, so from there - /// on the kind changes nothing. + /// on the kind only decides what a refused route says: not here to a request for + /// content, uninterested to an offer of it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Kind { /// SUBSCRIBE_ERROR, draft-14 section 13.1.2. @@ -237,75 +238,33 @@ pub(crate) mod request { } } - /// What a rejection reports, before the draft picks the number for it. - /// - /// Named separately from [`Error`] because a rejection says less than an error does: a - /// dozen local failures are one INTERNAL_ERROR on the wire, and the two conditions the - /// registry does distinguish (asking for something absent versus offering something - /// unwanted) are the same [`Error::Unroutable`] here. A caller that knows which it means - /// names it; one that only holds an error converts. - #[derive(Clone, Copy, Debug, PartialEq, Eq)] - pub(crate) enum Condition { - /// Something went wrong that the registry has no value for. - Internal, - /// The peer's credentials do not cover the request. - Unauthorized, - /// The request outlived an implementation-specific deadline. - Timeout, - /// This endpoint does not implement the request at all. - NotSupported, - /// The broadcast or track the peer asked for is not here. - DoesNotExist, - /// The content the peer offered is not wanted here, so it should stop offering it. - Uninterested, - /// The track's content could not be parsed. - MalformedTrack, - /// A GOAWAY is draining the session, so no new request is accepted. - GoingAway, - } - - impl From<&Error> for Condition { - fn from(err: &Error) -> Self { - match err { - Error::Unauthorized => Self::Unauthorized, - Error::Timeout => Self::Timeout, - Error::Unsupported | Error::Version => Self::NotSupported, - Error::NotFound => Self::DoesNotExist, - // A path with no route is one we will not carry. On a request that offers - // content that is UNINTERESTED; on one that asks for it, [`to_code`] reads - // it as the answer the asker can act on instead. - Error::Unroutable => Self::Uninterested, - // Our own parse failure is, from the peer's side, a malformed track. - Error::Decode(_) | Error::BoundsExceeded(_) | Error::MalformedTrack => Self::MalformedTrack, - Error::GoingAway => Self::GoingAway, - // Everything else, a duplicate included: no draft assigns it a value, and - // INTERNAL_ERROR is how a peer reads an unregistered code anyway. - _ => Self::Internal, - } - } - } - /// The code to reject a request with, on the negotiated draft. /// - /// A condition the draft does not register for this request falls back to - /// INTERNAL_ERROR rather than borrowing a number from another draft, which would say - /// something the peer's registry gives a different meaning. - pub(crate) fn to_code(condition: Condition, kind: Kind, version: Version) -> u64 { - let registered = match condition { - Condition::Internal => return INTERNAL_ERROR, - Condition::Unauthorized => return UNAUTHORIZED, - Condition::Timeout => return TIMEOUT, - Condition::NotSupported => return NOT_SUPPORTED, - Condition::DoesNotExist => does_not_exist(kind, version), - // A subscriber that asked for content cannot act on "we do not want it": what it - // needs to know is that we do not have it, which is the same refusal from its - // side. Only the requests that offer content say UNINTERESTED. - Condition::Uninterested => match kind { + /// Lossy on purpose, like [`to_stream_code`](super::to_stream_code): an error says what went + /// wrong here, while the registry is what the peer can act on, so a dozen local failures are + /// one INTERNAL_ERROR on the wire. A condition the draft does not register for this request + /// falls back to INTERNAL_ERROR too, rather than borrowing a number from another draft, which + /// would say something the peer's registry gives a different meaning. + pub(crate) fn to_code(err: &Error, kind: Kind, version: Version) -> u64 { + let registered = match err { + Error::Unauthorized => return UNAUTHORIZED, + Error::Timeout => return TIMEOUT, + Error::Unsupported | Error::Version => return NOT_SUPPORTED, + Error::NotFound => does_not_exist(kind, version), + // A path with no route is one we will not carry. A subscriber that asked for it + // cannot act on "we do not want it": what it needs to know is that we do not have + // it, which is the same refusal from its side. Only the requests that offer content + // say UNINTERESTED. + Error::Unroutable => match kind { Kind::Subscribe | Kind::Fetch => does_not_exist(kind, version), - _ => uninterested(kind, version), + Kind::Publish | Kind::PublishNamespace | Kind::SubscribeNamespace => uninterested(kind, version), }, - Condition::MalformedTrack => malformed_track(kind, version), - Condition::GoingAway => going_away(version), + // Our own parse failure is, from the peer's side, a malformed track. + Error::Decode(_) | Error::BoundsExceeded(_) | Error::MalformedTrack => malformed_track(kind, version), + Error::GoingAway => going_away(version), + // Everything else, a duplicate included: no draft assigns it a value, and + // INTERNAL_ERROR is how a peer reads an unregistered code anyway. + _ => return INTERNAL_ERROR, }; registered.unwrap_or(INTERNAL_ERROR) @@ -350,17 +309,19 @@ pub(crate) mod request { Kind::SubscribeNamespace, ]; - /// Every condition a rejection can carry, so the checks below cover the whole space - /// rather than the variants someone remembered. A new variant belongs here. - const EVERY_CONDITION: [Condition; 8] = [ - Condition::Internal, - Condition::Unauthorized, - Condition::Timeout, - Condition::NotSupported, - Condition::DoesNotExist, - Condition::Uninterested, - Condition::MalformedTrack, - Condition::GoingAway, + /// Every error a rejection distinguishes, plus one it does not, so the checks below cover + /// the whole registry rather than the variants someone remembered. A new arm in + /// [`to_code`] belongs here. + const EVERY_ERROR: [Error; 9] = [ + Error::Duplicate, + Error::Unauthorized, + Error::Timeout, + Error::Unsupported, + Error::NotFound, + Error::Unroutable, + Error::MalformedTrack, + Error::GoingAway, + Error::Remote(0x30), ]; /// Draft-14 numbers a missing track 0x4 and draft-15 moved it to 0x10, which is @@ -370,22 +331,19 @@ pub(crate) mod request { #[test] fn a_missing_broadcast_uses_the_draft_s_own_number() { for kind in [Kind::Subscribe, Kind::Fetch] { - assert_eq!(to_code(Condition::DoesNotExist, kind, Version::Draft14), 0x4); + assert_eq!(to_code(&Error::NotFound, kind, Version::Draft14), 0x4); assert!(matches!(from_code(0x4, kind, Version::Draft14), Error::NotFound)); for version in ALL.into_iter().skip(1) { - assert_eq!(to_code(Condition::DoesNotExist, kind, version), 0x10); + assert_eq!(to_code(&Error::NotFound, kind, version), 0x10); assert!(matches!(from_code(0x10, kind, version), Error::NotFound)); // 0x4 is MALFORMED_AUTH_TOKEN from draft-15 on, which is not ours to claim. assert!(matches!(from_code(0x4, kind, version), Error::Remote(0x4))); } } - // And an error with no more specific meaning reaches the same value. - assert_eq!( - to_code(Condition::from(&Error::NotFound), Kind::Subscribe, Version::Draft20), - 0x10 - ); + // A broadcast with no route is, to the peer that asked for it, not here either. + assert_eq!(to_code(&Error::Unroutable, Kind::Subscribe, Version::Draft20), 0x10); } /// Draft-14 gives 0x4 to UNINTERESTED on the requests that offer content and to @@ -394,11 +352,11 @@ pub(crate) mod request { #[test] fn draft_14_reads_0x4_per_request() { for kind in [Kind::Publish, Kind::PublishNamespace] { - assert_eq!(to_code(Condition::Uninterested, kind, Version::Draft14), 0x4); + assert_eq!(to_code(&Error::Unroutable, kind, Version::Draft14), 0x4); assert!(matches!(from_code(0x4, kind, Version::Draft14), Error::Unroutable)); // Those requests offer content, so "it is not here" is not a rejection they // can carry. - assert_eq!(to_code(Condition::DoesNotExist, kind, Version::Draft14), INTERNAL_ERROR); + assert_eq!(to_code(&Error::NotFound, kind, Version::Draft14), INTERNAL_ERROR); } // And neither meaning reaches a request draft-14 gives neither to. @@ -414,12 +372,12 @@ pub(crate) mod request { fn going_away_only_exists_from_draft_17() { for kind in KINDS { for version in [Version::Draft14, Version::Draft15, Version::Draft16] { - assert_eq!(to_code(Condition::GoingAway, kind, version), INTERNAL_ERROR); + assert_eq!(to_code(&Error::GoingAway, kind, version), INTERNAL_ERROR); assert!(matches!(from_code(GOING_AWAY, kind, version), Error::Remote(0x6))); } for version in [Version::Draft17, Version::Draft18, Version::Draft19, Version::Draft20] { - assert_eq!(to_code(Condition::GoingAway, kind, version), GOING_AWAY); + assert_eq!(to_code(&Error::GoingAway, kind, version), GOING_AWAY); assert!(matches!(from_code(GOING_AWAY, kind, version), Error::GoingAway)); } } @@ -431,13 +389,13 @@ pub(crate) mod request { fn every_emitted_code_round_trips() { for version in ALL { for kind in KINDS { - for condition in EVERY_CONDITION { - let code = to_code(condition, kind, version); - let decoded = Condition::from(&from_code(code, kind, version)); + for err in &EVERY_ERROR { + let code = to_code(err, kind, version); + let decoded = from_code(code, kind, version); assert_eq!( - to_code(decoded, kind, version), + to_code(&decoded, kind, version), code, - "{condition:?} on {version:?}/{kind:?} did not survive a round trip" + "{err:?} on {version:?}/{kind:?} did not survive a round trip" ); } } @@ -471,29 +429,35 @@ pub(crate) mod request { for version in ALL { for kind in KINDS { - for condition in EVERY_CONDITION { - let code = to_code(condition, kind, version); + for err in &EVERY_ERROR { + let code = to_code(err, kind, version); assert!( registered(kind, version).contains(&code), - "{condition:?} sends {code:#x}, which {version} does not register for {kind:?}" + "{err:?} sends {code:#x}, which {version} does not register for {kind:?}" ); } } } } - /// The conditions a local error degrades to. A failure with no registered meaning - /// says INTERNAL_ERROR rather than borrowing a number that means something else. + /// A failure with no registered meaning says INTERNAL_ERROR rather than borrowing a + /// number that means something else, and comes back as the opaque remote code it was. #[test] - fn a_local_error_degrades_to_a_registered_condition() { + fn an_unregistered_error_is_internal() { for err in [Error::Duplicate, Error::Cancel, Error::ProtocolViolation, Error::Closed] { - assert_eq!(Condition::from(&err), Condition::Internal, "{err} is not internal"); + for kind in KINDS { + assert_eq!( + to_code(&err, kind, Version::Draft20), + INTERNAL_ERROR, + "{err} is not internal on {kind:?}" + ); + } } - assert_eq!(Condition::from(&Error::Unsupported), Condition::NotSupported); - assert_eq!(Condition::from(&Error::Unauthorized), Condition::Unauthorized); - assert_eq!(Condition::from(&Error::Unroutable), Condition::Uninterested); - assert_eq!(Condition::from(&Error::GoingAway), Condition::GoingAway); + assert!(matches!( + from_code(INTERNAL_ERROR, Kind::Subscribe, Version::Draft20), + Error::Remote(0) + )); } } } diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index 566d426d1e1..754e7982f21 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -439,18 +439,14 @@ where // authorization or a drain says so, and only an unroutable path means the // broadcast is not here. Err(err) => { - return self - .reject_subscribe(stream, request_id, (&err).into(), &err.to_string()) - .await; + return self.reject_subscribe(stream, request_id, &err, &err.to_string()).await; } }; let track = match broadcast.track(&msg.track_name) { Ok(track) => track, Err(err) => { - return self - .reject_subscribe(stream, request_id, (&err).into(), &err.to_string()) - .await; + return self.reject_subscribe(stream, request_id, &err, &err.to_string()).await; } }; @@ -465,9 +461,7 @@ where match track.subscribe(subscription.clone()).await { Ok(subscribed) => (track, subscribed), Err(err) => { - return self - .reject_subscribe(stream, request_id, (&err).into(), &err.to_string()) - .await; + return self.reject_subscribe(stream, request_id, &err, &err.to_string()).await; } } }; @@ -591,10 +585,10 @@ where &self, mut stream: Stream, request_id: RequestId, - condition: request::Condition, + err: &Error, reason: &str, ) -> Result<(), Error> { - self.write_subscribe_error(&mut stream.writer, request_id, condition, reason) + self.write_subscribe_error(&mut stream.writer, request_id, err, reason) .await?; // The peer dropping the stream once it has the rejection is a normal end, not our failure. @@ -607,10 +601,10 @@ where &self, writer: &mut Writer, request_id: RequestId, - condition: request::Condition, + err: &Error, reason: &str, ) -> Result<(), Error> { - let error_code = request::to_code(condition, request::Kind::Subscribe, self.version); + let error_code = request::to_code(err, request::Kind::Subscribe, self.version); match self.version { Version::Draft14 => { @@ -903,12 +897,7 @@ where let _subscribe_id = match msg.fetch_type { FetchType::Standalone { .. } => { return self - .reject_fetch( - stream, - msg.request_id, - request::Condition::NotSupported, - "not supported", - ) + .reject_fetch(stream, msg.request_id, &Error::Unsupported, "not supported") .await; } FetchType::RelativeJoining { @@ -917,24 +906,14 @@ where } => { if group_offset != 0 { return self - .reject_fetch( - stream, - msg.request_id, - request::Condition::NotSupported, - "not supported", - ) + .reject_fetch(stream, msg.request_id, &Error::Unsupported, "not supported") .await; } subscriber_request_id } FetchType::AbsoluteJoining { .. } => { return self - .reject_fetch( - stream, - msg.request_id, - request::Condition::NotSupported, - "not supported", - ) + .reject_fetch(stream, msg.request_id, &Error::Unsupported, "not supported") .await; } }; @@ -995,10 +974,10 @@ where &self, mut stream: Stream, request_id: RequestId, - condition: request::Condition, + err: &Error, reason: &str, ) -> Result<(), Error> { - self.write_fetch_error(&mut stream.writer, request_id, condition, reason) + self.write_fetch_error(&mut stream.writer, request_id, err, reason) .await?; let _ = stream.writer.close().await; @@ -1009,10 +988,10 @@ where &self, writer: &mut Writer, request_id: RequestId, - condition: request::Condition, + err: &Error, reason: &str, ) -> Result<(), Error> { - let error_code = request::to_code(condition, request::Kind::Fetch, self.version); + let error_code = request::to_code(err, request::Kind::Fetch, self.version); match self.version { Version::Draft14 => { diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index eb749ead1bc..266d197065f 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -861,7 +861,7 @@ where self.write_error( &mut stream, request_id, - request::Condition::Uninterested, + &Error::Unroutable, "route loops through this relay", ) .await?; @@ -878,7 +878,7 @@ where } } Err(err) => { - self.write_error(&mut stream, request_id, (&err).into(), &err.to_string()) + self.write_error(&mut stream, request_id, &err, &err.to_string()) .await?; let _ = stream.writer.close().await; return Ok(()); @@ -1028,7 +1028,7 @@ where self.write_publish_error( &mut stream, msg.request_id, - request::Condition::NotSupported, + &Error::Unsupported, "PUBLISH is not supported", ) .await?; @@ -1068,10 +1068,10 @@ where &self, stream: &mut Stream, request_id: RequestId, - condition: request::Condition, + err: &Error, reason: &str, ) -> Result<(), Error> { - let error_code = request::to_code(condition, request::Kind::PublishNamespace, self.version); + let error_code = request::to_code(err, request::Kind::PublishNamespace, self.version); match self.version { Version::Draft14 => { @@ -1118,10 +1118,10 @@ where &self, stream: &mut Stream, request_id: RequestId, - condition: request::Condition, + err: &Error, reason: &str, ) -> Result<(), Error> { - let error_code = request::to_code(condition, request::Kind::Publish, self.version); + let error_code = request::to_code(err, request::Kind::Publish, self.version); match self.version { Version::Draft14 => {