Skip to main content

iroh_live_node/
node.rs

1//! The node: one route table, its publications, and its links.
2
3use std::{
4    collections::{HashMap, HashSet, VecDeque},
5    convert::Infallible,
6    sync::{
7        Arc, Mutex,
8        atomic::{AtomicBool, Ordering},
9    },
10    time::Duration,
11};
12
13use iroh::{
14    Endpoint, EndpointAddr, EndpointId,
15    endpoint::Connection,
16    protocol::{AcceptError, ProtocolHandler, RouterBuilder},
17};
18use moq_ext_json::ValueWriter;
19use moq_net::{Path, broadcast, origin, track};
20use n0_error::{AnyError, e};
21use n0_future::{Stream, StreamExt, stream, task::AbortOnDropHandle};
22use n0_watcher::{Watchable, Watcher};
23use serde::Serialize;
24use tokio::sync::{Notify, mpsc, oneshot};
25use tokio_util::sync::CancellationToken;
26use tracing::{Instrument, debug, info, info_span, trace, warn};
27
28use crate::{
29    Audience, BroadcastTicket, ConnectOptions, Direction, Error, Grant, LinkId, Publication,
30    RelayConfig, RelayLink, Session, Subscription,
31    actor::{Actor, ActorMessage},
32    admission,
33    handshake::{Hop, SessionParts},
34    json,
35    layout::Layout,
36    policy::{self, Authorization, DynPolicy, Policy},
37    publish, reauth, relay, route,
38    state::State,
39};
40
41/// How [`Node::subscribe`] reaches a path the route table has no route to yet.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum Reach {
44    /// Dials the publisher and waits for it to announce the path.
45    ///
46    /// A media relay route that is in the table, or arrives during the dial, also
47    /// resolves the path.
48    Direct(EndpointId),
49    /// Waits for an attached media relay to route the path.
50    Relays,
51    /// Dials the publisher and waits on media relays at the same time.
52    Both(EndpointId),
53}
54
55/// How long the node waits for its policy by default.
56pub const DECIDE_TIMEOUT: Duration = Duration::from_secs(10);
57
58/// How many messages may wait for the node's actor.
59///
60/// Every message is a connect or a session to register. Sixteen absorb a
61/// burst of dials, and a full inbox only makes the next sender wait.
62const ACTOR_INBOX: usize = 16;
63
64/// The configuration of a [`Node`].
65#[derive(Clone, derive_more::Debug)]
66#[non_exhaustive]
67pub struct NodeConfig {
68    /// Decides who may hold a session with the node, and with which rights.
69    ///
70    /// The node asks it when it accepts a session, after the peer's MoQ
71    /// SETUP, and before it dials a peer. A rejection closes an accepted
72    /// session with the rejection's code, and fails a dial with
73    /// [`Error::Rejected`]. Each session is decided on its own, with the
74    /// request and token it opened with, so a peer's second session asks
75    /// the policy again.
76    ///
77    /// The node asks again about a live session when its authorization
78    /// expires and on [`Node::reauthorize`], with
79    /// [`Event::Reauthorize`](policy::Event::Reauthorize). An expired
80    /// session may do nothing until the new decision applies.
81    ///
82    /// `None` is [`policy::Open`] with [`Grant::subscribe_only`]: every peer
83    /// may subscribe to anything and publish nothing.
84    pub policy: Option<Arc<dyn DynPolicy<EndpointId>>>,
85    /// How long the node waits for each decision of its policy.
86    ///
87    /// A decision that takes longer is a rejection with
88    /// [`moq_net::Error::Timeout`]. The default is [`DECIDE_TIMEOUT`]. Raise it
89    /// when a person answers, as with a [`policy::Queue`].
90    ///
91    /// When the node asks again about a live session, a timeout or a full
92    /// queue ([`moq_net::Error::TooManyRequests`]) is no rejection: the
93    /// session keeps its authorization, and the node asks again later.
94    pub decide_timeout: Duration,
95    /// A route table to use instead of a new one, such as a media relay's cluster origin.
96    ///
97    /// The caller runs its driver. The node serves the table's local view,
98    /// which hides routes from handles tagged [`Link::Peer`](origin::Link::Peer)
99    /// or [`Link::Upstream`](origin::Link::Upstream). `None` creates a table
100    /// under the hop derived from the endpoint id.
101    #[debug("{}", table.is_some())]
102    pub table: Option<origin::Producer>,
103    /// The path layout that names the peer owning a path, for [`Node::claim_path`].
104    ///
105    /// `None` uses the generic rule: a path is a peer's when exactly one of
106    /// its segments is the peer's endpoint id.
107    #[debug("{}", layout.is_some())]
108    pub layout: Option<Arc<dyn Layout<EndpointId>>>,
109}
110
111impl Default for NodeConfig {
112    fn default() -> Self {
113        Self {
114            policy: None,
115            decide_timeout: DECIDE_TIMEOUT,
116            table: None,
117            layout: None,
118        }
119    }
120}
121
122impl NodeConfig {
123    /// Returns this configuration with `policy` deciding who may hold a session.
124    #[must_use]
125    pub fn with_policy(mut self, policy: impl Policy<EndpointId>) -> Self {
126        self.policy = Some(Arc::new(policy));
127        self
128    }
129
130    /// Returns this configuration with `timeout` bounding each decision of the policy.
131    ///
132    /// See [`decide_timeout`](Self::decide_timeout).
133    #[must_use]
134    pub fn with_decide_timeout(mut self, timeout: Duration) -> Self {
135        self.decide_timeout = timeout;
136        self
137    }
138
139    /// Returns this configuration with `table` as the node's route table.
140    ///
141    /// See [`table`](Self::table).
142    #[must_use]
143    pub fn with_table(mut self, table: origin::Producer) -> Self {
144        self.table = Some(table);
145        self
146    }
147
148    /// Returns this configuration with `layout` naming the peer that owns a path.
149    ///
150    /// See [`layout`](Self::layout).
151    #[must_use]
152    pub fn with_layout(mut self, layout: impl Layout<EndpointId>) -> Self {
153        self.layout = Some(Arc::new(layout));
154        self
155    }
156}
157
158/// A MoQ node on an iroh endpoint.
159///
160/// Cheap to clone, and [`shutdown`](Self::shutdown) ends it for every clone.
161/// Mount it on a [`Router`](iroh::protocol::Router) with [`mount`](Self::mount).
162///
163/// # Examples
164///
165/// Publish a broadcast and serve it to whoever connects:
166///
167/// ```no_run
168/// use iroh::{Endpoint, protocol::Router};
169/// use iroh_live_node::{Audience, MinimalPreset, Node, NodeConfig};
170///
171/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
172/// let endpoint = Endpoint::bind(MinimalPreset).await?;
173/// let node = Node::new(endpoint.clone(), NodeConfig::default());
174/// let _router = node.mount(Router::builder(endpoint)).spawn();
175///
176/// let publication = node.publish("demo/camera", Audience::Granted)?;
177/// // write tracks into the broadcast in the route table:
178/// let _track = publication.broadcast().create_track("video", None).ok_or("the track exists")?;
179/// # Ok(())
180/// # }
181/// ```
182#[derive(Clone, derive_more::Debug)]
183#[debug("Node({}, origin node {})", shared.id.fmt_short(), shared.table.node())]
184pub struct Node {
185    pub(crate) shared: Arc<Shared>,
186    /// Aborts the node's tasks when the last handle drops.
187    pub(crate) tasks: Arc<Tasks>,
188}
189
190/// What every handle of a node shares.
191pub(crate) struct Shared {
192    pub(crate) endpoint: Endpoint,
193    pub(crate) id: EndpointId,
194    pub(crate) policy: Arc<dyn DynPolicy<EndpointId>>,
195    pub(crate) decide_timeout: Duration,
196    /// The re-decides the application asked for, until the actor takes them.
197    pub(crate) reauth_requests: Mutex<reauth::Requests>,
198    /// Wakes the actor for new [`reauth_requests`](Self::reauth_requests).
199    pub(crate) reauth_notify: Notify,
200    pub(crate) layout: Option<Arc<dyn Layout<EndpointId>>>,
201    pub(crate) table: origin::Producer,
202    /// The node's publications and links.
203    ///
204    /// Lock order: this lock first, then a subscription's `routes`. Never
205    /// await while holding either.
206    pub(crate) state: Mutex<State>,
207    pub(crate) sessions: Watchable<Vec<Session>>,
208    pub(crate) actor: mpsc::Sender<ActorMessage>,
209    pub(crate) shutdown: CancellationToken,
210    pub(crate) done: Watchable<bool>,
211    /// Set by [`Node::mount`], or by the first session the node accepts.
212    mounted: AtomicBool,
213    /// Set once a publish has warned that no peer can connect.
214    warned_unreachable: AtomicBool,
215}
216
217/// The node's tasks, kept apart from [`Shared`] so the tasks can hold it.
218pub(crate) struct Tasks {
219    /// Cancelled on drop, so [`Node::closed`] resolves when the last handle goes.
220    shutdown: CancellationToken,
221    _actor: AbortOnDropHandle<()>,
222    /// Runs the route table's driver, unless the caller supplied the table.
223    _table: Option<AbortOnDropHandle<()>>,
224    /// Relay links, by link id.
225    pub(crate) relays: Mutex<HashMap<LinkId, crate::relay::RelayTask>>,
226}
227
228impl Drop for Tasks {
229    fn drop(&mut self) {
230        self.shutdown.cancel();
231    }
232}
233
234impl Node {
235    /// Creates a node on `endpoint`.
236    ///
237    /// # Panics
238    ///
239    /// Panics when called outside a Tokio runtime.
240    #[must_use]
241    pub fn new(endpoint: Endpoint, config: NodeConfig) -> Self {
242        let id = endpoint.id();
243        let (table, table_task) = match config.table {
244            Some(table) => (table, None),
245            None => {
246                let (table, driver) = origin::Producer::new(origin::Config::new(Hop::of(&id).id()));
247                let task = tokio::spawn(
248                    async move {
249                        let err = moq_net::time::run(driver).await;
250                        debug!(error = %err, "route table finished");
251                    }
252                    .instrument(info_span!("route_table")),
253                );
254                (table, Some(AbortOnDropHandle::new(task)))
255            }
256        };
257        let policy = config
258            .policy
259            .unwrap_or_else(|| Arc::new(policy::Open(Grant::subscribe_only())));
260        let (actor_tx, actor_rx) = mpsc::channel(ACTOR_INBOX);
261        let shared = Arc::new(Shared {
262            endpoint,
263            id,
264            policy,
265            decide_timeout: config.decide_timeout,
266            reauth_requests: Mutex::new(reauth::Requests::default()),
267            reauth_notify: Notify::new(),
268            layout: config.layout,
269            table,
270            state: Mutex::new(State::default()),
271            sessions: Watchable::new(Vec::new()),
272            actor: actor_tx,
273            shutdown: CancellationToken::new(),
274            done: Watchable::new(false),
275            mounted: AtomicBool::new(false),
276            warned_unreachable: AtomicBool::new(false),
277        });
278        info!(id = %id.fmt_short(), node = %shared.table.node(), "moq node started");
279        let shutdown = shared.shutdown.clone();
280        let actor = Actor::new(shared.clone());
281        let actor_task = tokio::spawn(
282            actor
283                .run(actor_rx)
284                .instrument(info_span!("moq", id = %id.fmt_short())),
285        );
286        Self {
287            shared,
288            tasks: Arc::new(Tasks {
289                shutdown,
290                _actor: AbortOnDropHandle::new(actor_task),
291                _table: table_task,
292                relays: Mutex::new(HashMap::new()),
293            }),
294        }
295    }
296
297    /// Mounts the node on `router` under every ALPN in [`alpns`](crate::alpns).
298    ///
299    /// Without a router, or an accept loop that hands connections to the
300    /// node, the endpoint refuses every incoming connection.
301    #[must_use]
302    pub fn mount(&self, mut router: RouterBuilder) -> RouterBuilder {
303        debug_assert_eq!(
304            router.endpoint().id(),
305            self.shared.id,
306            "the router runs on another endpoint"
307        );
308        self.shared.mounted.store(true, Ordering::Relaxed);
309        for alpn in crate::alpns() {
310            router = router.accept(alpn, self.clone());
311        }
312        router
313    }
314
315    /// Returns the endpoint id of the node.
316    #[must_use]
317    pub fn id(&self) -> EndpointId {
318        self.shared.id
319    }
320
321    /// Returns the authorization the policy gave the newest session with `peer` that holds one.
322    ///
323    /// The node decides each session on its own, so two sessions with one
324    /// peer may hold different authorizations. [`Session::grant`] reads the
325    /// grant of one session, with the ticket claims that widen it. An expired
326    /// authorization stays here until the policy decides again, while
327    /// [`Session::grant`] already grants nothing. Returns `None` once the peer
328    /// has no session, or none that holds an authorization.
329    #[must_use]
330    pub fn authorization_for(&self, peer: EndpointId) -> Option<Authorization> {
331        self.shared
332            .state
333            .lock()
334            .expect("poisoned")
335            .newest_authorization(&peer)
336            .cloned()
337    }
338
339    /// Asks the policy again about every live session with `peer`.
340    ///
341    /// Call it when state the policy reads changes, such as a
342    /// [`filter`](Policy::filter) predicate. The decisions run in the
343    /// background: a new authorization replaces a session's, and a
344    /// rejection closes that session with its code.
345    ///
346    /// A session of any peer whose first decision is still running when
347    /// this is called is decided again once it registers, and holds nothing
348    /// until then, so it never keeps rights from before the call.
349    pub fn reauthorize(&self, peer: EndpointId) {
350        self.shared.state.lock().expect("poisoned").reauthorized += 1;
351        self.shared
352            .reauth_requests
353            .lock()
354            .expect("poisoned")
355            .peers
356            .insert(peer);
357        self.shared.reauth_notify.notify_one();
358    }
359
360    /// Asks the policy again about every live session.
361    ///
362    /// It does for every peer what [`reauthorize`](Self::reauthorize) does for one.
363    pub fn reauthorize_all(&self) {
364        self.shared.state.lock().expect("poisoned").reauthorized += 1;
365        self.shared.reauth_requests.lock().expect("poisoned").all = true;
366        self.shared.reauth_notify.notify_one();
367    }
368
369    /// Returns a future that resolves when the node shuts down.
370    ///
371    /// Resolves once [`shutdown`](Self::shutdown) starts, or once the last
372    /// handle drops. Cancellation safe.
373    pub fn closed(&self) -> impl Future<Output = ()> + Send + 'static {
374        self.shared.shutdown.clone().cancelled_owned()
375    }
376
377    /// Returns the endpoint the node runs on.
378    #[must_use]
379    pub fn endpoint(&self) -> &Endpoint {
380        &self.shared.endpoint
381    }
382
383    /// Creates a broadcast at `path` in the route table, for `audience`.
384    ///
385    /// Fill it through [`Publication::broadcast`]. moq's limits on a grant
386    /// bound how many publications one peer can see, as
387    /// [`moq_ext_access::visible_paths`] describes.
388    ///
389    /// A link sees a path through a grant prefix, which covers every path
390    /// beneath it. A publication beneath another with a narrower audience
391    /// therefore hides the upper one from every link outside its own
392    /// audience, media relays included when the lower one is
393    /// [`Audience::Peers`]. The node logs a warning when that happens.
394    /// Publish a private broadcast beside a public one, not beneath it.
395    ///
396    /// # Errors
397    ///
398    /// Fails with [`Error::Duplicate`] if another publication has the path,
399    /// [`Error::Moq`] if `path` does not parse, [`Error::InvalidPath`] for an
400    /// empty path or one with a `*` segment, and [`Error::ShutDown`] once the
401    /// node has shut down.
402    ///
403    /// # Panics
404    ///
405    /// Panics when called outside a Tokio runtime.
406    pub fn publish(
407        &self,
408        path: impl TryInto<Path, Error: Into<moq_net::Error>>,
409        audience: Audience,
410    ) -> Result<Publication, Error> {
411        let path = crate::error::to_path(path)?;
412        self.warn_if_unreachable(&path);
413        let (publication, ()) =
414            publish::publish(&self.shared, path, audience, |_| Ok::<_, Infallible>(()))?;
415        Ok(publication)
416    }
417
418    /// Publishes as [`publish`](Self::publish) does, filling the broadcast before it is announced.
419    ///
420    /// `fill` runs once, before anyone can see the broadcast, and its result
421    /// comes back with the publication. Create the tracks a reader needs
422    /// first there, such as a catalog. It runs before the node takes its
423    /// lock, so it may call back into the node. If the path turns out to be
424    /// taken, the broadcast is closed and what `fill` returned is dropped.
425    ///
426    /// # Errors
427    ///
428    /// As [`publish`](Self::publish), and [`Error::Fill`] if `fill` fails,
429    /// which closes the broadcast. `fill` may fail with any error that boxes
430    /// into a `std::error::Error`, an `anyhow::Error` included.
431    ///
432    /// # Panics
433    ///
434    /// Panics when called outside a Tokio runtime.
435    pub fn publish_with<T, E>(
436        &self,
437        path: impl TryInto<Path, Error: Into<moq_net::Error>>,
438        audience: Audience,
439        fill: impl FnOnce(&broadcast::Producer) -> Result<T, E>,
440    ) -> Result<(Publication, T), Error>
441    where
442        E: Into<Box<dyn std::error::Error + Send + Sync>>,
443    {
444        let path = crate::error::to_path(path)?;
445        self.warn_if_unreachable(&path);
446        publish::publish(&self.shared, path, audience, fill)
447    }
448
449    /// Publishes a broadcast at `path` whose one track `name` holds a latest-value JSON track.
450    ///
451    /// For state such as a setting, a status or a result: each
452    /// [`update`](ValueWriter::update) replaces the value, and a reader that
453    /// subscribes late gets the current one at once. The track counts
454    /// milliseconds, and the [`ValueWriter`] stamps each update with the time
455    /// it is made; [`update_at`](ValueWriter::update_at) takes a time of the
456    /// caller's choice instead. The last clone of the writer to drop finishes
457    /// the track. The track exists before the broadcast is announced, so no
458    /// reader misses it. Readers open it with [`Subscription::value_track`].
459    /// To put the track next to others, create it in
460    /// [`publish_with`](Self::publish_with)'s fill and pass it to
461    /// [`ValueWriter::new`].
462    ///
463    /// # Errors
464    ///
465    /// As [`publish_with`](Self::publish_with).
466    ///
467    /// # Panics
468    ///
469    /// Panics when called outside a Tokio runtime.
470    ///
471    /// # Examples
472    ///
473    /// ```no_run
474    /// # fn run(node: iroh_live_node::Node) -> Result<(), Box<dyn std::error::Error>> {
475    /// use iroh_live_node::Audience;
476    ///
477    /// let (_publication, latency) =
478    ///     node.publish_value::<u64>("live/control", Audience::Granted, "latency")?;
479    /// latency.update(&150)?;
480    /// # Ok(())
481    /// # }
482    /// ```
483    pub fn publish_value<T: Serialize>(
484        &self,
485        path: impl TryInto<Path, Error: Into<moq_net::Error>>,
486        audience: Audience,
487        name: &str,
488    ) -> Result<(Publication, ValueWriter<T>), Error> {
489        self.publish_with(path, audience, |broadcast| {
490            let info = track::Info::default().with_timescale(moq_net::Timescale::MILLI);
491            let track = broadcast
492                .create_track(name, info)
493                .ok_or(moq_net::Error::Duplicate)?;
494            Ok::<_, moq_net::Error>(ValueWriter::new(track, json::snapshot::Config::default()))
495        })
496    }
497
498    /// Warns once if no peer can connect to the node to read `path`.
499    ///
500    /// Forgetting to mount the node fails silently otherwise: dialers get an
501    /// ALPN error, and the publisher logs nothing.
502    fn warn_if_unreachable(&self, path: &Path) {
503        if self.shared.mounted.load(Ordering::Relaxed)
504            || !self.tasks.relays.lock().expect("poisoned").is_empty()
505            || self.shared.warned_unreachable.swap(true, Ordering::Relaxed)
506        {
507            return;
508        }
509        warn!(
510            %path,
511            "publishing on a node that is neither mounted on a router nor attached to a relay: \
512             only peers this node dials can read it"
513        );
514    }
515
516    /// Resolves `path` in the route table.
517    ///
518    /// If no route exists yet, reaches out as `reach` says. Cancellation safe:
519    /// a dial this call started continues for other callers.
520    ///
521    /// The [crate docs](crate#trust-and-grants) explain the trust model.
522    ///
523    /// # Errors
524    ///
525    /// Fails with:
526    ///
527    /// - [`Error::Moq`] or [`Error::InvalidPath`] for a path that cannot be
528    ///   published, as [`publish`](Self::publish) does.
529    /// - [`Error::NoRoute`] if `reach` allows no way to reach the path.
530    /// - [`Error::Transport`] if the publisher cannot be dialed and no media relay can
531    ///   stand in.
532    /// - [`Error::NotGranted`] if the publisher's grant does not let it
533    ///   publish the path and no media relay can stand in.
534    /// - [`Error::NotAnnounced`] if the publisher's session ends before it
535    ///   announces the path.
536    /// - [`Error::Unresolved`] if the route table refuses the path.
537    /// - [`Error::ShutDown`] once the node has shut down.
538    pub async fn subscribe(
539        &self,
540        path: impl TryInto<Path, Error: Into<moq_net::Error>>,
541        reach: Reach,
542    ) -> Result<Subscription, Error> {
543        route::subscribe(self, crate::error::to_path(path)?, reach).await
544    }
545
546    /// Resolves the broadcast `ticket` names, whatever grants this node has.
547    ///
548    /// The node first claims the path for the ticket's peer with
549    /// [`claim_path`](Self::claim_path), and the subscription holds the claim
550    /// for as long as it lives. Then this is [`subscribe`](Self::subscribe)
551    /// with [`Reach::Both`]. When the last subscription of a path drops, the
552    /// grant narrows again, and moq ends what local readers read there.
553    ///
554    /// # Errors
555    ///
556    /// As [`claim_path`](Self::claim_path), and as [`subscribe`](Self::subscribe).
557    pub async fn subscribe_ticket(&self, ticket: &BroadcastTicket) -> Result<Subscription, Error> {
558        route::subscribe_ticket(self, ticket).await
559    }
560
561    /// Returns the route table.
562    ///
563    /// It holds what [`subscribe`](Self::subscribe) resolves in, and its
564    /// [`announced`](origin::Consumer::announced) stream lists the paths.
565    #[must_use]
566    pub fn origin(&self) -> origin::Consumer {
567        self.shared.table.consume()
568    }
569
570    /// Returns the session with `peer`, dialing if there is none.
571    ///
572    /// Concurrent calls share one dial, which continues if this future is
573    /// dropped. The dialer's half of the handshake completes before the peer
574    /// decides whether to admit it, so a peer that refuses usually closes the
575    /// session right after this returns. [`Session::closed`] then says why.
576    ///
577    /// # Errors
578    ///
579    /// Fails with [`Error::Rejected`] if this node's policy rejects the peer,
580    /// [`Error::Transport`] if the dial fails, [`Error::Refused`] if a peer on
581    /// an older protocol version refuses during the handshake, and
582    /// [`Error::ShutDown`] once the node has shut down. A handshake that takes
583    /// longer than [`HANDSHAKE_TIMEOUT`](crate::HANDSHAKE_TIMEOUT) fails with
584    /// [`Error::Moq`].
585    pub async fn connect(&self, peer: impl Into<EndpointAddr>) -> Result<Session, Error> {
586        self.connect_with(peer, ConnectOptions::default()).await
587    }
588
589    /// Dials `peer` with a token, a path, a cost, or iroh's connect options.
590    ///
591    /// An existing session with the peer, or a dial in flight to it, is
592    /// returned as it is, and the options go unused. A token then reaches
593    /// the peer only if you close that session first.
594    ///
595    /// # Errors
596    ///
597    /// As [`connect`](Self::connect).
598    pub async fn connect_with(
599        &self,
600        peer: impl Into<EndpointAddr>,
601        options: ConnectOptions,
602    ) -> Result<Session, Error> {
603        if self.shared.shutdown.is_cancelled() {
604            return Err(e!(Error::ShutDown));
605        }
606        let (reply, reply_rx) = oneshot::channel();
607        self.shared
608            .actor
609            .send(ActorMessage::Connect {
610                peer: peer.into(),
611                options,
612                reply,
613            })
614            .await
615            .map_err(|_| e!(Error::ShutDown))?;
616        reply_rx.await.map_err(|_| e!(Error::ShutDown))?
617    }
618
619    /// Returns the open direct sessions, dialed and accepted, as they change.
620    #[must_use]
621    pub fn sessions(&self) -> n0_watcher::Direct<Vec<Session>> {
622        self.shared.sessions.watch()
623    }
624
625    /// Returns a stream of the sessions this node accepts.
626    ///
627    /// Yields every accepted session open when it is called, then each new
628    /// one as it opens, each once, and ends when the node shuts down. It
629    /// leaves out the sessions this node dialed, which
630    /// [`sessions`](Self::sessions) lists too. It reads the same list, so a
631    /// session that opens and closes between two polls may be skipped.
632    ///
633    /// # Examples
634    ///
635    /// Serve each peer that connects in a task of its own:
636    ///
637    /// ```no_run
638    /// use n0_future::StreamExt;
639    ///
640    /// # async fn run(node: iroh_live_node::Node) {
641    /// let mut accepted = node.accepted();
642    /// while let Some(session) = accepted.next().await {
643    ///     tokio::spawn(async move {
644    ///         // Serve the peer, until the session ends.
645    ///         let reason = session.closed().await;
646    ///         println!("{} left: {reason:#}", session.peer());
647    ///     });
648    /// }
649    /// # }
650    /// ```
651    pub fn accepted(&self) -> impl Stream<Item = Session> + Send + Unpin + 'static {
652        /// What the stream carries from one poll to the next.
653        struct State {
654            /// Every list of sessions the node publishes.
655            lists: n0_watcher::Stream<n0_watcher::Direct<Vec<Session>>>,
656            shutdown: CancellationToken,
657            /// The links of the accepted sessions already yielded and still listed.
658            seen: HashSet<LinkId>,
659            /// Accepted sessions not yielded yet.
660            pending: VecDeque<Session>,
661        }
662        let state = State {
663            lists: self.shared.sessions.watch().stream(),
664            shutdown: self.shared.shutdown.clone(),
665            seen: HashSet::new(),
666            pending: VecDeque::new(),
667        };
668        Box::pin(stream::unfold(state, |mut state| async move {
669            loop {
670                if let Some(session) = state.pending.pop_front() {
671                    return Some((session, state));
672                }
673                let sessions = tokio::select! {
674                    sessions = state.lists.next() => sessions?,
675                    () = state.shutdown.cancelled() => return None,
676                };
677                let listed: HashSet<LinkId> =
678                    sessions.iter().map(|session| session.inner.link).collect();
679                state.seen.retain(|link| listed.contains(link));
680                for session in sessions {
681                    if session.direction() == Direction::Accepted
682                        && state.seen.insert(session.inner.link)
683                    {
684                        trace!(
685                            peer = %session.peer().fmt_short(),
686                            link = %session.inner.link,
687                            "yielding accepted session"
688                        );
689                        state.pending.push_back(session);
690                    }
691                }
692            }
693        }))
694    }
695
696    /// Attaches to the media relay at `config.url`, redialing it with backoff.
697    ///
698    /// # Errors
699    ///
700    /// Fails with [`Error::InvalidRelayUrl`] for an unsupported URL scheme or
701    /// an `iroh://` URL without an endpoint id, [`Error::Relay`] if the client
702    /// cannot be set up, and [`Error::ShutDown`] once the node has shut down.
703    ///
704    /// # Panics
705    ///
706    /// Panics when called outside a Tokio runtime.
707    pub fn attach_relay(&self, config: RelayConfig) -> Result<RelayLink, Error> {
708        relay::attach(self, config)
709    }
710
711    /// Shuts the node down for every clone.
712    ///
713    /// Closes every session, detaches media relays and withdraws publications.
714    /// Gives sessions a short grace to tell their peers, so the endpoint can
715    /// be closed once this returns. Idempotent. Not cancellation safe: call it
716    /// again to finish.
717    ///
718    /// A node [mounted](Self::mount) on a router shuts down with
719    /// `Router::shutdown`, which calls this before it closes the endpoint, so
720    /// there is no need to call both. Call it for a node without a router, or
721    /// to stop the node while the router's other protocols keep running.
722    pub async fn shutdown(&self) {
723        // Set first, so a racing publish or attach fails instead of being
724        // added and then cleared.
725        self.shared.state.lock().expect("poisoned").closed = true;
726        self.shared.shutdown.cancel();
727        self.tasks.shutdown_relays().await;
728        let mut done = self.shared.done.watch();
729        while !done.get() {
730            if done.updated().await.is_err() {
731                break;
732            }
733        }
734    }
735}
736
737impl ProtocolHandler for Node {
738    async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
739        // Covers an accept loop of the caller's own, which skips `mount`.
740        self.shared.mounted.store(true, Ordering::Relaxed);
741        admission::accept(&self.shared, connection)
742            .await
743            .map_err(AnyError::from)?;
744        Ok(())
745    }
746
747    /// Shuts the node down with the router, as [`Node::shutdown`] does.
748    async fn shutdown(&self) {
749        // Resolves to the inherent method.
750        Self::shutdown(self).await;
751    }
752}
753
754impl Shared {
755    /// Hands an established session to the actor, which runs it.
756    pub(crate) async fn register(&self, parts: SessionParts) -> Result<Session, Error> {
757        let (reply, reply_rx) = oneshot::channel();
758        self.actor
759            .send(ActorMessage::Register {
760                parts: Box::new(parts),
761                reply,
762            })
763            .await
764            .map_err(|_| e!(Error::ShutDown))?;
765        reply_rx.await.map_err(|_| e!(Error::ShutDown))
766    }
767}