Skip to main content

iroh_live_node/
session.rs

1//! Direct sessions with peers: the handle an application holds.
2
3use std::sync::{
4    Arc, Weak,
5    atomic::{AtomicBool, Ordering},
6};
7
8use iroh::{EndpointId, endpoint::Connection};
9use moq_net::Path;
10use n0_error::e;
11use tracing::info;
12
13use crate::{
14    Direction, Error, Grant, LinkId, NetworkPath, NetworkSample, SessionRequest, Subscription,
15    handshake::Hop, link::LatestSample, node::Shared, route,
16};
17
18/// A direct session with a peer.
19///
20/// Cheap to clone. Dropping the handles does not close it: it ends when either
21/// side closes it, the connection fails, or the node shuts down.
22///
23/// # Examples
24///
25/// ```no_run
26/// # async fn run(node: iroh_live_node::Node, peer: iroh::EndpointId)
27/// # -> Result<(), iroh_live_node::Error> {
28/// let session = node.connect(peer).await?;
29/// // Resolves through this session only, never through a media relay.
30/// let subscription = session.subscribe("live/camera").await?;
31/// # drop(subscription);
32/// session.close(moq_net::Error::Cancel);
33/// let reason = session.closed().await;
34/// # drop(reason);
35/// # Ok(())
36/// # }
37/// ```
38#[derive(Clone, derive_more::Debug)]
39#[debug("Session({}, {}, {:?})", inner.peer.fmt_short(), inner.link, inner.direction)]
40pub struct Session {
41    pub(crate) inner: Arc<SessionInner>,
42}
43
44/// What every clone of a [`Session`] shares.
45pub(crate) struct SessionInner {
46    pub(crate) link: LinkId,
47    pub(crate) peer: EndpointId,
48    pub(crate) direction: Direction,
49    pub(crate) request: SessionRequest,
50    pub(crate) connection: Connection,
51    pub(crate) moq: moq_net::Session,
52    /// The identity the peer's routes are attributed to in the route table.
53    pub(crate) hop: Hop,
54    pub(crate) latest_sample: LatestSample,
55    pub(crate) shared: Weak<Shared>,
56    /// Set by [`Session::close`], so a connect right after it dials anew.
57    pub(crate) closing: AtomicBool,
58}
59
60impl PartialEq for Session {
61    fn eq(&self, other: &Self) -> bool {
62        Arc::ptr_eq(&self.inner, &other.inner)
63    }
64}
65
66impl Eq for Session {}
67
68impl Session {
69    /// Returns the peer's endpoint id.
70    #[must_use]
71    pub fn peer(&self) -> EndpointId {
72        self.inner.peer
73    }
74
75    /// Returns which side opened the session.
76    #[must_use]
77    pub fn direction(&self) -> Direction {
78        self.inner.direction
79    }
80
81    /// Returns what the peer may do on this session.
82    ///
83    /// That is the grant the policy decided for this session, widened by the
84    /// paths that live ticket subscriptions claimed for the peer (see
85    /// [`Node::claim_path`](crate::Node::claim_path)). It is
86    /// [`Grant::nothing`] after a rejection, once the authorization expired,
87    /// and once the session has ended.
88    #[must_use]
89    pub fn grant(&self) -> Grant {
90        self.inner
91            .shared
92            .upgrade()
93            .map(|shared| {
94                let state = shared.state.lock().expect("poisoned");
95                state.session_grant(self.inner.link)
96            })
97            .unwrap_or_else(Grant::nothing)
98    }
99
100    /// Returns what the peer asked for when it opened the session.
101    ///
102    /// For a dialed session, the path this node requested, without a token.
103    #[must_use]
104    pub fn request(&self) -> &SessionRequest {
105        &self.inner.request
106    }
107
108    /// Resolves `path` through this session's peer, and not through a media relay.
109    ///
110    /// Waits for the peer to announce the path, then pins the subscription to
111    /// the stream the peer announced: moq may move it to another route of
112    /// that stream, but never to another stream at the path.
113    ///
114    /// The session is told from other links by the hop its routes carry: the
115    /// one derived from the peer's id, or, for a peer that declares a hop of
116    /// its own (as moq-relay does), one no other link carries. This node
117    /// cannot read the declaration on a session it dialed, so the guarantee
118    /// is only as strong as the grants: a peer whose grant lets it publish
119    /// the path could declare this peer's hop and be resolved here.
120    ///
121    /// # Errors
122    ///
123    /// Fails with [`Error::NotGranted`] if the session's grant does not let
124    /// the peer publish the path, [`Error::NotAnnounced`] if the session ends
125    /// before the peer announces it, [`Error::Unresolved`] if the route table
126    /// refuses the path, and [`Error::ShutDown`] once the node is gone.
127    pub async fn subscribe(
128        &self,
129        path: impl TryInto<Path, Error: Into<moq_net::Error>>,
130    ) -> Result<Subscription, Error> {
131        let path = crate::error::to_path(path)?;
132        let grant = self.grant();
133        if !grant.allows_publish(path.as_str()) {
134            return Err(Error::not_granted(path, self.inner.peer, &grant));
135        }
136        let Some(shared) = self.inner.shared.upgrade() else {
137            return Err(e!(Error::ShutDown));
138        };
139        let view = route::direct_view(&shared.table);
140        // A hop no other link carries is taken to be the peer's own declaration.
141        let own = self.inner.hop;
142        let link = self.inner.link;
143        let ours = |hop: Hop| {
144            hop == own
145                || shared
146                    .state
147                    .lock()
148                    .expect("poisoned")
149                    .link_with_hop(hop)
150                    .is_none_or(|other| other == link)
151        };
152        let instance = tokio::select! {
153            found = route::announced_by(&view, &path, ours) => match found {
154                Ok(instance) => instance,
155                Err(moq_net::Error::Closed) => return Err(e!(Error::NotAnnounced { path })),
156                Err(source) => return Err(e!(Error::Unresolved { path, source })),
157            },
158            _ = self.inner.moq.closed() => return Err(e!(Error::NotAnnounced { path })),
159        };
160        let broadcast = match view.request(&path, instance.clone()).await {
161            Ok(broadcast) => broadcast,
162            Err(moq_net::Error::Closed) => return Err(e!(Error::NotAnnounced { path })),
163            Err(source) => return Err(e!(Error::Unresolved { path, source })),
164        };
165        Ok(Subscription::new(
166            path,
167            view,
168            broadcast,
169            Some((self.inner.link, instance)),
170            self.inner.shared.clone(),
171        ))
172    }
173
174    /// Returns the iroh connection under the session.
175    ///
176    /// Its paths are iroh's: [`Connection::paths`] lists the open ones, with
177    /// each one's remote address, whether it is selected, and its RTT, and
178    /// [`Connection::paths_stream`] yields the list again whenever it
179    /// changes. [`Connection::stats`] holds the counters of the whole
180    /// connection. [`network_paths`](Self::network_paths) summarizes each
181    /// path.
182    ///
183    /// # Examples
184    ///
185    /// ```no_run
186    /// # fn run(session: iroh_live_node::Session) {
187    /// for path in session.connection().paths().iter() {
188    ///     println!(
189    ///         "{:?} selected={} rtt={:?}",
190    ///         path.remote_addr(),
191    ///         path.is_selected(),
192    ///         path.rtt()
193    ///     );
194    /// }
195    /// # }
196    /// ```
197    #[must_use]
198    pub fn connection(&self) -> &Connection {
199        &self.inner.connection
200    }
201
202    /// Returns the open network paths of the session's connection, the selected one first.
203    ///
204    /// The counters are per path and cumulative, unlike the windowed,
205    /// connection-wide rates of [`sample`](Self::sample). They count QUIC
206    /// packets and leave out path MTU probes.
207    ///
208    /// # Examples
209    ///
210    /// ```no_run
211    /// # fn run(session: iroh_live_node::Session) {
212    /// for path in session.network_paths() {
213    ///     println!(
214    ///         "{} {} selected={} rtt={:?}",
215    ///         path.kind(),
216    ///         path.addr(),
217    ///         path.selected,
218    ///         path.rtt
219    ///     );
220    /// }
221    /// # }
222    /// ```
223    #[must_use]
224    pub fn network_paths(&self) -> Vec<NetworkPath> {
225        let mut paths: Vec<NetworkPath> = self
226            .inner
227            .connection
228            .paths()
229            .iter()
230            .map(|path| {
231                NetworkPath::new(
232                    path.id(),
233                    path.remote_addr(),
234                    path.is_selected(),
235                    &path.stats(),
236                )
237            })
238            .collect();
239        paths.sort_by_key(|path| !path.selected);
240        paths
241    }
242
243    /// Returns the latest reading of the session's link.
244    ///
245    /// The connection monitor refreshes it every 200 ms. A publisher reads its
246    /// uplink here as [`NetworkSample::send_rate`]. A subscriber reaches the
247    /// same reading through [`Subscription::serving_link`], and the session
248    /// itself through [`Subscription::session`].
249    #[must_use]
250    pub fn sample(&self) -> NetworkSample {
251        self.inner.latest_sample.get()
252    }
253
254    /// Returns the moq-net session, for its statistics, bandwidth estimates and announcements.
255    ///
256    /// Closing it closes this session, as [`close`](Self::close) does.
257    #[must_use]
258    pub fn moq(&self) -> &moq_net::Session {
259        &self.inner.moq
260    }
261
262    /// Closes the session, and every subscription over it, in both directions.
263    ///
264    /// The peer receives `code` as the session's close code, and its
265    /// [`closed`](Self::closed) reports it as a [`moq_net::Error::Session`]
266    /// source, for example `Session(SessionError::App(7))` for `App(7)`.
267    pub fn close(&self, code: moq_net::Error) {
268        info!(peer = %self.inner.peer.fmt_short(), %code, "closing session");
269        self.inner.closing.store(true, Ordering::Release);
270        self.inner.moq.abort(code);
271    }
272
273    /// Reports whether the session is closed or on its way to closing.
274    pub(crate) fn is_closing(&self) -> bool {
275        self.inner.closing.load(Ordering::Acquire) || self.inner.connection.close_reason().is_some()
276    }
277
278    /// Waits until the session ends, and returns why.
279    ///
280    /// A close either side asked for is [`Error::SessionClosed`] with
281    /// [`moq_net::Error::Cancel`] as its source. Cancellation safe.
282    pub async fn closed(&self) -> Error {
283        let source = self.inner.moq.closed().await;
284        e!(Error::SessionClosed { source })
285    }
286}