Skip to main content

iroh_live_rooms/
room.rs

1//! The room handle, and the path layout of room broadcasts.
2
3use std::{
4    collections::{BTreeMap, BTreeSet},
5    sync::{Arc, Mutex, Weak},
6    time::Instant,
7};
8
9use iroh::EndpointId;
10use iroh_gossip::TopicId;
11use iroh_live_node::{Audience, Node, Publication, Subscription, ValueWriter, layout::Layout};
12use moq_net::{Prefix, Prefixes, broadcast, track};
13use n0_error::e;
14use n0_future::task::AbortOnDropHandle;
15use n0_watcher::{Watchable, Watcher};
16use serde::Serialize;
17use tokio::sync::{mpsc, oneshot};
18use tracing::{debug, info};
19
20use crate::{rooms::Error, ticket::RoomTicket};
21
22/// Who is in a room, and what each member publishes into it.
23#[derive(Debug, Clone, Default, PartialEq, Eq)]
24pub struct RoomState {
25    /// Every other member, by endpoint id. This node is not among them.
26    pub members: BTreeMap<EndpointId, RoomMember>,
27}
28
29impl RoomState {
30    /// Returns the name member `id` goes by: its display name, or its short endpoint id.
31    ///
32    /// The short id stands in for a member that announced no name, and for an
33    /// id that is not a member, such as one that just left.
34    #[must_use]
35    pub fn member_name(&self, id: EndpointId) -> String {
36        self.members
37            .get(&id)
38            .and_then(|member| member.display_name.clone())
39            .unwrap_or_else(|| id.fmt_short().to_string())
40    }
41}
42
43/// One member of a room.
44#[derive(Debug, Clone, Default, PartialEq, Eq)]
45pub struct RoomMember {
46    /// The name the member announced, if any.
47    pub display_name: Option<String>,
48    /// The broadcasts the member publishes into the room, by name.
49    pub broadcasts: BTreeSet<String>,
50    /// Whether this node has a direct session with the member.
51    pub connection: MemberConnection,
52}
53
54/// Whether this node has a direct session with a room member.
55///
56/// Gossip lists a member until its lease runs out, about two minutes after
57/// its last renewal. A member that vanishes without [`Room::leave`] stays
58/// listed for that long. This node's sessions tell sooner: a member turns
59/// [`Disconnected`](Self::Disconnected) once its last direct session closes.
60///
61/// Only direct sessions count, dialed or accepted, as [`Node::sessions`]
62/// lists them. The room's gossip connections do not count, and neither does
63/// a route through a media relay. A member that had no direct session with this
64/// node while listed is [`Unknown`](Self::Unknown). It may be present or
65/// gone, and only its lease tells which.
66#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
67pub enum MemberConnection {
68    /// This node has not had a direct session with the member since it was listed.
69    #[default]
70    Unknown,
71    /// This node has a direct session with the member open.
72    Connected,
73    /// The last direct session with the member closed, and none is open.
74    ///
75    /// A close from either side counts, including one that this node asked
76    /// for with [`Session::close`](iroh_live_node::Session::close). A member
77    /// whose process exits closes its sessions at once. A member that crashes
78    /// or loses its network closes nothing, so this node notices only when
79    /// the QUIC idle timeout ends the session, after 30 seconds by default.
80    /// A new session makes the member [`Connected`](Self::Connected) again.
81    Disconnected {
82        /// When this node saw the last session close.
83        since: Instant,
84    },
85}
86
87/// A joined room.
88///
89/// Cheap to clone. The actor behind it runs while any clone exists, and
90/// [`leave`](Self::leave) ends it for all of them.
91#[derive(Debug, Clone)]
92pub struct Room {
93    pub(crate) inner: Arc<Inner>,
94    pub(crate) _actor: Arc<AbortOnDropHandle<()>>,
95}
96
97/// A room that does not keep its actor running, see [`Room::downgrade`].
98#[derive(Debug)]
99pub(crate) struct WeakRoom {
100    inner: Weak<Inner>,
101    actor: Weak<AbortOnDropHandle<()>>,
102}
103
104impl WeakRoom {
105    /// Returns the room if a handle still keeps its actor running.
106    pub(crate) fn upgrade(&self) -> Option<Room> {
107        Some(Room {
108            inner: self.inner.upgrade()?,
109            _actor: self.actor.upgrade()?,
110        })
111    }
112}
113
114/// What every handle of a room shares with its actor.
115#[derive(derive_more::Debug)]
116pub(crate) struct Inner {
117    /// This node's endpoint id.
118    pub(crate) me: EndpointId,
119    pub(crate) ticket: RoomTicket,
120    #[debug(skip)]
121    pub(crate) node: Node,
122    pub(crate) state: Watchable<RoomState>,
123    /// The members' ids, which every publication into the room is offered to.
124    pub(crate) members: Watchable<BTreeSet<EndpointId>>,
125    /// Asks the actor to leave, and hears back once it did.
126    #[debug(skip)]
127    pub(crate) leave: mpsc::Sender<oneshot::Sender<()>>,
128    /// This member's publications, by name.
129    #[debug(skip)]
130    pub(crate) local: Mutex<BTreeMap<String, LocalPublication>>,
131    /// Bumped whenever [`Inner::local`] changes, so the actor re-announces.
132    pub(crate) local_changed: Watchable<u64>,
133    /// The name this member announces.
134    pub(crate) display_name: Watchable<Option<String>>,
135    /// Set once the actor has stopped.
136    pub(crate) done: Watchable<bool>,
137    /// Asks the actor to resubscribe to its gossip map, and hears back once it did.
138    #[cfg(feature = "test-util")]
139    #[debug(skip)]
140    pub(crate) restart_map: mpsc::Sender<oneshot::Sender<()>>,
141}
142
143/// One of this member's publications.
144pub(crate) struct LocalPublication {
145    pub(crate) publication: Publication,
146    /// Forgets the entry once the publication is withdrawn, however it goes.
147    _withdrawn: AbortOnDropHandle<()>,
148}
149
150impl Room {
151    /// Ends the room's gossip map subscription, as smol-kv does with one that falls behind.
152    ///
153    /// Returns once the room has resubscribed. Only for tests of that path,
154    /// which no test can reach otherwise.
155    #[cfg(feature = "test-util")]
156    #[doc(hidden)]
157    pub async fn restart_map_subscription(&self) {
158        let (reply, resubscribed) = oneshot::channel();
159        if self.inner.restart_map.send(reply).await.is_ok() {
160            resubscribed.await.ok();
161        }
162    }
163
164    /// Returns a ticket for this room with this member as its bootstrap peer.
165    #[must_use]
166    pub fn ticket(&self) -> RoomTicket {
167        self.inner.ticket.with_bootstrap(self.inner.me)
168    }
169
170    /// Returns the members, their broadcasts and connections, as they change.
171    #[must_use]
172    pub fn state(&self) -> n0_watcher::Direct<RoomState> {
173        self.inner.state.watch()
174    }
175
176    /// Publishes a broadcast into the room as `name`, to its members only, and returns it.
177    ///
178    /// The path is `rooms/<this member>/<topic>/<name>`. `B` is built from the
179    /// route table's `broadcast::Producer`: a `LocalBroadcast`, or the producer
180    /// itself. The broadcast stays announced until it closes,
181    /// [`unpublish`](Self::unpublish) takes it out, or the room is left.
182    ///
183    /// # Errors
184    ///
185    /// Fails with [`Error::InvalidName`] for an empty name or one holding a
186    /// slash, [`Error::Node`] if the name is already published or `B`
187    /// cannot be built, and [`Error::Left`] once the room was left.
188    ///
189    /// # Panics
190    ///
191    /// Panics when called outside a Tokio runtime.
192    pub fn publish<B>(&self, name: &str) -> Result<B, Error>
193    where
194        B: TryFrom<broadcast::Producer, Error: std::error::Error + Send + Sync + 'static>,
195    {
196        let path = self.local_path(name)?;
197        // `B` is built before the broadcast is announced, so no member finds
198        // it without the tracks `B` creates, such as a catalog.
199        let (publication, filled) =
200            self.inner
201                .node
202                .publish_with(path, self.audience(), |producer| {
203                    B::try_from(producer.clone())
204                })?;
205        self.add_local(name, &publication, None);
206        Ok(filled)
207    }
208
209    /// Publishes a broadcast into the room as `name` whose one track `track` holds a latest-value JSON value.
210    ///
211    /// For state the members share, such as presence, a cursor or a game:
212    /// each [`update`](ValueWriter::update) replaces the value, and a member
213    /// that subscribes late gets the current one at once. Members read it
214    /// from everyone with [`read_values`](Self::read_values), or from one
215    /// member with [`subscribe`](Self::subscribe) and
216    /// [`Subscription::value_track`]. The track exists before the broadcast
217    /// is announced, so no member misses it, and the broadcast carries no
218    /// media catalog. The last clone of the writer to drop finishes the track
219    /// and closes the broadcast, which takes `name` out of the room. Otherwise
220    /// it stays as [`publish`](Self::publish) describes.
221    ///
222    /// # Errors
223    ///
224    /// As [`publish`](Self::publish).
225    ///
226    /// # Panics
227    ///
228    /// Panics when called outside a Tokio runtime.
229    ///
230    /// # Examples
231    ///
232    /// ```no_run
233    /// # fn run(room: iroh_live_rooms::Room) -> Result<(), Box<dyn std::error::Error>> {
234    /// let presence = room.publish_value::<String>("presence", "status")?;
235    /// presence.update(&"typing".to_owned())?;
236    /// # Ok(())
237    /// # }
238    /// ```
239    pub fn publish_value<T: Serialize>(
240        &self,
241        name: &str,
242        track: &str,
243    ) -> Result<ValueWriter<T>, Error> {
244        let path = self.local_path(name)?;
245        let (publication, writer) = self
246            .inner
247            .node
248            .publish_value(path, self.audience(), track)?;
249        self.add_local(name, &publication, Some(writer.producer().demand()));
250        Ok(writer)
251    }
252
253    /// Returns the path of this member's broadcast `name` in the room.
254    ///
255    /// Fails as [`publish`](Self::publish) does for an invalid name or a left room.
256    fn local_path(&self, name: &str) -> Result<String, Error> {
257        if name.is_empty() || name.contains('/') {
258            return Err(e!(Error::InvalidName {
259                name: name.to_owned()
260            }));
261        }
262        if self.inner.done.get() {
263            return Err(e!(Error::Left));
264        }
265        Ok(room_path(self.inner.ticket.topic_id(), self.inner.me, name))
266    }
267
268    /// Returns the audience of this member's room broadcasts, the other members.
269    fn audience(&self) -> Audience {
270        Audience::Peers(self.inner.members.clone())
271    }
272
273    /// Announces `publication` as this member's broadcast `name`, until it is withdrawn.
274    ///
275    /// With `track`, closes the broadcast once that track ends, which
276    /// withdraws it.
277    fn add_local(&self, name: &str, publication: &Publication, track: Option<track::Demand>) {
278        info!(%name, path = %publication.path(), "published into the room");
279        {
280            let mut local = self.inner.local.lock().expect("poisoned");
281            // Spawned under the lock, so the task cannot run before the entry
282            // exists.
283            let withdrawn = {
284                let inner = Arc::downgrade(&self.inner);
285                let name = name.to_owned();
286                let publication = publication.clone();
287                AbortOnDropHandle::new(tokio::spawn(async move {
288                    let ended = async {
289                        match track {
290                            // Ends with any outcome, a finish or a drop.
291                            Some(track) => drop(track.closed().await),
292                            None => std::future::pending().await,
293                        }
294                    };
295                    tokio::select! {
296                        () = publication.withdrawn() => {}
297                        () = ended => {
298                            debug!(%name, "the value track ended, closing the broadcast");
299                            publication.broadcast().close();
300                            publication.withdrawn().await;
301                        }
302                    }
303                    if let Some(inner) = inner.upgrade() {
304                        debug!(%name, "room broadcast withdrawn");
305                        inner.remove_local(&name, &publication);
306                    }
307                }))
308            };
309            local.insert(
310                name.to_owned(),
311                LocalPublication {
312                    publication: publication.clone(),
313                    _withdrawn: withdrawn,
314                },
315            );
316        }
317        self.inner.bump_local();
318    }
319
320    /// Takes `name` out of the room, if this member publishes it.
321    ///
322    /// The broadcast stays open for whoever holds it, unannounced. Returns
323    /// whether `name` was published.
324    #[must_use]
325    pub fn unpublish(&self, name: &str) -> bool {
326        let publication = self
327            .inner
328            .local
329            .lock()
330            .expect("poisoned")
331            .get(name)
332            .map(|local| local.publication.clone());
333        match publication {
334            Some(publication) => {
335                // Its withdrawn task takes the name out of the announcement.
336                publication.unpublish();
337                true
338            }
339            None => false,
340        }
341    }
342
343    /// Resolves `peer`'s broadcast `name` over the session with that member.
344    ///
345    /// Reads what the member itself announces on that session, so no other
346    /// peer can stand in for it. Waits until the member announces `name`, so
347    /// bound the wait if the member may never publish it.
348    ///
349    /// # Errors
350    ///
351    /// Fails with [`Error::Left`] once the room was left, and with
352    /// [`Error::Node`] if the member cannot be dialed, the node's policy does
353    /// not grant the member its [`RoomsLayout`] scope, or the session ends
354    /// before the member announces `name`.
355    pub async fn subscribe(&self, peer: EndpointId, name: &str) -> Result<Subscription, Error> {
356        if self.inner.done.get() {
357            return Err(e!(Error::Left));
358        }
359        let path = room_path(self.inner.ticket.topic_id(), peer, name);
360        let session = self.inner.node.connect(peer).await?;
361        Ok(session.subscribe(path).await?)
362    }
363
364    /// Sets the name other members see, or clears it.
365    pub fn set_display_name(&self, name: Option<String>) {
366        self.inner.display_name.set(name).ok();
367    }
368
369    /// Leaves the room for every clone of this handle.
370    ///
371    /// Tells the other members and withdraws this member's publications.
372    /// Subscriptions made with [`subscribe`](Self::subscribe) stay open, so
373    /// drop them too. Returns within seconds even if every other member is
374    /// gone. Idempotent. Not cancellation safe: call it again to finish.
375    pub async fn leave(&self) {
376        let (reply, reply_rx) = oneshot::channel();
377        if self.inner.leave.send(reply).await.is_ok() {
378            reply_rx.await.ok();
379        }
380        let mut done = self.inner.done.watch();
381        while !done.get() {
382            if done.updated().await.is_err() {
383                break;
384            }
385        }
386    }
387
388    /// Returns a handle that does not keep the room's actor running.
389    pub(crate) fn downgrade(&self) -> WeakRoom {
390        WeakRoom {
391            inner: Arc::downgrade(&self.inner),
392            actor: Arc::downgrade(&self._actor),
393        }
394    }
395}
396
397impl Drop for Inner {
398    /// Unpublishes this member's broadcasts when the last handle drops.
399    ///
400    /// Applies when [`Room::leave`] was not called, so that rejoining can
401    /// publish the same names.
402    fn drop(&mut self) {
403        for local in self.local.get_mut().expect("poisoned").values() {
404            local.publication.unpublish();
405        }
406    }
407}
408
409impl Inner {
410    /// Forgets the local publication `name`, if it is still `publication`.
411    ///
412    /// Compared by identity: `name` may have been published anew since, and
413    /// the new publication must stay.
414    pub(crate) fn remove_local(&self, name: &str, publication: &Publication) {
415        let mut local = self.local.lock().expect("poisoned");
416        if local
417            .get(name)
418            .is_some_and(|entry| entry.publication == *publication)
419        {
420            local.remove(name);
421            drop(local);
422            self.bump_local();
423        }
424    }
425
426    /// Signals the actor that [`Inner::local`] changed.
427    pub(crate) fn bump_local(&self) {
428        self.local_changed.set(self.local_changed.get() + 1).ok();
429    }
430
431    /// Returns the names this member publishes into the room.
432    pub(crate) fn local_names(&self) -> BTreeSet<String> {
433        self.local
434            .lock()
435            .expect("poisoned")
436            .keys()
437            .cloned()
438            .collect()
439    }
440}
441
442/// The path layout of room broadcasts: `rooms/<member>/<topic>/<name>`.
443///
444/// A member publishes under the prefix `rooms/<member>`, which names it
445/// before the topic so that one prefix covers every room it is in. A node
446/// that runs rooms lets every peer publish there, as
447/// [`policy((LiveLayout::default(), RoomsLayout))`](iroh_live_node::layout::policy)
448/// does.
449#[derive(Debug, Clone, Copy, Default)]
450pub struct RoomsLayout;
451
452impl Layout<EndpointId> for RoomsLayout {
453    fn scope(&self, peer: &EndpointId) -> Prefixes {
454        Prefixes::from(publish_scope(*peer))
455    }
456
457    fn owner(&self, path: &str) -> Option<EndpointId> {
458        parse_room_path(path).map(|(_topic, member, _name)| member)
459    }
460}
461
462/// Returns the prefix `member` publishes room broadcasts under, `rooms/<member>`.
463fn publish_scope(member: EndpointId) -> Prefix {
464    format!("rooms/{member}")
465        .parse()
466        .expect("an endpoint id is a valid path segment")
467}
468
469/// Returns the path a room broadcast lives at: `rooms/<publisher>/<topic>/<name>`.
470pub(crate) fn room_path(topic: TopicId, publisher: EndpointId, name: &str) -> String {
471    format!("rooms/{publisher}/{topic}/{name}")
472}
473
474/// Returns the topic, publisher and name of a room broadcast's path.
475///
476/// Returns `None` for any other path, and for a topic or publisher that is
477/// not spelled canonically.
478fn parse_room_path(path: &str) -> Option<(TopicId, EndpointId, &str)> {
479    let (publisher_str, rest) = path.strip_prefix("rooms/")?.split_once('/')?;
480    let (topic_str, name) = rest.split_once('/')?;
481    let topic: TopicId = topic_str.parse().ok()?;
482    let publisher: EndpointId = publisher_str.parse().ok()?;
483    let canonical = topic.to_string() == topic_str && publisher.to_string() == publisher_str;
484    (canonical && !name.is_empty()).then_some((topic, publisher, name))
485}
486
487#[cfg(test)]
488mod tests {
489    use iroh::SecretKey;
490
491    use super::*;
492
493    #[test]
494    fn a_member_goes_by_its_display_name_or_its_short_id() {
495        let (named, unnamed, gone) = (
496            SecretKey::from_bytes(&[1; 32]).public(),
497            SecretKey::from_bytes(&[2; 32]).public(),
498            SecretKey::from_bytes(&[3; 32]).public(),
499        );
500        let mut state = RoomState::default();
501        state.members.insert(
502            named,
503            RoomMember {
504                display_name: Some("ada".into()),
505                ..Default::default()
506            },
507        );
508        state.members.insert(unnamed, RoomMember::default());
509        assert_eq!(state.member_name(named), "ada");
510        assert_eq!(state.member_name(unnamed), unnamed.fmt_short().to_string());
511        assert_eq!(state.member_name(gone), gone.fmt_short().to_string());
512    }
513
514    #[test]
515    fn a_room_path_names_topic_and_publisher() {
516        let topic = TopicId::from_bytes([7; 32]);
517        let publisher = SecretKey::from_bytes(&[3; 32]).public();
518        let path = room_path(topic, publisher, "cam");
519        assert_eq!(path, format!("rooms/{publisher}/{topic}/cam"));
520        assert!(publish_scope(publisher).matches(&path));
521        assert!(!publish_scope(SecretKey::from_bytes(&[4; 32]).public()).matches(&path));
522    }
523
524    #[test]
525    fn the_rooms_layout_owns_what_it_scopes() {
526        let topic = TopicId::from_bytes([5; 32]);
527        let (member, other) = (
528            SecretKey::from_bytes(&[6; 32]).public(),
529            SecretKey::from_bytes(&[7; 32]).public(),
530        );
531        let scope = RoomsLayout.scope(&member);
532        for name in ["cam", "cam/hd"] {
533            let path = room_path(topic, member, name);
534            assert!(scope.matches(&path), "{path}");
535            assert_eq!(RoomsLayout.owner(&path), Some(member), "{path}");
536            assert!(!RoomsLayout.scope(&other).matches(&path), "{path}");
537        }
538        assert_eq!(RoomsLayout.owner(&format!("live/{member}/cam")), None);
539    }
540
541    #[test]
542    fn the_live_and_rooms_layouts_compose() {
543        use iroh_live_node::{
544            SessionRequest,
545            layout::{LiveLayout, grant, policy},
546            policy::{Event, PeerRequest, Policy},
547        };
548
549        let both = (LiveLayout::default(), RoomsLayout);
550        let (peer, other) = (
551            SecretKey::from_bytes(&[8; 32]).public(),
552            SecretKey::from_bytes(&[9; 32]).public(),
553        );
554        let granted = grant(&both, peer);
555        assert!(granted.allows_publish(&format!("live/{peer}/cam")));
556        assert!(granted.allows_publish(&format!("rooms/{peer}/topic/cam")));
557        assert!(!granted.allows_publish(&format!("rooms/{other}/topic/cam")));
558        assert!(!granted.allows_publish(&format!("live/{other}/cam")));
559        let request = PeerRequest::new(peer, SessionRequest::default(), Event::Connect);
560        let decided = n0_future::future::block_on(Policy::decide(&policy(both), &request))
561            .expect("admitted")
562            .grant;
563        assert_eq!(decided, granted);
564    }
565
566    #[test]
567    fn a_room_path_parses_back() {
568        let topic = TopicId::from_bytes([3; 32]);
569        let publisher = SecretKey::from_bytes(&[4; 32]).public();
570        let path = room_path(topic, publisher, "cam/hd");
571        assert_eq!(parse_room_path(&path), Some((topic, publisher, "cam/hd")));
572        assert_eq!(
573            parse_room_path(&format!("rooms/{publisher}/{topic}/")),
574            None
575        );
576        assert_eq!(
577            parse_room_path(&format!("rooms/{publisher}/topic/cam")),
578            None
579        );
580        assert_eq!(
581            parse_room_path(&format!("live/{publisher}/{topic}/cam")),
582            None
583        );
584        let upper = publisher.to_string().to_uppercase();
585        assert_eq!(parse_room_path(&format!("rooms/{upper}/{topic}/cam")), None);
586    }
587}