Skip to main content

iroh_live_node/
route.rs

1//! The route table, and the subscriptions that resolve paths in it.
2//!
3//! Every link announces straight into the node's route table. A session's
4//! subscriber is the table tagged [`Link::Peer`], gated by the session's
5//! authorization. A media relay's subscriber is the table tagged [`Link::Upstream`].
6//! Every link serves the table's local view, which hides both, so no route
7//! learned on one link is offered on another. Which link a route came from is
8//! the route's [`Source`].
9
10use std::{
11    sync::{Arc, Mutex, OnceLock, Weak},
12    time::Duration,
13};
14
15use moq_net::{
16    Identity, Path, Prefix, Prefixes, broadcast,
17    origin::{self, Link, RouteEvent, RouteKind},
18};
19use n0_error::e;
20use n0_future::task::AbortOnDropHandle;
21use serde::de::DeserializeOwned;
22use tokio::sync::watch;
23use tokio_util::sync::CancellationToken;
24use tracing::{debug, info};
25
26use crate::{
27    BroadcastTicket, Error, LinkId, Node, PathClaim, Reach, ServingLink, Session, ValueReader,
28    handshake::{Hop, Source},
29    node::Shared,
30    publish::check_path,
31    state::{LinkEntry, State},
32};
33
34/// The pause before asking the table again once a broadcast ended.
35///
36/// A successor, such as a second session with the publisher that may
37/// announce only once the first ends, needs a moment to enter the table.
38const REASK_PAUSE: Duration = Duration::from_millis(100);
39
40/// A path resolved in a route table.
41///
42/// moq moves the broadcast between routes of one identity without ending it.
43/// When another identity takes the path over, [`broadcast`](Self::broadcast)
44/// switches to what serves it now. moq-lite-06 names no identity on the wire,
45/// so each session mints its own: a move between a direct link and a media relay is
46/// such a switch, and readers of the old broadcast start over on the new. Cheap
47/// to clone. For media, `iroh_live::media::SubscriptionExt::remote_broadcast` reads it
48/// as a `RemoteBroadcast` that adapts to the serving link.
49///
50/// # Examples
51///
52/// ```no_run
53/// # async fn run(node: iroh_live_node::Node, peer: iroh::EndpointId)
54/// # -> Result<(), iroh_live_node::Error> {
55/// use iroh_live_node::Reach;
56///
57/// let subscription = node.subscribe("live/camera", Reach::Both(peer)).await?;
58/// let broadcast = subscription.broadcast();
59/// # drop(broadcast);
60/// // Resolves once no route serves the path any more.
61/// subscription.closed().await;
62/// # Ok(())
63/// # }
64/// ```
65#[derive(Clone, derive_more::Debug)]
66#[debug("Subscription({}, pinned {})", inner.path, inner.pin.is_some())]
67pub struct Subscription {
68    inner: Arc<SubscriptionInner>,
69}
70
71/// What every clone of a [`Subscription`] shares.
72struct SubscriptionInner {
73    path: Path,
74    origin: origin::Consumer,
75    /// The broadcast [`Subscription::broadcast`] returns, which the follow task updates.
76    current: watch::Sender<broadcast::Consumer>,
77    /// Cancelled once nothing serves the path.
78    ended: CancellationToken,
79    /// Follows the path for as long as the subscription lives.
80    _follow: AbortOnDropHandle<()>,
81    /// The link the subscription reads from, if it does not follow the whole table.
82    pin: Option<LinkId>,
83    /// The route serving the path, as the table announces it.
84    routes: Mutex<Routes>,
85    shared: Weak<Shared>,
86    /// The ticket claim that lets the publisher announce the path, while held.
87    claim: OnceLock<PathClaim>,
88}
89
90/// The route that serves one path, as the route table announces it.
91struct Routes {
92    path: Path,
93    announced: Option<origin::Routes>,
94    source: Option<Source>,
95}
96
97impl Routes {
98    /// Starts following the routes at exactly `path` in `table`.
99    fn new(table: &origin::Consumer, path: &Path) -> Self {
100        let announced = routes_under(table, path).ok();
101        Self {
102            path: path.clone(),
103            announced,
104            source: None,
105        }
106    }
107
108    /// Returns where the route serving the path entered the node.
109    fn source(&mut self) -> Option<Source> {
110        let announced = self.announced.as_mut()?;
111        while let Some(event) = announced.try_next() {
112            if event.announce.prefix == self.path {
113                self.source = live_route(&event).map(|announce| Source::of(&announce.route));
114            }
115        }
116        self.source
117    }
118}
119
120/// Returns the routes `table` announces at `path` and beneath it.
121///
122/// A scope is a set of prefixes, so a caller after the route at exactly
123/// `path` skips the events of paths beneath it.
124fn routes_under(table: &origin::Consumer, path: &Path) -> Result<origin::Routes, moq_net::Error> {
125    let prefix = path
126        .as_str()
127        .parse::<Prefix>()
128        .map_err(|_| moq_net::Error::Unauthorized)?;
129    Ok(table.scope("", &Prefixes::from(prefix))?.routes())
130}
131
132impl Subscription {
133    /// Creates a subscription that reads `broadcast`, resolved at `path` in `origin`.
134    ///
135    /// `pin` is the link, and the identity it announced, that the subscription
136    /// is limited to. Must run inside a tokio runtime.
137    pub(crate) fn new(
138        path: Path,
139        origin: origin::Consumer,
140        broadcast: broadcast::Consumer,
141        pin: Option<(LinkId, Identity)>,
142        shared: Weak<Shared>,
143    ) -> Self {
144        let routes = Routes::new(&origin, &path);
145        let current = watch::Sender::new(broadcast);
146        let ended = CancellationToken::new();
147        let follow = tokio::spawn(follow(
148            path.clone(),
149            origin.clone(),
150            pin.as_ref().map(|(_, identity)| identity.clone()),
151            current.clone(),
152            ended.clone(),
153        ));
154        Self {
155            inner: Arc::new(SubscriptionInner {
156                path,
157                origin,
158                current,
159                ended,
160                _follow: AbortOnDropHandle::new(follow),
161                pin: pin.map(|(link, _)| link),
162                routes: Mutex::new(routes),
163                shared,
164                claim: OnceLock::new(),
165            }),
166        }
167    }
168
169    /// Keeps `claim` alive for as long as the subscription lives.
170    fn holding(self, claim: PathClaim) -> Self {
171        self.inner.claim.set(claim).ok();
172        self
173    }
174
175    /// Returns the path this subscription resolves.
176    #[must_use]
177    pub fn path(&self) -> &Path {
178        &self.inner.path
179    }
180
181    /// Returns the route table the path was resolved in.
182    #[must_use]
183    pub fn origin(&self) -> origin::Consumer {
184        self.inner.origin.clone()
185    }
186
187    /// Returns the broadcast that serves the path now.
188    ///
189    /// A later call may return a newer broadcast than an earlier one. For
190    /// media, `iroh_live::media::SubscriptionExt::remote_broadcast` reads it
191    /// as a `RemoteBroadcast` that adapts to the serving link.
192    #[must_use]
193    pub fn broadcast(&self) -> broadcast::Consumer {
194        self.inner.current.borrow().clone()
195    }
196
197    /// Returns a reader of the latest-value JSON track `name` of the broadcast.
198    ///
199    /// The publisher writes it with [`Node::publish_value`] or a
200    /// [`ValueWriter`](crate::ValueWriter) of its own. Each value carries the
201    /// time it was published in [`Timed::at`]. The reader skips to the newest
202    /// value with [`latest`](ValueReader::latest), and a late reader gets the
203    /// current value at once. The reader follows the subscription: when the
204    /// publisher restarts, it reads the track of the new broadcast, and it
205    /// ends only once the subscription closes. For a reader of one broadcast
206    /// with other limits, pass [`broadcast`](Self::broadcast)`().track(name)`
207    /// to [`json::snapshot::Consumer::new`] with a config of its own.
208    ///
209    /// [`Timed::at`]: crate::json::Timed::at
210    /// [`json::snapshot::Consumer::new`]: crate::json::snapshot::Consumer::new
211    ///
212    /// # Errors
213    ///
214    /// Fails with [`Error::Moq`] when the broadcast has ended, or when a local
215    /// broadcast has no track `name`. A remote publisher answers for its
216    /// tracks itself, so there a missing track fails the first read instead.
217    ///
218    /// # Examples
219    ///
220    /// ```no_run
221    /// # async fn run(subscription: iroh_live_node::Subscription)
222    /// # -> Result<(), Box<dyn std::error::Error>> {
223    /// let mut latency = subscription.value_track::<u64>("latency")?;
224    /// while let Some(newest) = latency.latest().await? {
225    ///     println!("latency {} ms", newest.value);
226    /// }
227    /// # Ok(())
228    /// # }
229    /// ```
230    pub fn value_track<T: DeserializeOwned>(&self, name: &str) -> Result<ValueReader<T>, Error> {
231        let reader = ValueReader::new(self.clone(), self.inner.current.subscribe(), name)
232            .map_err(|source| e!(Error::Moq { source }))?;
233        debug!(path = %self.inner.path, track = name, "reading value track");
234        Ok(reader)
235    }
236
237    /// Returns the session serving the broadcast now, if a direct session does.
238    ///
239    /// The session gives the iroh connection with its paths
240    /// ([`Session::connection`]) and the latest reading of the link
241    /// ([`Session::sample`]). Asking the subscription each time, rather than
242    /// keeping a session from an earlier dial, follows the subscription when
243    /// another link takes over. `None` while a media relay serves the broadcast.
244    #[must_use]
245    pub fn session(&self) -> Option<Session> {
246        let shared = self.inner.shared.upgrade()?;
247        let (link, _) = self.serving(&shared.state.lock().expect("poisoned"))?;
248        // Link ids are unique across sessions and relays, so a relay finds none.
249        shared
250            .sessions
251            .get()
252            .into_iter()
253            .find(|session| session.inner.link == link)
254    }
255
256    /// Returns the link serving the broadcast now, and its latest reading.
257    ///
258    /// `None` before the table announces a route, for a publication of this
259    /// node, and once the serving link is gone. Also `None` when a media relay
260    /// serves the route and several media relays feed the table, since a media relay's
261    /// route does not say which media relay it came from.
262    ///
263    /// For the iroh connection and its paths, use [`session`](Self::session).
264    #[must_use]
265    pub fn serving_link(&self) -> Option<ServingLink> {
266        let shared = self.inner.shared.upgrade()?;
267        let state = shared.state.lock().expect("poisoned");
268        let (link, entry) = self.serving(&state)?;
269        Some(ServingLink {
270            id: link,
271            kind: entry.kind(),
272            sample: entry.latest_sample.get(),
273        })
274    }
275
276    /// Returns the link serving the broadcast now: the pinned one, or the best route's.
277    fn serving<'a>(&self, state: &'a State) -> Option<(LinkId, &'a LinkEntry)> {
278        let link = match self.inner.pin {
279            Some(link) => link,
280            None => {
281                let source = self.inner.routes.lock().expect("poisoned").source()?;
282                state.link_for(source)?
283            }
284        };
285        Some((link, state.links.get(&link)?))
286    }
287
288    /// Waits until nothing serves the path.
289    ///
290    /// A pinned subscription never moves to another identity, and ends once
291    /// its own no longer serves the path. Cancellation safe.
292    pub async fn closed(&self) {
293        self.inner.ended.cancelled().await;
294    }
295}
296
297/// Follows `path` in `origin` and keeps `current` on what serves it, until nothing does.
298///
299/// moq moves between routes of one identity by itself, and hands out each
300/// identity that takes the path over. Once the broadcast ends, this asks the
301/// table again after [`REASK_PAUSE`], and ends if no route serves the path.
302/// With `identity` set, it follows only that identity.
303async fn follow(
304    path: Path,
305    origin: origin::Consumer,
306    identity: Option<Identity>,
307    current: watch::Sender<broadcast::Consumer>,
308    ended: CancellationToken,
309) {
310    let _ended = ended.drop_guard();
311    let mut following = origin.follow(&path, identity.clone()).ok();
312    loop {
313        let serving = current.borrow().clone();
314        let taken = async {
315            match following.as_mut() {
316                Some(following) => following.available().await,
317                None => std::future::pending().await,
318            }
319        };
320        tokio::select! {
321            taken = taken => match taken {
322                Ok(Some(next)) if !next.is_closed() => {
323                    debug!(%path, "another identity serves the path");
324                    current.send_replace(next);
325                    continue;
326                }
327                // The path went offline, or a takeover ended before it was
328                // read. moq hands out what serves the path next.
329                Ok(_) => continue,
330                Err(moq_net::Error::Closed) => return,
331                // A refusal: moq waits for the route to change.
332                Err(_) => continue,
333            },
334            _ = serving.closed() => {}
335        }
336        tokio::time::sleep(REASK_PAUSE).await;
337        match origin.request(&path, identity.clone()).await {
338            Ok(next) if !next.is_closed() => {
339                debug!(%path, "broadcast ended, a route still serves it");
340                current.send_replace(next);
341            }
342            _ => return,
343        }
344    }
345}
346
347/// Resolves the broadcast `ticket` names, for [`Node::subscribe_ticket`].
348pub(crate) async fn subscribe_ticket(
349    node: &Node,
350    ticket: &BroadcastTicket,
351) -> Result<Subscription, Error> {
352    let (peer, path) = (ticket.peer(), ticket.path());
353    // A no-op for a path the node's grant policy already covers.
354    let claim = node.claim_path(peer, path)?;
355    let subscription = node.subscribe(path.clone(), Reach::Both(peer)).await?;
356    Ok(subscription.holding(claim))
357}
358
359/// Returns the route table as direct sessions fill it, without media relays' routes.
360pub(crate) fn direct_view(table: &origin::Producer) -> origin::Consumer {
361    table.clone().with_link(Link::Upstream).consume()
362}
363
364/// Waits for a route to `path` that entered from a hop `from` accepts, and returns its identity.
365pub(crate) async fn announced_by(
366    view: &origin::Consumer,
367    path: &Path,
368    from: impl Fn(Hop) -> bool,
369) -> Result<Identity, moq_net::Error> {
370    let mut announced = routes_under(view, path)?;
371    while let Some(event) = announced.next().await {
372        if event.announce.prefix == *path
373            && let Some(announce) = live_route(&event)
374            && Hop::of_route(Source::of(&announce.route)).is_some_and(&from)
375        {
376            return Ok(announce.route.identity().clone());
377        }
378    }
379    Err(moq_net::Error::Closed)
380}
381
382/// Returns the route an event leaves covering the prefix, or `None` once no route does.
383fn live_route(event: &RouteEvent) -> Option<&moq_net::announce::Announce> {
384    match event.kind {
385        RouteKind::Start | RouteKind::Update | RouteKind::Restart => Some(&event.announce),
386        RouteKind::End | RouteKind::Offline => None,
387        kind => {
388            debug!(?kind, prefix = %event.announce.prefix, "unknown route kind, read as ended");
389            None
390        }
391    }
392}
393
394/// Resolves `path` in the route table, for [`Node::subscribe`](crate::Node::subscribe).
395pub(crate) async fn subscribe(
396    node: &Node,
397    path: Path,
398    reach: Reach,
399) -> Result<Subscription, Error> {
400    check_path(&path)?;
401    if node.shared.shutdown.is_cancelled() {
402        return Err(e!(Error::ShutDown));
403    }
404    let table = node.shared.table.consume();
405    // A route the table already knows answers at once.
406    if let Ok(broadcast) = table.request(&path, None).await {
407        debug!(%path, "resolved through an existing route");
408        return Ok(subscription(&node.shared, path, table, broadcast));
409    }
410
411    let (dial, relays) = match reach {
412        Reach::Direct(peer) => (Some(peer), false),
413        Reach::Relays => (None, true),
414        Reach::Both(peer) => (Some(peer), true),
415    };
416    let relays = relays && node.shared.state.lock().expect("poisoned").has_relays();
417    // This node's own publications are in the table already.
418    let Some(peer) = dial.filter(|peer| *peer != node.shared.id) else {
419        if !relays {
420            return Err(e!(Error::NoRoute { path }));
421        }
422        debug!(%path, "waiting for a relay to route the path");
423        let resolved = routed(&table, &path).await;
424        return outcome(&node.shared, path, table, resolved);
425    };
426
427    debug!(%path, peer = %peer.fmt_short(), relays, "dialing the publisher");
428    let routed = {
429        let (table, path) = (table.clone(), path.clone());
430        async move { routed(&table, &path).await }
431    };
432    tokio::pin!(routed);
433    let connected = tokio::select! {
434        resolved = &mut routed => return outcome(&node.shared, path, table, resolved),
435        connected = node.connect(peer) => connected,
436    };
437    match connected {
438        // The peer's announcement of the path would never enter the table.
439        Ok(session) if !session.grant().allows_publish(path.as_str()) => {
440            if !relays {
441                return Err(Error::not_granted(path, peer, &session.grant()));
442            }
443            info!(%path, "the publisher may not publish the path here, waiting for a relay");
444        }
445        Ok(session) => {
446            // The session ending is the end of the wait unless a relay can
447            // still bring the path.
448            tokio::select! {
449                resolved = &mut routed => return outcome(&node.shared, path, table, resolved),
450                _ = session.closed() => {}
451            }
452            if !relays {
453                return Err(e!(Error::NotAnnounced { path }));
454            }
455        }
456        Err(err) if relays => {
457            info!(%path, error = %err, "publisher unreachable, waiting for a relay")
458        }
459        Err(err) => return Err(err),
460    }
461    let resolved = routed.await;
462    outcome(&node.shared, path, table, resolved)
463}
464
465/// Waits until a route serves `path`, and resolves it.
466pub(crate) async fn routed(
467    table: &origin::Consumer,
468    path: &Path,
469) -> Result<broadcast::Consumer, moq_net::Error> {
470    table
471        .follow(path, None)?
472        .available()
473        .await?
474        .ok_or(moq_net::Error::Closed)
475}
476
477/// Returns the subscription `resolved` makes, or why there is none.
478fn outcome(
479    shared: &Arc<Shared>,
480    path: Path,
481    table: origin::Consumer,
482    resolved: Result<broadcast::Consumer, moq_net::Error>,
483) -> Result<Subscription, Error> {
484    match resolved {
485        Ok(broadcast) => Ok(subscription(shared, path, table, broadcast)),
486        Err(moq_net::Error::Closed) => Err(e!(Error::ShutDown)),
487        Err(source) => Err(e!(Error::Unresolved { path, source })),
488    }
489}
490
491/// Returns a subscription to `path` that follows the route table.
492fn subscription(
493    shared: &Arc<Shared>,
494    path: Path,
495    table: origin::Consumer,
496    broadcast: broadcast::Consumer,
497) -> Subscription {
498    Subscription::new(path, table, broadcast, None, Arc::downgrade(shared))
499}
500
501#[cfg(test)]
502mod tests {
503    use moq_net::origin::RouteOptions;
504
505    use super::*;
506
507    const TIMEOUT: Duration = Duration::from_secs(5);
508
509    /// A follow task over a local route table, and the broadcast it keeps current.
510    struct Followed {
511        current: watch::Sender<broadcast::Consumer>,
512        ended: CancellationToken,
513        _task: AbortOnDropHandle<()>,
514    }
515
516    impl Followed {
517        /// Resolves `path` in `table` and follows it, pinned to `identity` if given.
518        async fn start(table: &origin::Producer, path: &str, identity: Option<Identity>) -> Self {
519            let path = Path::new(path).expect("a path");
520            let consumer = table.consume();
521            let broadcast =
522                tokio::time::timeout(TIMEOUT, consumer.request(&path, identity.clone()))
523                    .await
524                    .expect("resolved in time")
525                    .expect("a route serves the path");
526            let current = watch::Sender::new(broadcast);
527            let ended = CancellationToken::new();
528            let task = tokio::spawn(follow(
529                path,
530                consumer,
531                identity,
532                current.clone(),
533                ended.clone(),
534            ));
535            Self {
536                current,
537                ended,
538                _task: AbortOnDropHandle::new(task),
539            }
540        }
541
542        /// Returns the identity of the broadcast the follow task keeps current.
543        fn identity(&self) -> Option<Identity> {
544            self.current.borrow().info().identity.clone()
545        }
546
547        /// Waits until the current broadcast is one of `identity`.
548        async fn moves_to(&self, identity: &Identity) {
549            tokio::time::timeout(TIMEOUT, async {
550                while self.identity().as_ref() != Some(identity) {
551                    tokio::time::sleep(Duration::from_millis(10)).await;
552                }
553            })
554            .await
555            .expect("the subscription moved in time");
556        }
557
558        /// Waits until the follow task reports that nothing serves the path.
559        async fn ends(&self) {
560            tokio::time::timeout(TIMEOUT, self.ended.cancelled())
561                .await
562                .expect("the subscription ended in time");
563        }
564    }
565
566    /// Publishes a broadcast at `path` with `cost`, until the route drops.
567    fn route(table: &origin::Producer, path: &str, cost: u64) -> origin::Route {
568        table
569            .route(path, RouteOptions::default().with_cost(cost))
570            .expect("a route")
571    }
572
573    #[tokio::test]
574    async fn a_cheaper_instance_taking_over_moves_the_subscription() {
575        let table = moq_tokio::origin::spawn();
576        let first = route(&table, "cam", 5);
577        let followed = Followed::start(&table, "cam", None).await;
578        assert_eq!(followed.identity(), Some(first.identity()));
579
580        let second = route(&table, "cam", 1);
581        followed.moves_to(&second.identity()).await;
582        assert!(!followed.ended.is_cancelled());
583    }
584
585    #[tokio::test]
586    async fn an_ending_instance_hands_over_to_one_that_remains() {
587        let table = moq_tokio::origin::spawn();
588        let first = route(&table, "cam", 1);
589        let second = route(&table, "cam", 5);
590        let followed = Followed::start(&table, "cam", None).await;
591        assert_eq!(followed.identity(), Some(first.identity()));
592
593        drop(first);
594        followed.moves_to(&second.identity()).await;
595        assert!(!followed.ended.is_cancelled());
596    }
597
598    #[tokio::test]
599    async fn a_successor_that_routes_just_after_the_end_takes_over() {
600        let table = moq_tokio::origin::spawn();
601        let first = route(&table, "cam", 1);
602        let followed = Followed::start(&table, "cam", None).await;
603        // Long enough that the end is not a quick one.
604        tokio::time::sleep(Duration::from_millis(1100)).await;
605
606        drop(first);
607        tokio::time::sleep(REASK_PAUSE / 4).await;
608        let second = route(&table, "cam", 1);
609        followed.moves_to(&second.identity()).await;
610        assert!(!followed.ended.is_cancelled());
611    }
612
613    #[tokio::test]
614    async fn the_subscription_ends_once_nothing_serves_the_path() {
615        let table = moq_tokio::origin::spawn();
616        let only = route(&table, "cam", 1);
617        let followed = Followed::start(&table, "cam", None).await;
618
619        drop(only);
620        followed.ends().await;
621    }
622
623    #[tokio::test]
624    async fn a_pinned_subscription_never_moves_to_another_instance() {
625        let table = moq_tokio::origin::spawn();
626        let first = route(&table, "cam", 5);
627        let followed = Followed::start(&table, "cam", Some(first.identity())).await;
628
629        let _second = route(&table, "cam", 1);
630        tokio::time::sleep(Duration::from_millis(200)).await;
631        assert_eq!(followed.identity(), Some(first.identity()));
632        drop(first);
633        followed.ends().await;
634    }
635
636    #[tokio::test]
637    async fn a_pinned_subscription_stays_while_its_instance_serves() {
638        let table = moq_tokio::origin::spawn();
639        let first = route(&table, "cam", 1);
640        let followed = Followed::start(&table, "cam", Some(first.identity())).await;
641
642        let other = route(&table, "other", 1);
643        tokio::time::sleep(Duration::from_millis(200)).await;
644        assert!(!followed.ended.is_cancelled());
645        drop((first, other));
646        followed.ends().await;
647    }
648}