Skip to main content

iroh_live_rooms/
members.rs

1//! Following one broadcast of every member, or of one: a task per member, the subscriptions to a member, and the value reader built on both.
2
3use std::{collections::HashMap, fmt, future::Future, time::Duration};
4
5use iroh::EndpointId;
6use iroh_live_node::{Subscription, json::Timed};
7use n0_future::task::AbortOnDropHandle;
8use n0_watcher::{Direct, Watcher};
9use serde::de::DeserializeOwned;
10use tokio::{sync::mpsc, time::Instant};
11use tracing::{debug, info};
12
13use crate::{Room, RoomState, room::WeakRoom};
14
15/// The first wait before subscribing to a member again, after a subscription that failed or ended early.
16const RETRY: Duration = Duration::from_secs(2);
17
18/// The longest wait before subscribing to a member again.
19///
20/// A subscription that served this long counts as one that worked, and the
21/// next starts at once.
22const RETRY_MAX: Duration = Duration::from_secs(16);
23
24/// How many member updates wait in [`MemberValues`].
25const VALUE_QUEUE: usize = 64;
26
27/// The wait before a member is subscribed to again.
28///
29/// A member that crashed stays listed until its lease runs out, minutes
30/// later, and a broadcast can close as soon as it opens, so the wait doubles
31/// with each subscription in a row that fails or ends early, from [`RETRY`]
32/// up to [`RETRY_MAX`]. One that served longer resets it.
33#[derive(Debug)]
34struct Retry {
35    wait: Duration,
36}
37
38impl Default for Retry {
39    fn default() -> Self {
40        Self { wait: RETRY }
41    }
42}
43
44impl Retry {
45    /// Returns the wait after a subscription that served from `since` until now, `None` to subscribe again at once.
46    fn served(&mut self, since: Instant) -> Option<Duration> {
47        if since.elapsed() >= RETRY_MAX {
48            self.wait = RETRY;
49            return None;
50        }
51        Some(self.failed())
52    }
53
54    /// Returns the wait after a subscription that failed, and doubles the next one.
55    fn failed(&mut self) -> Duration {
56        let wait = self.wait;
57        self.wait = (self.wait * 2).min(RETRY_MAX);
58        wait
59    }
60}
61
62impl Room {
63    /// Runs `task` for every member that publishes `name`, as the membership changes.
64    ///
65    /// Starts `task(member)` once a member lists `name`, and aborts it once
66    /// the member no longer does. A task that ends on its own is started
67    /// again only after the member lists `name` anew, so a task that should
68    /// outlast a closed broadcast retries itself, for example with
69    /// [`subscriptions`](Self::subscriptions). Runs until the room is left,
70    /// its last handle drops, or the returned handle drops. It holds no
71    /// handle of the room itself, so it does not keep the room joined.
72    ///
73    /// # Panics
74    ///
75    /// Panics when called outside a Tokio runtime.
76    ///
77    /// # Examples
78    ///
79    /// ```no_run
80    /// # fn run(room: iroh_live_rooms::Room) {
81    /// let _readers = room.for_each_member("cam", |member| async move {
82    ///     println!("{} publishes a camera", member.fmt_short());
83    /// });
84    /// # }
85    /// ```
86    #[must_use = "dropping the handle stops the tasks"]
87    pub fn for_each_member<F, Fut>(&self, name: &str, task: F) -> AbortOnDropHandle<()>
88    where
89        F: FnMut(EndpointId) -> Fut + Send + 'static,
90        Fut: Future<Output = ()> + Send + 'static,
91    {
92        let follow = follow(self.watchers(), name.to_owned(), task, |_| async {});
93        AbortOnDropHandle::new(tokio::spawn(follow))
94    }
95
96    /// Returns the subscriptions to member `peer`'s broadcast `name`, a new one after each end while the member lists it.
97    ///
98    /// The first [`next`](MemberSubscriptions::next) waits for the member to
99    /// list `name`, however long, so bound the wait if it may never do. Each
100    /// later one waits for the previous subscription to close, such as when
101    /// the member restarts its broadcast or the session with it fails, and
102    /// subscribes again. After a subscription that failed, or closed within
103    /// sixteen seconds, it waits first, from two seconds up to sixteen, since
104    /// a member that vanished stays listed for minutes.
105    ///
106    /// The subscriptions end once the member stops listing `name` after it
107    /// did, the room is left, or its last handle drops. They hold a handle
108    /// of the room only while they subscribe, so they do not keep the room
109    /// joined.
110    ///
111    /// # Examples
112    ///
113    /// ```no_run
114    /// # async fn run(room: iroh_live_rooms::Room, peer: iroh::EndpointId) {
115    /// let mut subscriptions = room.subscriptions(peer, "cam");
116    /// while let Some(subscription) = subscriptions.next().await {
117    ///     let _broadcast = subscription.broadcast();
118    ///     // Read the broadcast until it closes, then take the next one.
119    /// }
120    /// # }
121    /// ```
122    #[must_use]
123    pub fn subscriptions(&self, peer: EndpointId, name: &str) -> MemberSubscriptions {
124        let (state, left) = self.watchers();
125        MemberSubscriptions {
126            room: self.downgrade(),
127            peer,
128            name: name.to_owned(),
129            state,
130            left,
131            retry: Retry::default(),
132            listed: false,
133            current: None,
134        }
135    }
136
137    /// Reads track `track` of broadcast `name` from every member that publishes it.
138    ///
139    /// The counterpart of [`publish_value`](Self::publish_value): each member
140    /// reports its newest value, and `None` once it no longer lists `name`.
141    /// A member is read through [`subscriptions`](Self::subscriptions), so
142    /// one whose subscription ends while it still lists `name`, such as one
143    /// whose session failed, is read again. A value that does not decode is
144    /// skipped, and a member whose broadcast has no track `track` is not
145    /// read until it lists `name` anew. Dropping the returned
146    /// [`MemberValues`] stops every reader. The readers do not keep the room
147    /// joined.
148    ///
149    /// # Panics
150    ///
151    /// Panics when called outside a Tokio runtime.
152    ///
153    /// # Examples
154    ///
155    /// ```no_run
156    /// # async fn run(room: iroh_live_rooms::Room) {
157    /// let mut presence = room.read_values::<String>("presence", "status");
158    /// while let Some(update) = presence.recv().await {
159    ///     let member = update.member.fmt_short();
160    ///     match update.value {
161    ///         Some(status) => println!("{member}: {}", status.value),
162    ///         None => println!("{member} left"),
163    ///     }
164    /// }
165    /// # }
166    /// ```
167    pub fn read_values<T>(&self, name: &str, track: &str) -> MemberValues<T>
168    where
169        T: DeserializeOwned + Send + 'static,
170    {
171        let (tx, rx) = mpsc::channel(VALUE_QUEUE);
172        let read = {
173            let (room, name, track, tx) = (
174                self.downgrade(),
175                name.to_owned(),
176                track.to_owned(),
177                tx.clone(),
178            );
179            move |member| {
180                let subscriptions = room.upgrade().map(|room| room.subscriptions(member, &name));
181                read_member(subscriptions, member, track.clone(), tx.clone())
182            }
183        };
184        let stopped = move |member| {
185            let tx = tx.clone();
186            async move {
187                tx.send(MemberValue {
188                    member,
189                    value: None,
190                })
191                .await
192                .ok();
193            }
194        };
195        let task = tokio::spawn(follow(self.watchers(), name.to_owned(), read, stopped));
196        MemberValues {
197            rx,
198            _follow: AbortOnDropHandle::new(task),
199        }
200    }
201
202    /// Returns watchers of the room's state and of whether it was left.
203    ///
204    /// Both end once the room's last handle drops.
205    fn watchers(&self) -> (Direct<RoomState>, Direct<bool>) {
206        (self.state(), self.inner.done.watch())
207    }
208}
209
210/// The subscriptions to one member's broadcast, one after another, from [`Room::subscriptions`].
211pub struct MemberSubscriptions {
212    room: WeakRoom,
213    peer: EndpointId,
214    name: String,
215    state: Direct<RoomState>,
216    left: Direct<bool>,
217    retry: Retry,
218    /// Whether the member listed the name since these subscriptions began.
219    listed: bool,
220    /// The last subscription handed out, and when it was.
221    current: Option<(Subscription, Instant)>,
222}
223
224impl fmt::Debug for MemberSubscriptions {
225    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226        f.debug_struct("MemberSubscriptions")
227            .field("peer", &format_args!("{}", self.peer.fmt_short()))
228            .field("name", &self.name)
229            .field(
230                "current",
231                &self.current.as_ref().map(|(current, _)| current),
232            )
233            .finish_non_exhaustive()
234    }
235}
236
237impl MemberSubscriptions {
238    /// Waits for the previous subscription to close, and returns the next one.
239    ///
240    /// Returns `None` once the subscriptions end, as
241    /// [`Room::subscriptions`] describes. Not cancellation safe: a cancelled
242    /// call may drop a subscription it just made, and waits through the
243    /// previous one again.
244    pub async fn next(&mut self) -> Option<Subscription> {
245        if let Some((subscription, since)) = self.current.take() {
246            tokio::select! {
247                () = subscription.closed() => {}
248                () = unlisted(&mut self.state, &mut self.left, self.peer, &self.name) => return None,
249            }
250            if let Some(wait) = self.retry.served(since) {
251                debug!(peer = %self.peer.fmt_short(), name = %self.name, ?wait, "the subscription ended early, waiting");
252                if !self.sleep(wait).await {
253                    return None;
254                }
255            }
256        }
257        loop {
258            if !self.until_listed().await {
259                return None;
260            }
261            let room = self.room.upgrade()?;
262            let subscribed = tokio::select! {
263                subscribed = room.subscribe(self.peer, &self.name) => subscribed,
264                () = unlisted(&mut self.state, &mut self.left, self.peer, &self.name) => return None,
265            };
266            drop(room);
267            match subscribed {
268                Ok(subscription) => {
269                    self.current = Some((subscription.clone(), Instant::now()));
270                    return Some(subscription);
271                }
272                Err(err) => {
273                    let wait = self.retry.failed();
274                    debug!(peer = %self.peer.fmt_short(), name = %self.name, error = %err, ?wait, "subscribing failed, trying again");
275                    if !self.sleep(wait).await {
276                        return None;
277                    }
278                }
279            }
280        }
281    }
282
283    /// Waits until the member lists the name, and returns `false` once the subscriptions end instead.
284    async fn until_listed(&mut self) -> bool {
285        loop {
286            if self.left.get() {
287                return false;
288            }
289            if lists(&self.state.get(), self.peer, &self.name) {
290                self.listed = true;
291                return true;
292            }
293            if self.listed {
294                return false;
295            }
296            let changed = tokio::select! {
297                changed = self.state.updated() => changed.is_ok(),
298                changed = self.left.updated() => changed.is_ok(),
299            };
300            if !changed {
301                return false;
302            }
303        }
304    }
305
306    /// Sleeps for `wait`, and returns `false` if the subscriptions end first.
307    async fn sleep(&mut self, wait: Duration) -> bool {
308        tokio::select! {
309            () = tokio::time::sleep(wait) => true,
310            () = unlisted(&mut self.state, &mut self.left, self.peer, &self.name) => false,
311        }
312    }
313}
314
315/// Returns whether `state` lists broadcast `name` of member `peer`.
316fn lists(state: &RoomState, peer: EndpointId, name: &str) -> bool {
317    state
318        .members
319        .get(&peer)
320        .is_some_and(|member| member.broadcasts.contains(name))
321}
322
323/// Waits until member `peer` no longer lists `name`, the room is left, or its last handle drops.
324async fn unlisted(
325    state: &mut Direct<RoomState>,
326    left: &mut Direct<bool>,
327    peer: EndpointId,
328    name: &str,
329) {
330    loop {
331        if left.get() || !lists(&state.get(), peer, name) {
332            return;
333        }
334        let changed = tokio::select! {
335            changed = state.updated() => changed.is_ok(),
336            changed = left.updated() => changed.is_ok(),
337        };
338        if !changed {
339            return;
340        }
341    }
342}
343
344/// One update of a member's value, from [`MemberValues`].
345#[derive(Debug, Clone)]
346#[non_exhaustive]
347pub struct MemberValue<T> {
348    /// The member whose value this is.
349    pub member: EndpointId,
350    /// The member's newest value, or `None` once it stopped publishing it.
351    pub value: Option<Timed<T>>,
352}
353
354/// The values of one track across every member, from [`Room::read_values`].
355///
356/// Dropping it stops every reader.
357pub struct MemberValues<T> {
358    rx: mpsc::Receiver<MemberValue<T>>,
359    _follow: AbortOnDropHandle<()>,
360}
361
362impl<T> fmt::Debug for MemberValues<T> {
363    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364        f.debug_struct("MemberValues")
365            .field("queued", &self.rx.len())
366            .finish_non_exhaustive()
367    }
368}
369
370impl<T> MemberValues<T> {
371    /// Returns the next member update, if one is waiting.
372    pub fn try_recv(&mut self) -> Option<MemberValue<T>> {
373        self.rx.try_recv().ok()
374    }
375
376    /// Waits for the next member update.
377    ///
378    /// Returns `None` once the room was left. Cancel safe.
379    pub async fn recv(&mut self) -> Option<MemberValue<T>> {
380        self.rx.recv().await
381    }
382}
383
384/// Keeps one `start` task per member that lists `name`, until dropped or the room is left.
385///
386/// Aborts a member's task once the member no longer lists `name`, waits for
387/// it to end, and then runs `stopped` for that member, so nothing the task
388/// sent arrives after what `stopped` sends.
389async fn follow<Fut, Stop>(
390    (mut state, mut left): (Direct<RoomState>, Direct<bool>),
391    name: String,
392    mut start: impl FnMut(EndpointId) -> Fut,
393    mut stopped: impl FnMut(EndpointId) -> Stop,
394) where
395    Fut: Future<Output = ()> + Send + 'static,
396    Stop: Future<Output = ()>,
397{
398    let mut tasks: HashMap<EndpointId, AbortOnDropHandle<()>> = HashMap::new();
399    loop {
400        if left.get() {
401            return;
402        }
403        let state_now = state.get();
404        let gone: Vec<_> = tasks
405            .keys()
406            .filter(|id| !lists(&state_now, **id, &name))
407            .copied()
408            .collect();
409        for id in gone {
410            let task = tasks.remove(&id).expect("listed above");
411            task.abort();
412            task.await.ok();
413            stopped(id).await;
414        }
415        for id in state_now.members.keys() {
416            if lists(&state_now, *id, &name) {
417                tasks
418                    .entry(*id)
419                    .or_insert_with(|| AbortOnDropHandle::new(tokio::spawn(start(*id))));
420            }
421        }
422        let changed = tokio::select! {
423            changed = state.updated() => changed.is_ok(),
424            changed = left.updated() => changed.is_ok(),
425        };
426        if !changed {
427            return;
428        }
429    }
430}
431
432/// Reads member `member`'s value track into `tx` from each of `subscriptions`, until they end or `tx` closes.
433///
434/// `None` for `subscriptions` stands for a room whose last handle dropped.
435async fn read_member<T: DeserializeOwned>(
436    subscriptions: Option<MemberSubscriptions>,
437    member: EndpointId,
438    track: String,
439    tx: mpsc::Sender<MemberValue<T>>,
440) {
441    let Some(mut subscriptions) = subscriptions else {
442        return;
443    };
444    loop {
445        let subscription = tokio::select! {
446            subscription = subscriptions.next() => subscription,
447            () = tx.closed() => return,
448        };
449        let Some(subscription) = subscription else {
450            return;
451        };
452        if !read_once(&subscription, member, &track, &tx).await {
453            return;
454        }
455    }
456}
457
458/// Reads the value track of `subscription` into `tx` until the subscription closes.
459///
460/// Skips a value that does not decode. Returns `false` when the member
461/// should not be read again: `tx` closed, or the member's broadcast has no
462/// such track.
463async fn read_once<T: DeserializeOwned>(
464    subscription: &Subscription,
465    member: EndpointId,
466    track: &str,
467    tx: &mpsc::Sender<MemberValue<T>>,
468) -> bool {
469    let peer = member.fmt_short();
470    let mut reader = match subscription.value_track::<T>(track) {
471        Ok(reader) => reader,
472        Err(err) => {
473            debug!(%peer, %track, error = %err, "the value track did not open");
474            return true;
475        }
476    };
477    loop {
478        let value = tokio::select! {
479            value = reader.latest() => value,
480            () = tx.closed() => return false,
481        };
482        let err = match value {
483            Ok(Some(value)) => {
484                let update = MemberValue {
485                    member,
486                    value: Some(value),
487                };
488                if tx.send(update).await.is_err() {
489                    return false;
490                }
491                continue;
492            }
493            Ok(None) => return true,
494            Err(err) => err.into_json(),
495        };
496        match err {
497            moq_json::Error::Net(
498                moq_net::Error::NotFound | moq_net::Error::Stream(moq_net::StreamError::NotFound),
499            ) => {
500                info!(%peer, %track, "the member's broadcast has no such value track, not reading it");
501                return false;
502            }
503            moq_json::Error::Net(err) => {
504                debug!(%peer, %track, error = %err, "the value track failed");
505                return true;
506            }
507            // The reader moved past the value, and reads on.
508            err => debug!(%peer, %track, error = %err, "skipping a value that does not decode"),
509        }
510    }
511}
512
513#[cfg(test)]
514mod tests {
515    use super::*;
516
517    /// Subscriptions that end early wait longer each time, up to the most, and one that served on resets the wait.
518    #[tokio::test(start_paused = true)]
519    async fn a_subscription_that_ends_early_waits_longer_each_time() {
520        let mut retry = Retry::default();
521        let waits: Vec<_> = (0..5).map(|_| retry.served(Instant::now())).collect();
522        let secs = |secs| Some(Duration::from_secs(secs));
523        assert_eq!(waits, [secs(2), secs(4), secs(8), secs(16), secs(16)]);
524
525        let started = Instant::now();
526        tokio::time::advance(RETRY_MAX).await;
527        assert_eq!(
528            retry.served(started),
529            None,
530            "a subscription that served on subscribes again at once"
531        );
532        assert_eq!(retry.failed(), RETRY);
533        assert_eq!(
534            retry.failed(),
535            RETRY * 2,
536            "a failed subscription waits longer"
537        );
538    }
539}