From 90e30994865506e405372b29ad53b50eee5143f5 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 07:17:10 -0800 Subject: [PATCH 1/9] chore(quest): claim quest/m2/session-codes.md Quest-Claim: d9a5cc99e4520ded From f974adcce8819f3a5032b594c4fb4d6b5e6fea23 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 07:30:00 -0800 Subject: [PATCH 2/9] wip: session codes name only moq-lite's registry --- go/wrapper/types.go | 14 -- js/net/src/connection/handshake.ts | 5 +- js/net/src/error.test.ts | 40 +++-- js/net/src/error.ts | 78 +++++++--- js/net/src/errors.ts | 4 +- js/net/src/ietf/connection.test.ts | 19 +-- js/net/src/ietf/connection.ts | 4 +- js/net/src/ietf/error.ts | 24 +++ js/net/src/ietf/malformed.test.ts | 13 +- js/net/src/ietf/request_ids.test.ts | 5 +- js/net/src/ietf/session.ts | 3 +- js/net/src/ietf/token.test.ts | 9 +- js/net/src/ietf/token.ts | 7 +- js/net/src/resume.ts | 24 +-- js/watch/src/broadcast.ts | 8 +- rs/moq-c/src/error.rs | 38 ++--- rs/moq-ffi/src/error.rs | 39 ++--- rs/moq-gst/src/source/imp.rs | 35 ++--- rs/moq-net/src/coding/codes.rs | 8 +- rs/moq-net/src/error.rs | 206 ++++++++++++++------------ rs/moq-net/src/ietf/control.rs | 6 +- rs/moq-net/src/ietf/error.rs | 69 ++++++++- rs/moq-net/src/ietf/publisher.rs | 10 +- rs/moq-net/src/ietf/request_update.rs | 6 +- rs/moq-net/src/ietf/session.rs | 30 ++-- rs/moq-net/src/ietf/subscriber.rs | 6 +- rs/moq-net/src/ietf/token.rs | 18 +-- rs/moq-net/src/lite/error.rs | 21 +-- rs/moq-net/src/lite/publisher.rs | 2 +- rs/moq-net/src/lite/session.rs | 6 +- rs/moq-net/src/lite/subscriber.rs | 18 +-- rs/moq-net/src/server.rs | 2 +- 32 files changed, 430 insertions(+), 347 deletions(-) diff --git a/go/wrapper/types.go b/go/wrapper/types.go index a38b8625881..79ebbb654f9 100644 --- a/go/wrapper/types.go +++ b/go/wrapper/types.go @@ -213,8 +213,6 @@ const ( ProtocolKindExpired = ffi.MoqProtocolKindExpired // ProtocolKindProtocolViolation identifies protocol violation. ProtocolKindProtocolViolation = ffi.MoqProtocolKindProtocolViolation - // ProtocolKindKeyValueFormatting identifies key value formatting. - ProtocolKindKeyValueFormatting = ffi.MoqProtocolKindKeyValueFormatting // ProtocolKindGoawayTimeout identifies goaway timeout. ProtocolKindGoawayTimeout = ffi.MoqProtocolKindGoawayTimeout // ProtocolKindTimeout identifies timeout. @@ -249,20 +247,8 @@ const ( ProtocolKindUnknown = ffi.MoqProtocolKindUnknown // ProtocolKindTooManyRequests identifies an exceeded session request cap. ProtocolKindTooManyRequests = ffi.MoqProtocolKindTooManyRequests - // ProtocolKindAuthTokenCacheOverflow identifies an exceeded token cache limit. - ProtocolKindAuthTokenCacheOverflow = ffi.MoqProtocolKindAuthTokenCacheOverflow // ProtocolKindMalformedAuthToken identifies an unparseable authorization token. ProtocolKindMalformedAuthToken = ffi.MoqProtocolKindMalformedAuthToken - // ProtocolKindUnknownAuthTokenAlias identifies an unregistered token alias. - ProtocolKindUnknownAuthTokenAlias = ffi.MoqProtocolKindUnknownAuthTokenAlias - // ProtocolKindInvalidRequestId identifies an invalid request ID. - ProtocolKindInvalidRequestId = ffi.MoqProtocolKindInvalidRequestId - // ProtocolKindInvalidPath identifies an invalid session path. - ProtocolKindInvalidPath = ffi.MoqProtocolKindInvalidPath - // ProtocolKindInvalidAuthority identifies an invalid session authority. - ProtocolKindInvalidAuthority = ffi.MoqProtocolKindInvalidAuthority - // ProtocolKindTooManyRequestUpdates identifies an exceeded request update limit. - ProtocolKindTooManyRequestUpdates = ffi.MoqProtocolKindTooManyRequestUpdates ) // AudioSampleFormat values: the raw PCM sample layout fed to or returned from the diff --git a/js/net/src/connection/handshake.ts b/js/net/src/connection/handshake.ts index 50f6d3ecc38..9411693aee8 100644 --- a/js/net/src/connection/handshake.ts +++ b/js/net/src/connection/handshake.ts @@ -1,3 +1,4 @@ +import { IetfSessionCode } from "../ietf/error.ts"; import { Duration } from "@moq/clock"; import { closeReason, ProtocolViolation, SessionCode, StreamError } from "../error.ts"; import { type Hop, randomHop } from "../hop.ts"; @@ -154,10 +155,10 @@ async function receiveSetup( // A server sends neither PATH nor AUTHORITY (draft-22 sections 9.1.1 and 9.1.2). if (client && setup.parameters.getBytes(Ietf.SetupOption.Path) !== undefined) { - throw new ProtocolViolation("server SETUP carries PATH", { code: SessionCode.InvalidPath }); + throw new ProtocolViolation("server SETUP carries PATH", { code: IetfSessionCode.InvalidPath }); } if (client && setup.parameters.getBytes(Ietf.SetupOption.Authority) !== undefined) { - throw new ProtocolViolation("server SETUP carries AUTHORITY", { code: SessionCode.InvalidAuthority }); + throw new ProtocolViolation("server SETUP carries AUTHORITY", { code: IetfSessionCode.InvalidAuthority }); } // Nothing here uses the peer's token, but one that cannot be decoded still closes the // session (draft-22 section 8.9). diff --git a/js/net/src/error.test.ts b/js/net/src/error.test.ts index b0eef03f9a0..e542740ff5e 100644 --- a/js/net/src/error.test.ts +++ b/js/net/src/error.test.ts @@ -10,6 +10,8 @@ import { NotFound, ProtocolViolation, reason, + Retry, + retry, SessionCode, SessionError, StreamCode, @@ -93,8 +95,35 @@ test("the error type names the registry the code came from", () => { expect(Number(stream.code)).toBe(Number(session?.code)); }); -test("invalid request IDs keep their session registry code", () => { - expect(fromClose({ closeCode: 0x4 })?.code).toBe(SessionCode.InvalidRequestId); +test("a code only moq-transport defines keeps its number", () => { + for (const code of [0x4, 0x6, 0x8, 0x13, 0x17, 0x19, 0x1b]) { + expect(fromClose({ closeCode: code })?.code).toBe(code); + expect(Object.values(SessionCode)).not.toContain(code); + } +}); + +test("retry separates a failed delivery from a verdict", () => { + for (const err of [ + new SessionError(SessionCode.Unauthorized), + new SessionError(0x4 as SessionCode), + new StreamError(StreamCode.SessionClosed), + new StreamError(StreamCode.Cancel), + new StreamError(StreamCode.ControlTimeout), + Object.assign(new Error("closed"), { source: "session" }), + ]) { + expect([err.message, retry(err)]).toEqual([err.message, Retry.Same]); + } + expect(retry(new StreamError(StreamCode.Unroutable))).toBe(Retry.Reroute); + for (const err of [ + new NotFound("broadcast"), + new StreamError(StreamCode.Unauthorized), + new StreamError(StreamCode.MalformedTrack), + new StreamError(0x22 as StreamCode), + new Error("malformed"), + "thrown", + ]) { + expect([String(err), retry(err)]).toEqual([String(err), Retry.Never]); + } }); test("the code types reject the other registry", () => { @@ -214,19 +243,12 @@ test("session codes match the draft's Session Error Codes table", () => { Internal: 0x1, Unauthorized: 0x2, ProtocolViolation: 0x3, - InvalidRequestId: 0x4, - KeyValueFormatting: 0x6, TooManyRequests: 0x7, - InvalidPath: 0x8, GoawayTimeout: 0x10, Timeout: 0x11, - AuthTokenCacheOverflow: 0x13, Version: 0x15, MalformedAuthToken: 0x16, - UnknownAuthTokenAlias: 0x17, Expired: 0x18, - InvalidAuthority: 0x19, - TooManyRequestUpdates: 0x1b, Unsupported: 0x30, }); }); diff --git a/js/net/src/error.ts b/js/net/src/error.ts index c4a9cedb871..de77c955a87 100644 --- a/js/net/src/error.ts +++ b/js/net/src/error.ts @@ -18,12 +18,14 @@ export type SessionCode = number & { readonly [SESSION_CODE]: true }; /** * Codes a peer sends when terminating the session, mirroring the Rust `Session`. * - * Specified by moq-lite, which reuses moq-transport's codes unchanged. Call `SessionCode(code)` - * to construct an application code in the 64+ range. {@link StreamCode} is the other registry, - * and the two are disjoint, so the same integer means different things in each. + * moq-lite's registry, which reuses moq-transport's value for each code the two share. Call + * `SessionCode(code)` to construct an application code in the 64+ range. {@link StreamCode} is + * the other registry, and the two are disjoint, so the same integer means different things in + * each. * * Codes 32-47 are reserved: nothing is sent there, and the draft gives a received one no - * meaning, so treat anything not listed below as an unspecified error rather than guessing. + * meaning. A code only moq-transport defines arrives as its number too, so treat anything not + * listed below as an unspecified error rather than guessing. * * @public */ @@ -39,32 +41,18 @@ export const SessionCode = Object.freeze( Expired: 0x18 as SessionCode, /** A protocol rule was broken; the session is unusable. */ ProtocolViolation: 0x3 as SessionCode, - /** A request ID was reused or violated the negotiated draft’s order or parity rules. */ - InvalidRequestId: 0x4 as SessionCode, - /** A key-value pair was malformed or repeated more than allowed. */ - KeyValueFormatting: 0x6 as SessionCode, /** The peer went past what the session allows: a request ID past MAX_REQUEST_ID, or too many announcements. */ TooManyRequests: 0x7 as SessionCode, - /** A PATH the peer may not send, such as a server sending one at all. */ - InvalidPath: 0x8 as SessionCode, /** The peer did not close within the GOAWAY drain deadline. */ GoawayTimeout: 0x10 as SessionCode, /** A control message took too long. */ Timeout: 0x11 as SessionCode, - /** A token registration would exceed the advertised token cache size, which is 0 when unadvertised. */ - AuthTokenCacheOverflow: 0x13 as SessionCode, /** No version could be negotiated. */ Version: 0x15 as SessionCode, /** The token could not be parsed. Retrying with the same token will fail again. */ MalformedAuthToken: 0x16 as SessionCode, - /** A token named an alias that was never registered. */ - UnknownAuthTokenAlias: 0x17 as SessionCode, - /** An AUTHORITY the peer may not send, such as a server sending one at all. */ - InvalidAuthority: 0x19 as SessionCode, - /** The peer cannot support the requested feature; moq-lite only. */ + /** The peer cannot support the requested feature, token, or grant. */ Unsupported: 0x30 as SessionCode, - /** The peer left more request updates unanswered than MAX_REQUEST_UPDATES allows. */ - TooManyRequestUpdates: 0x1b as SessionCode, } as const), ); @@ -410,6 +398,58 @@ function localStreamCode(err: unknown): StreamCode { return StreamCode.Internal; } +/** + * What a caller does after a request fails, as {@link retry} answers it. Mirrors the Rust `Retry`. + * + * @public + */ +export const Retry = Object.freeze({ + /** + * The source failed to deliver rather than judging the request, so asking it again may + * succeed: its connection dropped, its session ended, or it is going away. + */ + Same: "same", + /** + * The source lost its route to the content, so only another route continues it. Asking the + * same source again can only replace the withdrawal's cause with a refusal. + */ + Reroute: "reroute", + /** + * The answer judged the request or what it carried, so it repeats on every attempt: refused, + * not found, or malformed. + */ + Never: "never", +} as const); + +/** One of the {@link Retry} answers. @public */ +export type Retry = (typeof Retry)[keyof typeof Retry]; + +// Stream codes that report the source failing to deliver rather than judging what it carried. +const DELIVERY_FAILURES: ReadonlySet = new Set([ + StreamCode.Internal, + StreamCode.Cancel, + StreamCode.SessionClosed, + StreamCode.GoingAway, + StreamCode.ControlTimeout, +]); + +/** + * What to do after a request failed with `err`: ask the same source again, find another route, + * or give up. Mirrors the Rust `Error::retry`. + * + * A session closing, whatever its code, is the route failing to deliver: whether the session + * comes back is the connection's call, not the request's. + * + * @public + */ +export function retry(err: unknown): Retry { + if (err instanceof Stream) { + if (err.code === StreamCode.Unroutable) return Retry.Reroute; + return DELIVERY_FAILURES.has(err.code) ? Retry.Same : Retry.Never; + } + return err instanceof Session || sessionClosed(err) ? Retry.Same : Retry.Never; +} + /** * A group was created at a sequence its track declared skipped. * diff --git a/js/net/src/errors.ts b/js/net/src/errors.ts index 3e9157c1cec..2a441b47848 100644 --- a/js/net/src/errors.ts +++ b/js/net/src/errors.ts @@ -1,5 +1,5 @@ /** - * Session and stream error types. + * Session and stream error types, and what to do after one. * * @module */ @@ -10,6 +10,8 @@ export { NotFound, ProtocolViolation, RefusedRedirect, + Retry, + retry, Session, Skipped, Stream, diff --git a/js/net/src/ietf/connection.test.ts b/js/net/src/ietf/connection.test.ts index a4a6e7b3e0f..18d3a27a4b3 100644 --- a/js/net/src/ietf/connection.test.ts +++ b/js/net/src/ietf/connection.test.ts @@ -1,3 +1,4 @@ +import { IetfSessionCode } from "./error.ts"; import { expect, spyOn, test } from "bun:test"; import { yieldNow } from "@moq/clock"; import { offered } from "../connection/extensions.ts"; @@ -380,11 +381,11 @@ function updateWithTokens(...tokens: (readonly number[])[]): Uint8Array { */ for (const [version, alpn] of [[Version.DRAFT_22, ALPN.DRAFT_22]] as const) { for (const [name, token, code] of [ - ["REGISTER", [0x01, 0x07, 0x00], SessionCode.AuthTokenCacheOverflow], - ["DELETE", [0x00, 0x07], SessionCode.UnknownAuthTokenAlias], - ["USE_ALIAS", [0x02, 0x07], SessionCode.UnknownAuthTokenAlias], - ["USE_VALUE without a type", [0x03], SessionCode.KeyValueFormatting], - ["an unknown alias type", [0x04, 0x00], SessionCode.KeyValueFormatting], + ["REGISTER", [0x01, 0x07, 0x00], IetfSessionCode.AuthTokenCacheOverflow], + ["DELETE", [0x00, 0x07], IetfSessionCode.UnknownAuthTokenAlias], + ["USE_ALIAS", [0x02, 0x07], IetfSessionCode.UnknownAuthTokenAlias], + ["USE_VALUE without a type", [0x03], IetfSessionCode.KeyValueFormatting], + ["an unknown alias type", [0x04, 0x00], IetfSessionCode.KeyValueFormatting], ] as const) { test(`a request token with ${name} closes ${alpn}`, async () => { const logged = spyOn(console, "error").mockImplementation(() => void 0); @@ -418,10 +419,10 @@ for (const [version, alpn] of [[Version.DRAFT_22, ALPN.DRAFT_22]] as const) { */ for (const [version, alpn] of [[Version.DRAFT_22, ALPN.DRAFT_22]] as const) { for (const [name, token, code] of [ - ["REGISTER", [0x01, 0x07, 0x00], SessionCode.AuthTokenCacheOverflow], - ["DELETE", [0x00, 0x07], SessionCode.UnknownAuthTokenAlias], - ["USE_ALIAS", [0x02, 0x07], SessionCode.UnknownAuthTokenAlias], - ["USE_VALUE without a type", [0x03], SessionCode.KeyValueFormatting], + ["REGISTER", [0x01, 0x07, 0x00], IetfSessionCode.AuthTokenCacheOverflow], + ["DELETE", [0x00, 0x07], IetfSessionCode.UnknownAuthTokenAlias], + ["USE_ALIAS", [0x02, 0x07], IetfSessionCode.UnknownAuthTokenAlias], + ["USE_VALUE without a type", [0x03], IetfSessionCode.KeyValueFormatting], ] as const) { test(`an update token with ${name} closes ${alpn}`, async () => { const logged = spyOn(console, "error").mockImplementation(() => void 0); diff --git a/js/net/src/ietf/connection.ts b/js/net/src/ietf/connection.ts index b478adf752d..b2a529a3d6f 100644 --- a/js/net/src/ietf/connection.ts +++ b/js/net/src/ietf/connection.ts @@ -14,7 +14,7 @@ import { type Reader, Readers, type Stream } from "../stream.ts"; import { withTimeout } from "../util/timeout.ts"; import { registerWire } from "../wire.ts"; import * as Cluster from "./cluster.ts"; -import type { RequestKind } from "./error.ts"; +import { IetfSessionCode, type RequestKind } from "./error.ts"; import { Fetch, FetchHeader } from "./fetch.ts"; import { GoAway } from "./goaway.ts"; import * as Message from "./message.ts"; @@ -575,7 +575,7 @@ export class Connection implements Session { } if (msg.requestId !== undefined && msg.requestId % 2n !== (this.#client ? 0n : 1n)) { throw new ProtocolViolation("GOAWAY Request ID has the wrong parity", { - code: SessionCode.InvalidRequestId, + code: IetfSessionCode.InvalidRequestId, }); } // Reject bytes already behind GOAWAY before a caller can close on the drain. diff --git a/js/net/src/ietf/error.ts b/js/net/src/ietf/error.ts index 34fac9aea5d..8ac473ea3b6 100644 --- a/js/net/src/ietf/error.ts +++ b/js/net/src/ietf/error.ts @@ -8,8 +8,32 @@ * @module */ +import type { SessionCode } from "../error.ts"; import { type IetfVersion, Version } from "./version.ts"; +/** + * Session close codes only moq-transport defines. + * + * moq-lite assigns none of them, so {@link SessionCode} names none: this layer sends them, and + * one a peer sends reads back as its number. Mirrors the Rust `ietf::error::session` module. + * + * @internal + */ +export const IetfSessionCode = Object.freeze({ + /** A request ID was reused or broke the negotiated draft's order or parity rules. */ + InvalidRequestId: 0x4 as SessionCode, + /** A key-value pair was malformed or repeated more than allowed. */ + KeyValueFormatting: 0x6 as SessionCode, + /** A PATH the peer may not send, such as a server sending one at all. */ + InvalidPath: 0x8 as SessionCode, + /** A token registration would exceed the advertised token cache size, which is 0 when unadvertised. */ + AuthTokenCacheOverflow: 0x13 as SessionCode, + /** A token named an alias that was never registered. */ + UnknownAuthTokenAlias: 0x17 as SessionCode, + /** An AUTHORITY the peer may not send, such as a server sending one at all. */ + InvalidAuthority: 0x19 as SessionCode, +} as const); + /** * Whether `code` means the same thing in the moq-transport stream reset registry as it does * in moq-lite's. diff --git a/js/net/src/ietf/malformed.test.ts b/js/net/src/ietf/malformed.test.ts index 398d447804b..9d34d65129b 100644 --- a/js/net/src/ietf/malformed.test.ts +++ b/js/net/src/ietf/malformed.test.ts @@ -1,3 +1,4 @@ +import { IetfSessionCode } from "./error.ts"; import { expect, spyOn, test } from "bun:test"; import { Duration } from "@moq/clock"; import type { Manual } from "@moq/clock/test"; @@ -108,7 +109,7 @@ function goaways(count: number, version: IetfVersion, requestId?: number): Uint8 for (const [version, alpn] of DRAFTS) { for (const [name, bytes, code] of [ - ["a wrong-parity Request ID", subscribe([field(4)], 5, 1), SessionCode.InvalidRequestId], + ["a wrong-parity Request ID", subscribe([field(4)], 5, 1), IetfSessionCode.InvalidRequestId], ["an empty namespace field", subscribe([field(0)], 5), SessionCode.ProtocolViolation], ["a namespace over 4096 bytes", subscribe([field(4097)], 1), SessionCode.ProtocolViolation], ["a full track name over 4096 bytes", subscribe([field(4000)], 97), SessionCode.ProtocolViolation], @@ -258,9 +259,9 @@ for (const [version, alpn] of DRAFTS) { // A server sends neither PATH nor AUTHORITY, and a token that cannot be decoded closes. for (const [name, key, value, code] of [ - ["PATH", SetupOption.Path, [0x2f], SessionCode.InvalidPath], - ["AUTHORITY", SetupOption.Authority, [0x61], SessionCode.InvalidAuthority], - ["a malformed token", SetupOption.AuthorizationToken, [0x04], SessionCode.KeyValueFormatting], + ["PATH", SetupOption.Path, [0x2f], IetfSessionCode.InvalidPath], + ["AUTHORITY", SetupOption.Authority, [0x61], IetfSessionCode.InvalidAuthority], + ["a malformed token", SetupOption.AuthorizationToken, [0x04], IetfSessionCode.KeyValueFormatting], ["a REGISTER token", SetupOption.AuthorizationToken, [0x01, 0x07, 0x00], undefined], ] as const) { test(`a server SETUP with ${name} ${code === undefined ? "is accepted" : "closes"} ${alpn}`, async () => { @@ -288,8 +289,8 @@ for (const [version, alpn] of DRAFTS) { for (const [requestId, code] of [ [0, undefined], [4, undefined], - [1, SessionCode.InvalidRequestId], - [5, SessionCode.InvalidRequestId], + [1, IetfSessionCode.InvalidRequestId], + [5, IetfSessionCode.InvalidRequestId], [undefined, SessionCode.ProtocolViolation], ] as const) { const name = requestId === undefined ? "without a Request ID" : `Request ID ${requestId}`; diff --git a/js/net/src/ietf/request_ids.test.ts b/js/net/src/ietf/request_ids.test.ts index efa71f65058..694ebd67969 100644 --- a/js/net/src/ietf/request_ids.test.ts +++ b/js/net/src/ietf/request_ids.test.ts @@ -1,3 +1,4 @@ +import { IetfSessionCode } from "./error.ts"; import { describe, expect, test } from "bun:test"; import { SessionCode, SessionError } from "../error.ts"; import { checkPeerRequestId } from "./session.ts"; @@ -16,11 +17,11 @@ describe("peer request IDs", () => { test.each([false, true])("accept any order and reuse, but only the peer's parity, client=%s", (client) => { const first = client ? 1n : 0n; for (const offset of [4n, 0n, 2n, 4n]) expect(code(first + offset, client)).toBeUndefined(); - expect(code(first ^ 1n, client)).toBe(SessionCode.InvalidRequestId); + expect(code(first ^ 1n, client)).toBe(IetfSessionCode.InvalidRequestId); }); test("IDs past 2^62 are refused", () => { expect(code((1n << 62n) - 2n, false)).toBeUndefined(); - for (const id of [1n << 62n, (1n << 64n) - 2n]) expect(code(id, false)).toBe(SessionCode.InvalidRequestId); + for (const id of [1n << 62n, (1n << 64n) - 2n]) expect(code(id, false)).toBe(IetfSessionCode.InvalidRequestId); }); }); diff --git a/js/net/src/ietf/session.ts b/js/net/src/ietf/session.ts index 39a461a1bd1..82159ff0190 100644 --- a/js/net/src/ietf/session.ts +++ b/js/net/src/ietf/session.ts @@ -1,3 +1,4 @@ +import { IetfSessionCode } from "./error.ts"; import { SessionCode, SessionError } from "../error.ts"; import { type OpenOptions, Stream } from "../stream.ts"; import type { IetfVersion } from "./version.ts"; @@ -80,5 +81,5 @@ export class NativeSession implements Session { */ export function checkPeerRequestId(id: bigint, client: boolean): void { // No peer reaches 2^62 requests; refusing past it matches moq-net, whose counter would overflow. - if (id >= 1n << 62n || id % 2n !== (client ? 1n : 0n)) throw new SessionError(SessionCode.InvalidRequestId); + if (id >= 1n << 62n || id % 2n !== (client ? 1n : 0n)) throw new SessionError(IetfSessionCode.InvalidRequestId); } diff --git a/js/net/src/ietf/token.test.ts b/js/net/src/ietf/token.test.ts index c6cacfcc65b..e9ba6b90764 100644 --- a/js/net/src/ietf/token.test.ts +++ b/js/net/src/ietf/token.test.ts @@ -1,3 +1,4 @@ +import { IetfSessionCode } from "./error.ts"; import { expect, test } from "bun:test"; import { ProtocolViolation, SessionCode } from "../error.ts"; import { Reader, Writer } from "../stream.ts"; @@ -124,7 +125,7 @@ test("a SETUP alias reference is a protocol violation", () => { test("an undecodable structure is a formatting error", () => { for (const fields of [[], [0x3n], [0x1n], [0x1n, 7n], [0x0n], [0x2n], [0x4n, 0n]]) { const params = structure(fields); - expect(sessionCode(() => tokenFromSetup(params))).toBe(SessionCode.KeyValueFormatting); + expect(sessionCode(() => tokenFromSetup(params))).toBe(IetfSessionCode.KeyValueFormatting); } }); @@ -148,13 +149,13 @@ test("a request token by value decodes", () => { /** Only SETUP falls back to a value: on a request, a registration overflows the cache. */ test("a request registration overflows the cache", () => { const token = raw([0x1n, 7n, TOKEN.kind], TOKEN.value); - expect(sessionCode(() => tokenFromRequest(token))).toBe(SessionCode.AuthTokenCacheOverflow); + expect(sessionCode(() => tokenFromRequest(token))).toBe(IetfSessionCode.AuthTokenCacheOverflow); }); test("a request alias reference is an unknown alias", () => { for (const aliasType of [0x0n, 0x2n]) { const token = raw([aliasType, 7n]); - expect(sessionCode(() => tokenFromRequest(token))).toBe(SessionCode.UnknownAuthTokenAlias); + expect(sessionCode(() => tokenFromRequest(token))).toBe(IetfSessionCode.UnknownAuthTokenAlias); } }); @@ -163,6 +164,6 @@ test("an undecodable request token is a formatting error", () => { // carrying a token type. for (const fields of [[], [0x3n], [0x1n], [0x1n, 7n], [0x0n], [0x2n], [0x2n, 7n, 0n], [0x4n, 0n]]) { const token = raw(fields); - expect(sessionCode(() => tokenFromRequest(token))).toBe(SessionCode.KeyValueFormatting); + expect(sessionCode(() => tokenFromRequest(token))).toBe(IetfSessionCode.KeyValueFormatting); } }); diff --git a/js/net/src/ietf/token.ts b/js/net/src/ietf/token.ts index 8d4cd98b223..eca52bd0da2 100644 --- a/js/net/src/ietf/token.ts +++ b/js/net/src/ietf/token.ts @@ -1,3 +1,4 @@ +import { IetfSessionCode } from "./error.ts"; import { ProtocolViolation, SessionCode } from "../error.ts"; import * as Varint from "../varint.ts"; import type { Parameters } from "./parameters.ts"; @@ -122,7 +123,7 @@ export function tokenFromRequest(raw: Uint8Array): Token { function decode(raw: Uint8Array, setup: boolean): Token { // Section 8.9: a structure that cannot be decoded closes with KEY_VALUE_FORMATTING_ERROR. const malformed = (cause?: unknown) => - new ProtocolViolation("malformed AUTHORIZATION TOKEN", { cause, code: SessionCode.KeyValueFormatting }); + new ProtocolViolation("malformed AUTHORIZATION TOKEN", { cause, code: IetfSessionCode.KeyValueFormatting }); const unvarint = (buf: Uint8Array): [bigint, Uint8Array] => { try { return Varint.decodeLeadingOnes(buf); @@ -144,7 +145,7 @@ function decode(raw: Uint8Array, setup: boolean): Token { if (!setup) { unvarint(rest); throw new ProtocolViolation("AUTHORIZATION TOKEN registration", { - code: SessionCode.AuthTokenCacheOverflow, + code: IetfSessionCode.AuthTokenCacheOverflow, }); } break; @@ -158,7 +159,7 @@ function decode(raw: Uint8Array, setup: boolean): Token { // Section 8.9 rejects the message, but 0x17 is only a session code (section 12.2), // so the session closes; doc/concept/standard.md records the deviation. throw new ProtocolViolation("unknown AUTHORIZATION TOKEN alias", { - code: SessionCode.UnknownAuthTokenAlias, + code: IetfSessionCode.UnknownAuthTokenAlias, }); } default: diff --git a/js/net/src/resume.ts b/js/net/src/resume.ts index ac9a55e89f7..1b323c52db7 100644 --- a/js/net/src/resume.ts +++ b/js/net/src/resume.ts @@ -49,7 +49,7 @@ import { Duration, Instant, now, sleepUntil } from "@moq/clock"; import { type Dispose, type Getter, race, Signal } from "@moq/signals"; import * as broadcast from "./broadcast.ts"; import { Delivered } from "./delivered.ts"; -import { NotFound, SessionError, StreamCode, StreamError, sessionClosed } from "./error.ts"; +import { NotFound, Retry, retry, SessionError, StreamCode, StreamError, sessionClosed } from "./error.ts"; import type { Consumer as GroupConsumer } from "./group.ts"; import { type DropRun, @@ -74,17 +74,6 @@ import { max, min, UNBOUNDED } from "./util/sequence.ts"; import { clamped, type Resolved, type Window } from "./window.ts"; import { type Broadcast as BroadcastWire, registerWire, wireOf } from "./wire.ts"; -// Stream codes that report the route failing to deliver rather than judging what it carried: -// another copy may still deliver what it failed. Mirrors the Rust `Error::retryable`. -const ROUTE_FAILURES: ReadonlySet = new Set([ - StreamCode.Internal, - StreamCode.Cancel, - StreamCode.SessionClosed, - StreamCode.GoingAway, - StreamCode.ControlTimeout, - StreamCode.Unroutable, -]); - /** A copy claiming the same content with different metadata: refused rather than reinterpreted. */ class Incompatible extends Error { constructor(name: string) { @@ -95,14 +84,12 @@ class Incompatible extends Error { /** * Whether `err` is the route failing to deliver rather than judging what it carried, so a new copy - * may fix it: its session closed or failed underneath it, or a delivery code. Anything else would - * repeat on every copy. + * may fix it. Mirrors the Rust `Error::retryable`. * * @internal */ export function routeFailed(err: Error): boolean { - if (err instanceof StreamError) return ROUTE_FAILURES.has(err.code); - return err instanceof SessionError || sessionClosed(err); + return retry(err) !== Retry.Never; } // Whether `err` from `source` judges its route rather than the track: a received route that lost @@ -119,11 +106,10 @@ function closing(err: Error): boolean { return err instanceof SessionError || sessionClosed(err); } -// A source losing its route to the content: only another route continues it, since asking the -// same one again could only replace the withdrawal's cause with a refusal. Mirrors the Rust +// A source losing its route to the content: only another route continues it. Mirrors the Rust // `Error::unroutable`. function unroutable(err: Error): boolean { - return err instanceof StreamError && err.code === StreamCode.Unroutable; + return retry(err) === Retry.Reroute; } // A copy's delivery failure says nothing about its content. A terminal track verdict does. diff --git a/js/watch/src/broadcast.ts b/js/watch/src/broadcast.ts index f86aa9e62ac..1bbf4163b61 100644 --- a/js/watch/src/broadcast.ts +++ b/js/watch/src/broadcast.ts @@ -2,7 +2,7 @@ import * as Catalog from "@moq/hang/catalog"; import * as Json from "@moq/json"; import * as Msf from "@moq/msf"; import type * as Moq from "@moq/net"; -import { Instance, Error as NetError, Path, StreamCode, Track } from "@moq/net"; +import { Instance, Error as NetError, Path, Track } from "@moq/net"; import { Derived, Effect, @@ -544,9 +544,9 @@ export class Broadcast { const closed = nested.get(request.closed); if (!closed) return; // A follower outlives its instances, so only a refusal ends it. A plain request - // ends with its accepted instance, which reads as offline rather than an error. - const offline = - !follow && resolved && closed instanceof NetError.Stream && closed.code === StreamCode.Unroutable; + // ends with its accepted instance losing its route, which reads as offline rather + // than an error. + const offline = !follow && resolved && NetError.retry(closed) === NetError.Retry.Reroute; if (!offline) nested.set(this.#out.error, closed, undefined); }); } diff --git a/rs/moq-c/src/error.rs b/rs/moq-c/src/error.rs index 55435dcf6fc..e2c101f7344 100644 --- a/rs/moq-c/src/error.rs +++ b/rs/moq-c/src/error.rs @@ -114,15 +114,13 @@ pub enum moq_protocol_kind { MOQ_PROTOCOL_KIND_UNAUTHORIZED = 2, /// Protocol violation. MOQ_PROTOCOL_KIND_PROTOCOL_VIOLATION = 3, - /// Key value formatting. - MOQ_PROTOCOL_KIND_KEY_VALUE_FORMATTING = 4, /// Goaway timeout. MOQ_PROTOCOL_KIND_GOAWAY_TIMEOUT = 5, /// Timeout. MOQ_PROTOCOL_KIND_TIMEOUT = 6, /// Version. MOQ_PROTOCOL_KIND_VERSION = 7, - // 8 through 10 are unassigned; the values that follow stay put for compiled consumers. + // 4 and 8 through 10 are unassigned; the values that follow stay put for compiled consumers. /// Delivery timeout. MOQ_PROTOCOL_KIND_DELIVERY_TIMEOUT = 11, /// Session closed. @@ -155,20 +153,8 @@ pub enum moq_protocol_kind { MOQ_PROTOCOL_KIND_TOO_MANY_REQUESTS = 25, /// The authorization token expired and can be refreshed. MOQ_PROTOCOL_KIND_EXPIRED = 26, - /// A token registration exceeded the advertised cache size. - MOQ_PROTOCOL_KIND_AUTH_TOKEN_CACHE_OVERFLOW = 27, /// The peer could not parse an authorization token. MOQ_PROTOCOL_KIND_MALFORMED_AUTH_TOKEN = 28, - /// A token referred to an alias that was never registered. - MOQ_PROTOCOL_KIND_UNKNOWN_AUTH_TOKEN_ALIAS = 29, - /// The peer reused or sent an invalid request ID. - MOQ_PROTOCOL_KIND_INVALID_REQUEST_ID = 30, - /// The peer sent a path it may not send. - MOQ_PROTOCOL_KIND_INVALID_PATH = 31, - /// The peer sent an authority it may not send. - MOQ_PROTOCOL_KIND_INVALID_AUTHORITY = 32, - /// The peer exceeded its outstanding request update limit. - MOQ_PROTOCOL_KIND_TOO_MANY_REQUEST_UPDATES = 33, } /// A protocol failure a peer sent: scope, verbatim wire code, and recognized kind. @@ -457,18 +443,11 @@ fn session_kind(err: &moq_net::SessionError) -> moq_protocol_kind { moq_net::SessionError::Unauthorized => MOQ_PROTOCOL_KIND_UNAUTHORIZED, moq_net::SessionError::Expired => MOQ_PROTOCOL_KIND_EXPIRED, moq_net::SessionError::ProtocolViolation => MOQ_PROTOCOL_KIND_PROTOCOL_VIOLATION, - moq_net::SessionError::KeyValueFormatting => MOQ_PROTOCOL_KIND_KEY_VALUE_FORMATTING, moq_net::SessionError::GoawayTimeout => MOQ_PROTOCOL_KIND_GOAWAY_TIMEOUT, moq_net::SessionError::Timeout => MOQ_PROTOCOL_KIND_TIMEOUT, moq_net::SessionError::Version => MOQ_PROTOCOL_KIND_VERSION, moq_net::SessionError::TooManyRequests => MOQ_PROTOCOL_KIND_TOO_MANY_REQUESTS, - moq_net::SessionError::AuthTokenCacheOverflow => MOQ_PROTOCOL_KIND_AUTH_TOKEN_CACHE_OVERFLOW, moq_net::SessionError::MalformedAuthToken => MOQ_PROTOCOL_KIND_MALFORMED_AUTH_TOKEN, - moq_net::SessionError::UnknownAuthTokenAlias => MOQ_PROTOCOL_KIND_UNKNOWN_AUTH_TOKEN_ALIAS, - moq_net::SessionError::InvalidRequestId => MOQ_PROTOCOL_KIND_INVALID_REQUEST_ID, - moq_net::SessionError::InvalidPath => MOQ_PROTOCOL_KIND_INVALID_PATH, - moq_net::SessionError::InvalidAuthority => MOQ_PROTOCOL_KIND_INVALID_AUTHORITY, - moq_net::SessionError::TooManyRequestUpdates => MOQ_PROTOCOL_KIND_TOO_MANY_REQUEST_UPDATES, moq_net::SessionError::App(_) => MOQ_PROTOCOL_KIND_APP, moq_net::SessionError::Unknown(_) => MOQ_PROTOCOL_KIND_UNKNOWN, _ => MOQ_PROTOCOL_KIND_UNKNOWN, @@ -597,19 +576,20 @@ mod tests { (0x1, MOQ_PROTOCOL_KIND_INTERNAL), (0x2, MOQ_PROTOCOL_KIND_UNAUTHORIZED), (0x3, MOQ_PROTOCOL_KIND_PROTOCOL_VIOLATION), - (0x4, MOQ_PROTOCOL_KIND_INVALID_REQUEST_ID), - (0x6, MOQ_PROTOCOL_KIND_KEY_VALUE_FORMATTING), (0x7, MOQ_PROTOCOL_KIND_TOO_MANY_REQUESTS), - (0x8, MOQ_PROTOCOL_KIND_INVALID_PATH), (0x10, MOQ_PROTOCOL_KIND_GOAWAY_TIMEOUT), (0x11, MOQ_PROTOCOL_KIND_TIMEOUT), - (0x13, MOQ_PROTOCOL_KIND_AUTH_TOKEN_CACHE_OVERFLOW), (0x15, MOQ_PROTOCOL_KIND_VERSION), (0x16, MOQ_PROTOCOL_KIND_MALFORMED_AUTH_TOKEN), - (0x17, MOQ_PROTOCOL_KIND_UNKNOWN_AUTH_TOKEN_ALIAS), (0x18, MOQ_PROTOCOL_KIND_EXPIRED), - (0x19, MOQ_PROTOCOL_KIND_INVALID_AUTHORITY), - (0x1b, MOQ_PROTOCOL_KIND_TOO_MANY_REQUEST_UPDATES), + // Only moq-transport defines these, so they are no kind of ours. + (0x4, MOQ_PROTOCOL_KIND_UNKNOWN), + (0x6, MOQ_PROTOCOL_KIND_UNKNOWN), + (0x8, MOQ_PROTOCOL_KIND_UNKNOWN), + (0x13, MOQ_PROTOCOL_KIND_UNKNOWN), + (0x17, MOQ_PROTOCOL_KIND_UNKNOWN), + (0x19, MOQ_PROTOCOL_KIND_UNKNOWN), + (0x1b, MOQ_PROTOCOL_KIND_UNKNOWN), ] { let error = super::from_session(&moq_net::SessionError::from_code(code)); assert_eq!(error.scope, super::moq_error_scope::MOQ_ERROR_SCOPE_SESSION as u32); diff --git a/rs/moq-ffi/src/error.rs b/rs/moq-ffi/src/error.rs index 8c802b63ea2..5a36fb25b87 100644 --- a/rs/moq-ffi/src/error.rs +++ b/rs/moq-ffi/src/error.rs @@ -29,8 +29,6 @@ pub enum MoqProtocolKind { Unauthorized, /// The peer broke a protocol rule; the session is unusable. ProtocolViolation, - /// A key-value pair was malformed or repeated more than allowed. - KeyValueFormatting, /// The peer did not close within the GOAWAY drain deadline. GoawayTimeout, /// A control message took too long. @@ -67,20 +65,8 @@ pub enum MoqProtocolKind { TooManyRequests, /// The authorization token expired and can be refreshed. Session 0x18. Expired, - /// A token registration exceeded the advertised cache size. - AuthTokenCacheOverflow, /// The peer could not parse an authorization token. MalformedAuthToken, - /// A token referred to an alias that was never registered. - UnknownAuthTokenAlias, - /// The peer reused or sent an invalid request ID. - InvalidRequestId, - /// The peer sent a path it may not send. - InvalidPath, - /// The peer sent an authority it may not send. - InvalidAuthority, - /// The peer exceeded its outstanding request update limit. - TooManyRequestUpdates, } /// A protocol failure a peer sent (or this side will send): scope, verbatim code, kind, @@ -134,18 +120,11 @@ fn session_kind(err: &moq_net::SessionError) -> MoqProtocolKind { moq_net::SessionError::Unauthorized => MoqProtocolKind::Unauthorized, moq_net::SessionError::Expired => MoqProtocolKind::Expired, moq_net::SessionError::ProtocolViolation => MoqProtocolKind::ProtocolViolation, - moq_net::SessionError::KeyValueFormatting => MoqProtocolKind::KeyValueFormatting, moq_net::SessionError::GoawayTimeout => MoqProtocolKind::GoawayTimeout, moq_net::SessionError::Timeout => MoqProtocolKind::Timeout, moq_net::SessionError::Version => MoqProtocolKind::Version, moq_net::SessionError::TooManyRequests => MoqProtocolKind::TooManyRequests, - moq_net::SessionError::AuthTokenCacheOverflow => MoqProtocolKind::AuthTokenCacheOverflow, moq_net::SessionError::MalformedAuthToken => MoqProtocolKind::MalformedAuthToken, - moq_net::SessionError::UnknownAuthTokenAlias => MoqProtocolKind::UnknownAuthTokenAlias, - moq_net::SessionError::InvalidRequestId => MoqProtocolKind::InvalidRequestId, - moq_net::SessionError::InvalidPath => MoqProtocolKind::InvalidPath, - moq_net::SessionError::InvalidAuthority => MoqProtocolKind::InvalidAuthority, - moq_net::SessionError::TooManyRequestUpdates => MoqProtocolKind::TooManyRequestUpdates, moq_net::SessionError::App(_) => MoqProtocolKind::App, moq_net::SessionError::Unknown(_) => MoqProtocolKind::Unknown, _ => MoqProtocolKind::Unknown, @@ -565,19 +544,12 @@ mod tests { (0x1, MoqProtocolKind::Internal), (0x2, MoqProtocolKind::Unauthorized), (0x3, MoqProtocolKind::ProtocolViolation), - (0x4, MoqProtocolKind::InvalidRequestId), - (0x6, MoqProtocolKind::KeyValueFormatting), (0x7, MoqProtocolKind::TooManyRequests), - (0x8, MoqProtocolKind::InvalidPath), (0x10, MoqProtocolKind::GoawayTimeout), (0x11, MoqProtocolKind::Timeout), - (0x13, MoqProtocolKind::AuthTokenCacheOverflow), (0x15, MoqProtocolKind::Version), (0x16, MoqProtocolKind::MalformedAuthToken), - (0x17, MoqProtocolKind::UnknownAuthTokenAlias), (0x18, MoqProtocolKind::Expired), - (0x19, MoqProtocolKind::InvalidAuthority), - (0x1b, MoqProtocolKind::TooManyRequestUpdates), ] { let error = MoqProtocolError::from_session(&moq_net::SessionError::from_code(code)); assert_eq!(error.scope, MoqErrorScope::Session); @@ -586,6 +558,17 @@ mod tests { } } + /// A code only moq-transport defines is no kind of ours, and keeps its number. + #[test] + fn moq_transport_session_codes_are_unknown() { + for code in [0x4, 0x6, 0x8, 0x13, 0x17, 0x19, 0x1b] { + let error = MoqProtocolError::from_session(&moq_net::SessionError::from_code(code)); + assert_eq!(error.scope, MoqErrorScope::Session); + assert_eq!(error.code, code); + assert_eq!(error.kind, MoqProtocolKind::Unknown, "session code {code:#x}"); + } + } + #[test] fn session_limit_has_a_known_kind() { let error = super::MoqProtocolError::from_session(&moq_net::SessionError::TooManyRequests); diff --git a/rs/moq-gst/src/source/imp.rs b/rs/moq-gst/src/source/imp.rs index 7bc52c4ebca..fbfb24b8ed7 100644 --- a/rs/moq-gst/src/source/imp.rs +++ b/rs/moq-gst/src/source/imp.rs @@ -1029,23 +1029,10 @@ impl Session { } /// Whether a failure is the source going away (its session closing, or its route going), which -/// holds the pads for the next start. A refusal is not: no restart answers a path that names -/// nothing or a token that doesn't grant it, so it fails the session, as a malformed catalog does. +/// holds the pads for the next start. A verdict is not: no restart answers a path that names +/// nothing, a token that doesn't grant it, or malformed content, so it fails the session. fn source_lost(err: &moq_net::Error) -> bool { - if matches!(err, moq_net::Error::NotFound | moq_net::Error::Unauthorized) { - return false; - } - let code = match err { - moq_net::Error::Stream(moq_net::StreamError::Session(code)) => code.clone(), - _ => moq_net::SessionError::from(err), - }; - !matches!( - code, - moq_net::SessionError::Unauthorized - | moq_net::SessionError::ProtocolViolation - | moq_net::SessionError::KeyValueFormatting - | moq_net::SessionError::InvalidRequestId - ) + err.retry() != moq_net::Retry::Never } /// [`source_lost`] for a catalog read, where anything but a transport failure is malformed. @@ -2594,20 +2581,28 @@ mod session_tests { }) } + /// A refusal or malformed input fails the session, wherever it was judged. A session ending, + /// whatever its code, is the source going away: the connection decides whether it returns. #[test] - fn malformed_input_is_not_a_lost_source() { + fn a_verdict_is_not_a_lost_source() { for err in [ moq_net::Error::ProtocolViolation, moq_net::Error::WrongSize, - moq_net::Error::Session(moq_net::SessionError::ProtocolViolation), - moq_net::Error::Session(moq_net::SessionError::KeyValueFormatting), + moq_net::Error::NotFound, + moq_net::Error::Unauthorized, + moq_net::Error::Stream(moq_net::StreamError::NotFound), + moq_net::Error::Stream(moq_net::StreamError::Unauthorized), + moq_net::Error::Stream(moq_net::StreamError::MalformedTrack), ] { assert!(!super::source_lost(&err), "{err:?}"); } for err in [ moq_net::Error::Closed, - moq_net::Error::Stream(moq_net::StreamError::Session(moq_net::SessionError::Cancel)), moq_net::Error::Cancel, + moq_net::Error::Unroutable, + moq_net::Error::Stream(moq_net::StreamError::Session(moq_net::SessionError::Cancel)), + moq_net::Error::Session(moq_net::SessionError::ProtocolViolation), + moq_net::Error::Session(moq_net::SessionError::from_code(0x6)), ] { assert!(super::source_lost(&err), "{err:?}"); } diff --git a/rs/moq-net/src/coding/codes.rs b/rs/moq-net/src/coding/codes.rs index 59f74bf43dd..013231339e3 100644 --- a/rs/moq-net/src/coding/codes.rs +++ b/rs/moq-net/src/coding/codes.rs @@ -46,10 +46,6 @@ pub trait StreamCodes { /// moq-lite's registry, specified by draft-lcurley-moq-lite (Error Codes). A code a version /// lacks is sent there as the closest one it has, and not read back there. impl StreamCodes for lite::Version { - fn decode_session_code(&self, code: u32) -> crate::SessionError { - lite::error::from_session_code(code) - } - fn encode_stream_code(&self, err: &StreamError) -> u32 { err.to_code() } @@ -61,6 +57,10 @@ impl StreamCodes for lite::Version { /// moq-transport's registry. impl StreamCodes for ietf::Version { + fn decode_session_code(&self, code: u32) -> crate::SessionError { + ietf::error::from_session_code(code) + } + fn encode_stream_code(&self, err: &StreamError) -> u32 { ietf::error::to_stream_code(err) } diff --git a/rs/moq-net/src/error.rs b/rs/moq-net/src/error.rs index 7690a5e522a..0cef3f15a65 100644 --- a/rs/moq-net/src/error.rs +++ b/rs/moq-net/src/error.rs @@ -2,14 +2,14 @@ use crate::coding; /// A code sent when terminating the session. /// -/// One of the two wire registries specified by moq-lite, which reuse moq-transport's codes -/// unchanged; 64+ are the application's. The stream registry is [`StreamError`] and the two +/// moq-lite's session registry, which reuses moq-transport's value for each code the two +/// share; 64+ are the application's. The stream registry is [`StreamError`] and the two /// are disjoint, so the same integer means different things in each. /// -/// Shared codes round-trip through [`to_code`](Self::to_code) and -/// [`from_code`](Self::from_code). Protocol drivers translate Lite-only variants at -/// their wire boundary; the shared decoder keeps those numbers [`Unknown`](Self::Unknown). -/// Codes 32 through 47 are reserved and have no assigned meaning. +/// Every variant is a code moq-lite assigns, and round-trips through +/// [`to_code`](Self::to_code) and [`from_code`](Self::from_code). A code moq-lite does not +/// assign, including those only moq-transport defines, is [`Unknown`](Self::Unknown) with +/// its number. Codes 32 through 47 are reserved and have no assigned meaning. #[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)] #[non_exhaustive] pub enum SessionError { @@ -34,10 +34,6 @@ pub enum SessionError { #[error("protocol violation")] ProtocolViolation, - /// A key-value pair was malformed or repeated more than allowed. - #[error("key-value formatting error")] - KeyValueFormatting, - /// The peer went past what the session allows, such as more announcements than its /// `crate::session::Limits`. #[error("too many requests")] @@ -51,11 +47,6 @@ pub enum SessionError { #[error("control message timeout")] Timeout, - /// A token registration would exceed the advertised `MAX_AUTH_TOKEN_CACHE_SIZE`, which is - /// 0 when unadvertised. - #[error("auth token cache overflow")] - AuthTokenCacheOverflow, - /// No version could be negotiated. #[error("version negotiation failed")] Version, @@ -64,42 +55,22 @@ pub enum SessionError { #[error("malformed auth token")] MalformedAuthToken, - /// A token named an alias that was never registered. - #[error("unknown auth token alias")] - UnknownAuthTokenAlias, - - /// The peer left more unacknowledged REQUEST_UPDATEs outstanding on one request stream - /// than the MAX_REQUEST_UPDATES it was advertised (draft-22 section 9.1.7). - #[error("too many request updates")] - TooManyRequestUpdates, - /// An application-chosen code, offset into the 64+ range on the wire. #[error("app code={0}")] App(u16), - /// A code this version does not recognize, kept verbatim. + /// A code moq-lite does not assign, kept verbatim: one this version does not recognize, + /// or one only moq-transport defines. #[error("unknown code={0}")] Unknown(u32), - /// The peer cannot support the requested feature; moq-lite only. + /// The peer cannot support the requested feature, token, or grant. #[error("not supported")] Unsupported, - - /// A request ID was reused or violated the negotiated draft’s order or parity rules. - #[error("invalid request id")] - InvalidRequestId, - - /// The peer sent a PATH it may not send, such as a server sending one at all. - #[error("invalid path")] - InvalidPath, - - /// The peer sent an AUTHORITY it may not send, such as a server sending one at all. - #[error("invalid authority")] - InvalidAuthority, } impl SessionError { - /// The shared session code; Lite-only conditions fall back to an internal error. + /// The code moq-lite sends for this error. pub fn to_code(&self) -> u32 { match self { Self::Cancel => 0x0, @@ -107,29 +78,23 @@ impl SessionError { Self::Unauthorized => 0x2, Self::Expired => 0x18, Self::ProtocolViolation => 0x3, - Self::InvalidRequestId => 0x4, - Self::KeyValueFormatting => 0x6, Self::TooManyRequests => 0x7, - Self::InvalidPath => 0x8, Self::GoawayTimeout => 0x10, Self::Timeout => 0x11, - Self::AuthTokenCacheOverflow => 0x13, Self::Version => 0x15, Self::MalformedAuthToken => 0x16, - Self::UnknownAuthTokenAlias => 0x17, - Self::InvalidAuthority => 0x19, - Self::Unsupported => 0x1, - Self::TooManyRequestUpdates => 0x1B, + Self::Unsupported => 0x30, Self::App(app) => *app as u32 + 64, Self::Unknown(code) => *code, } } - /// Decode a shared session code, leaving protocol-specific codes unknown. + /// Decode a code from moq-lite's registry. /// /// Unlike a raw peer code, the registered ones are specified, so decoding them is a /// wire contract rather than an assumption. Anything unregistered stays - /// [`Self::Unknown`], including the reserved 32-47. + /// [`Self::Unknown`], including the reserved 32-47 and the codes only moq-transport + /// defines. pub fn from_code(code: u32) -> Self { match code { 0x0 => Self::Cancel, @@ -137,18 +102,12 @@ impl SessionError { 0x2 => Self::Unauthorized, 0x18 => Self::Expired, 0x3 => Self::ProtocolViolation, - 0x4 => Self::InvalidRequestId, - 0x6 => Self::KeyValueFormatting, 0x7 => Self::TooManyRequests, - 0x8 => Self::InvalidPath, 0x10 => Self::GoawayTimeout, 0x11 => Self::Timeout, - 0x13 => Self::AuthTokenCacheOverflow, 0x15 => Self::Version, 0x16 => Self::MalformedAuthToken, - 0x17 => Self::UnknownAuthTokenAlias, - 0x19 => Self::InvalidAuthority, - 0x1B => Self::TooManyRequestUpdates, + 0x30 => Self::Unsupported, code @ 64.. => match u16::try_from(code - 64) { Ok(app) => Self::App(app), Err(_) => Self::Unknown(code), @@ -604,42 +563,66 @@ impl Error { } } - /// Whether asking again may succeed: the route failed to deliver rather than judging what - /// it carried, which would repeat on every attempt. Mirrors `routeFailed` in - /// `js/net/src/resume.ts`. + /// What to do after a request failed with this error: ask the same source again, find + /// another route, or give up. Mirrors `retry` in `js/net/src/error.ts`. + /// + /// A session closing, whatever its code, is the route failing to deliver: whether the + /// session comes back is the connection's call, not the request's. + pub fn retry(&self) -> Retry { + match self { + Self::Unroutable | Self::Stream(StreamError::Unroutable) => Retry::Reroute, + Self::Transport(_) + | Self::IdleTimeout + | Self::Session(_) + | Self::GoingAway + | Self::GoawayTimeout + | Self::Dropped + | Self::Closed + | Self::Cancel + | Self::Stream( + StreamError::Session(_) + | StreamError::Internal + | StreamError::Cancel + | StreamError::GoingAway + | StreamError::ControlTimeout, + ) => Retry::Same, + _ => Retry::Never, + } + } + + /// Whether asking again may succeed, on this route or another. pub(crate) fn retryable(&self) -> bool { - self.unroutable() || self.transient() + self.retry() != Retry::Never } /// Whether a source lost its route to the content: only another route continues it. pub(crate) fn unroutable(&self) -> bool { - matches!(self, Self::Unroutable | Self::Stream(StreamError::Unroutable)) + self.retry() == Retry::Reroute } - /// Whether the same source may deliver a fresh copy. An unroutable source needs a new - /// route instead: asking it again can replace the withdrawal's cause with a refusal. + /// Whether the same source may deliver a fresh copy. pub(crate) fn transient(&self) -> bool { - matches!( - self, - Self::Transport(_) - | Self::IdleTimeout - | Self::Session(_) - | Self::GoingAway - | Self::GoawayTimeout - | Self::Dropped - | Self::Closed - | Self::Cancel - | Self::Stream( - StreamError::Session(_) - | StreamError::Internal - | StreamError::Cancel - | StreamError::GoingAway - | StreamError::ControlTimeout - ) - ) + self.retry() == Retry::Same } } +/// What a caller does after a request fails, as [`Error::retry`] answers it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum Retry { + /// The source failed to deliver rather than judging the request, so asking it again may + /// succeed: its connection dropped, its session ended, or it is going away. + Same, + + /// The source lost its route to the content, so only another route continues it. Asking + /// the same source again can only replace the withdrawal's cause with a refusal. + Reroute, + + /// The answer judged the request or what it carried, so it repeats on every attempt: + /// refused, not found, or malformed. + Never, +} + /// Preserve the session registry when carrying a protocol error. impl From for Error { fn from(err: SessionError) -> Self { @@ -809,34 +792,23 @@ mod tests { // Both registries are wire contracts now (draft-lcurley-moq-lite, Error Codes), so // every code we send must decode back to what we meant. - #[test] - fn lite_unsupported_is_not_in_the_shared_session_registry() { - assert_eq!(SessionError::from(&Error::Unsupported).to_code(), 0x1); - assert_eq!(SessionError::from_code(0x30), SessionError::Unknown(0x30)); - } - #[test] fn session_codes_round_trip() { // Only the registered codes are a wire contract, so only they round trip, each on // the value the drafts assign (moq-transport's, where we reuse its code). + assert_eq!(SessionError::from(&Error::Unsupported), SessionError::Unsupported); for (err, spec) in [ + (SessionError::Unsupported, 0x30), (SessionError::Cancel, 0x0), (SessionError::Internal, 0x1), (SessionError::Unauthorized, 0x2), (SessionError::ProtocolViolation, 0x3), - (SessionError::InvalidRequestId, 0x4), - (SessionError::KeyValueFormatting, 0x6), (SessionError::TooManyRequests, 0x7), - (SessionError::InvalidPath, 0x8), (SessionError::GoawayTimeout, 0x10), (SessionError::Timeout, 0x11), - (SessionError::AuthTokenCacheOverflow, 0x13), (SessionError::Version, 0x15), (SessionError::MalformedAuthToken, 0x16), - (SessionError::UnknownAuthTokenAlias, 0x17), (SessionError::Expired, 0x18), - (SessionError::InvalidAuthority, 0x19), - (SessionError::TooManyRequestUpdates, 0x1B), (SessionError::App(0), 0x40), (SessionError::App(404), 0x40 + 404), ] { @@ -845,10 +817,16 @@ mod tests { } // The reserved 32-47 range, and anything else unregistered, keeps its value instead - // of being given a meaning. A peer on the old placeholders (0x20-0x22) lands here. - for code in [0x1f, 0x20, 0x21, 0x22, 0x2f, 0x30] { + // of being given a meaning. A peer on the old placeholders (0x20-0x22) lands here, as + // does every code only moq-transport defines. + for code in [0x1f, 0x20, 0x21, 0x22, 0x2f, 0x31] { assert_eq!(SessionError::from_code(code), SessionError::Unknown(code)); } + for code in [0x4, 0x6, 0x8, 0x13, 0x17, 0x19, 0x1b] { + let err = SessionError::from_code(code); + assert_eq!(err, SessionError::Unknown(code)); + assert_eq!(err.to_code(), code); + } // A disallowed stream fails the session as a protocol violation, and resets just // the stream as an internal error rather than claiming the session closed. @@ -960,6 +938,42 @@ mod tests { assert_eq!(SessionError::from(&Error::Dropped), SessionError::Internal); } + /// A failed delivery asks again, a lost route asks elsewhere, and a verdict on the + /// request or its content ends it, whether raised here or received from a peer. + #[test] + fn retry_separates_delivery_from_verdicts() { + for err in [ + Error::Transport("reset".into()), + Error::IdleTimeout, + Error::Cancel, + Error::Closed, + Error::GoingAway, + Error::Session(SessionError::Unauthorized), + Error::Session(SessionError::Unknown(0x4)), + Error::Stream(StreamError::Session(SessionError::Cancel)), + Error::Stream(StreamError::ControlTimeout), + ] { + assert_eq!(err.retry(), Retry::Same, "{err:?}"); + } + for err in [Error::Unroutable, Error::Stream(StreamError::Unroutable)] { + assert_eq!(err.retry(), Retry::Reroute, "{err:?}"); + } + for err in [ + Error::NotFound, + Error::Unauthorized, + Error::Expired, + Error::ProtocolViolation, + Error::WrongSize, + Error::Remote(0x7), + Error::Stream(StreamError::NotFound), + Error::Stream(StreamError::Unauthorized), + Error::Stream(StreamError::MalformedTrack), + Error::Stream(StreamError::Unknown(0x22)), + ] { + assert_eq!(err.retry(), Retry::Never, "{err:?}"); + } + } + // The registry a code is read with depends on what failed, and picking the wrong one // silently mistranslates rather than erroring. #[test] diff --git a/rs/moq-net/src/ietf/control.rs b/rs/moq-net/src/ietf/control.rs index 5e2d3f1ad18..b51de2b3fcc 100644 --- a/rs/moq-net/src/ietf/control.rs +++ b/rs/moq-net/src/ietf/control.rs @@ -59,7 +59,7 @@ impl Control { // No peer reaches 2^62 requests, and refusing the IDs past it keeps `peer_next` from // overflowing on a varint that can carry a full 64 bits. if id.0 >= 1 << 62 || id.0 % 2 != state.peer_next % 2 { - return Err(SessionError::InvalidRequestId.into()); + return Err(crate::ietf::error::session::INVALID_REQUEST_ID.into()); } if id.0 < state.peer_next { return Ok(()); @@ -119,7 +119,7 @@ mod tests { assert!( matches!( control.accept(RequestId(id)), - Err(Error::Session(SessionError::InvalidRequestId)) + Err(Error::Session(crate::ietf::error::session::INVALID_REQUEST_ID)) ), "accepted wrong-parity ID {id}" ); @@ -136,7 +136,7 @@ mod tests { for id in [1 << 62, u64::MAX - 1] { assert!(matches!( control.accept(RequestId(id)), - Err(Error::Session(SessionError::InvalidRequestId)) + Err(Error::Session(crate::ietf::error::session::INVALID_REQUEST_ID)) )); } assert!(matches!(control.goaway(), Err(Error::Session(SessionError::Internal)))); diff --git a/rs/moq-net/src/ietf/error.rs b/rs/moq-net/src/ietf/error.rs index dd314fd3aac..d2ba113f793 100644 --- a/rs/moq-net/src/ietf/error.rs +++ b/rs/moq-net/src/ietf/error.rs @@ -1,6 +1,6 @@ //! The moq-transport error code registries, per negotiated draft. //! -//! This module holds the stream reset registry and the session close encoder; [`request`] +//! This module holds the stream reset registry and the session close codes; [`request`] //! holds the one for rejecting a request. The reset and request registries are disjoint, so //! the same integer means different things in each. //! @@ -95,17 +95,56 @@ pub fn from_stream_code(code: u32) -> StreamError { } } +/// Session close codes only moq-transport defines. +/// +/// moq-lite assigns none of them, so each is a [`SessionError::Unknown`] carrying its number: +/// this layer sends them, and one a peer sends decodes back to the same value. +pub(crate) mod session { + use crate::SessionError; + + /// A request ID was reused or broke the negotiated draft's order or parity rules. + pub(crate) const INVALID_REQUEST_ID: SessionError = SessionError::Unknown(0x4); + + /// A key-value pair was malformed or repeated more than allowed. + pub(crate) const KEY_VALUE_FORMATTING: SessionError = SessionError::Unknown(0x6); + + /// The peer sent a PATH it may not send, such as a server sending one at all. + pub(crate) const INVALID_PATH: SessionError = SessionError::Unknown(0x8); + + /// A token registration would exceed the advertised `MAX_AUTH_TOKEN_CACHE_SIZE`, which is + /// 0 when unadvertised. + pub(crate) const AUTH_TOKEN_CACHE_OVERFLOW: SessionError = SessionError::Unknown(0x13); + + /// A token named an alias that was never registered. + pub(crate) const UNKNOWN_AUTH_TOKEN_ALIAS: SessionError = SessionError::Unknown(0x17); + + /// The peer sent an AUTHORITY it may not send, such as a server sending one at all. + pub(crate) const INVALID_AUTHORITY: SessionError = SessionError::Unknown(0x19); + + /// The peer left more unacknowledged REQUEST_UPDATEs outstanding on one request stream + /// than the MAX_REQUEST_UPDATES it was advertised (draft-22 section 9.1.7). + pub(crate) const TOO_MANY_REQUEST_UPDATES: SessionError = SessionError::Unknown(0x1b); +} + /// The code to close the session with. /// -/// The shared session registry, except moq-lite's own 0x30-0x3f range: a bridge must not -/// carry those codes onto this wire, so an unknown one closes as unspecified instead. +/// moq-lite's session registry, minus its own 0x30-0x3f range: moq-transport assigns nothing +/// there, so NOT_SUPPORTED and any unknown code from that range close as unspecified instead. pub(crate) fn to_session_code(error: &SessionError) -> u32 { match error { - SessionError::Unknown(0x30..=0x3f) => SessionError::Internal.to_code(), + SessionError::Unsupported | SessionError::Unknown(0x30..=0x3f) => SessionError::Internal.to_code(), error => error.to_code(), } } +/// Read a session close code, keeping moq-lite's own 0x30-0x3f range unknown. +pub(crate) fn from_session_code(code: u32) -> SessionError { + match code { + 0x30..=0x3f => SessionError::Unknown(code), + code => SessionError::from_code(code), + } +} + /// The moq-transport request error registry, per negotiated draft. /// /// Sent in a rejection response to a request, and read back off one. The registry is @@ -529,12 +568,14 @@ mod tests { fn the_lite_session_range_is_not_sent() { for code in 0x30..=0x3f { assert_eq!(to_session_code(&SessionError::Unknown(code)), 0x1); + assert_eq!(from_session_code(code), SessionError::Unknown(code)); assert_eq!( SessionError::Unknown(code).to_code(), code, "the shared encoder is unchanged" ); } + assert_eq!(to_session_code(&SessionError::Unsupported), 0x1); assert_eq!(to_session_code(&SessionError::Unknown(0x20)), 0x20); assert_eq!( to_session_code(&SessionError::Unauthorized), @@ -543,6 +584,26 @@ mod tests { assert_eq!(to_session_code(&SessionError::App(7)), 64 + 7); } + /// The codes only moq-transport defines go out on their draft values and come back as the + /// same number, a session close like any other. + #[test] + fn moq_transport_session_codes_keep_their_number() { + for (err, code) in [ + (session::INVALID_REQUEST_ID, 0x4), + (session::KEY_VALUE_FORMATTING, 0x6), + (session::INVALID_PATH, 0x8), + (session::AUTH_TOKEN_CACHE_OVERFLOW, 0x13), + (session::UNKNOWN_AUTH_TOKEN_ALIAS, 0x17), + (session::INVALID_AUTHORITY, 0x19), + (session::TOO_MANY_REQUEST_UPDATES, 0x1b), + ] { + assert_eq!(to_session_code(&err), code); + assert_eq!(from_session_code(code), err); + assert_eq!(SessionError::from_code(code), SessionError::Unknown(code)); + assert_eq!(Error::from(err).retry(), crate::Retry::Same, "{code:#x}"); + } + } + /// Every code we send must decode back to what we meant, or two moq-net peers disagree /// about what a stream reset said. #[test] diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index e62d9bcc764..eb0065685bc 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -10950,18 +10950,18 @@ mod serve_tests { for (token, expected, why) in [ ( &[0x01, 0x07, 0x00][..], - crate::SessionError::AuthTokenCacheOverflow, + crate::ietf::error::session::AUTH_TOKEN_CACHE_OVERFLOW, "REGISTER", ), - (&[0x00, 0x07][..], crate::SessionError::UnknownAuthTokenAlias, "DELETE"), + (&[0x00, 0x07][..], crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS, "DELETE"), ( &[0x02, 0x07][..], - crate::SessionError::UnknownAuthTokenAlias, + crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS, "USE_ALIAS", ), ( &[0x03][..], - crate::SessionError::KeyValueFormatting, + crate::ietf::error::session::KEY_VALUE_FORMATTING, "USE_VALUE without a type", ), ] { @@ -17529,7 +17529,7 @@ mod serve_tests { h.log .closes() .iter() - .any(|close| close.0 == crate::SessionError::TooManyRequestUpdates.to_code()), + .any(|close| close.0 == crate::ietf::error::session::TOO_MANY_REQUEST_UPDATES.to_code()), "the flood must close the session with TOO_MANY_REQUEST_UPDATES: {:?}", h.log.closes() ); diff --git a/rs/moq-net/src/ietf/request_update.rs b/rs/moq-net/src/ietf/request_update.rs index 2094c762013..e936104305d 100644 --- a/rs/moq-net/src/ietf/request_update.rs +++ b/rs/moq-net/src/ietf/request_update.rs @@ -9,12 +9,10 @@ //! //! The option is draft-22 (Option Type 0x08). Advertising it lets a conforming peer //! self-limit, so a peer that exceeds the advertised value broke a negotiated rule, which -//! the draft answers with a session close ([`SessionError::TooManyRequestUpdates`]). Drafts +//! the draft answers with a session close (TOO_MANY_REQUEST_UPDATES). Drafts //! below 19 carry no such option, so a peer there agreed to no ceiling: the receiver keeps //! a generous local guard that ends only the one request rather than fault a peer at //! session scope for a limit it never saw. -//! -//! [`SessionError::TooManyRequestUpdates`]: crate::SessionError::TooManyRequestUpdates use std::{collections::VecDeque, task::Poll}; @@ -130,7 +128,7 @@ pub(super) struct Verdict { #[cfg(feature = "async")] pub(super) fn too_many(session: &mut crate::driver::Transport) -> Error { use crate::transport::poll::Session as _; - let err = SessionError::TooManyRequestUpdates; + let err = crate::ietf::error::session::TOO_MANY_REQUEST_UPDATES; session.close(super::error::to_session_code(&err), "too many request updates"); Error::Session(err) } diff --git a/rs/moq-net/src/ietf/session.rs b/rs/moq-net/src/ietf/session.rs index 9f0a07cef7d..008fb2708d9 100644 --- a/rs/moq-net/src/ietf/session.rs +++ b/rs/moq-net/src/ietf/session.rs @@ -750,10 +750,10 @@ pub(crate) fn decode_peer_setup(parameters: &[u8], version: Version, client: boo let path = params.get_bytes(ietf::ParameterBytes::Path); // A server sends neither PATH nor AUTHORITY (draft-22 sections 9.1.1 and 9.1.2). if client && path.is_some() { - return Err(SessionError::InvalidPath.into()); + return Err(crate::ietf::error::session::INVALID_PATH.into()); } if client && params.get_bytes(ietf::ParameterBytes::Authority).is_some() { - return Err(SessionError::InvalidAuthority.into()); + return Err(crate::ietf::error::session::INVALID_AUTHORITY.into()); } let path = match path { Some(bytes) => Some( @@ -1707,7 +1707,7 @@ impl ReadGoaways { match msg.request_id { None if version == Version::Draft18 => return Poll::Ready(Err(Error::ProtocolViolation)), Some(request_id) if request_id.0 % 2 != u64::from(!self.client) => { - return Poll::Ready(Err(DecodeError::Session(SessionError::InvalidRequestId).into())); + return Poll::Ready(Err(DecodeError::Session(crate::ietf::error::session::INVALID_REQUEST_ID).into())); } _ => {} } @@ -3165,19 +3165,19 @@ mod tests { for (token, expected, why) in [ ( &[0x01, 0x07, 0x00][..], - SessionError::AuthTokenCacheOverflow, + crate::ietf::error::session::AUTH_TOKEN_CACHE_OVERFLOW, "REGISTER", ), - (&[0x00, 0x07][..], SessionError::UnknownAuthTokenAlias, "DELETE"), - (&[0x02, 0x07][..], SessionError::UnknownAuthTokenAlias, "USE_ALIAS"), + (&[0x00, 0x07][..], crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS, "DELETE"), + (&[0x02, 0x07][..], crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS, "USE_ALIAS"), ( &[0x03][..], - SessionError::KeyValueFormatting, + crate::ietf::error::session::KEY_VALUE_FORMATTING, "USE_VALUE without a type", ), ( &[0x04, 0x00][..], - SessionError::KeyValueFormatting, + crate::ietf::error::session::KEY_VALUE_FORMATTING, "an unknown alias type", ), ] { @@ -3279,8 +3279,8 @@ mod tests { async fn a_server_setup_with_path_or_authority_closes_the_session() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { for (param, expected) in [ - (ietf::ParameterBytes::Path, SessionError::InvalidPath), - (ietf::ParameterBytes::Authority, SessionError::InvalidAuthority), + (ietf::ParameterBytes::Path, crate::ietf::error::session::INVALID_PATH), + (ietf::ParameterBytes::Authority, crate::ietf::error::session::INVALID_AUTHORITY), ] { let mut params = ietf::Parameters::default(); params.set_bytes(param, b"a".to_vec()); @@ -3298,7 +3298,7 @@ mod tests { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { for (token, expected) in [ // An Alias Type of 4 does not exist. - (&[0x04][..], Some(SessionError::KeyValueFormatting)), + (&[0x04][..], Some(crate::ietf::error::session::KEY_VALUE_FORMATTING)), // REGISTER alias 7, type 0, empty value. (&[0x01, 0x07, 0x00][..], None), ] { @@ -3455,7 +3455,7 @@ mod tests { let closes = log.closes(); assert_eq!(closes.len(), 1, "{closes:?}"); - assert_eq!(SessionError::from_code(closes[0].0), SessionError::InvalidPath); + assert_eq!(SessionError::from_code(closes[0].0), crate::ietf::error::session::INVALID_PATH); let before = log.before_close().unwrap(); assert!( !before @@ -3477,8 +3477,8 @@ mod tests { for (request_id, expected) in [ (Some(0), None), (Some(4), None), - (Some(1), Some(SessionError::InvalidRequestId)), - (Some(5), Some(SessionError::InvalidRequestId)), + (Some(1), Some(crate::ietf::error::session::INVALID_REQUEST_ID)), + (Some(5), Some(crate::ietf::error::session::INVALID_REQUEST_ID)), // Required on the control stream. (None, Some(SessionError::ProtocolViolation)), ] { @@ -3617,7 +3617,7 @@ mod tests { for (payload, expected, why) in [ ( frame(version, ietf::SubscribeNamespace::ID, &[0, 0, 0]), - SessionError::InvalidRequestId, + crate::ietf::error::session::INVALID_REQUEST_ID, "a Request ID with our parity", ), ( diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index eb1ada63d65..fee42914c10 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -13841,7 +13841,7 @@ mod tests { }; assert_eq!( SessionError::from(&err), - SessionError::TooManyRequestUpdates, + crate::ietf::error::session::TOO_MANY_REQUEST_UPDATES, "the flood must surface TOO_MANY_REQUEST_UPDATES" ); assert!( @@ -13849,7 +13849,7 @@ mod tests { .log .closes() .iter() - .any(|close| close.0 == SessionError::TooManyRequestUpdates.to_code()), + .any(|close| close.0 == crate::ietf::error::session::TOO_MANY_REQUEST_UPDATES.to_code()), "the flood must close the session with TOO_MANY_REQUEST_UPDATES: {:?}", session.log.closes() ); @@ -14399,7 +14399,7 @@ mod tests { matches!( result, Err(Error::Decode(DecodeError::Session( - crate::SessionError::UnknownAuthTokenAlias + crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS ))) ), "the queued update's unknown alias closes the session: {result:?}" diff --git a/rs/moq-net/src/ietf/token.rs b/rs/moq-net/src/ietf/token.rs index d74d89c2789..3eb0f446f19 100644 --- a/rs/moq-net/src/ietf/token.rs +++ b/rs/moq-net/src/ietf/token.rs @@ -132,7 +132,7 @@ fn encode(token: &Token, version: Version) -> Result, EncodeError> { /// Decode a Token structure, refusing what this endpoint cannot accept. fn decode(buf: &[u8], version: Version, setup: bool) -> Result { // Section 8.9: a structure that cannot be decoded closes with KEY_VALUE_FORMATTING_ERROR. - let malformed = |_| SessionError::KeyValueFormatting; + let malformed = |_| crate::ietf::error::session::KEY_VALUE_FORMATTING; let mut r = Decoder::new(buf, version.into()); // Every field an alias type names decodes before its meaning applies, so a truncated @@ -145,13 +145,13 @@ fn decode(buf: &[u8], version: Version, setup: bool) -> Result { r.varint().map_err(malformed)?; if !r.is_empty() { - return Err(SessionError::KeyValueFormatting); + return Err(crate::ietf::error::session::KEY_VALUE_FORMATTING); } // Section 9.1.4: nothing can have been registered before SETUP. if setup { @@ -160,9 +160,9 @@ fn decode(buf: &[u8], version: Version, setup: bool) -> Result return Err(SessionError::KeyValueFormatting), + _ => return Err(crate::ietf::error::session::KEY_VALUE_FORMATTING), } let kind = r.varint().map_err(malformed)?; @@ -377,7 +377,7 @@ mod tests { for version in VERSIONS { let err = request(version, &[REGISTER, 7, token().kind], &token().value).unwrap_err(); assert!( - matches!(err, DecodeError::Session(SessionError::AuthTokenCacheOverflow)), + matches!(err, DecodeError::Session(crate::ietf::error::session::AUTH_TOKEN_CACHE_OVERFLOW)), "{version:?}: {err:?}" ); } @@ -389,7 +389,7 @@ mod tests { for alias_type in [DELETE, USE_ALIAS] { let err = request(version, &[alias_type, 7], &[]).unwrap_err(); assert!( - matches!(err, DecodeError::Session(SessionError::UnknownAuthTokenAlias)), + matches!(err, DecodeError::Session(crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS)), "{version:?} {alias_type}: {err:?}" ); } @@ -411,7 +411,7 @@ mod tests { ] { let err = request(version, fields, &[]).unwrap_err(); assert!( - matches!(err, DecodeError::Session(SessionError::KeyValueFormatting)), + matches!(err, DecodeError::Session(crate::ietf::error::session::KEY_VALUE_FORMATTING)), "{version:?} {why}: {err:?}" ); } @@ -433,7 +433,7 @@ mod tests { let params = structure(version, fields, &[]); let err = from_setup(¶ms, version).unwrap_err(); assert!( - matches!(err, Error::Session(SessionError::KeyValueFormatting)), + matches!(err, Error::Session(crate::ietf::error::session::KEY_VALUE_FORMATTING)), "{version:?} {why}: {err:?}" ); } diff --git a/rs/moq-net/src/lite/error.rs b/rs/moq-net/src/lite/error.rs index 98c77a3984a..36fb345798e 100644 --- a/rs/moq-net/src/lite/error.rs +++ b/rs/moq-net/src/lite/error.rs @@ -1,10 +1,10 @@ -//! The Lite additions to the shared session error registry. +//! moq-lite's session close boundary. use crate::{Error, SessionError}; +/// The code to close a moq-lite session with. pub(crate) fn to_session_code(error: &SessionError) -> u32 { match error { - SessionError::Unsupported => 0x30, // moq-lite's own range is assigned only by its tables; a code from elsewhere // must not pick up a meaning there. SessionError::Unknown(0x30..=0x3f) => SessionError::Internal.to_code(), @@ -12,20 +12,6 @@ pub(crate) fn to_session_code(error: &SessionError) -> u32 { } } -pub(crate) fn from_session_code(code: u32) -> SessionError { - match code { - 0x30 => SessionError::Unsupported, - code => SessionError::from_code(code), - } -} - -pub(crate) fn from_transport(error: impl crate::transport::Error) -> Error { - if let Some((code, _)) = error.session_error() { - return from_session_code(code).into(); - } - Error::from_transport(error) -} - /// Classify control bytes at a stream boundary, keeping a transport FIN/reset distinct. #[cfg(feature = "async")] pub(super) fn control(session: &mut crate::driver::Transport, err: Error) -> Error { @@ -47,9 +33,8 @@ mod tests { #[test] fn an_unknown_code_does_not_gain_a_lite_meaning() { assert_eq!(to_session_code(&SessionError::Unsupported), 0x30); - assert_eq!(from_session_code(0x30), SessionError::Unsupported); + assert_eq!(SessionError::from_code(0x30), SessionError::Unsupported); assert_eq!(to_session_code(&SessionError::Expired), 0x18); - assert_eq!(from_session_code(0x18), SessionError::Expired); for code in 0x30..=0x3f { assert_eq!(to_session_code(&SessionError::Unknown(code)), 0x1); } diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index f60f510f90d..5d49100b3f3 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -6558,7 +6558,7 @@ impl GroupServe { Err(err) => { self.settle_open(false); self.state = GroupState::Done; - return Poll::Ready(Err(crate::lite::error::from_transport(err))); + return Poll::Ready(Err(Error::from_transport(err))); } }; self.settle_open(true); diff --git a/rs/moq-net/src/lite/session.rs b/rs/moq-net/src/lite/session.rs index 224d7db4747..40364af6a3e 100644 --- a/rs/moq-net/src/lite/session.rs +++ b/rs/moq-net/src/lite/session.rs @@ -81,7 +81,7 @@ impl SetupAccept { match stream { Ok(stream) => pending.push(Reader::new(stream, version)), Err(err) => { - accept_error = Some(crate::lite::error::from_transport(err)); + accept_error = Some(Error::from_transport(err)); break; } } @@ -773,7 +773,7 @@ impl PresentToken { let Ok(code) = u32::try_from(refused.code) else { return Poll::Ready(Error::ProtocolViolation); }; - let err = match crate::lite::error::from_session_code(code) { + let err = match crate::SessionError::from_code(code) { crate::SessionError::Unsupported => Error::Unsupported, code => Error::Session(code), }; @@ -856,7 +856,7 @@ impl SendSetup { fn poll_send(&mut self, waiter: &kio::Waiter) -> Poll> { // Waiting for stream credit on our own session handle. let stream = wait!(Open => self.session.poll_open_uni(&mut self.open, waiter, Default::default())) - .map_err(crate::lite::error::from_transport)?; + .map_err(Error::from_transport)?; let mut writer: Writer = Writer::new(stream, self.version).with_stats(&self.stats); writer.buffer(&super::DataType::Setup)?; diff --git a/rs/moq-net/src/lite/subscriber.rs b/rs/moq-net/src/lite/subscriber.rs index 2dcfa8c5857..bb235839943 100644 --- a/rs/moq-net/src/lite/subscriber.rs +++ b/rs/moq-net/src/lite/subscriber.rs @@ -1517,7 +1517,7 @@ impl UniAccept { }, }); } - Poll::Ready(Err(err)) => return Poll::Ready(Err(crate::lite::error::from_transport(err))), + Poll::Ready(Err(err)) => return Poll::Ready(Err(Error::from_transport(err))), Poll::Pending => break, } } @@ -2411,7 +2411,7 @@ impl DatagramRecv { for payload in std::mem::take(&mut self.held) { self.route(payload, false); } - return Poll::Ready(Err(crate::lite::error::from_transport(err))); + return Poll::Ready(Err(Error::from_transport(err))); } }; self.route(payload, hold); @@ -3468,7 +3468,7 @@ impl DatagramServe { let version = self.subscriber.version; loop { if let Poll::Ready(err) = self.closed.poll_closed(waiter) { - return Poll::Ready(Err(crate::lite::error::from_transport(err))); + return Poll::Ready(Err(Error::from_transport(err))); } if self.poll_unused(waiter).is_ready() { return Poll::Ready(Err(Error::Cancel)); @@ -12494,7 +12494,7 @@ impl Establish { // teardown instead. let resp = wait!(WaitOk => { if let Poll::Ready(err) = self.closed.poll_closed(waiter) { - return Poll::Ready(Err(crate::lite::error::from_transport(err))); + return Poll::Ready(Err(Error::from_transport(err))); } stream.reader.poll_decode::(waiter) })?; @@ -12640,7 +12640,7 @@ impl FinishedServe { // The groups it already holds stay readable, its clean end too once settled. if let Poll::Ready(err) = self.closed.poll_closed(waiter) { if let Some(serving) = self.serving.take() { - let _ = serving.abort(crate::lite::error::from_transport(err)); + let _ = serving.abort(Error::from_transport(err)); } return Poll::Ready(()); } @@ -13252,7 +13252,7 @@ impl TrackInfoFetch { let (ietf, info) = wait!(Read => { if let Poll::Ready(err) = self.closed.poll_closed(waiter) { - return Poll::Ready(Err(crate::lite::error::from_transport(err))); + return Poll::Ready(Err(Error::from_transport(err))); } match serve.subscriber.peer_setup.poll_ietf(waiter) { Poll::Ready(ietf) => stream.reader.poll_decode::(waiter).map_ok(|info| (ietf, info)), @@ -13272,7 +13272,7 @@ impl TrackInfoFetch { // Reading the TRACK_PROPERTIES the `ietf` extension sends after TRACK_INFO. let properties = wait!(Properties => { if let Poll::Ready(err) = self.closed.poll_closed(waiter) { - return Poll::Ready(Err(crate::lite::error::from_transport(err))); + return Poll::Ready(Err(Error::from_transport(err))); } stream.reader.poll_decode::(waiter) })?; @@ -14154,7 +14154,7 @@ impl ServeLoop { if !serve.subscriber.version.has_track_stream() { let _ = self.serving.finish_shared(); } - return Poll::Ready(ServeEnd::GiveBack(crate::lite::error::from_transport(err))); + return Poll::Ready(ServeEnd::GiveBack(Error::from_transport(err))); } return Poll::Pending; } @@ -14375,7 +14375,7 @@ impl ServeLoop { if poll_unparked(&self.sub, serve, waiter).is_pending() { return Poll::Pending; } - return Poll::Ready(ServeEnd::GiveBack(crate::lite::error::from_transport(err))); + return Poll::Ready(ServeEnd::GiveBack(Error::from_transport(err))); } return Poll::Pending; diff --git a/rs/moq-net/src/server.rs b/rs/moq-net/src/server.rs index 1856657c471..0cdd342b460 100644 --- a/rs/moq-net/src/server.rs +++ b/rs/moq-net/src/server.rs @@ -2074,7 +2074,7 @@ mod tests { let truncated = [0x3]; // USE_VALUE with no Token Type for (raw, code) in [ (&delete[..], SessionError::ProtocolViolation), - (&truncated[..], SessionError::KeyValueFormatting), + (&truncated[..], crate::ietf::error::session::KEY_VALUE_FORMATTING), ] { let mut params = ietf::Parameters::default(); params.set_bytes(ietf::ParameterBytes::AuthorizationToken, raw.to_vec()); From 7b5b82385a65909ba7d430a7c8bbd2eb1fefe9d6 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 07:45:39 -0800 Subject: [PATCH 3/9] wip: js, bindings, fmt --- dart/moq_ffi/lib/src/moq.dart | 57 +++++++++------------------ js/net/api/index.api.md | 14 +++---- js/net/src/connection/handshake.ts | 4 +- js/net/src/error.test.ts | 6 +-- js/net/src/ietf/connection.test.ts | 2 +- js/net/src/ietf/connection.ts | 2 +- js/net/src/ietf/malformed.test.ts | 2 +- js/net/src/ietf/request_ids.test.ts | 4 +- js/net/src/ietf/session.ts | 4 +- js/net/src/ietf/token.test.ts | 2 +- js/net/src/ietf/token.ts | 4 +- rs/moq-net/src/ietf/publisher.rs | 6 ++- rs/moq-net/src/ietf/request_update.rs | 2 +- rs/moq-net/src/ietf/session.rs | 27 ++++++++++--- rs/moq-net/src/ietf/token.rs | 15 +++++-- 15 files changed, 80 insertions(+), 71 deletions(-) diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index 74bbb704978..e636b1f0628 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -7190,7 +7190,6 @@ enum MoqProtocolKind { internal, unauthorized, protocolViolation, - keyValueFormatting, goawayTimeout, timeout, version, @@ -7209,13 +7208,7 @@ enum MoqProtocolKind { unknown, tooManyRequests, expired, - authTokenCacheOverflow, malformedAuthToken, - unknownAuthTokenAlias, - invalidRequestId, - invalidPath, - invalidAuthority, - tooManyRequestUpdates, } class FfiConverterMoqProtocolKind { @@ -7231,57 +7224,43 @@ class FfiConverterMoqProtocolKind { case 4: return LiftRetVal(MoqProtocolKind.protocolViolation, 4); case 5: - return LiftRetVal(MoqProtocolKind.keyValueFormatting, 4); - case 6: return LiftRetVal(MoqProtocolKind.goawayTimeout, 4); - case 7: + case 6: return LiftRetVal(MoqProtocolKind.timeout, 4); - case 8: + case 7: return LiftRetVal(MoqProtocolKind.version, 4); - case 9: + case 8: return LiftRetVal(MoqProtocolKind.deliveryTimeout, 4); - case 10: + case 9: return LiftRetVal(MoqProtocolKind.goingAway, 4); - case 11: + case 10: return LiftRetVal(MoqProtocolKind.tooFarBehind, 4); - case 12: + case 11: return LiftRetVal(MoqProtocolKind.malformedTrack, 4); - case 13: + case 12: return LiftRetVal(MoqProtocolKind.notFound, 4); - case 14: + case 13: return LiftRetVal(MoqProtocolKind.unroutable, 4); - case 15: + case 14: return LiftRetVal(MoqProtocolKind.old, 4); - case 16: + case 15: return LiftRetVal(MoqProtocolKind.evicted, 4); - case 17: + case 16: return LiftRetVal(MoqProtocolKind.wrongSize, 4); - case 18: + case 17: return LiftRetVal(MoqProtocolKind.frameTooLarge, 4); - case 19: + case 18: return LiftRetVal(MoqProtocolKind.timestampMismatch, 4); - case 20: + case 19: return LiftRetVal(MoqProtocolKind.app, 4); - case 21: + case 20: return LiftRetVal(MoqProtocolKind.unknown, 4); - case 22: + case 21: return LiftRetVal(MoqProtocolKind.tooManyRequests, 4); - case 23: + case 22: return LiftRetVal(MoqProtocolKind.expired, 4); - case 24: - return LiftRetVal(MoqProtocolKind.authTokenCacheOverflow, 4); - case 25: + case 23: return LiftRetVal(MoqProtocolKind.malformedAuthToken, 4); - case 26: - return LiftRetVal(MoqProtocolKind.unknownAuthTokenAlias, 4); - case 27: - return LiftRetVal(MoqProtocolKind.invalidRequestId, 4); - case 28: - return LiftRetVal(MoqProtocolKind.invalidPath, 4); - case 29: - return LiftRetVal(MoqProtocolKind.invalidAuthority, 4); - case 30: - return LiftRetVal(MoqProtocolKind.tooManyRequestUpdates, 4); default: throw UniffiInternalError( UniffiInternalError.unexpectedEnumCase, diff --git a/js/net/api/index.api.md b/js/net/api/index.api.md index 0a60027e0ec..1317294a4c1 100644 --- a/js/net/api/index.api.md +++ b/js/net/api/index.api.md @@ -330,6 +330,12 @@ export namespace Error { export class RefusedRedirect extends Error { constructor(reason: string); } + export const Retry: Readonly<{ + readonly Never: "never"; + readonly Reroute: "reroute"; + readonly Same: "same"; + }>; + export type Retry = typeof Error.Retry[keyof typeof Error.Retry]; export class Session extends Error { constructor(code: SessionCode, options?: { cause?: unknown; @@ -360,6 +366,7 @@ export namespace Error { cause?: unknown; }); } + export function retry(err: unknown): Error.Retry; } export namespace Frame { @@ -575,22 +582,15 @@ export namespace Path { } export const SessionCode: ((code: number) => SessionCode) & { - readonly AuthTokenCacheOverflow: SessionCode; readonly Cancel: SessionCode; readonly Expired: SessionCode; readonly GoawayTimeout: SessionCode; readonly Internal: SessionCode; - readonly InvalidAuthority: SessionCode; - readonly InvalidPath: SessionCode; - readonly InvalidRequestId: SessionCode; - readonly KeyValueFormatting: SessionCode; readonly MalformedAuthToken: SessionCode; readonly ProtocolViolation: SessionCode; readonly Timeout: SessionCode; - readonly TooManyRequestUpdates: SessionCode; readonly TooManyRequests: SessionCode; readonly Unauthorized: SessionCode; - readonly UnknownAuthTokenAlias: SessionCode; readonly Unsupported: SessionCode; readonly Version: SessionCode; }; diff --git a/js/net/src/connection/handshake.ts b/js/net/src/connection/handshake.ts index 9411693aee8..9f9882d1b51 100644 --- a/js/net/src/connection/handshake.ts +++ b/js/net/src/connection/handshake.ts @@ -1,7 +1,7 @@ -import { IetfSessionCode } from "../ietf/error.ts"; import { Duration } from "@moq/clock"; -import { closeReason, ProtocolViolation, SessionCode, StreamError } from "../error.ts"; +import { closeReason, ProtocolViolation, StreamError } from "../error.ts"; import { type Hop, randomHop } from "../hop.ts"; +import { IetfSessionCode } from "../ietf/error.ts"; import * as Ietf from "../ietf/index.ts"; import * as Message from "../ietf/message.ts"; import * as Lite from "../lite/index.ts"; diff --git a/js/net/src/error.test.ts b/js/net/src/error.test.ts index e542740ff5e..b1e11f5bc33 100644 --- a/js/net/src/error.test.ts +++ b/js/net/src/error.test.ts @@ -9,8 +9,8 @@ import { Lagged, NotFound, ProtocolViolation, - reason, Retry, + reason, retry, SessionCode, SessionError, @@ -97,8 +97,8 @@ test("the error type names the registry the code came from", () => { test("a code only moq-transport defines keeps its number", () => { for (const code of [0x4, 0x6, 0x8, 0x13, 0x17, 0x19, 0x1b]) { - expect(fromClose({ closeCode: code })?.code).toBe(code); - expect(Object.values(SessionCode)).not.toContain(code); + expect(Number(fromClose({ closeCode: code })?.code)).toBe(code); + expect(Object.values(SessionCode) as number[]).not.toContain(code); } }); diff --git a/js/net/src/ietf/connection.test.ts b/js/net/src/ietf/connection.test.ts index 18d3a27a4b3..7ae1dc62ba2 100644 --- a/js/net/src/ietf/connection.test.ts +++ b/js/net/src/ietf/connection.test.ts @@ -1,4 +1,3 @@ -import { IetfSessionCode } from "./error.ts"; import { expect, spyOn, test } from "bun:test"; import { yieldNow } from "@moq/clock"; import { offered } from "../connection/extensions.ts"; @@ -10,6 +9,7 @@ import * as Path from "../path.ts"; import { Stream, Writer } from "../stream.ts"; import { Timescale } from "../time.ts"; import { Connection } from "./connection.ts"; +import { IetfSessionCode } from "./error.ts"; import { Fetch, type FetchType } from "./fetch.ts"; import * as Message from "./message.ts"; import * as Namespace from "./namespace.ts"; diff --git a/js/net/src/ietf/connection.ts b/js/net/src/ietf/connection.ts index b2a529a3d6f..8b2a4c71ac1 100644 --- a/js/net/src/ietf/connection.ts +++ b/js/net/src/ietf/connection.ts @@ -7,7 +7,7 @@ import type { Drain } from "../connection/goaway.ts"; import type { Session } from "../connection/session.ts"; import { detect, type Probe, type Stats, transportStats } from "../connection/stats.ts"; import { type Transport, transportOf } from "../connection/transport.ts"; -import { error, fromClose, ProtocolViolation, SessionCode, StreamCode, StreamError, sessionClosed } from "../error.ts"; +import { error, fromClose, ProtocolViolation, StreamCode, StreamError, sessionClosed } from "../error.ts"; import type { Consumer as OriginConsumer } from "../origin.ts"; import * as Path from "../path.ts"; import { type Reader, Readers, type Stream } from "../stream.ts"; diff --git a/js/net/src/ietf/malformed.test.ts b/js/net/src/ietf/malformed.test.ts index 9d34d65129b..817c7ac4e7f 100644 --- a/js/net/src/ietf/malformed.test.ts +++ b/js/net/src/ietf/malformed.test.ts @@ -1,4 +1,3 @@ -import { IetfSessionCode } from "./error.ts"; import { expect, spyOn, test } from "bun:test"; import { Duration } from "@moq/clock"; import type { Manual } from "@moq/clock/test"; @@ -11,6 +10,7 @@ import * as Path from "../path.ts"; import { Stream, Writer } from "../stream.ts"; import { Timescale } from "../time.ts"; import { Connection } from "./connection.ts"; +import { IetfSessionCode } from "./error.ts"; import { GoAway } from "./goaway.ts"; import { RequestOk } from "./request.ts"; import { Setup } from "./setup.ts"; diff --git a/js/net/src/ietf/request_ids.test.ts b/js/net/src/ietf/request_ids.test.ts index 694ebd67969..6b4b3145e50 100644 --- a/js/net/src/ietf/request_ids.test.ts +++ b/js/net/src/ietf/request_ids.test.ts @@ -1,6 +1,6 @@ -import { IetfSessionCode } from "./error.ts"; import { describe, expect, test } from "bun:test"; -import { SessionCode, SessionError } from "../error.ts"; +import { type SessionCode, SessionError } from "../error.ts"; +import { IetfSessionCode } from "./error.ts"; import { checkPeerRequestId } from "./session.ts"; function code(id: bigint, client: boolean): SessionCode | undefined { diff --git a/js/net/src/ietf/session.ts b/js/net/src/ietf/session.ts index 82159ff0190..0c2a0cc6ffa 100644 --- a/js/net/src/ietf/session.ts +++ b/js/net/src/ietf/session.ts @@ -1,6 +1,6 @@ -import { IetfSessionCode } from "./error.ts"; -import { SessionCode, SessionError } from "../error.ts"; +import { SessionError } from "../error.ts"; import { type OpenOptions, Stream } from "../stream.ts"; +import { IetfSessionCode } from "./error.ts"; import type { IetfVersion } from "./version.ts"; /** How {@link Session.openBi} opens: its send order, and a signal that gives up the wait. */ diff --git a/js/net/src/ietf/token.test.ts b/js/net/src/ietf/token.test.ts index e9ba6b90764..a090bff82a2 100644 --- a/js/net/src/ietf/token.test.ts +++ b/js/net/src/ietf/token.test.ts @@ -1,8 +1,8 @@ -import { IetfSessionCode } from "./error.ts"; import { expect, test } from "bun:test"; import { ProtocolViolation, SessionCode } from "../error.ts"; import { Reader, Writer } from "../stream.ts"; import * as Varint from "../varint.ts"; +import { IetfSessionCode } from "./error.ts"; import { Parameters } from "./parameters.ts"; import { SetupOption, SetupOptions } from "./setup_options.ts"; import { diff --git a/js/net/src/ietf/token.ts b/js/net/src/ietf/token.ts index eca52bd0da2..c6fb5b346ff 100644 --- a/js/net/src/ietf/token.ts +++ b/js/net/src/ietf/token.ts @@ -1,6 +1,6 @@ -import { IetfSessionCode } from "./error.ts"; -import { ProtocolViolation, SessionCode } from "../error.ts"; +import { ProtocolViolation } from "../error.ts"; import * as Varint from "../varint.ts"; +import { IetfSessionCode } from "./error.ts"; import type { Parameters } from "./parameters.ts"; import type { SetupOptions } from "./setup_options.ts"; diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index eb0065685bc..6a6cbf58c06 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -10953,7 +10953,11 @@ mod serve_tests { crate::ietf::error::session::AUTH_TOKEN_CACHE_OVERFLOW, "REGISTER", ), - (&[0x00, 0x07][..], crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS, "DELETE"), + ( + &[0x00, 0x07][..], + crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS, + "DELETE", + ), ( &[0x02, 0x07][..], crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS, diff --git a/rs/moq-net/src/ietf/request_update.rs b/rs/moq-net/src/ietf/request_update.rs index e936104305d..8324fc59bf6 100644 --- a/rs/moq-net/src/ietf/request_update.rs +++ b/rs/moq-net/src/ietf/request_update.rs @@ -17,7 +17,7 @@ use std::{collections::VecDeque, task::Poll}; use super::Version; -use crate::{Error, SessionError, auth}; +use crate::{Error, auth}; /// MAX_REQUEST_UPDATES Setup Option (Option Type 0x08). Even, so the value is a bare varint. pub const OPTION: u64 = 0x08; diff --git a/rs/moq-net/src/ietf/session.rs b/rs/moq-net/src/ietf/session.rs index 008fb2708d9..6e64e135658 100644 --- a/rs/moq-net/src/ietf/session.rs +++ b/rs/moq-net/src/ietf/session.rs @@ -1707,7 +1707,10 @@ impl ReadGoaways { match msg.request_id { None if version == Version::Draft18 => return Poll::Ready(Err(Error::ProtocolViolation)), Some(request_id) if request_id.0 % 2 != u64::from(!self.client) => { - return Poll::Ready(Err(DecodeError::Session(crate::ietf::error::session::INVALID_REQUEST_ID).into())); + return Poll::Ready(Err(DecodeError::Session( + crate::ietf::error::session::INVALID_REQUEST_ID, + ) + .into())); } _ => {} } @@ -3168,8 +3171,16 @@ mod tests { crate::ietf::error::session::AUTH_TOKEN_CACHE_OVERFLOW, "REGISTER", ), - (&[0x00, 0x07][..], crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS, "DELETE"), - (&[0x02, 0x07][..], crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS, "USE_ALIAS"), + ( + &[0x00, 0x07][..], + crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS, + "DELETE", + ), + ( + &[0x02, 0x07][..], + crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS, + "USE_ALIAS", + ), ( &[0x03][..], crate::ietf::error::session::KEY_VALUE_FORMATTING, @@ -3280,7 +3291,10 @@ mod tests { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { for (param, expected) in [ (ietf::ParameterBytes::Path, crate::ietf::error::session::INVALID_PATH), - (ietf::ParameterBytes::Authority, crate::ietf::error::session::INVALID_AUTHORITY), + ( + ietf::ParameterBytes::Authority, + crate::ietf::error::session::INVALID_AUTHORITY, + ), ] { let mut params = ietf::Parameters::default(); params.set_bytes(param, b"a".to_vec()); @@ -3455,7 +3469,10 @@ mod tests { let closes = log.closes(); assert_eq!(closes.len(), 1, "{closes:?}"); - assert_eq!(SessionError::from_code(closes[0].0), crate::ietf::error::session::INVALID_PATH); + assert_eq!( + SessionError::from_code(closes[0].0), + crate::ietf::error::session::INVALID_PATH + ); let before = log.before_close().unwrap(); assert!( !before diff --git a/rs/moq-net/src/ietf/token.rs b/rs/moq-net/src/ietf/token.rs index 3eb0f446f19..59b53e2ac02 100644 --- a/rs/moq-net/src/ietf/token.rs +++ b/rs/moq-net/src/ietf/token.rs @@ -377,7 +377,10 @@ mod tests { for version in VERSIONS { let err = request(version, &[REGISTER, 7, token().kind], &token().value).unwrap_err(); assert!( - matches!(err, DecodeError::Session(crate::ietf::error::session::AUTH_TOKEN_CACHE_OVERFLOW)), + matches!( + err, + DecodeError::Session(crate::ietf::error::session::AUTH_TOKEN_CACHE_OVERFLOW) + ), "{version:?}: {err:?}" ); } @@ -389,7 +392,10 @@ mod tests { for alias_type in [DELETE, USE_ALIAS] { let err = request(version, &[alias_type, 7], &[]).unwrap_err(); assert!( - matches!(err, DecodeError::Session(crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS)), + matches!( + err, + DecodeError::Session(crate::ietf::error::session::UNKNOWN_AUTH_TOKEN_ALIAS) + ), "{version:?} {alias_type}: {err:?}" ); } @@ -411,7 +417,10 @@ mod tests { ] { let err = request(version, fields, &[]).unwrap_err(); assert!( - matches!(err, DecodeError::Session(crate::ietf::error::session::KEY_VALUE_FORMATTING)), + matches!( + err, + DecodeError::Session(crate::ietf::error::session::KEY_VALUE_FORMATTING) + ), "{version:?} {why}: {err:?}" ); } From 1595f6748cd8b5a6abc1efb5f8cb3d84898c6d71 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 07:57:59 -0800 Subject: [PATCH 4/9] wip: moq-gst follows Error::retry --- doc/bin/gstreamer.md | 5 +++-- rs/moq-gst/src/source/imp.rs | 21 +++++++++------------ 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/doc/bin/gstreamer.md b/doc/bin/gstreamer.md index 326f66adc73..4e820bf01f0 100644 --- a/doc/bin/gstreamer.md +++ b/doc/bin/gstreamer.md @@ -171,8 +171,9 @@ its pads without EOS until it is announced again, so the pipeline does not end on its own. Losing the relay connection also holds the pads: `moqsrc` redials without a retry deadline and resumes when the broadcast returns. A first connect that reaches no relay posts an error rather than retrying. A refused -connection, refused path or catalog, or malformed protocol input or catalog posts -an error. Properties: `url`, +connection, refused path or catalog, malformed input or catalog, or a track its +publisher ended with an application code posts an error. A session the relay +closes is redialed, whatever its code. Properties: `url`, `broadcast`, `max-delay`, `connect-version` (comma-separated protocol versions to offer, most preferred first; every stable version by default), `tls-disable-verify`, `quic-idle-timeout`, `quic-keep-alive`, and `quic-keylog`. diff --git a/rs/moq-gst/src/source/imp.rs b/rs/moq-gst/src/source/imp.rs index fbfb24b8ed7..b83fabbffa7 100644 --- a/rs/moq-gst/src/source/imp.rs +++ b/rs/moq-gst/src/source/imp.rs @@ -2593,6 +2593,7 @@ mod session_tests { moq_net::Error::Stream(moq_net::StreamError::NotFound), moq_net::Error::Stream(moq_net::StreamError::Unauthorized), moq_net::Error::Stream(moq_net::StreamError::MalformedTrack), + moq_net::Error::Stream(moq_net::StreamError::App(1)), ] { assert!(!super::source_lost(&err), "{err:?}"); } @@ -6124,25 +6125,19 @@ mod session_tests { assert!(error.is_none(), "a refused redial failed the pipeline: {error:?}"); } + /// A session the relay closes for a protocol violation ends like any other: the connection + /// redials, which is its call rather than the source's, and the pads play on. #[test] - fn a_protocol_violation_posts_a_bus_error_after_playback() { + fn a_protocol_violation_redials_after_playback() { let _pad_ids = pad_ids(); let relay = Relay::new(); let mut publisher = Publisher::new(&relay.origin, Default::default(), video_rendition()); let (pipeline, sink) = pipeline(&relay.url); rendered(&sink, &mut publisher, 1); relay.close.send(moq_net::Error::ProtocolViolation).unwrap(); - let error = pipeline - .bus() - .unwrap() - .timed_pop_filtered(gst::ClockTime::from_seconds(10), &[gst::MessageType::Error]); - pipeline.set_state(gst::State::Null).unwrap(); + rendered(&sink, &mut publisher, 2); + assert_played_cleanly(pipeline); relay.stop(); - let error = error.expect("protocol violation did not fail the pipeline"); - let gst::MessageView::Error(error) = error.view() else { - unreachable!() - }; - assert!(error.debug().unwrap().contains("protocol violation"), "{error:?}"); } /// End to end through a relay: a publisher restarted under a new instance, the old one still up. @@ -6311,7 +6306,9 @@ mod session_tests { rendered(&sink, &mut old, 1); let mut announced = announced(&relay.origin); - session.abort(moq_net::Error::App(1)); + // Not an application code: a relay forwards one to its readers as the publisher's + // verdict, which fails the source. + session.abort(moq_net::SessionError::Internal.into()); await_event(&mut announced, |event| { matches!( event, From 7150a05ee4dfd1beddb21a3ce956c8a8d3e9625d Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 08:14:52 -0800 Subject: [PATCH 5/9] wip: finish the quest, docs, and a follow-up --- quest/m2/README.md | 3 +- quest/m2/net-renames.md | 1 - quest/m2/session-codes.md | 68 ------------------------------------- quest/m2/ts-follow-retry.md | 34 +++++++++++++++++++ rs/moq-c/src/error.rs | 2 +- rs/moq-ffi/src/error.rs | 3 +- 6 files changed, 38 insertions(+), 73 deletions(-) delete mode 100644 quest/m2/session-codes.md create mode 100644 quest/m2/ts-follow-retry.md diff --git a/quest/m2/README.md b/quest/m2/README.md index 42df4d4cfa6..d745806d0f2 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -36,8 +36,7 @@ removal, a rename, or a wire, catalog, or format change that is free until [switch](/quest/m2/multicast/switch.md) also settles the public route API and retires the moq-cluster draft. - **moq-net API.** [Groups](/quest/m2/group-api.md), - [reconnect](/quest/m2/reconnect-off.md), [names](/quest/m2/net-renames.md), - and [session codes](/quest/m2/session-codes.md). + [reconnect](/quest/m2/reconnect-off.md), and [names](/quest/m2/net-renames.md). [Socket endpoints](/quest/m2/sockets/README.md) leave for Kixel, and the demos return to their earlier format. - **Unused API.** [One sweep per area](/quest/m2/unused-api/README.md), each diff --git a/quest/m2/net-renames.md b/quest/m2/net-renames.md index c0d08a2a2ca..3b2f2174d13 100644 --- a/quest/m2/net-renames.md +++ b/quest/m2/net-renames.md @@ -82,5 +82,4 @@ them. Wire: none. ## Related - [The route switch](/quest/m2/multicast/switch.md) - removes the route key beside the node identity this renames -- [Session close codes](/quest/m2/session-codes.md) - the other public moq-net cleanup in `error.rs` - [Unused moq-net API](/quest/m2/unused-api/net.md) - makes the lite version predicates crate-private beside the opaque `Version` diff --git a/quest/m2/session-codes.md b/quest/m2/session-codes.md deleted file mode 100644 index 9f62cb040c0..00000000000 --- a/quest/m2/session-codes.md +++ /dev/null @@ -1,68 +0,0 @@ -# [M] Session close codes name only moq-lite's registry, and errors classify themselves - -## Goal - -`moq_net::SessionError` has a variant only for a code in moq-lite's registry. -The seven codes only moq-transport defines decode to -`SessionError::Unknown(code)`, which already keeps the number, and are gone -from moq-ffi's `MoqProtocolKind`, moq-c's `MOQ_PROTOCOL_KIND_*`, and JS's -session codes. `moq_net::Error` has a public method that answers what a -caller does next (retry on the same source, find another route, or stop), so -no crate matches error variants to decide, and moq-gst uses it. - -## Plan - -Decided 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): ✅ the -seven moq-transport-only codes decode to `Unknown(code)` and a classification -method becomes public (rejected: also folding the flat `Error` variants into -the two registries now; keeping the variants). AGENTS.md says never to add -API for functionality only moq-transport has, and never to match on errors; -today the first forces the second. - -Facts found by the audit, checked at `80ca9787e3`: - -- The seven are `InvalidRequestId`, `KeyValueFormatting`, `InvalidPath`, - `AuthTokenCacheOverflow`, `UnknownAuthTokenAlias`, `InvalidAuthority`, and - `TooManyRequestUpdates` (`rs/moq-net/src/error.rs:90,39,94,57,69,98,74`). - None is in the lite-07 registry in `drafts/draft-lcurley-moq-lite.md`, - which removed KEY_VALUE_FORMATTING_ERROR in lite-07. Six were added in the - window. -- Each is mirrored into moq-ffi (`rs/moq-ffi/src/error.rs`) and moq-c - (`rs/moq-c/src/error.rs`), 7 lines each, and JS lists them in - `js/net/src/error.ts:43-63`. -- The only classification, `Error::retryable`, `unroutable`, and `transient` - (`rs/moq-net/src/error.rs:609-620`), is `pub(crate)`. moq-gst rebuilt it by - matching variants, two of the seven among them - (`rs/moq-gst/src/source/imp.rs:1034-1049`, `source_lost`). -- `Error` says "unauthorized" three ways (`Error::Unauthorized`, - `Session(SessionError::Unauthorized)`, `Stream(StreamError::Unauthorized)`), - and its doc defers folding them to "a later decision" - (`rs/moq-net/src/error.rs:342`). That fold stays deferred. - -For the PR: - -- The moq-transport layer keeps a private table to send these codes; only - decoding and the public enum change. A code received from a peer is - logged with its number. -- Design the public method from its callers, not from the private three: - moq-gst asks "did the source go away, or did it refuse me", and resume - asks "same source or another route". Recommended: one method returning a - small `#[non_exhaustive]` enum (for example `Retry::{Same, Reroute, Never}`) - rather than three booleans, mirrored by JS's `routeFailed` - (`js/net/src/resume.ts`). Survey every match on a `moq_net::Error` variant - outside moq-net first (about 50 lines by grep) and move each caller the - method answers; list the ones it cannot answer in the PR. -- moq-gst's `source_lost` and `catalog_lost` become calls to it. -- Mirror the removal in moq-ffi, moq-c, each wrapper's error type, and JS. - -Tests: each of the seven code numbers received on a moq-transport session -closes it with `Unknown(code)` and the same classification as before; moq-gst -holds its pads on a lost source and fails on a refusal, as today. - -Public API: breaking in Rust (`SessionError` variants), moq-ffi -(`MoqProtocolKind`), moq-c (`moq.h` constants), the wrappers, and JS; adds -the classification method. Wire: none. - -## Related - -- [moq-net's node, version, handshake, and route priority](/quest/m2/net-renames.md) - the renames beside this in the same crate diff --git a/quest/m2/ts-follow-retry.md b/quest/m2/ts-follow-retry.md new file mode 100644 index 00000000000..6c91e85384e --- /dev/null +++ b/quest/m2/ts-follow-retry.md @@ -0,0 +1,34 @@ +# [S] The TS follower judges a publisher leaving by its error's retry answer + +## Goal + +`moq_mux::container::ts::follower::left` asks `moq_net::Error::retry` +whether the publisher left, instead of matching `moq_net::Error` variants, +so the TS export and moq-gst's `moqsrc` agree on what ends a run. + +## Plan + +`left` (`rs/moq-mux/src/container/ts/follower.rs`) matches `Unroutable`, +`Stream(Unroutable | Session(_))`, `Session(_)`, `Transport(_)`, +`IdleTimeout`, and `Remote(_)`. `retry() != Retry::Never` differs on two +groups, each pinned by a test in `export_test.rs`: + +- `Cancel`, `Closed`, `GoingAway`, `Dropped`, and the stream codes + `Internal`, `Cancel`, `GoingAway`, and `ControlTimeout` are a failed + delivery to `retry` but the export's own failure to `left` + (`a_follower_fails_at_once_on_its_own_failure`). +- `Remote(_)`, an unregistered moq-transport request code, is a verdict to + `retry` but a publisher leaving to `left`, because a relay's lost route + reaches a moq-transport reader as an unregistered PUBLISH_DONE status + (`a_follower_waits_out_the_follow_on_a_lost_route`). + +Recommended: adopt `retry`, treating a cancel or GOAWAY reset as the +publisher leaving as `moqsrc` does, and have the moq-transport subscriber +read PUBLISH_DONE's unregistered status as `Unroutable` so a lost route +stays a reroute without `left` special-casing `Remote`. + +## Waiting + +- Maintainer: whether a cancel, GOAWAY, or INTERNAL_ERROR reset counts as + the publisher leaving (follow it) or as the export's own failure (end at + once). Recommended: leaving, matching `moqsrc` and `Error::retry`. diff --git a/rs/moq-c/src/error.rs b/rs/moq-c/src/error.rs index e2c101f7344..3ded7ef53b2 100644 --- a/rs/moq-c/src/error.rs +++ b/rs/moq-c/src/error.rs @@ -147,7 +147,7 @@ pub enum moq_protocol_kind { MOQ_PROTOCOL_KIND_TIMESTAMP_MISMATCH = 22, /// App. MOQ_PROTOCOL_KIND_APP = 23, - /// Unknown. + /// A code moq-lite does not name, such as one only moq-transport defines. MOQ_PROTOCOL_KIND_UNKNOWN = 24, /// The session exceeded its announcement or subscription cap. MOQ_PROTOCOL_KIND_TOO_MANY_REQUESTS = 25, diff --git a/rs/moq-ffi/src/error.rs b/rs/moq-ffi/src/error.rs index 5a36fb25b87..d484690b21a 100644 --- a/rs/moq-ffi/src/error.rs +++ b/rs/moq-ffi/src/error.rs @@ -59,7 +59,8 @@ pub enum MoqProtocolKind { TimestampMismatch, /// An application-chosen code, offset into the 64+ range on the wire. App, - /// A code this version does not recognize; [`MoqProtocolError::code`] is the value. + /// A code moq-lite does not name, such as one only moq-transport defines; + /// [`MoqProtocolError::code`] is the value. Unknown, /// The session exceeded its announcement or subscription cap. TooManyRequests, From 4339595da69d8949aa24eaef506f385933d52f45 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 09:14:08 -0800 Subject: [PATCH 6/9] fix: a moq-transport INTERNAL_ERROR PUBLISH_DONE reads as a lost route --- js/net/src/ietf/subscriber.ts | 8 ++++++++ js/net/src/ietf/tail.test.ts | 6 ++++-- quest/m2/ts-follow-retry.md | 12 ++++++------ rs/moq-ffi/src/test.rs | 11 ++++------- rs/moq-mux/src/container/ts/export_test.rs | 4 ++-- rs/moq-net/src/ietf/publish.rs | 11 ++++++++++- rs/moq-net/src/ietf/subscriber/tracks.rs | 5 ++++- 7 files changed, 38 insertions(+), 19 deletions(-) diff --git a/js/net/src/ietf/subscriber.ts b/js/net/src/ietf/subscriber.ts index 2b898d488b8..bd5df310365 100644 --- a/js/net/src/ietf/subscriber.ts +++ b/js/net/src/ietf/subscriber.ts @@ -1361,6 +1361,14 @@ export class Subscriber { message: `publish done: malformed track reason=${done.reasonPhrase}`, }); } + // moq-transport has no code for a lost route, so a relay that loses its upstream ends the + // subscription with INTERNAL_ERROR, where a moq-lite relay resets with UNROUTABLE. Read the + // two alike, so a reader asks another route on either wire. Mirrors the Rust `PublishDone::end`. + if (done.statusCode === PublishDoneStatus.INTERNAL_ERROR) { + throw new StreamError(StreamCode.Unroutable, { + message: `publish done: internal error reason=${done.reasonPhrase}`, + }); + } if (!publishDoneClean(done.statusCode, version)) { throw new Error(`publish done: status=0x${done.statusCode.toString(16)} reason=${done.reasonPhrase}`); } diff --git a/js/net/src/ietf/tail.test.ts b/js/net/src/ietf/tail.test.ts index c2b880d8693..0ea05576e65 100644 --- a/js/net/src/ietf/tail.test.ts +++ b/js/net/src/ietf/tail.test.ts @@ -162,10 +162,12 @@ test("a Stream Count of 0 is a hint, so a late stream within the grace is still expect(await reader.closed).toBeNull(); }); -test("a PUBLISH_DONE with an error status aborts the track", async () => { +test("an INTERNAL_ERROR PUBLISH_DONE reads as the lost route a moq-lite relay names", async () => { const { reader, done } = await subscribed(); await done(INTERNAL_ERROR, 0n); - expect(await reader.closed).toBeInstanceOf(Error); + const closed = await reader.closed; + expect(closed).toBeInstanceOf(StreamError); + expect((closed as StreamError).code).toBe(StreamCode.Unroutable); }); // SUBSCRIPTION_ENDED ends only the subscription: a later one continues the track past these diff --git a/quest/m2/ts-follow-retry.md b/quest/m2/ts-follow-retry.md index 6c91e85384e..57940ccc2aa 100644 --- a/quest/m2/ts-follow-retry.md +++ b/quest/m2/ts-follow-retry.md @@ -18,14 +18,14 @@ groups, each pinned by a test in `export_test.rs`: delivery to `retry` but the export's own failure to `left` (`a_follower_fails_at_once_on_its_own_failure`). - `Remote(_)`, an unregistered moq-transport request code, is a verdict to - `retry` but a publisher leaving to `left`, because a relay's lost route - reaches a moq-transport reader as an unregistered PUBLISH_DONE status - (`a_follower_waits_out_the_follow_on_a_lost_route`). + `retry` but a publisher leaving to `left` + (`a_follower_waits_out_the_follow_on_a_lost_route`). A relay's lost route + no longer arrives this way: PUBLISH_DONE's INTERNAL_ERROR reads as + `Unroutable` on both wires. Recommended: adopt `retry`, treating a cancel or GOAWAY reset as the -publisher leaving as `moqsrc` does, and have the moq-transport subscriber -read PUBLISH_DONE's unregistered status as `Unroutable` so a lost route -stays a reroute without `left` special-casing `Remote`. +publisher leaving as `moqsrc` does, and an unregistered moq-transport code +as the verdict it is to every other reader. ## Waiting diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index 7b55eaeedf9..418fe8ea246 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -5966,13 +5966,10 @@ async fn server_client_run_end(version: &str) { else { panic!("withdrawal falsely declared the unfinished track complete"); }; - if version == "moq-lite-07-wip" { - assert_protocol(&error, crate::error::MoqErrorScope::Stream, MoqProtocolKind::Unroutable); - } else { - // The IETF PUBLISH_DONE registry has no Unroutable, so the publisher sends INTERNAL_ERROR - // and the reader keeps it. Neither TRACK_ENDED nor an EOF fits withdrawn content. - assert!(matches!(error, MoqError::Internal { .. }), "{version}: {error:?}"); - } + // The IETF PUBLISH_DONE registry has no Unroutable, so the publisher sends INTERNAL_ERROR, + // which the reader takes for the lost route a moq-lite reset names. Neither TRACK_ENDED nor + // an EOF fits withdrawn content. + assert_protocol(&error, crate::error::MoqErrorScope::Stream, MoqProtocolKind::Unroutable); while kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("catalog end timed out") diff --git a/rs/moq-mux/src/container/ts/export_test.rs b/rs/moq-mux/src/container/ts/export_test.rs index 90493d18f9b..e0d97034791 100644 --- a/rs/moq-mux/src/container/ts/export_test.rs +++ b/rs/moq-mux/src/container/ts/export_test.rs @@ -9980,8 +9980,8 @@ async fn a_follower_fails_at_once_on_its_own_failure() { /// A track that lost its route, or whose session ended, says the publisher left even with the /// broadcast still announced: the follower waits out the follow for a return, then fails with -/// that cause. moq-transport's PUBLISH_DONE has no code for a lost route, so a relay's copy -/// reads there as an unregistered one. +/// that cause. An unregistered moq-transport code names no cause, so it reads as leaving +/// too. #[tokio::test(start_paused = true)] async fn a_follower_waits_out_the_follow_on_a_lost_route() { let causes = [ diff --git a/rs/moq-net/src/ietf/publish.rs b/rs/moq-net/src/ietf/publish.rs index e1e0ad6dc63..c4bf1cbb766 100644 --- a/rs/moq-net/src/ietf/publish.rs +++ b/rs/moq-net/src/ietf/publish.rs @@ -172,6 +172,12 @@ impl PublishDone<'_> { match self.status_code { code if code == PublishDoneStatus::TrackEnded.code() => Ok(()), code if code == PublishDoneStatus::Unauthorized.code() => Err(crate::Error::Unauthorized), + // moq-transport has no code for a lost route, so a relay that loses its upstream ends + // the subscription with INTERNAL_ERROR, where a moq-lite relay resets with UNROUTABLE. + // Read the two alike, so a reader asks another route on either wire. + code if code == PublishDoneStatus::InternalError.code() => { + Err(crate::Error::Stream(crate::StreamError::Unroutable)) + } // The peer's code, as a moq-lite MALFORMED_TRACK reset reads, so bindings name it. code if code == PublishDoneStatus::MalformedTrack.code() => { Err(crate::Error::Stream(crate::StreamError::MalformedTrack)) @@ -527,7 +533,10 @@ mod tests { "{version:?}" ); assert!( - matches!(done(0x0).end(version), Err(crate::Error::Remote(0x0))), + matches!( + done(0x0).end(version), + Err(crate::Error::Stream(crate::StreamError::Unroutable)) + ), "{version:?}" ); assert!( diff --git a/rs/moq-net/src/ietf/subscriber/tracks.rs b/rs/moq-net/src/ietf/subscriber/tracks.rs index ff282d90eb2..347f05e50b9 100644 --- a/rs/moq-net/src/ietf/subscriber/tracks.rs +++ b/rs/moq-net/src/ietf/subscriber/tracks.rs @@ -2164,7 +2164,10 @@ mod tests { let version = Version::Draft22; for (status, expected) in [ (ietf::PublishDoneStatus::Unauthorized, Error::Unauthorized), - (ietf::PublishDoneStatus::InternalError, Error::Remote(0)), + ( + ietf::PublishDoneStatus::InternalError, + Error::Stream(crate::StreamError::Unroutable), + ), ] { let mut h = harness(version); let _listing = h.establish().await; From 88369cd80e5baa0594504d9f7d1753719519154d Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 13:07:13 -0800 Subject: [PATCH 7/9] fix: an INTERNAL_ERROR PUBLISH_DONE stays a verdict, and moq-transport paths read session codes with its registry PUBLISH_DONE INTERNAL_ERROR carries publisher verdicts as well as a relay's lost upstream, so reading it as Unroutable parked readers on a verdict. Revert to Remote(0), as moq-lite's UNROUTABLE stays the only lost-route signal. The moq-transport paths that called Error::from_transport directly decoded a session close with moq-lite's registry, reading 0x30 as Unsupported. Route them through the negotiated version. Co-Authored-By: Claude Sonnet 5.5 --- js/net/src/ietf/subscriber.ts | 8 ------ js/net/src/ietf/tail.test.ts | 6 ++-- quest/m2/ts-follow-retry.md | 14 +++++----- rs/moq-ffi/src/test.rs | 11 +++++--- rs/moq-mux/src/container/ts/export_test.rs | 4 +-- rs/moq-net/src/ietf/publish.rs | 11 +------- rs/moq-net/src/ietf/publisher.rs | 8 +++--- rs/moq-net/src/ietf/session.rs | 32 ++++++++++++++++++---- rs/moq-net/src/ietf/subscriber.rs | 4 +-- rs/moq-net/src/ietf/subscriber/tracks.rs | 5 +--- 10 files changed, 53 insertions(+), 50 deletions(-) diff --git a/js/net/src/ietf/subscriber.ts b/js/net/src/ietf/subscriber.ts index bd5df310365..2b898d488b8 100644 --- a/js/net/src/ietf/subscriber.ts +++ b/js/net/src/ietf/subscriber.ts @@ -1361,14 +1361,6 @@ export class Subscriber { message: `publish done: malformed track reason=${done.reasonPhrase}`, }); } - // moq-transport has no code for a lost route, so a relay that loses its upstream ends the - // subscription with INTERNAL_ERROR, where a moq-lite relay resets with UNROUTABLE. Read the - // two alike, so a reader asks another route on either wire. Mirrors the Rust `PublishDone::end`. - if (done.statusCode === PublishDoneStatus.INTERNAL_ERROR) { - throw new StreamError(StreamCode.Unroutable, { - message: `publish done: internal error reason=${done.reasonPhrase}`, - }); - } if (!publishDoneClean(done.statusCode, version)) { throw new Error(`publish done: status=0x${done.statusCode.toString(16)} reason=${done.reasonPhrase}`); } diff --git a/js/net/src/ietf/tail.test.ts b/js/net/src/ietf/tail.test.ts index 0ea05576e65..c2b880d8693 100644 --- a/js/net/src/ietf/tail.test.ts +++ b/js/net/src/ietf/tail.test.ts @@ -162,12 +162,10 @@ test("a Stream Count of 0 is a hint, so a late stream within the grace is still expect(await reader.closed).toBeNull(); }); -test("an INTERNAL_ERROR PUBLISH_DONE reads as the lost route a moq-lite relay names", async () => { +test("a PUBLISH_DONE with an error status aborts the track", async () => { const { reader, done } = await subscribed(); await done(INTERNAL_ERROR, 0n); - const closed = await reader.closed; - expect(closed).toBeInstanceOf(StreamError); - expect((closed as StreamError).code).toBe(StreamCode.Unroutable); + expect(await reader.closed).toBeInstanceOf(Error); }); // SUBSCRIPTION_ENDED ends only the subscription: a later one continues the track past these diff --git a/quest/m2/ts-follow-retry.md b/quest/m2/ts-follow-retry.md index 57940ccc2aa..dcdf85c5549 100644 --- a/quest/m2/ts-follow-retry.md +++ b/quest/m2/ts-follow-retry.md @@ -17,15 +17,15 @@ groups, each pinned by a test in `export_test.rs`: `Internal`, `Cancel`, `GoingAway`, and `ControlTimeout` are a failed delivery to `retry` but the export's own failure to `left` (`a_follower_fails_at_once_on_its_own_failure`). -- `Remote(_)`, an unregistered moq-transport request code, is a verdict to - `retry` but a publisher leaving to `left` - (`a_follower_waits_out_the_follow_on_a_lost_route`). A relay's lost route - no longer arrives this way: PUBLISH_DONE's INTERNAL_ERROR reads as - `Unroutable` on both wires. +- `Remote(_)`, a code moq-lite does not assign, is a verdict to `retry` but a + publisher leaving to `left` (`a_follower_waits_out_the_follow_on_a_lost_route`). + Over moq-transport a relay's lost upstream and a publisher's own failure both + end with PUBLISH_DONE INTERNAL_ERROR (`Remote(0)`), which no reader can tell + apart, so `retry` cannot answer for it. Recommended: adopt `retry`, treating a cancel or GOAWAY reset as the -publisher leaving as `moqsrc` does, and an unregistered moq-transport code -as the verdict it is to every other reader. +publisher leaving as `moqsrc` does, and keep `Remote(_)` as the one case +`left` still matches, as moq-transport's lost route. ## Waiting diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index 418fe8ea246..7b55eaeedf9 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -5966,10 +5966,13 @@ async fn server_client_run_end(version: &str) { else { panic!("withdrawal falsely declared the unfinished track complete"); }; - // The IETF PUBLISH_DONE registry has no Unroutable, so the publisher sends INTERNAL_ERROR, - // which the reader takes for the lost route a moq-lite reset names. Neither TRACK_ENDED nor - // an EOF fits withdrawn content. - assert_protocol(&error, crate::error::MoqErrorScope::Stream, MoqProtocolKind::Unroutable); + if version == "moq-lite-07-wip" { + assert_protocol(&error, crate::error::MoqErrorScope::Stream, MoqProtocolKind::Unroutable); + } else { + // The IETF PUBLISH_DONE registry has no Unroutable, so the publisher sends INTERNAL_ERROR + // and the reader keeps it. Neither TRACK_ENDED nor an EOF fits withdrawn content. + assert!(matches!(error, MoqError::Internal { .. }), "{version}: {error:?}"); + } while kio::clock::timeout(TIMEOUT, catalog_consumer.next()) .await .expect("catalog end timed out") diff --git a/rs/moq-mux/src/container/ts/export_test.rs b/rs/moq-mux/src/container/ts/export_test.rs index e0d97034791..90493d18f9b 100644 --- a/rs/moq-mux/src/container/ts/export_test.rs +++ b/rs/moq-mux/src/container/ts/export_test.rs @@ -9980,8 +9980,8 @@ async fn a_follower_fails_at_once_on_its_own_failure() { /// A track that lost its route, or whose session ended, says the publisher left even with the /// broadcast still announced: the follower waits out the follow for a return, then fails with -/// that cause. An unregistered moq-transport code names no cause, so it reads as leaving -/// too. +/// that cause. moq-transport's PUBLISH_DONE has no code for a lost route, so a relay's copy +/// reads there as an unregistered one. #[tokio::test(start_paused = true)] async fn a_follower_waits_out_the_follow_on_a_lost_route() { let causes = [ diff --git a/rs/moq-net/src/ietf/publish.rs b/rs/moq-net/src/ietf/publish.rs index c4bf1cbb766..e1e0ad6dc63 100644 --- a/rs/moq-net/src/ietf/publish.rs +++ b/rs/moq-net/src/ietf/publish.rs @@ -172,12 +172,6 @@ impl PublishDone<'_> { match self.status_code { code if code == PublishDoneStatus::TrackEnded.code() => Ok(()), code if code == PublishDoneStatus::Unauthorized.code() => Err(crate::Error::Unauthorized), - // moq-transport has no code for a lost route, so a relay that loses its upstream ends - // the subscription with INTERNAL_ERROR, where a moq-lite relay resets with UNROUTABLE. - // Read the two alike, so a reader asks another route on either wire. - code if code == PublishDoneStatus::InternalError.code() => { - Err(crate::Error::Stream(crate::StreamError::Unroutable)) - } // The peer's code, as a moq-lite MALFORMED_TRACK reset reads, so bindings name it. code if code == PublishDoneStatus::MalformedTrack.code() => { Err(crate::Error::Stream(crate::StreamError::MalformedTrack)) @@ -533,10 +527,7 @@ mod tests { "{version:?}" ); assert!( - matches!( - done(0x0).end(version), - Err(crate::Error::Stream(crate::StreamError::Unroutable)) - ), + matches!(done(0x0).end(version), Err(crate::Error::Remote(0x0))), "{version:?}" ); assert!( diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index 6a6cbf58c06..d2249a1587c 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -2697,7 +2697,7 @@ impl RunFill { let stream = match opening { Ok(stream) => stream, Err(err) => { - tracing::debug!(err = %Error::from_transport(err), fill = %self.request_id, "fill stream failed to open"); + tracing::debug!(err = %publisher.version.transport_error(err), fill = %self.request_id, "fill stream failed to open"); return Poll::Ready(()); } }; @@ -5495,7 +5495,7 @@ impl FetchRespond { waiter, self.rank.as_mut().expect("ranked until opened").options(), )) - .map_err(Error::from_transport)?; + .map_err(|err| self.version.transport_error(err))?; let mut writer: Writer, Version> = Writer::new(Ranked::new(uni, self.rank.take()).lapsing(&self.lapse), self.version); writer.buffer_varint(FetchHeader::TYPE)?; @@ -7678,7 +7678,7 @@ impl EndOfTrack { object: self.end.frame, }); let stream = wait!(Open => serve.session.poll_open_uni(&mut self.open, waiter, rank.options())) - .map_err(Error::from_transport)?; + .map_err(|err| serve.version.transport_error(err))?; serve.opened.fetch_add(1, Ordering::Relaxed); let stream = Ranked::new(stream, Some(rank)).lapsing(&serve.ranking.lapse); let mut writer: Writer, Version> = @@ -8011,7 +8011,7 @@ impl GroupServe { Ok(stream) => stream, Err(err) => { self.state = GroupState::Done; - return Poll::Ready(Err(Error::from_transport(err))); + return Poll::Ready(Err(self.version.transport_error(err))); } }; self.opened.fetch_add(1, Ordering::Relaxed); diff --git a/rs/moq-net/src/ietf/session.rs b/rs/moq-net/src/ietf/session.rs index 6e64e135658..73ec6f3796e 100644 --- a/rs/moq-net/src/ietf/session.rs +++ b/rs/moq-net/src/ietf/session.rs @@ -3,7 +3,7 @@ use crate::origin; use crate::transport::poll::Session as _; use crate::{ Error, Hop, SessionError, StreamError, - coding::{Decode, DecodeError, Encode, Reader, Stream, Writer}, + coding::{Decode, DecodeError, Encode, Reader, Stream, StreamCodes as _, Writer}, ietf::{self, FetchHeader, RequestId}, setup, util::TaskSet, @@ -405,6 +405,7 @@ impl Launch { let datagrams = (session.max_datagram_size() != 0).then(|| Datagrams { session: session.clone(), subscriber: subscriber.clone(), + version, held: Vec::new(), caught_up: true, }); @@ -675,7 +676,8 @@ impl SetupAccept { self.step = SetupStep::Accept; } SetupStep::Accept => { - let recv = ready!(session.poll_accept_uni(waiter)).map_err(Error::from_transport)?; + let recv = + ready!(session.poll_accept_uni(waiter)).map_err(|err| self.version.transport_error(err))?; self.step = SetupStep::Peek(Reader::new(recv, crate::Version::Ietf(self.version))); } SetupStep::Peek(reader) => { @@ -890,7 +892,7 @@ impl SendSetup { match &mut self.step { SetupSend::Open(open, _) => { let send = ready!(self.session.poll_open_uni(open, waiter, Default::default())) - .map_err(Error::from_transport)?; + .map_err(|err| self.version.transport_error(err))?; let SetupSend::Open(_, params) = std::mem::replace(&mut self.step, SetupSend::Done) else { unreachable!("matched above"); }; @@ -1073,7 +1075,7 @@ impl Unis { None => match self.session.poll_accept_uni(waiter) { Poll::Ready(Ok(recv)) => Reader::new(recv, crate::Version::Ietf(self.uni.version)), Poll::Ready(Err(err)) => { - self.ended = Some(Error::from_transport(err)); + self.ended = Some(self.uni.version.transport_error(err)); break; } Poll::Pending => break, @@ -1301,6 +1303,7 @@ fn died_before_header(err: &Error) -> bool { struct Datagrams { session: Transport, subscriber: Subscriber, + version: Version, /// Unknown aliases held before the source machines run: at most one receive budget. held: Vec, /// Whether the receive pass read the queue empty rather than yielding to its budget. @@ -1325,7 +1328,7 @@ impl Datagrams { for payload in std::mem::take(&mut self.held) { self.route(payload, false)?; } - return Poll::Ready(Err(Error::from_transport(err))); + return Poll::Ready(Err(self.version.transport_error(err))); } }; self.route(payload, hold)?; @@ -2704,6 +2707,25 @@ mod tests { (log, None) } + /// A session close reads against moq-transport's registry on every path, so a peer closing + /// with a code only moq-lite assigns (0x30, NOT_SUPPORTED there) is an unknown code here. + #[kio::test] + async fn a_session_closed_with_a_moq_lite_code_reads_unknown() { + for version in [Version::Draft18, Version::Draft20, Version::Draft22] { + let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()); + crate::transport::poll::Session::close(&session, 0x30, "closed by the peer"); + let (_, result) = drive_unis(version, session, None, None).await; + let Some(Err(err)) = result else { + panic!("{version:?}: the closed session did not end the accept loop: {result:?}"); + }; + assert_eq!( + err.session(), + Some(&SessionError::Unknown(0x30)), + "{version:?}: {err:?}" + ); + } + } + /// A peer opening uni streams at once gets a budget of them accepted per poll, leaving /// the rest for later so the session's other tasks run in between. #[kio::test] diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index fee42914c10..69e3d451685 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -8,7 +8,7 @@ use std::{ use crate::{ Error, Path, SessionError, Timescale, broadcast, - coding::{Decode, DecodeError, Decoder, Reader, Stream, Writer}, + coding::{Decode, DecodeError, Decoder, Reader, Stream, StreamCodes as _, Writer}, frame, group, ietf::{self, Control, FetchType, Filter, GroupOrder, RequestId}, origin, track, @@ -5959,7 +5959,7 @@ impl LearnTrackStatus { } else if let Poll::Ready(res) = response { Some(SetupResponse::Response(res)) } else if let Poll::Ready(err) = this.session.poll_closed(waiter) { - Some(SetupResponse::Cancelled(Error::from_transport(err))) + Some(SetupResponse::Cancelled(this.version.transport_error(err))) } else { // A fetch needs nothing from the status to go out, only to read its objects. while let Poll::Ready(Ok(fill)) = asked.dynamic.poll_requested_fill(waiter) { diff --git a/rs/moq-net/src/ietf/subscriber/tracks.rs b/rs/moq-net/src/ietf/subscriber/tracks.rs index 347f05e50b9..ff282d90eb2 100644 --- a/rs/moq-net/src/ietf/subscriber/tracks.rs +++ b/rs/moq-net/src/ietf/subscriber/tracks.rs @@ -2164,10 +2164,7 @@ mod tests { let version = Version::Draft22; for (status, expected) in [ (ietf::PublishDoneStatus::Unauthorized, Error::Unauthorized), - ( - ietf::PublishDoneStatus::InternalError, - Error::Stream(crate::StreamError::Unroutable), - ), + (ietf::PublishDoneStatus::InternalError, Error::Remote(0)), ] { let mut h = harness(version); let _listing = h.establish().await; From b6722595b5a8bf8b04e1af8193f29a9a6c803bff Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 14:39:19 -0800 Subject: [PATCH 8/9] quest: record the TS follower retry decision Co-Authored-By: Claude Sonnet 5.5 --- quest/m2/ts-follow-retry.md | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/quest/m2/ts-follow-retry.md b/quest/m2/ts-follow-retry.md index dcdf85c5549..4279a5478ed 100644 --- a/quest/m2/ts-follow-retry.md +++ b/quest/m2/ts-follow-retry.md @@ -23,12 +23,9 @@ groups, each pinned by a test in `export_test.rs`: end with PUBLISH_DONE INTERNAL_ERROR (`Remote(0)`), which no reader can tell apart, so `retry` cannot answer for it. -Recommended: adopt `retry`, treating a cancel or GOAWAY reset as the -publisher leaving as `moqsrc` does, and keep `Remote(_)` as the one case -`left` still matches, as moq-transport's lost route. - -## Waiting - -- Maintainer: whether a cancel, GOAWAY, or INTERNAL_ERROR reset counts as - the publisher leaving (follow it) or as the export's own failure (end at - once). Recommended: leaving, matching `moqsrc` and `Error::retry`. +Settled (maintainer, 2026-11-16, +[#8955](https://github.com/moq-dev/moq/pull/8955#issuecomment-6930707585)): +adopt `retry`, so a cancel, GOAWAY, or INTERNAL_ERROR reset counts as the +publisher leaving, as `moqsrc` does. Rejected: counting it as the export's +own failure. `left` keeps `Remote(_)` as the one case it still matches, as +moq-transport's lost route. From 0e8ea0350f2096d81ed9117c3e1c290e84734ce3 Mon Sep 17 00:00:00 2001 From: quest fixer Date: Mon, 16 Nov 2026 15:04:31 -0800 Subject: [PATCH 9/9] fix(net): use consolidated transport error conversion in route stream --- rs/moq-net/src/lite/subscriber/route_stream.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rs/moq-net/src/lite/subscriber/route_stream.rs b/rs/moq-net/src/lite/subscriber/route_stream.rs index e51f2a70c7f..716c62a8c5b 100644 --- a/rs/moq-net/src/lite/subscriber/route_stream.rs +++ b/rs/moq-net/src/lite/subscriber/route_stream.rs @@ -160,7 +160,7 @@ impl RouteStream { State::Opening => { let session = &self.subscriber.session; let stream = ready!(session.poll_open_uni(&mut self.open, waiter, Default::default())) - .map_err(lite::error::from_transport)?; + .map_err(Error::from_transport)?; let mut writer: Writer = Writer::new(stream, self.subscriber.version).with_stats(self.subscriber.origin.stats()); writer.buffer(&lite::DataType::Announce)?;