diff --git a/doc/bin/gstreamer.md b/doc/bin/gstreamer.md index 8ada68a53b7..4fca7f8465f 100644 --- a/doc/bin/gstreamer.md +++ b/doc/bin/gstreamer.md @@ -171,9 +171,14 @@ gets EOS once its track ends. A broadcast that ends or loses its publisher holds 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`, +that reaches no relay posts an error rather than retrying, as does a first +connection the relay refuses, or a session it closes before the connection has +stayed up for a second. Once playback has begun, a session the relay closes is +redialed, whatever its code, and a refused redial is retried like any other +failure. A refused path or catalog, malformed input or catalog, or a catalog its +publisher ended with an application code posts an error. A media track its +publisher ended with an application code logs a warning and leaves its pad idle; +it posts no error. 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/go/wrapper/types.go b/go/wrapper/types.go index c284d6067c1..38fb711a0c8 100644 --- a/go/wrapper/types.go +++ b/go/wrapper/types.go @@ -217,8 +217,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. @@ -253,20 +251,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/api/index.api.md b/js/net/api/index.api.md index b1c2986f661..af73062d5d3 100644 --- a/js/net/api/index.api.md +++ b/js/net/api/index.api.md @@ -332,6 +332,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; @@ -362,6 +368,7 @@ export namespace Error { cause?: unknown; }); } + export function retry(err: unknown): Error.Retry; } export namespace Frame { @@ -578,22 +585,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 0b1ccedc0af..1c8dea06bec 100644 --- a/js/net/src/connection/handshake.ts +++ b/js/net/src/connection/handshake.ts @@ -1,6 +1,7 @@ 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"; @@ -160,10 +161,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 fa73a4a18bf..e4713226780 100644 --- a/js/net/src/error.test.ts +++ b/js/net/src/error.test.ts @@ -9,7 +9,9 @@ import { Lagged, NotFound, ProtocolViolation, + Retry, reason, + 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(Number(fromClose({ closeCode: code })?.code)).toBe(code); + expect(Object.values(SessionCode) as number[]).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 48ee48fabfd..529ad9fe5f3 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), ); @@ -405,6 +393,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 bdbb532bf1e..efc993f5436 100644 --- a/js/net/src/ietf/connection.test.ts +++ b/js/net/src/ietf/connection.test.ts @@ -8,6 +8,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"; @@ -378,11 +379,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); @@ -416,10 +417,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 8a4c2a92856..46fb4933ab9 100644 --- a/js/net/src/ietf/connection.ts +++ b/js/net/src/ietf/connection.ts @@ -7,14 +7,14 @@ import type { Goaway } 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"; 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"; @@ -578,7 +578,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 57d17924007..cb1f7bbfe21 100644 --- a/js/net/src/ietf/malformed.test.ts +++ b/js/net/src/ietf/malformed.test.ts @@ -9,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 { GoAway } from "./goaway.ts"; import { RequestOk } from "./request.ts"; import { Setup } from "./setup.ts"; @@ -107,7 +108,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], @@ -257,9 +258,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 () => { @@ -287,8 +288,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..6b4b3145e50 100644 --- a/js/net/src/ietf/request_ids.test.ts +++ b/js/net/src/ietf/request_ids.test.ts @@ -1,5 +1,6 @@ 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 { @@ -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..0c2a0cc6ffa 100644 --- a/js/net/src/ietf/session.ts +++ b/js/net/src/ietf/session.ts @@ -1,5 +1,6 @@ -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. */ @@ -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..a090bff82a2 100644 --- a/js/net/src/ietf/token.test.ts +++ b/js/net/src/ietf/token.test.ts @@ -2,6 +2,7 @@ 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 { @@ -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..c6fb5b346ff 100644 --- a/js/net/src/ietf/token.ts +++ b/js/net/src/ietf/token.ts @@ -1,5 +1,6 @@ -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"; @@ -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 883b2dd73d6..03724a28914 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 165814dd72a..173b5560f0b 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, @@ -548,9 +548,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/quest/m2/README.md b/quest/m2/README.md index 0f156eb979f..d6339ba8fa8 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -35,8 +35,7 @@ removal, a rename, or a wire, catalog, or format change that is free until of [cache-aware multicast](/quest/m2/multicast/README.md), whose [switch](/quest/m2/multicast/switch.md) also settles the public route API and retires the moq-cluster draft. -- **moq-net API.** [Session codes](/quest/m2/session-codes.md). - [Socket endpoints](/quest/m2/sockets/README.md) leave for Kixel, and the +- **moq-net API.** [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 item re-checked for a downstream caller first. diff --git a/quest/m2/session-codes.md b/quest/m2/session-codes.md deleted file mode 100644 index 72982b867b5..00000000000 --- a/quest/m2/session-codes.md +++ /dev/null @@ -1,64 +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. diff --git a/quest/m2/ts-follow-retry.md b/quest/m2/ts-follow-retry.md new file mode 100644 index 00000000000..4279a5478ed --- /dev/null +++ b/quest/m2/ts-follow-retry.md @@ -0,0 +1,31 @@ +# [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(_)`, 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. + +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. diff --git a/rs/moq-c/src/error.rs b/rs/moq-c/src/error.rs index 956e85252e3..ef274a54bc3 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. @@ -149,26 +147,14 @@ 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, /// 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. @@ -467,18 +453,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, @@ -607,19 +586,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 11d1af231e9..aa83e19fe42 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. @@ -61,26 +59,15 @@ 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, /// 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 +121,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 +545,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 +559,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 fc0cb003329..690ff47d73f 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,29 @@ 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), + moq_net::Error::Stream(moq_net::StreamError::App(1)), ] { 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:?}"); } @@ -6048,25 +6044,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. @@ -6235,7 +6225,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, diff --git a/rs/moq-net/src/coding/codes.rs b/rs/moq-net/src/coding/codes.rs index 4ab8833c24a..b3f5ab181a7 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 ce179f91d5f..a697914e9bd 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), @@ -597,42 +556,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 { @@ -802,34 +785,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), ] { @@ -838,10 +810,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. @@ -952,6 +930,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 6b23f7942d4..042ee93dfcb 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 b64e6c9e80d..4bb8b07bc6a 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -2674,7 +2674,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(()); } }; @@ -5446,7 +5446,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)?; @@ -7592,7 +7592,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> = @@ -7964,7 +7964,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); @@ -10860,18 +10860,22 @@ 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", ), ] { @@ -17504,7 +17508,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..8324fc59bf6 100644 --- a/rs/moq-net/src/ietf/request_update.rs +++ b/rs/moq-net/src/ietf/request_update.rs @@ -9,17 +9,15 @@ //! //! 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}; 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; @@ -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 6a98fc388f1..4b268378cc6 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) => { @@ -750,10 +752,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( @@ -888,7 +890,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"); }; @@ -1071,7 +1073,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, @@ -1299,6 +1301,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. @@ -1323,7 +1326,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)?; @@ -1705,7 +1708,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(SessionError::InvalidRequestId).into())); + return Poll::Ready(Err(DecodeError::Session( + crate::ietf::error::session::INVALID_REQUEST_ID, + ) + .into())); } _ => {} } @@ -2699,6 +2705,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] @@ -3162,19 +3187,27 @@ 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", ), ] { @@ -3276,8 +3309,11 @@ 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()); @@ -3295,7 +3331,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), ] { @@ -3452,7 +3488,10 @@ 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 @@ -3474,8 +3513,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)), ] { @@ -3614,7 +3653,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 2142f90687b..d2c91de2652 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, @@ -5932,7 +5932,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_groups(waiter) { @@ -13844,7 +13844,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!( @@ -13852,7 +13852,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() ); @@ -14402,7 +14402,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..59b53e2ac02 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,10 @@ 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 +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(SessionError::UnknownAuthTokenAlias)), + 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(SessionError::KeyValueFormatting)), + matches!( + err, + DecodeError::Session(crate::ietf::error::session::KEY_VALUE_FORMATTING) + ), "{version:?} {why}: {err:?}" ); } @@ -433,7 +442,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 c483653976a..5e2ce460ae5 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -6264,7 +6264,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 b1149ac05a6..c1250a7bf37 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; } } @@ -774,7 +774,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), }; @@ -857,7 +857,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 a78f4f23b72..36f45b791e9 100644 --- a/rs/moq-net/src/lite/subscriber.rs +++ b/rs/moq-net/src/lite/subscriber.rs @@ -1274,7 +1274,7 @@ impl UniAccept { // here opens its group in the order the streams arrived. let _ = self.children.poll(waiter); } - 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, } } @@ -2023,7 +2023,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); @@ -2954,7 +2954,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)); @@ -11592,7 +11592,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) })?; @@ -11737,7 +11737,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(()); } @@ -12353,7 +12353,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)), @@ -12373,7 +12373,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) })?; @@ -13218,7 +13218,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; } @@ -13443,7 +13443,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/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)?; diff --git a/rs/moq-net/src/server.rs b/rs/moq-net/src/server.rs index 35a97eb2dfc..05187b1ca3e 100644 --- a/rs/moq-net/src/server.rs +++ b/rs/moq-net/src/server.rs @@ -2130,7 +2130,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());