Skip to main content

iroh_live_relay/
pull.rs

1//! Pull mode: serving a broadcast ticket's broadcast from the media relay.
2//!
3//! The media relay's [`Node`] uses the cluster origin as its route table. When a
4//! session names a valid [`BroadcastTicket`], the node subscribes to the
5//! ticket's broadcast, and the publisher's session announces it straight into
6//! the cluster at its own path. The node's base grant is nothing, and each
7//! pull holds a [`PathClaim`] that lets the publisher announce the pulled path
8//! and the paths beneath it, so its other broadcasts stay out. The media relay pulls only a path
9//! the ticket's peer owns: its canonical `live/<peer>/<name>` path, or a room
10//! path with the peer as member. Anything else is refused with
11//! [`NotOwner`](iroh_live_node::Error::NotOwner). A session that named the
12//! ticket reads it under the name it asked for through [`mounted`].
13//!
14//! A pull retires once no local session that named the ticket has held its
15//! [`PullGuard`] for the linger window. Its path then leaves the publisher's
16//! grant, which takes the broadcast out of the cluster, and when the last pull
17//! of a publisher retires, the media relay closes its session with that publisher.
18//! An idle timer on the connection cannot stand in for the guards, since
19//! iroh's keep-alives move its counters too.
20//!
21//! Every pull dials an iroh endpoint the session chose, so admission into
22//! pulls is bounded. [`Access`] says which sessions may pull at all: by
23//! default only one whose token grants reading the ticket's path. [`Limits`]
24//! caps the pulls the media relay holds at once, the pulls one [`Client`] holds, and
25//! how fast one client starts new dials. A session names one broadcast in its
26//! path, so it holds at most one pull.
27//!
28//! [`run`](crate::run) sets this up. The module is public for a binary that
29//! embeds the media relay, and for the tests.
30
31use std::{
32    collections::HashMap,
33    net::IpAddr,
34    sync::{Arc, Mutex},
35    time::Duration,
36};
37
38use iroh::EndpointId;
39use iroh_live_node::{
40    BroadcastTicket, Grant, Node, NodeConfig, PathClaim, Subscription, layout::LiveLayout, policy,
41};
42use iroh_live_rooms::RoomsLayout;
43use moq_relay::cluster::Cluster;
44use n0_error::e;
45use n0_watcher::Watcher;
46use tokio::{sync::watch, task::JoinSet, time::Instant};
47use tracing::{debug, info, warn};
48
49use crate::Error;
50
51/// Default for [`Pulls::with_linger`].
52const DEFAULT_LINGER: Duration = Duration::from_secs(10);
53
54/// How long to wait for the publisher's broadcast to resolve.
55const SUBSCRIBE_TIMEOUT: Duration = Duration::from_secs(15);
56
57/// The first wait before resolving a broadcast again after it ended.
58///
59/// Doubles per failure, up to [`RESOLVE_BACKOFF_MAX`].
60const RESOLVE_BACKOFF: Duration = Duration::from_millis(500);
61
62/// The longest wait between attempts to resolve a broadcast again.
63const RESOLVE_BACKOFF_MAX: Duration = Duration::from_secs(8);
64
65/// How many times in a row resolving again may fail before the pull retires.
66const MAX_RESOLVES: u32 = 5;
67
68/// Which sessions may pull the ticket they name.
69///
70/// [`admit`](crate::admit) and [`IrohSessions`](crate::IrohSessions) check it
71/// before they start a pull. [`Pulls::pull`] and [`Pulls::start`] do not.
72#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
73pub enum Access {
74    /// Only a session whose token grants reading the ticket's path.
75    ///
76    /// The media relay verifies the token as it does for the session itself, but at
77    /// the path of the ticket's broadcast. Without `--auth-key` no token
78    /// verifies, so nobody pulls.
79    #[default]
80    Authorized,
81    /// Any session, with or without a token.
82    ///
83    /// Anyone who reaches the media relay can then make it dial any iroh endpoint,
84    /// within the [`Limits`]. Use it for local and development media relays, never
85    /// for a public one.
86    Open,
87}
88
89/// Bounds on the pulls a media relay holds and starts.
90///
91/// `#[non_exhaustive]`, so start from [`Limits::default`] and set the fields.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93#[non_exhaustive]
94pub struct Limits {
95    /// The most pulls, dialing, live or lingering, the media relay holds at once.
96    ///
97    /// Defaults to 256.
98    pub total: usize,
99    /// The most pulls one [`Client`] holds at once, over all its sessions.
100    ///
101    /// Defaults to 16.
102    pub per_client: usize,
103    /// How many new dials one [`Client`] may start in a burst.
104    ///
105    /// Joining a pull that is already dialing or live starts no dial.
106    /// Defaults to 8.
107    pub dial_burst: u32,
108    /// How long a [`Client`] waits to earn one more dial, up to [`dial_burst`](Self::dial_burst).
109    ///
110    /// Defaults to five seconds.
111    pub dial_interval: Duration,
112}
113
114impl Default for Limits {
115    fn default() -> Self {
116        Self {
117            total: 256,
118            per_client: 16,
119            dial_burst: 8,
120            dial_interval: Duration::from_secs(5),
121        }
122    }
123}
124
125/// Who asks for a pull, as the per-client [`Limits`] count it.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
127#[non_exhaustive]
128pub enum Client {
129    /// A browser, by its IP address.
130    Addr(IpAddr),
131    /// An iroh client, by its endpoint id.
132    ///
133    /// Endpoint ids cost nothing to make, so the global
134    /// [`total`](Limits::total) is what bounds a client that makes many.
135    Peer(EndpointId),
136    /// A session whose transport reports no address. All of them share one budget.
137    Unknown,
138}
139
140impl Client {
141    /// Returns the client at `addr`, with an IPv4-mapped IPv6 address folded to IPv4.
142    #[must_use]
143    pub fn from_addr(addr: Option<std::net::SocketAddr>) -> Self {
144        addr.map_or(Self::Unknown, |addr| Self::Addr(addr.ip().to_canonical()))
145    }
146}
147
148/// What one client holds and may still start.
149#[derive(Debug)]
150struct Budget {
151    /// How many [`PullGuard`]s the client holds.
152    holds: usize,
153    /// How many dials the client may start now.
154    dials: u32,
155    /// When `dials` was last topped up.
156    since: Instant,
157}
158
159impl Budget {
160    /// Returns the budget of a client that has started nothing yet.
161    fn full(limits: &Limits, now: Instant) -> Self {
162        Self {
163            holds: 0,
164            dials: limits.dial_burst,
165            since: now,
166        }
167    }
168
169    /// Adds the dials earned since the last top-up, up to the burst.
170    fn refill(&mut self, limits: &Limits, now: Instant) {
171        let interval = limits.dial_interval.max(Duration::from_millis(1));
172        let earned = now.saturating_duration_since(self.since).as_nanos() / interval.as_nanos();
173        let missing = limits.dial_burst.saturating_sub(self.dials);
174        match u32::try_from(earned) {
175            Ok(earned) if earned < missing => {
176                self.dials += earned;
177                // Keeps the part of an interval already waited.
178                self.since = interval
179                    .checked_mul(earned)
180                    .and_then(|spent| self.since.checked_add(spent))
181                    .unwrap_or(now);
182            }
183            _ => {
184                self.dials = limits.dial_burst;
185                self.since = now;
186            }
187        }
188    }
189
190    /// Takes one dial, if the client has one left.
191    fn take_dial(&mut self, limits: &Limits, now: Instant) -> bool {
192        self.refill(limits, now);
193        let Some(left) = self.dials.checked_sub(1) else {
194            return false;
195        };
196        self.dials = left;
197        true
198    }
199
200    /// Returns whether forgetting this budget changes nothing: no holds and every dial back.
201    fn is_idle(&mut self, limits: &Limits, now: Instant) -> bool {
202        self.refill(limits, now);
203        self.holds == 0 && self.dials >= limits.dial_burst
204    }
205}
206
207/// The budgets of the clients that hold a pull or started one recently.
208type Clients = Arc<Mutex<HashMap<Client, Budget>>>;
209
210/// How many budgets the media relay keeps before it forgets the idle ones.
211const CLIENTS_KEPT: usize = 1024;
212
213/// Returns the layout whose paths a pull may claim: `live/` and room paths.
214fn pull_layout() -> (LiveLayout, RoomsLayout) {
215    (LiveLayout::default(), RoomsLayout)
216}
217
218/// Returns `cluster` with `requested` reading the broadcast its ticket names.
219///
220/// Hand it to the session that named the ticket, which then finds the pulled
221/// broadcast at `requested`. `None` if `requested` is no ticket, or the origin
222/// refuses the mount.
223#[must_use]
224pub fn mounted(cluster: &Cluster, requested: &str) -> Option<Cluster> {
225    let ticket = requested.parse::<BroadcastTicket>().ok()?;
226    match cluster.origin.mount(requested, ticket.path()) {
227        Ok(origin) => {
228            let mut cluster = cluster.clone();
229            cluster.origin = origin;
230            Some(cluster)
231        }
232        Err(err) => {
233            warn!(%requested, error = %err, "cannot mount the ticket's broadcast");
234            None
235        }
236    }
237}
238
239/// The media relay's pulls, shared by every session that names a ticket.
240///
241/// Cheap to clone. Each pull runs in a task that the clones own together, so
242/// dropping the last clone ends every pull.
243///
244/// # Examples
245///
246/// ```no_run
247/// # async fn run(
248/// #     endpoint: iroh::Endpoint,
249/// #     cluster: moq_relay::cluster::Cluster,
250/// #     requested: &str,
251/// # ) -> Result<(), iroh_live_relay::Error> {
252/// use iroh_live_node::BroadcastTicket;
253/// use iroh_live_relay::pull::{Client, Pulls, mounted};
254///
255/// let pulls = Pulls::new(endpoint, cluster.clone());
256/// if let Ok(ticket) = requested.parse::<BroadcastTicket>() {
257///     // Hold the guard while the session that asked runs.
258///     let _guard = pulls.pull(Client::Unknown, requested, &ticket).await?;
259///     let _view = mounted(&cluster, requested);
260/// }
261/// # Ok(())
262/// # }
263/// ```
264#[derive(Clone, derive_more::Debug)]
265pub struct Pulls {
266    shared: Shared,
267    /// Which sessions may pull, checked by the admissions.
268    access: Access,
269    /// The task of each pull: its dial, and then its hold.
270    #[debug(skip)]
271    tasks: Arc<Mutex<JoinSet<()>>>,
272}
273
274/// What the pull tasks share: all of [`Pulls`] but its tasks.
275///
276/// A task holds this, so it never keeps its own set alive.
277#[derive(Clone, derive_more::Debug)]
278struct Shared {
279    /// The node that dials publishers.
280    node: Node,
281    /// How long a pull without sessions stays connected.
282    linger: Duration,
283    /// Live or dialing pulls, by local broadcast name.
284    ///
285    /// Claims and retirements happen under this lock, so an entry found here
286    /// is still open.
287    pulls: Arc<Mutex<HashMap<String, Arc<Pull>>>>,
288    /// How many pulls, live or dialing, each publisher has.
289    publishers: Publishers,
290    /// The bounds on pulls.
291    limits: Limits,
292    /// What each client holds and may still start.
293    ///
294    /// Taken after `pulls` when both are held.
295    clients: Clients,
296}
297
298/// How far a pull's dial has got.
299#[derive(Debug, Clone)]
300enum Dial {
301    /// Still in flight. Every caller for this ticket waits on it.
302    Pending,
303    /// The session is up and the publisher announced the broadcast.
304    Connected,
305    /// The dial failed. Every waiter gets a copy of the error.
306    Failed(Arc<Error>),
307}
308
309/// One pulled ticket.
310#[derive(Debug)]
311struct Pull {
312    /// The outcome of the dial.
313    dial: watch::Sender<Dial>,
314    /// How many local sessions that named this ticket hold a guard on it.
315    holders: watch::Sender<usize>,
316}
317
318impl Pull {
319    /// Creates a pull whose dial is pending and that no session holds.
320    fn new() -> Self {
321        Self {
322            dial: watch::Sender::new(Dial::Pending),
323            holders: watch::Sender::new(0),
324        }
325    }
326
327    /// Returns whether a local session that named this ticket still holds it.
328    fn is_held(&self) -> bool {
329        *self.holders.borrow() > 0
330    }
331}
332
333/// A hold on a pull, which keeps it alive while the session that asked for it runs.
334///
335/// Dropping it releases the session's hold on the pull, and the client's
336/// share of [`Limits::per_client`].
337#[derive(derive_more::Debug)]
338#[must_use = "dropping the guard releases the hold on the pull"]
339pub struct PullGuard {
340    pull: Arc<Pull>,
341    client: Client,
342    #[debug(skip)]
343    clients: Clients,
344    limits: Limits,
345}
346
347impl PullGuard {
348    /// Waits until the pull's dial connects, or returns its error.
349    ///
350    /// A guard from [`Pulls::start`] holds the pull from the start; this
351    /// only reports how its dial went. Every holder of one pull gets the same
352    /// outcome.
353    ///
354    /// # Errors
355    ///
356    /// Fails as [`Pulls::pull`] does once its limits passed.
357    pub async fn connected(&self) -> Result<(), Error> {
358        let mut dial = self.pull.dial.subscribe();
359        let outcome = dial
360            .wait_for(|dial| !matches!(dial, Dial::Pending))
361            .await
362            .map_or_else(
363                // The dialing task holds a sender until it reports.
364                |_| Dial::Failed(Arc::new(e!(Error::Dropped))),
365                |dial| dial.clone(),
366            );
367        match outcome {
368            Dial::Failed(err) => Err(Error::clone(&err)),
369            Dial::Pending | Dial::Connected => Ok(()),
370        }
371    }
372}
373
374impl Drop for PullGuard {
375    fn drop(&mut self) {
376        self.pull.holders.send_modify(|holders| *holders -= 1);
377        let mut clients = self.clients.lock().expect("poisoned");
378        if let Some(budget) = clients.get_mut(&self.client) {
379            budget.holds -= 1;
380            if budget.is_idle(&self.limits, Instant::now()) {
381                clients.remove(&self.client);
382            }
383        }
384    }
385}
386
387impl Pulls {
388    /// Creates the pulls of a media relay, which dial over `endpoint` into `cluster`.
389    ///
390    /// # Panics
391    ///
392    /// Panics when called outside a Tokio runtime.
393    #[must_use]
394    pub fn new(endpoint: iroh::Endpoint, cluster: Cluster) -> Self {
395        let config = NodeConfig::default()
396            .with_policy(policy::Open(Grant::nothing()))
397            .with_table(cluster.origin.clone())
398            .with_layout(pull_layout());
399        Self {
400            shared: Shared {
401                node: Node::new(endpoint, config),
402                linger: DEFAULT_LINGER,
403                pulls: Arc::new(Mutex::new(HashMap::new())),
404                publishers: Arc::new(Mutex::new(HashMap::new())),
405                limits: Limits::default(),
406                clients: Arc::new(Mutex::new(HashMap::new())),
407            },
408            access: Access::default(),
409            tasks: Arc::new(Mutex::new(JoinSet::new())),
410        }
411    }
412
413    /// Sets which sessions may pull, which defaults to [`Access::Authorized`].
414    #[must_use]
415    pub fn with_access(mut self, access: Access) -> Self {
416        self.access = access;
417        self
418    }
419
420    /// Returns which sessions may pull.
421    #[must_use]
422    pub fn access(&self) -> Access {
423        self.access
424    }
425
426    /// Sets the bounds on pulls, which default to [`Limits::default`].
427    #[must_use]
428    pub fn with_limits(mut self, limits: Limits) -> Self {
429        self.shared.limits = limits;
430        self
431    }
432
433    /// Sets how long an unused pull stays connected.
434    ///
435    /// Defaults to ten seconds, long enough for a page reload to reuse the
436    /// connection.
437    #[must_use]
438    pub fn with_linger(mut self, linger: Duration) -> Self {
439        self.shared.linger = linger;
440        self
441    }
442
443    /// Pulls the broadcast `ticket` names into the cluster, and waits for it to connect.
444    ///
445    /// The pull is for a session of `client` that asked for `requested`.
446    /// Hold the returned [`PullGuard`] while that session runs, and serve it
447    /// the cluster [`mounted`] at `requested`. Concurrent pulls of one name
448    /// share a dial. It does not check [`Access`].
449    ///
450    /// Cancellation safe: dropping this future only drops the caller's hold.
451    /// The dial runs on, and the pull retires as usual.
452    ///
453    /// # Errors
454    ///
455    /// Fails as [`start`](Self::start) does, then with [`Error::Claim`] if
456    /// the ticket's peer does not own its path, [`Error::Connect`] or
457    /// [`Error::Subscribe`] if the publisher cannot be reached or refuses the
458    /// path, and [`Error::Timeout`] if it does not announce the broadcast
459    /// within 15 seconds.
460    pub async fn pull(
461        &self,
462        client: Client,
463        requested: &str,
464        ticket: &BroadcastTicket,
465    ) -> Result<PullGuard, Error> {
466        let guard = self.start(client, requested, ticket)?;
467        guard.connected().await?;
468        Ok(guard)
469    }
470
471    /// Starts pulling the broadcast `ticket` names, or joins the pull of `requested`.
472    ///
473    /// Returns at once with the hold, before the dial connects: await
474    /// [`PullGuard::connected`] for its outcome. The [`Limits`] are checked
475    /// here, so a session that exceeds them can be refused before it starts.
476    /// It does not check [`Access`].
477    ///
478    /// # Errors
479    ///
480    /// Fails with [`Error::ClientPullLimit`] if `client` already holds
481    /// [`Limits::per_client`] pulls. A new dial also fails with
482    /// [`Error::PullLimit`] if the media relay holds [`Limits::total`] pulls, and
483    /// with [`Error::DialRateLimit`] if `client` has used up its dials.
484    pub fn start(
485        &self,
486        client: Client,
487        requested: &str,
488        ticket: &BroadcastTicket,
489    ) -> Result<PullGuard, Error> {
490        // Keyed by the name the client asked for, as its mount is. Two
491        // spellings of one ticket share the publisher's session, but are
492        // held apart.
493        let local_name = requested.to_owned();
494        let limits = self.shared.limits;
495
496        // Held under the lock retirement takes, so an entry found here
497        // outlives this call.
498        let (pull, dial) = {
499            let mut pulls = self.shared.pulls.lock().expect("poisoned");
500            let mut clients = self.shared.clients.lock().expect("poisoned");
501            let now = Instant::now();
502            if clients.len() >= CLIENTS_KEPT {
503                clients.retain(|_, budget| !budget.is_idle(&limits, now));
504            }
505            let budget = clients
506                .entry(client)
507                .or_insert_with(|| Budget::full(&limits, now));
508            if budget.holds >= limits.per_client {
509                return Err(e!(Error::ClientPullLimit {
510                    limit: limits.per_client
511                }));
512            }
513            let (pull, dial) = match pulls.get(&local_name) {
514                Some(pull) => (Arc::clone(pull), false),
515                None => {
516                    if pulls.len() >= limits.total {
517                        return Err(e!(Error::PullLimit {
518                            limit: limits.total
519                        }));
520                    }
521                    if !budget.take_dial(&limits, now) {
522                        return Err(e!(Error::DialRateLimit));
523                    }
524                    let pull = Arc::new(Pull::new());
525                    pulls.insert(local_name.clone(), Arc::clone(&pull));
526                    (pull, true)
527                }
528            };
529            budget.holds += 1;
530            pull.holders.send_modify(|holders| *holders += 1);
531            (pull, dial)
532        };
533        let guard = PullGuard {
534            pull,
535            client,
536            clients: Arc::clone(&self.shared.clients),
537            limits,
538        };
539
540        if dial {
541            let shared = self.shared.clone();
542            let ticket = ticket.clone();
543            let name = local_name;
544            let pull = Arc::clone(&guard.pull);
545            self.spawn(async move {
546                match shared.establish(&ticket, &name).await {
547                    Ok((subscription, publisher)) => {
548                        pull.dial.send_replace(Dial::Connected);
549                        shared
550                            .hold(ticket, name, pull, subscription, publisher)
551                            .await;
552                    }
553                    Err(err) => {
554                        // Retire it, so the next pull dials again.
555                        warn!(local_name = %name, error = %err, "pull dial failed");
556                        shared.retire(&name, &pull);
557                        pull.dial.send_replace(Dial::Failed(Arc::new(err)));
558                    }
559                }
560            });
561        } else {
562            debug!(%local_name, "joining an existing pull");
563        }
564        Ok(guard)
565    }
566
567    /// Spawns a pull task into the set, and drops the tasks that finished.
568    fn spawn(&self, task: impl Future<Output = ()> + Send + 'static) {
569        let mut tasks = self.tasks.lock().expect("poisoned");
570        while let Some(finished) = tasks.try_join_next() {
571            if let Err(err) = finished
572                && err.is_panic()
573            {
574                warn!(error = %err, "a pull task panicked");
575            }
576        }
577        tasks.spawn(task);
578    }
579}
580
581impl Shared {
582    /// Resolves the ticket's broadcast, and returns it with the publisher's claim.
583    async fn establish(
584        &self,
585        ticket: &BroadcastTicket,
586        local_name: &str,
587    ) -> Result<(Subscription, PublisherClaim), Error> {
588        info!(
589            peer = %ticket.peer().fmt_short(),
590            path = %ticket.path(),
591            "pulling remote broadcast"
592        );
593        // Held for the whole of the pull, dial included: it grants the
594        // publisher its path, and a retiring pull cannot close the session
595        // this one is about to use.
596        let publisher = PublisherClaim::new(self, ticket)?;
597        let subscription = self.resolve(ticket).await?;
598        info!(
599            %local_name,
600            peer = %ticket.peer().fmt_short(),
601            path = %subscription.path(),
602            "remote broadcast available in the cluster"
603        );
604        Ok((subscription, publisher))
605    }
606
607    /// Waits for the publisher to announce the ticket's broadcast into the cluster.
608    ///
609    /// The caller's [`PublisherClaim`] already lets the publisher announce
610    /// the path, so a session dialed now is authorized for it before its
611    /// handshake. The path resolves through that session, so no other peer
612    /// can stand in for the publisher.
613    async fn resolve(&self, ticket: &BroadcastTicket) -> Result<Subscription, Error> {
614        // A publisher that never announces the path to us would keep the
615        // subscription waiting forever.
616        tokio::time::timeout(SUBSCRIBE_TIMEOUT, async {
617            let session = self.node.connect(ticket.peer()).await.map_err(|source| {
618                e!(Error::Connect {
619                    peer: ticket.peer(),
620                    source: Box::new(source)
621                })
622            })?;
623            session.subscribe(ticket.path()).await.map_err(|source| {
624                e!(Error::Subscribe {
625                    path: ticket.path().clone(),
626                    source: Box::new(source)
627                })
628            })
629        })
630        .await
631        .map_err(|_| {
632            e!(Error::Timeout {
633                path: ticket.path().clone(),
634                timeout: SUBSCRIBE_TIMEOUT
635            })
636        })?
637    }
638
639    /// Holds the session with the publisher until nothing wants the pull.
640    ///
641    /// When no route serves the publisher's broadcast any more while sessions
642    /// still want it, the pull resolves it again, which redials. The pull
643    /// retires once nobody wants it, or once resolving fails [`MAX_RESOLVES`]
644    /// times in a row.
645    async fn hold(
646        &self,
647        ticket: BroadcastTicket,
648        local_name: String,
649        pull: Arc<Pull>,
650        mut current: Subscription,
651        publisher: PublisherClaim,
652    ) {
653        loop {
654            let broadcast_ended = tokio::select! {
655                () = current.closed() => {
656                    info!(%local_name, "nothing serves the pulled broadcast any more");
657                    true
658                }
659                () = self.wait_idle(&local_name, &pull) => {
660                    info!(%local_name, "pull went idle, retiring it");
661                    false
662                }
663            };
664            if !broadcast_ended {
665                break;
666            }
667            if !pull.is_held() {
668                self.retire(&local_name, &pull);
669                break;
670            }
671            match self.resolve_again(&ticket, &local_name).await {
672                Some(next) => current = next,
673                None => {
674                    self.retire(&local_name, &pull);
675                    break;
676                }
677            }
678        }
679        // Closes the publisher's session if this was its last pull.
680        drop(publisher);
681    }
682
683    /// Resolves the ticket's broadcast again, backing off between attempts.
684    ///
685    /// Does not look at the pull's holders. A pull that loses its last session
686    /// while this runs still tries [`MAX_RESOLVES`] times, about 90 seconds at
687    /// worst, and redials the publisher for nobody.
688    async fn resolve_again(
689        &self,
690        ticket: &BroadcastTicket,
691        local_name: &str,
692    ) -> Option<Subscription> {
693        let mut backoff = RESOLVE_BACKOFF;
694        for attempt in 1..=MAX_RESOLVES {
695            tokio::time::sleep(backoff).await;
696            match self.resolve(ticket).await {
697                Ok(next) => return Some(next),
698                Err(err) => {
699                    warn!(%local_name, attempt, error = %err, "could not resolve the pull again");
700                    backoff = (backoff * 2).min(RESOLVE_BACKOFF_MAX);
701                }
702            }
703        }
704        None
705    }
706
707    /// Waits until no session has held the pull for the linger window.
708    ///
709    /// The final check runs under the lock that [`Pulls::pull`] takes a hold
710    /// under, so a pull held during the linger keeps running.
711    async fn wait_idle(&self, local_name: &str, pull: &Arc<Pull>) {
712        loop {
713            if pull.is_held() {
714                let mut holders = pull.holders.subscribe();
715                // `Err` needs every sender gone, and this task holds `pull`.
716                let _ = holders.wait_for(|holders| *holders == 0).await;
717                continue;
718            }
719
720            // Quiet for now. Wait out the linger, then confirm under the lock.
721            tokio::time::sleep(self.linger).await;
722
723            let mut pulls = self.pulls.lock().expect("poisoned");
724            if pull.is_held() {
725                continue;
726            }
727            remove_current(&mut pulls, local_name, pull);
728            return;
729        }
730    }
731
732    /// Drops `pull` from the map, if it is still the entry for `local_name`.
733    ///
734    /// A retired pull may have been replaced by a fresh dial for the same name.
735    fn retire(&self, local_name: &str, pull: &Arc<Pull>) {
736        remove_current(&mut self.pulls.lock().expect("poisoned"), local_name, pull);
737    }
738}
739
740/// Removes the entry for `local_name` if it is `pull`.
741fn remove_current(pulls: &mut HashMap<String, Arc<Pull>>, local_name: &str, pull: &Arc<Pull>) {
742    if pulls
743        .get(local_name)
744        .is_some_and(|entry| Arc::ptr_eq(entry, pull))
745    {
746        pulls.remove(local_name);
747    }
748}
749
750/// How many pulls each publisher has.
751type Publishers = Arc<Mutex<HashMap<EndpointId, usize>>>;
752
753/// One pull's share in the session with a publisher, and the claim on its path.
754///
755/// Dropping it takes the path out of the cluster. Dropping the last share of
756/// a publisher closes every session the media relay's node has with it.
757struct PublisherClaim {
758    publisher: EndpointId,
759    /// The count this claim is part of, kept in [`Shared`].
760    publishers: Publishers,
761    node: Node,
762    /// Released after [`Drop::drop`] closes the session, as fields drop after it.
763    _path: PathClaim,
764}
765
766impl PublisherClaim {
767    /// Claims the ticket's path for its peer, if the peer owns it.
768    fn new(shared: &Shared, ticket: &BroadcastTicket) -> Result<Self, Error> {
769        let publisher = ticket.peer();
770        let path = shared
771            .node
772            .claim_path(publisher, ticket.path())
773            .map_err(|source| {
774                e!(Error::Claim {
775                    path: ticket.path().clone(),
776                    source: Box::new(source)
777                })
778            })?;
779        *shared
780            .publishers
781            .lock()
782            .expect("poisoned")
783            .entry(publisher)
784            .or_default() += 1;
785        Ok(Self {
786            publisher,
787            publishers: Arc::clone(&shared.publishers),
788            node: shared.node.clone(),
789            _path: path,
790        })
791    }
792}
793
794impl Drop for PublisherClaim {
795    fn drop(&mut self) {
796        // Decided and done under the lock a new claim takes, so a pull that
797        // starts now either counts before this and keeps the session, or
798        // counts after the close and dials anew.
799        let mut publishers = self.publishers.lock().expect("poisoned");
800        let Some(count) = publishers.get_mut(&self.publisher) else {
801            return;
802        };
803        *count -= 1;
804        if *count > 0 {
805            return;
806        }
807        publishers.remove(&self.publisher);
808        for session in self.node.sessions().get() {
809            if session.peer() == self.publisher {
810                info!(
811                    peer = %self.publisher.fmt_short(),
812                    "last pull of the publisher retired, closing its session"
813                );
814                session.close(moq_net::Error::Cancel);
815            }
816        }
817    }
818}
819
820#[cfg(test)]
821mod tests {
822    use iroh_live_node::layout::Layout;
823    use moq_net::Path;
824
825    use super::*;
826
827    /// Parses `path`, which must be valid.
828    fn path(path: &str) -> Path {
829        Path::new(path).expect("a path")
830    }
831
832    /// A client spends its burst, then earns one dial per interval, never more than the burst.
833    #[test]
834    fn a_budget_refills_one_dial_per_interval() {
835        let limits = Limits {
836            dial_burst: 2,
837            dial_interval: Duration::from_secs(10),
838            ..Limits::default()
839        };
840        let start = Instant::now();
841        let mut budget = Budget::full(&limits, start);
842        assert!(budget.take_dial(&limits, start));
843        assert!(budget.take_dial(&limits, start));
844        assert!(!budget.take_dial(&limits, start + Duration::from_secs(9)));
845        assert!(budget.take_dial(&limits, start + Duration::from_secs(10)));
846        assert!(!budget.take_dial(&limits, start + Duration::from_secs(15)));
847        // The five seconds already waited count towards the next dial.
848        assert!(budget.take_dial(&limits, start + Duration::from_secs(20)));
849        // A long wait refills to the burst, and no further.
850        let later = start + Duration::from_secs(3600);
851        assert!(budget.is_idle(&limits, later));
852        assert!(budget.take_dial(&limits, later));
853        assert!(budget.take_dial(&limits, later));
854        assert!(!budget.take_dial(&limits, later));
855    }
856
857    #[test]
858    fn owner_accepts_only_canonical_live_and_rooms_paths() {
859        let owner = |path: &Path| pull_layout().owner(path.as_str());
860        let peer = iroh::SecretKey::from_bytes(&[3; 32]).public();
861        let other = iroh::SecretKey::from_bytes(&[4; 32]).public();
862        assert_eq!(owner(&path(&format!("live/{peer}/cam"))), Some(peer));
863        assert_eq!(owner(&path(&format!("live/{peer}/cam/hd"))), Some(peer));
864        let topic = iroh_live_rooms::RoomTicket::generate().topic_id();
865        assert_eq!(
866            owner(&path(&format!("rooms/{peer}/{topic}/cam"))),
867            Some(peer)
868        );
869        assert_eq!(owner(&path(&format!("rooms/{peer}/{topic}"))), None);
870        assert_eq!(owner(&path(&format!("rooms/{peer}/topic/cam"))), None);
871        assert_eq!(owner(&path("fleet/robot/cam")), None);
872        assert_eq!(owner(&path(&format!("live/{peer}"))), None);
873        assert_eq!(owner(&path(&format!("other/{peer}/cam"))), None);
874        let base32 = data_encoding::BASE32_NOPAD
875            .encode(other.as_bytes())
876            .to_ascii_lowercase();
877        assert_eq!(owner(&path(&format!("live/{base32}/cam"))), None);
878    }
879}