Skip to main content

iroh_live_node/
error.rs

1//! The crate's error type.
2
3use std::sync::Arc;
4
5use iroh::EndpointId;
6use moq_net::Path;
7use n0_error::{AnyError, stack_error};
8
9/// An error from a [`Node`](crate::Node) or one of its handles.
10///
11/// moq-net's and the transport's errors stay typed, and the rest carry an
12/// [`AnyError`]. The error is cheap to clone, so the callers waiting on one
13/// dial each get the same failure.
14#[stack_error(derive, add_meta)]
15#[derive(Clone)]
16pub enum Error {
17    /// The QUIC connection could not be set up.
18    ///
19    /// The peer could not be dialed, or it negotiated an ALPN this build does
20    /// not speak.
21    #[error("the transport failed")]
22    Transport {
23        #[error(source, std_err)]
24        source: moq_transport_iroh::Error,
25    },
26    /// moq-net refused an operation.
27    ///
28    /// The MoQ handshake or the session failed, a path did not parse, or the
29    /// route table refused to create or announce a broadcast.
30    #[error("moq-net failed")]
31    Moq {
32        #[error(source, std_err)]
33        source: moq_net::Error,
34    },
35    /// The fill passed to [`Node::publish_with`](crate::Node::publish_with) failed.
36    ///
37    /// The broadcast was closed and never announced.
38    #[error("failed to fill the broadcast")]
39    Fill {
40        #[error(source, std_err)]
41        source: Arc<AnyError>,
42    },
43    /// The peer refused the session this node opened.
44    #[error("the peer refused the session")]
45    Refused {
46        #[error(source, std_err)]
47        source: moq_net::Error,
48    },
49    /// This node's policy rejected the peer.
50    ///
51    /// A dial fails with it before it reaches the peer.
52    #[error("the policy rejected the session")]
53    Rejected {
54        #[error(source, std_err)]
55        source: crate::policy::Rejection,
56    },
57    /// The session ended.
58    #[error("the session closed")]
59    SessionClosed {
60        /// Is [`moq_net::Error::Cancel`] if either side closed it.
61        #[error(source, std_err)]
62        source: moq_net::Error,
63    },
64    /// A publication already exists at this path.
65    #[error("a broadcast is already published at {path}")]
66    Duplicate { path: Path },
67    /// The path cannot be published or subscribed.
68    ///
69    /// It is empty, holds a `*`, or has more segments than a path may have.
70    #[error("invalid path {path:?}")]
71    InvalidPath { path: String },
72    /// The session's grant does not cover the path.
73    ///
74    /// For a subscribe, the peer may not publish the path. `publish_prefixes`
75    /// are the prefixes the grant lets the peer publish.
76    #[error(
77        "the grant of {} does not let it publish {path}, it may publish [{}]",
78        peer.fmt_short(),
79        list_prefixes(publish_prefixes)
80    )]
81    NotGranted {
82        path: Path,
83        peer: EndpointId,
84        publish_prefixes: moq_net::Prefixes,
85    },
86    /// The peer does not own the path, so it cannot be claimed for the peer.
87    #[error("{} does not own {path}", peer.fmt_short())]
88    NotOwner { path: Path, peer: EndpointId },
89    /// The peer already holds as many claimed paths as the node allows.
90    #[error("too many claimed paths for {}", peer.fmt_short())]
91    TooManyClaims { peer: EndpointId },
92    /// The path was not announced before its only link went away.
93    #[error("{path} was not announced before the session ended")]
94    NotAnnounced { path: Path },
95    /// No link can serve the path.
96    ///
97    /// The reach asks for media relays and none is attached, or names this node as
98    /// the publisher of a path it does not publish.
99    #[error("no link can reach {path}")]
100    NoRoute { path: Path },
101    /// The path could not be resolved.
102    ///
103    /// The peer refused it, or it lies outside what this node may see.
104    #[error("{path} could not be resolved")]
105    Unresolved {
106        path: Path,
107        #[error(source, std_err)]
108        source: moq_net::Error,
109    },
110    /// A media relay URL names no media relay this node can attach to.
111    #[error("invalid relay URL {url}: {reason}")]
112    InvalidRelayUrl {
113        url: Box<url::Url>,
114        reason: &'static str,
115    },
116    /// A relay link could not be set up.
117    #[error("the relay link failed")]
118    Relay {
119        #[error(source, std_err)]
120        source: Arc<AnyError>,
121    },
122    /// A string is not a [`BroadcastTicket`](crate::BroadcastTicket).
123    #[error("invalid broadcast ticket: {reason}")]
124    InvalidTicket { reason: &'static str },
125    /// The node has shut down.
126    #[error("the node has shut down")]
127    ShutDown,
128}
129
130impl From<moq_transport_iroh::Error> for Error {
131    fn from(source: moq_transport_iroh::Error) -> Self {
132        n0_error::e!(Self::Transport { source })
133    }
134}
135
136/// How many prefixes [`Error::NotGranted`] lists.
137const LISTED_PREFIXES: usize = 8;
138
139/// Renders the first few of `prefixes` for an error message.
140fn list_prefixes(prefixes: &moq_net::Prefixes) -> String {
141    let mut text = prefixes
142        .iter()
143        .take(LISTED_PREFIXES)
144        .map(ToString::to_string)
145        .collect::<Vec<_>>()
146        .join(", ");
147    if prefixes.len() > LISTED_PREFIXES {
148        text.push_str(&format!(", and {} more", prefixes.len() - LISTED_PREFIXES));
149    }
150    text
151}
152
153impl Error {
154    /// Returns the error for `peer` publishing `path` outside `grant`.
155    pub(crate) fn not_granted(path: Path, peer: EndpointId, grant: &crate::Grant) -> Self {
156        n0_error::e!(Self::NotGranted {
157            path,
158            peer,
159            publish_prefixes: grant.publish.clone(),
160        })
161    }
162}
163
164/// Converts a caller's path, failing like moq-net's own entry points do.
165pub(crate) fn to_path(
166    path: impl TryInto<moq_net::Path, Error: Into<moq_net::Error>>,
167) -> Result<moq_net::Path, Error> {
168    path.try_into().map_err(|source| {
169        n0_error::e!(Error::Moq {
170            source: source.into()
171        })
172    })
173}
174
175#[cfg(test)]
176mod tests {
177    use moq_net::{Prefix, Prefixes};
178
179    use super::*;
180
181    #[test]
182    fn not_granted_lists_at_most_eight_prefixes() {
183        let prefixes: Prefixes = (0..12)
184            .map(|n| format!("live/p{n}/cam").parse::<Prefix>().expect("prefix"))
185            .collect();
186        let listed = list_prefixes(&prefixes);
187        assert_eq!(listed.matches("/cam").count(), 8, "{listed}");
188        assert!(listed.ends_with("and 4 more"), "{listed}");
189        assert_eq!(list_prefixes(&Prefixes::new()), "");
190    }
191}