moq_net/error.rs
1use crate::coding;
2
3/// A code sent when terminating the session.
4///
5/// moq-lite's session registry, which reuses moq-transport's value for each code the two
6/// share; 64+ are the application's. The stream registry is [`StreamError`] and the two
7/// are disjoint, so the same integer means different things in each.
8///
9/// Every variant is a code moq-lite assigns, and round-trips through
10/// [`to_code`](Self::to_code) and [`from_code`](Self::from_code). A code moq-lite does not
11/// assign, including those only moq-transport defines, is [`Unknown`](Self::Unknown) with
12/// its number. Codes 32 through 47 are reserved and have no assigned meaning.
13#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum SessionError {
16 /// Ending the session normally, with no error.
17 #[error("no error")]
18 Cancel,
19
20 /// Something went wrong that isn't worth a dedicated code.
21 #[error("internal error")]
22 Internal,
23
24 /// The peer's token does not grant the requested path or operation. Retrying with the
25 /// same credentials will fail again.
26 #[error("unauthorized")]
27 Unauthorized,
28
29 /// The peer's token has expired. Retrying with refreshed credentials may succeed.
30 #[error("authorization token expired")]
31 Expired,
32
33 /// The peer broke a protocol rule; the session is unusable.
34 #[error("protocol violation")]
35 ProtocolViolation,
36
37 /// The peer went past what the session allows, such as more announcements than its
38 /// `crate::session::Limits`.
39 #[error("too many requests")]
40 TooManyRequests,
41
42 /// The peer did not close within the GOAWAY drain deadline.
43 #[error("goaway timeout")]
44 GoawayTimeout,
45
46 /// A control message took too long.
47 #[error("control message timeout")]
48 Timeout,
49
50 /// No version could be negotiated.
51 #[error("version negotiation failed")]
52 Version,
53
54 /// The peer's token could not be parsed. Retrying with the same token will fail again.
55 #[error("malformed auth token")]
56 MalformedAuthToken,
57
58 /// An application-chosen code, offset into the 64+ range on the wire.
59 #[error("app code={0}")]
60 App(u16),
61
62 /// A code moq-lite does not assign, kept verbatim: one this version does not recognize,
63 /// or one only moq-transport defines.
64 #[error("unknown code={0}")]
65 Unknown(u32),
66
67 /// The peer cannot support the requested feature, token, or grant.
68 #[error("not supported")]
69 Unsupported,
70}
71
72impl SessionError {
73 /// The code moq-lite sends for this error.
74 pub fn to_code(&self) -> u32 {
75 match self {
76 Self::Cancel => 0x0,
77 Self::Internal => 0x1,
78 Self::Unauthorized => 0x2,
79 Self::Expired => 0x18,
80 Self::ProtocolViolation => 0x3,
81 Self::TooManyRequests => 0x7,
82 Self::GoawayTimeout => 0x10,
83 Self::Timeout => 0x11,
84 Self::Version => 0x15,
85 Self::MalformedAuthToken => 0x16,
86 Self::Unsupported => 0x30,
87 Self::App(app) => *app as u32 + 64,
88 Self::Unknown(code) => *code,
89 }
90 }
91
92 /// Decode a code from moq-lite's registry.
93 ///
94 /// Unlike a raw peer code, the registered ones are specified, so decoding them is a
95 /// wire contract rather than an assumption. Anything unregistered stays
96 /// [`Self::Unknown`], including the reserved 32-47 and the codes only moq-transport
97 /// defines.
98 pub fn from_code(code: u32) -> Self {
99 match code {
100 0x0 => Self::Cancel,
101 0x1 => Self::Internal,
102 0x2 => Self::Unauthorized,
103 0x18 => Self::Expired,
104 0x3 => Self::ProtocolViolation,
105 0x7 => Self::TooManyRequests,
106 0x10 => Self::GoawayTimeout,
107 0x11 => Self::Timeout,
108 0x15 => Self::Version,
109 0x16 => Self::MalformedAuthToken,
110 0x30 => Self::Unsupported,
111 code @ 64.. => match u16::try_from(code - 64) {
112 Ok(app) => Self::App(app),
113 Err(_) => Self::Unknown(code),
114 },
115 code => Self::Unknown(code),
116 }
117 }
118}
119
120/// A code sent when resetting a stream, or refusing to receive one.
121///
122/// The counterpart to [`SessionError`], and a disjoint space: a stream reset of 0 is
123/// [`Internal`](Self::Internal), not a cancellation ([`Cancel`](Self::Cancel) is 1).
124///
125/// Conditions the shared codes don't cover are assigned in moq-lite's own 48-63 range and
126/// round-trip like any other registered code. 32 through 47 is reserved: nothing is sent
127/// there and a received one stays [`Unknown`](Self::Unknown).
128#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
129#[non_exhaustive]
130pub enum StreamError {
131 /// The session ended, taking this stream with it.
132 ///
133 /// The specific [`SessionError`] is local only: the two registries are disjoint, so
134 /// this encodes to a single `SESSION_CLOSED` and the peer learns the reason from the
135 /// session close itself.
136 #[error("session closed: {0}")]
137 Session(#[from] SessionError),
138
139 /// Something went wrong that isn't worth a dedicated code.
140 #[error("internal error")]
141 Internal,
142
143 /// The sender is done with this stream, not failing. A routine unsubscribe.
144 #[error("cancelled")]
145 Cancel,
146
147 /// The content missed its delivery deadline.
148 #[error("delivery timeout")]
149 DeliveryTimeout,
150
151 /// The request asks what the publisher can't serve on this track.
152 #[error("not supported")]
153 NotSupported,
154
155 /// A control request took too long to be answered. The stream counterpart to
156 /// [`SessionError::Timeout`], which covers the same condition at session scope.
157 #[error("control timeout")]
158 ControlTimeout,
159
160 /// The session is going away (a GOAWAY was received).
161 #[error("going away")]
162 GoingAway,
163
164 /// The reader fell too far behind and content was dropped to catch up.
165 #[error("too far behind")]
166 TooFarBehind,
167
168 /// The track's content could not be parsed, or a track asked for again was accepted with
169 /// info other than what its readers already hold.
170 #[error("malformed track")]
171 MalformedTrack,
172
173 /// The requested broadcast or track does not exist at the peer.
174 #[error("not found")]
175 NotFound,
176
177 /// The broadcast is neither announced nor served, so there is no route to it.
178 #[error("unroutable")]
179 Unroutable,
180
181 /// The group was superseded by a newer group and dropped.
182 #[error("old")]
183 Old,
184
185 /// The group, or the frames a reader still needed from its front, was dropped under
186 /// memory pressure. Unlike [`Old`](Self::Old) it was still current, so it can be
187 /// re-fetched.
188 #[error("evicted")]
189 Evicted,
190
191 /// A frame's payload length disagreed with its declared size.
192 #[error("wrong frame size")]
193 WrongSize,
194
195 /// A frame declared a payload larger than the receiver accepts.
196 #[error("frame too large")]
197 FrameTooLarge,
198
199 /// A group could not make room for a write, even by shedding its front, and was aborted.
200 #[error("group too large")]
201 GroupTooLarge,
202
203 /// A frame's timestamp doesn't fit its track: missing on a timed track, present on an
204 /// untimed one, out of range for the track's timescale, or starting a group earlier
205 /// than the group before it.
206 #[error("frame timestamp doesn't fit its track")]
207 TimestampMismatch,
208
209 /// The publisher declared that no group will ever exist at these starts.
210 ///
211 /// Sent in `SUBSCRIBE_DROP` on lite-07: final, cacheable emptiness that ends no reader.
212 #[error("skipped")]
213 Skip,
214
215 /// The grant does not cover this subscription, fetch, or announcement, or no longer
216 /// does. Unlike [`SessionError::Unauthorized`], the session stays up.
217 #[error("unauthorized")]
218 Unauthorized,
219
220 /// An application-chosen code, offset into the 64+ range on the wire.
221 #[error("app code={0}")]
222 App(u16),
223
224 /// A code this version does not recognize, kept verbatim.
225 #[error("unknown code={0}")]
226 Unknown(u32),
227}
228
229impl StreamError {
230 /// The integer sent on the wire.
231 pub fn to_code(&self) -> u32 {
232 match self {
233 Self::Internal => 0x0,
234 Self::Cancel => 0x1,
235 Self::DeliveryTimeout => 0x2,
236 // Flattened: the session registry is disjoint, so the specific reason
237 // doesn't fit here and travels on the session close instead.
238 Self::Session(_) => 0x3,
239 Self::GoingAway => 0x4,
240 Self::TooFarBehind => 0x5,
241 Self::MalformedTrack => 0x12,
242 Self::ControlTimeout => 0x31,
243 Self::GroupTooLarge => 0x32,
244 Self::NotFound => 0x33,
245 Self::Old => 0x34,
246 Self::Evicted => 0x35,
247 Self::Unroutable => 0x36,
248 Self::WrongSize => 0x37,
249 Self::FrameTooLarge => 0x38,
250 Self::NotSupported => 0x30,
251 Self::TimestampMismatch => 0x39,
252 Self::Skip => 0x3a,
253 Self::Unauthorized => 0x3b,
254 Self::App(app) => *app as u32 + 64,
255 Self::Unknown(code) => *code,
256 }
257 }
258
259 /// Decode a code received off the wire.
260 ///
261 /// Only the registered codes decode; anything else, the reserved 32-47 range included,
262 /// stays [`Unknown`](Self::Unknown) rather than being given a meaning the draft does
263 /// not assign.
264 ///
265 /// `SESSION_CLOSED` decodes to `Session(SessionError::Internal)`: the peer's actual
266 /// session code is not on this stream, so the specific reason is unknown here.
267 pub fn from_code(code: u32) -> Self {
268 match code {
269 0x0 => Self::Internal,
270 0x1 => Self::Cancel,
271 0x2 => Self::DeliveryTimeout,
272 0x3 => Self::Session(SessionError::Internal),
273 0x4 => Self::GoingAway,
274 0x5 => Self::TooFarBehind,
275 0x12 => Self::MalformedTrack,
276 0x30 => Self::NotSupported,
277 0x31 => Self::ControlTimeout,
278 0x32 => Self::GroupTooLarge,
279 0x33 => Self::NotFound,
280 0x34 => Self::Old,
281 0x35 => Self::Evicted,
282 0x36 => Self::Unroutable,
283 0x37 => Self::WrongSize,
284 0x38 => Self::FrameTooLarge,
285 0x39 => Self::TimestampMismatch,
286 0x3a => Self::Skip,
287 0x3b => Self::Unauthorized,
288 code @ 64.. => match u16::try_from(code - 64) {
289 Ok(app) => Self::App(app),
290 Err(_) => Self::Unknown(code),
291 },
292 code => Self::Unknown(code),
293 }
294 }
295}
296
297/// Failures in this crate, both local conditions and codes received off the wire.
298///
299/// Local conditions are the flat variants (`Cancel`, `NotFound`, `Lagged`, and so
300/// on): this side decided what went wrong. Codes received from a peer are nested
301/// in [`Self::Session`] or [`Self::Stream`], preserving the registry and the numeric
302/// value. A stream also reads its session ending cleanly, whichever side closed it, as
303/// `Session(SessionError::Cancel)`: to the stream that is the session failing under it,
304/// while `Session::closed` reports the clean close itself as [`Self::Cancel`].
305/// [`Self::Remote`] is an unrecognized request-rejection code (the IETF
306/// request registry), not a session or stream unknown.
307///
308/// The two registries are the wire. Mapping a local condition onto a code is
309/// [`SessionError::from`] / [`StreamError::from`]; folding the flat variants into
310/// those registries is a later decision.
311#[derive(thiserror::Error, Debug, Clone)]
312#[non_exhaustive]
313pub enum Error {
314 /// The underlying QUIC/WebTransport connection failed; carries the backend's message.
315 #[error("transport: {0}")]
316 Transport(String),
317
318 /// A message off the wire could not be parsed.
319 #[error(transparent)]
320 Decode(#[from] coding::DecodeError),
321
322 /// Version negotiation failed, or the negotiated version lacks a requested feature
323 /// (e.g. a FETCH against a version without fetch support). Mostly a connect-time
324 /// error, but the feature-gap case can surface mid-session, so it can't simply move
325 /// to a connect-only error type.
326 #[error("unsupported versions")]
327 Version,
328
329 /// A known stream type arrived where this version or state does not allow it. Closes
330 /// the session as a protocol violation, or resets just the stream when it can be
331 /// refused on its own.
332 #[error("unexpected stream type")]
333 UnexpectedStream,
334
335 /// An integer was too large for the QUIC varint range.
336 #[error(transparent)]
337 BoundsExceeded(#[from] coding::BoundsExceeded),
338
339 /// A path holds a `*`, which no [`Prefix`](crate::Prefix) can name, so it could never be
340 /// listed or granted on its own.
341 #[error("path contains a `*`")]
342 InvalidPath,
343
344 /// A published broadcast or route contains a literal `.` or `..` segment.
345 #[error("broadcast path contains a navigation segment")]
346 NavigationSegment,
347
348 /// A string is not a valid path, such as one with an empty segment.
349 #[error(transparent)]
350 Path(crate::path::Error),
351
352 /// A duplicate ID was used
353 // The broadcast/track is a duplicate
354 #[error("duplicate")]
355 Duplicate,
356
357 /// A group was created at a key its track declared skipped: a skip says the
358 /// key will never be produced, so it is final. See `track::Producer::skip_groups`.
359 #[error("key was skipped")]
360 Skipped,
361
362 /// Nobody is reading any more, so the producer stopped; or the session closed cleanly,
363 /// by either side, as `Session::closed` reports it. Not a failure.
364 #[error("cancelled")]
365 Cancel,
366
367 /// It took too long to open or transmit a stream.
368 #[error("timeout")]
369 Timeout,
370
371 /// The group is older than the latest group and dropped.
372 #[error("old")]
373 Old,
374
375 /// An application-chosen close code. Bounded to `u16` and offset past the library's
376 /// reserved range (`+ 64`) on the wire by [`SessionError::to_code`] /
377 /// [`StreamError::to_code`], so app codes never collide with protocol ones.
378 ///
379 /// The width asymmetry with [`Self::Remote`] is deliberate: `App` is a code *this*
380 /// side chooses to send, while `Remote` carries a raw code *received* off the wire
381 /// that didn't map to a known variant, which can be any `u32`.
382 #[error("app code={0}")]
383 App(u16),
384
385 /// The requested broadcast or track does not exist at the peer.
386 #[error("not found")]
387 NotFound,
388
389 /// A joining FETCH named a request that is not an active subscription.
390 #[error("invalid joining request ID")]
391 InvalidJoiningRequestId,
392
393 /// A range is empty, lies beyond the published objects, or ends at the oldest group.
394 #[error("invalid fetch range")]
395 InvalidRange,
396
397 /// A broadcast was requested that is neither announced nor served by a dynamic
398 /// router, so there is no route to it.
399 #[error("unroutable")]
400 Unroutable,
401
402 /// A frame's payload length disagreed with its declared size.
403 #[error("wrong frame size")]
404 WrongSize,
405
406 /// The peer broke a protocol rule; the session is unusable.
407 #[error("protocol violation")]
408 ProtocolViolation,
409
410 /// The requested path or operation is not granted, either by the peer's token
411 /// or by the scope of the handle it was requested through.
412 #[error("unauthorized")]
413 Unauthorized,
414
415 /// The authorization token has expired and can be refreshed.
416 #[error("authorization token expired")]
417 Expired,
418
419 /// A valid message arrived in a state where it is not allowed.
420 #[error("unexpected message")]
421 UnexpectedMessage,
422
423 /// A feature was asked for that this endpoint, or the wire to the peer, does not implement.
424 #[error("unsupported")]
425 Unsupported,
426
427 /// A message could not be serialized for the negotiated version.
428 #[error(transparent)]
429 Encode(#[from] coding::EncodeError),
430
431 /// The peer went past this session's `crate::session::Limits`, such as too many
432 /// announcements.
433 #[error("too many requests")]
434 TooManyRequests,
435
436 /// The peer offered an ALPN this endpoint doesn't recognize, so no version could be
437 /// negotiated. A connect-time error.
438 #[error("unknown ALPN: {0}")]
439 UnknownAlpn(String),
440
441 /// The producer was dropped without finishing or aborting, so the content is incomplete,
442 /// with no cause to report. A track's reader sees it only when no request handler can serve
443 /// the track again, when the producer that served such a request drops too before another
444 /// reader joins, or when the next producer could not continue it (a JSON log or window): a
445 /// track nobody wants ends cleanly when its last producer drops.
446 #[error("dropped without a finish or abort")]
447 Dropped,
448
449 /// The handle was already closed by this side.
450 #[error("closed")]
451 Closed,
452
453 /// The reader asked for a frame the group never held: below
454 /// `crate::group::Producer::start_at`. Named from the consumer's side; distinct
455 /// from [`Self::Evicted`], for frames the group held but shed from its front or
456 /// dropped whole under memory pressure.
457 #[error("lagged")]
458 Lagged,
459
460 /// A frame declared a payload size larger than the receiver accepts.
461 #[error("frame too large")]
462 FrameTooLarge,
463
464 /// A write could not make room in the group even by shedding its front: what is left,
465 /// such as the frame in flight, already fills the live tail
466 /// (32 MiB). The write is refused and the
467 /// group is aborted.
468 #[error("group too large")]
469 GroupTooLarge,
470
471 /// A frame's timestamp doesn't fit its track: it's missing on a timed track, present
472 /// on an untimed track, out of range for the track's timescale, or starts a group
473 /// earlier than the group before it.
474 #[error("frame timestamp doesn't fit its track")]
475 TimestampMismatch,
476
477 /// The group was evicted under memory pressure: by its own track to pay eviction debt
478 /// (see [`cache::Pool`](crate::cache::Pool)), or by the transport when incomplete
479 /// messages spent its receive window. Also a read of a frame the group shed from its
480 /// front, past its live tail or under that debt. Unlike [`Self::Old`], the group was
481 /// still fresh under the publisher's max age; it can be re-fetched.
482 #[error("evicted")]
483 Evicted,
484
485 /// The session is going away (a GOAWAY was received); new subscribe and
486 /// announce-interest requests are rejected while existing subscriptions
487 /// keep flowing.
488 #[error("going away")]
489 GoingAway,
490
491 /// The peer did not close the session within the GOAWAY drain deadline.
492 ///
493 /// Sent as the session termination code when the draining side force-closes
494 /// after the advertised drain deadline expires.
495 #[error("goaway timeout")]
496 GoawayTimeout,
497
498 /// The peer could not parse the track's content.
499 #[error("malformed track")]
500 MalformedTrack,
501
502 /// The track requires a moq-transport property this endpoint does not understand.
503 #[error("unsupported extension")]
504 UnsupportedExtension,
505
506 /// A session-scoped protocol error, with its registry and verbatim code.
507 ///
508 /// Produced by [`from_transport`](Self::from_transport) for a session close, and by
509 /// converting a [`SessionError`]. Local conditions use the specific variants above.
510 #[error(transparent)]
511 Session(SessionError),
512
513 /// A stream-scoped protocol error, with its registry and verbatim code.
514 ///
515 /// The stream counterpart to [`Self::Session`]. The two registries are disjoint, so
516 /// the same integer is a different failure in each.
517 #[error(transparent)]
518 Stream(StreamError),
519
520 /// An unrecognized request-rejection code (the IETF request registry).
521 ///
522 /// Session and stream unknowns are [`Self::Session`] / [`Self::Stream`], not this.
523 #[error("remote error: code={0}")]
524 Remote(u32),
525 /// The underlying connection reached its transport idle deadline, or a
526 /// [`KeepAlive`](crate::transport::KeepAlive)'s hard limit.
527 #[error("transport idle timeout")]
528 IdleTimeout,
529
530 /// The transport refused the session's [`KeepAlive`](crate::transport::KeepAlive), so the
531 /// session never opened.
532 #[error("keep-alive: {0}")]
533 KeepAlive(crate::transport::KeepAliveError),
534}
535
536impl Error {
537 /// The session-scoped protocol error, if this was received as one.
538 pub fn session(&self) -> Option<&SessionError> {
539 match self {
540 Self::Session(err) => Some(err),
541 _ => None,
542 }
543 }
544
545 /// The stream-scoped protocol error, if this was received as one.
546 pub fn stream(&self) -> Option<&StreamError> {
547 match self {
548 Self::Stream(err) => Some(err),
549 _ => None,
550 }
551 }
552
553 /// Convert a transport error into an [Error], decoding session close and stream reset
554 /// codes through their respective registries.
555 ///
556 /// The two spaces are disjoint, so which one applies depends on what failed: a session
557 /// close decodes via [`SessionError::from_code`], a stream reset via
558 /// [`StreamError::from_code`]. Reading a stream reset with the session table (or the
559 /// reverse) silently mistranslates, since e.g. 0 is "no error" for a session but an
560 /// internal error for a stream.
561 ///
562 /// Without either code, the transport's [`close_kind`](crate::transport::Error::close_kind)
563 /// decides: an idle timeout is [`Error::IdleTimeout`], a local close is
564 /// `Error::Session(SessionError::Cancel)`, and anything else is [`Error::Transport`].
565 pub fn from_transport(err: impl crate::transport::Error) -> Self {
566 if let Some((code, _reason)) = err.session_error() {
567 return SessionError::from_code(code).into();
568 }
569
570 if let Some(code) = err.stream_error() {
571 return StreamError::from_code(code).into();
572 }
573
574 match err.close_kind() {
575 crate::transport::CloseKind::IdleTimeout => Self::IdleTimeout,
576 crate::transport::CloseKind::Evicted => Self::Evicted,
577 // A connection ending must not become the model's clean end-of-content.
578 crate::transport::CloseKind::Closed => SessionError::Cancel.into(),
579 _ => Self::Transport(err.to_string()),
580 }
581 }
582
583 /// What to do after a request failed with this error: ask the same source again, find
584 /// another route, or give up. Mirrors `retry` in `js/net/src/error.ts`.
585 ///
586 /// A session closing, whatever its code, is the route failing to deliver: whether the
587 /// session comes back is the connection's call, not the request's.
588 pub fn retry(&self) -> Retry {
589 match self {
590 Self::Unroutable | Self::Stream(StreamError::Unroutable) => Retry::Reroute,
591 Self::Transport(_)
592 | Self::IdleTimeout
593 | Self::Session(_)
594 | Self::GoingAway
595 | Self::GoawayTimeout
596 | Self::Dropped
597 | Self::Closed
598 | Self::Cancel
599 | Self::Stream(
600 StreamError::Session(_)
601 | StreamError::Internal
602 | StreamError::Cancel
603 | StreamError::GoingAway
604 | StreamError::ControlTimeout,
605 ) => Retry::Same,
606 _ => Retry::Never,
607 }
608 }
609
610 /// Whether asking again may succeed, on this route or another.
611 pub(crate) fn retryable(&self) -> bool {
612 self.retry() != Retry::Never
613 }
614
615 /// Whether the session carrying the request is ending, rather than one stream failing on a
616 /// session that serves on: only then does another route take over. Mirrors `closing` in
617 /// `js/net/src/resume.ts`.
618 pub(crate) fn closing(&self) -> bool {
619 matches!(
620 self,
621 Self::Transport(_)
622 | Self::IdleTimeout
623 | Self::Session(_)
624 | Self::GoingAway
625 | Self::GoawayTimeout
626 | Self::Stream(StreamError::Session(_) | StreamError::GoingAway)
627 )
628 }
629
630 /// Whether a source lost its route to the content: only another route continues it.
631 pub(crate) fn unroutable(&self) -> bool {
632 self.retry() == Retry::Reroute
633 }
634
635 /// Whether the same source may deliver a fresh copy.
636 pub(crate) fn transient(&self) -> bool {
637 self.retry() == Retry::Same
638 }
639}
640
641/// What a caller does after a request fails, as [`Error::retry`] answers it.
642#[derive(Debug, Clone, Copy, PartialEq, Eq)]
643#[non_exhaustive]
644pub enum Retry {
645 /// The source failed to deliver rather than judging the request, so asking it again may
646 /// succeed: its connection dropped, its session ended, or it is going away.
647 Same,
648
649 /// The source lost its route to the content, so only another route continues it. Asking
650 /// the same source again can only replace the withdrawal's cause with a refusal.
651 Reroute,
652
653 /// The answer judged the request or what it carried, so it repeats on every attempt:
654 /// refused, not found, or malformed.
655 Never,
656}
657
658/// Preserve the session registry when carrying a protocol error.
659impl From<SessionError> for Error {
660 fn from(err: SessionError) -> Self {
661 Self::Session(err)
662 }
663}
664
665/// Preserve the stream registry when carrying a protocol error.
666impl From<StreamError> for Error {
667 fn from(err: StreamError) -> Self {
668 Self::Stream(err)
669 }
670}
671
672/// Lets an entry point taking `impl TryInto<Path, Error: Into<Error>>` accept a `Path` too.
673impl From<std::convert::Infallible> for Error {
674 fn from(never: std::convert::Infallible) -> Self {
675 match never {}
676 }
677}
678
679/// Which session code to send for a local error.
680///
681/// Lossy on purpose: [`Error`] describes what went wrong locally, while the registry is what
682/// the peer can act on. Anything stream-scoped reaching a session close is a bug on our side,
683/// so it degrades to [`SessionError::Internal`] rather than inventing a code.
684impl From<&Error> for SessionError {
685 fn from(err: &Error) -> Self {
686 match err {
687 Error::Session(err) | Error::Decode(coding::DecodeError::Session(err)) => err.clone(),
688 // App codes share the 64+ range in both registries.
689 Error::Stream(StreamError::App(app)) => Self::App(*app),
690 // A stream-scoped code has no meaning in this registry; don't forward the number.
691 Error::Stream(_) => Self::Internal,
692 Error::Cancel | Error::Closed | Error::GoingAway => Self::Cancel,
693 Error::Unauthorized => Self::Unauthorized,
694 Error::Expired => Self::Expired,
695 Error::Unsupported | Error::KeepAlive(_) => Self::Unsupported,
696 Error::Version | Error::UnknownAlpn(_) => Self::Version,
697 Error::TooManyRequests => Self::TooManyRequests,
698 Error::GoawayTimeout => Self::GoawayTimeout,
699 Error::Timeout => Self::Timeout,
700 Error::ProtocolViolation
701 | Error::UnexpectedMessage
702 | Error::UnexpectedStream
703 | Error::Duplicate
704 | Error::Skipped
705 | Error::Decode(_)
706 | Error::Encode(_)
707 | Error::WrongSize
708 | Error::BoundsExceeded(_)
709 | Error::InvalidPath
710 | Error::NavigationSegment
711 | Error::Path(_) => Self::ProtocolViolation,
712 Error::App(app) => Self::App(*app),
713 // A code we did not recognize, so we cannot say which space it came from.
714 // Forwarding it into this one risks landing on a value that IS registered here
715 // (a session 0x4 would become the stream's GOING_AWAY), and the draft already
716 // says an unrecognized code is an unspecified error. Send that instead.
717 Error::Remote(_) => Self::Internal,
718 // Our own transport failed: there is no code to say so.
719 Error::Transport(_) | Error::IdleTimeout => Self::Internal,
720 // Stream-scoped conditions have no session code.
721 Error::Old
722 | Error::Evicted
723 | Error::Lagged
724 | Error::NotFound
725 | Error::InvalidRange
726 | Error::InvalidJoiningRequestId
727 | Error::Unroutable
728 | Error::FrameTooLarge
729 | Error::GroupTooLarge
730 | Error::TimestampMismatch
731 | Error::MalformedTrack
732 | Error::UnsupportedExtension => Self::Internal,
733 // A producer dropped without an end is a bug here, so it is never given a meaning.
734 Error::Dropped => Self::Internal,
735 }
736 }
737}
738
739/// Which stream code to send for a local error.
740///
741/// Session-scoped conditions route through [`StreamError::Session`], which flattens to
742/// `SESSION_CLOSED` on the wire.
743impl From<&Error> for StreamError {
744 fn from(err: &Error) -> Self {
745 match err {
746 Error::Stream(err) => err.clone(),
747 // App codes share the 64+ range in both registries.
748 Error::Session(SessionError::App(app)) => Self::App(*app),
749 // A stream that can still be reset outlived the session that failed, so that was
750 // another one: the route this stream was served through. The path lost its route;
751 // this session is fine, and the failed session's code means nothing here.
752 Error::Session(_) | Error::Transport(_) | Error::IdleTimeout => Self::Unroutable,
753 Error::Cancel | Error::Closed => Self::Cancel,
754 Error::Decode(coding::DecodeError::Session(err)) => Self::Session(err.clone()),
755 Error::Old => Self::Old,
756 Error::Evicted => Self::Evicted,
757 Error::Lagged => Self::TooFarBehind,
758 Error::NotFound => Self::NotFound,
759 Error::Unroutable => Self::Unroutable,
760 Error::WrongSize => Self::WrongSize,
761 Error::FrameTooLarge => Self::FrameTooLarge,
762 Error::GroupTooLarge => Self::GroupTooLarge,
763 Error::TimestampMismatch => Self::TimestampMismatch,
764 // Losing access ends this stream, not the session. A request can expire on its
765 // own (REQUEST_ERROR 0x5), and the stream registry has no expiry code.
766 Error::Unauthorized | Error::Expired => Self::Unauthorized,
767 Error::Timeout => Self::DeliveryTimeout,
768 Error::GoingAway => Self::GoingAway,
769 // Our own parse failure is, from the peer's side, a malformed track.
770 Error::Decode(_)
771 | Error::BoundsExceeded(_)
772 | Error::InvalidPath
773 | Error::NavigationSegment
774 | Error::Path(_)
775 | Error::MalformedTrack => Self::MalformedTrack,
776 Error::App(app) => Self::App(*app),
777 // See the SessionError impl: an unregistered code carries no registry, so
778 // re-sending the number could mistranslate it.
779 Error::Remote(_) => Self::Internal,
780 // Session-scoped: the peer learns the detail from the session close.
781 // A stream refused on its own is not a session failure, so it does not claim
782 // SESSION_CLOSED; there is no stream-scoped PROTOCOL_VIOLATION to send instead.
783 Error::UnexpectedStream => Self::Internal,
784 Error::Version
785 | Error::UnknownAlpn(_)
786 | Error::TooManyRequests
787 | Error::Duplicate
788 | Error::Skipped
789 | Error::GoawayTimeout
790 | Error::ProtocolViolation
791 | Error::UnexpectedMessage => Self::Session(SessionError::from(err)),
792 // A request this side can't serve, such as an unknown stream type or a by-time
793 // request of a live-only track.
794 Error::Unsupported => Self::NotSupported,
795 // No stream code says so: a fault on our own side.
796 Error::KeepAlive(_)
797 | Error::UnsupportedExtension
798 | Error::InvalidRange
799 | Error::InvalidJoiningRequestId
800 | Error::Encode(_) => Self::Internal,
801 // A producer dropped without an end is a bug here, so it is never given a meaning.
802 Error::Dropped => Self::Internal,
803 }
804 }
805}
806
807impl crate::transport::Error for Error {
808 fn close_kind(&self) -> crate::transport::CloseKind {
809 match self {
810 Self::IdleTimeout => crate::transport::CloseKind::IdleTimeout,
811 // Closed also ends model handles and virtual streams, not just connections.
812 _ => crate::transport::CloseKind::Transport,
813 }
814 }
815 fn session_error(&self) -> Option<(u32, String)> {
816 None
817 }
818}
819
820/// A [`Result`](std::result::Result) with this crate's [`Error`].
821pub type Result<T> = std::result::Result<T, Error>;
822
823#[cfg(test)]
824mod tests {
825 use super::*;
826
827 // Both registries are wire contracts now (draft-lcurley-moq-lite, Error Codes), so
828 // every code we send must decode back to what we meant.
829 #[test]
830 fn session_codes_round_trip() {
831 // Only the registered codes are a wire contract, so only they round trip, each on
832 // the value the drafts assign (moq-transport's, where we reuse its code).
833 assert_eq!(SessionError::from(&Error::Unsupported), SessionError::Unsupported);
834 for (err, spec) in [
835 (SessionError::Unsupported, 0x30),
836 (SessionError::Cancel, 0x0),
837 (SessionError::Internal, 0x1),
838 (SessionError::Unauthorized, 0x2),
839 (SessionError::ProtocolViolation, 0x3),
840 (SessionError::TooManyRequests, 0x7),
841 (SessionError::GoawayTimeout, 0x10),
842 (SessionError::Timeout, 0x11),
843 (SessionError::Version, 0x15),
844 (SessionError::MalformedAuthToken, 0x16),
845 (SessionError::Expired, 0x18),
846 (SessionError::App(0), 0x40),
847 (SessionError::App(404), 0x40 + 404),
848 ] {
849 assert_eq!(err.to_code(), spec, "{err:?} moved off its assigned code");
850 assert_eq!(SessionError::from_code(spec), err, "{err:?} did not round trip");
851 }
852
853 // The reserved 32-47 range, and anything else unregistered, keeps its value instead
854 // of being given a meaning. A peer on the old placeholders (0x20-0x22) lands here, as
855 // does every code only moq-transport defines.
856 for code in [0x1f, 0x20, 0x21, 0x22, 0x2f, 0x31] {
857 assert_eq!(SessionError::from_code(code), SessionError::Unknown(code));
858 }
859 for code in [0x4, 0x6, 0x8, 0x13, 0x17, 0x19, 0x1b] {
860 let err = SessionError::from_code(code);
861 assert_eq!(err, SessionError::Unknown(code));
862 assert_eq!(err.to_code(), code);
863 }
864
865 // A disallowed stream fails the session as a protocol violation, and resets just
866 // the stream as an internal error rather than claiming the session closed.
867 assert_eq!(
868 SessionError::from(&Error::UnexpectedStream),
869 SessionError::ProtocolViolation
870 );
871 assert_eq!(StreamError::from(&Error::UnexpectedStream), StreamError::Internal);
872
873 // An expired request (REQUEST_ERROR 0x5) relayed onto a stream ends only that
874 // request; SESSION_CLOSED would falsely tell the peer its session is going away.
875 assert_eq!(StreamError::from(&Error::Expired), StreamError::Unauthorized);
876 }
877
878 #[test]
879 fn stream_codes_round_trip() {
880 // Only the registered codes are a wire contract, so only they round trip, each on
881 // the value the draft assigns.
882 for (err, spec) in [
883 (StreamError::Internal, 0x0),
884 (StreamError::Cancel, 0x1),
885 (StreamError::DeliveryTimeout, 0x2),
886 (StreamError::GoingAway, 0x4),
887 (StreamError::TooFarBehind, 0x5),
888 (StreamError::MalformedTrack, 0x12),
889 (StreamError::NotSupported, 0x30),
890 (StreamError::ControlTimeout, 0x31),
891 (StreamError::GroupTooLarge, 0x32),
892 (StreamError::NotFound, 0x33),
893 (StreamError::Old, 0x34),
894 (StreamError::Evicted, 0x35),
895 (StreamError::Unroutable, 0x36),
896 (StreamError::WrongSize, 0x37),
897 (StreamError::FrameTooLarge, 0x38),
898 (StreamError::TimestampMismatch, 0x39),
899 (StreamError::Skip, 0x3a),
900 (StreamError::Unauthorized, 0x3b),
901 (StreamError::App(7), 0x40 + 7),
902 ] {
903 assert_eq!(err.to_code(), spec, "{err:?} moved off its assigned code");
904 assert_eq!(StreamError::from_code(spec), err, "{err:?} did not round trip");
905 }
906
907 // The reserved 32-47 range carries no meaning, so a peer emitting it is not given one.
908 for code in 0x20..0x30 {
909 assert_eq!(StreamError::from_code(code), StreamError::Unknown(code));
910 }
911
912 // The spaces are disjoint: 0 is a cancellation for a session but an internal
913 // error for a stream, and a cancellation is 1 here.
914 assert_eq!(StreamError::Cancel.to_code(), 0x1);
915 assert_eq!(StreamError::from_code(0x0), StreamError::Internal);
916 assert_eq!(SessionError::from_code(0x0), SessionError::Cancel);
917
918 // A session close flattens to SESSION_CLOSED: the specific reason travels on the
919 // session close, not on the stream.
920 assert_eq!(StreamError::Session(SessionError::Unauthorized).to_code(), 0x3);
921 assert_eq!(
922 StreamError::from_code(0x3),
923 StreamError::Session(SessionError::Internal)
924 );
925 }
926
927 // A relay decodes a peer's code into `Error` and re-encodes it when it tears down the
928 // corresponding downstream stream. That hop must not change what the code means.
929 #[test]
930 fn relaying_a_code_does_not_change_registries() {
931 // SESSION_CLOSED used to decode into a session-space value, which came back out as
932 // 0x1: downstream read a routine CANCELLED for an upstream session teardown.
933 let relayed = StreamError::from(&Error::from(StreamError::from_code(0x3)));
934 assert_eq!(relayed.to_code(), 0x3);
935
936 // Registered stream codes survive the hop unchanged.
937 for code in [
938 0x0, 0x1, 0x2, 0x4, 0x5, 0x12, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3b,
939 ] {
940 let relayed = StreamError::from(&Error::from(StreamError::from_code(code)));
941 assert_eq!(relayed.to_code(), code, "stream {code:#x} changed across a relay");
942 }
943
944 // So do app codes, in both spaces.
945 assert_eq!(
946 StreamError::from(&Error::from(StreamError::from_code(64 + 7))).to_code(),
947 64 + 7
948 );
949 assert_eq!(
950 SessionError::from(&Error::from(SessionError::from_code(64 + 7))).to_code(),
951 64 + 7
952 );
953
954 // An upstream session's close must not be re-sent as a number that means something
955 // here: session 0x4 and 0x5 are GOING_AWAY and TOO_FAR_BEHIND on a stream. The
956 // downstream session is healthy; only the path lost its route.
957 for code in [0x0, 0x4, 0x5, 0x1f] {
958 let crossed = StreamError::from(&Error::from(SessionError::from_code(code)));
959 assert_eq!(
960 crossed,
961 StreamError::Unroutable,
962 "session {code:#x} leaked into the stream space"
963 );
964 }
965 assert_eq!(
966 StreamError::from(&Error::Transport("reset".into())),
967 StreamError::Unroutable
968 );
969 assert_eq!(StreamError::from(&Error::IdleTimeout), StreamError::Unroutable);
970
971 // A producer dropped without an end is a bug, never given a meaning.
972 assert_eq!(StreamError::from(&Error::Dropped), StreamError::Internal);
973 assert_eq!(SessionError::from(&Error::Dropped), SessionError::Internal);
974 }
975
976 /// A failed delivery asks again, a lost route asks elsewhere, and a verdict on the
977 /// request or its content ends it, whether raised here or received from a peer.
978 #[test]
979 fn retry_separates_delivery_from_verdicts() {
980 for err in [
981 Error::Transport("reset".into()),
982 Error::IdleTimeout,
983 Error::Cancel,
984 Error::Closed,
985 Error::GoingAway,
986 Error::Session(SessionError::Unauthorized),
987 Error::Session(SessionError::Unknown(0x4)),
988 Error::Stream(StreamError::Session(SessionError::Cancel)),
989 Error::Stream(StreamError::ControlTimeout),
990 ] {
991 assert_eq!(err.retry(), Retry::Same, "{err:?}");
992 }
993 for err in [Error::Unroutable, Error::Stream(StreamError::Unroutable)] {
994 assert_eq!(err.retry(), Retry::Reroute, "{err:?}");
995 }
996 for err in [
997 Error::NotFound,
998 Error::Unauthorized,
999 Error::Expired,
1000 Error::ProtocolViolation,
1001 Error::WrongSize,
1002 Error::Remote(0x7),
1003 Error::Stream(StreamError::NotFound),
1004 Error::Stream(StreamError::Unauthorized),
1005 Error::Stream(StreamError::MalformedTrack),
1006 Error::Stream(StreamError::Unknown(0x22)),
1007 ] {
1008 assert_eq!(err.retry(), Retry::Never, "{err:?}");
1009 }
1010 }
1011
1012 // The registry a code is read with depends on what failed, and picking the wrong one
1013 // silently mistranslates rather than erroring.
1014 #[test]
1015 fn from_transport_selects_the_matching_registry() {
1016 #[derive(Debug, thiserror::Error)]
1017 #[error("failed")]
1018 struct Failed {
1019 session: Option<u32>,
1020 stream: Option<u32>,
1021 }
1022
1023 impl crate::transport::Error for Failed {
1024 fn session_error(&self) -> Option<(u32, String)> {
1025 self.session.map(|code| (code, "closed".to_string()))
1026 }
1027 fn stream_error(&self) -> Option<u32> {
1028 self.stream
1029 }
1030 }
1031
1032 let session = |code| {
1033 Error::from_transport(Failed {
1034 session: Some(code),
1035 stream: None,
1036 })
1037 };
1038 let stream = |code| {
1039 Error::from_transport(Failed {
1040 session: None,
1041 stream: Some(code),
1042 })
1043 };
1044
1045 // A MoQ-layer auth rejection is now classifiable, because the code is specified.
1046 assert!(matches!(session(0x2), Error::Session(SessionError::Unauthorized)));
1047 assert_eq!(session(0x2).session(), Some(&SessionError::Unauthorized));
1048 assert!(matches!(session(0x0), Error::Session(SessionError::Cancel)));
1049
1050 // Same integer, different space: 0 ends a session cleanly but fails a stream.
1051 assert!(matches!(stream(0x1), Error::Stream(StreamError::Cancel)));
1052 assert_eq!(stream(0x1).stream(), Some(&StreamError::Cancel));
1053 assert!(matches!(stream(0x0), Error::Stream(StreamError::Internal)));
1054 assert!(matches!(stream(0x5), Error::Stream(StreamError::TooFarBehind)));
1055 assert!(matches!(stream(0x32), Error::Stream(StreamError::GroupTooLarge)));
1056
1057 // Assigned lite codes round-trip to the named error. The reserved 32-47 range
1058 // stays opaque: the draft forbids reading a meaning out of it.
1059 assert!(matches!(stream(0x34), Error::Stream(StreamError::Old)));
1060 assert!(matches!(stream(0x38), Error::Stream(StreamError::FrameTooLarge)));
1061 assert!(matches!(stream(0x31), Error::Stream(StreamError::ControlTimeout)));
1062 assert!(matches!(stream(0x22), Error::Stream(StreamError::Unknown(0x22))));
1063 assert!(matches!(session(0x22), Error::Session(SessionError::Unknown(0x22))));
1064
1065 // Neither: the transport itself failed.
1066 assert!(matches!(
1067 Error::from_transport(Failed {
1068 session: None,
1069 stream: None
1070 }),
1071 Error::Transport(_)
1072 ));
1073 }
1074}