Skip to main content

iroh_live_rooms/
rooms.rs

1//! The room service: joins rooms over one gossip instance.
2
3use std::{
4    collections::{BTreeMap, BTreeSet},
5    sync::{
6        Arc, Mutex,
7        atomic::{AtomicBool, Ordering},
8    },
9    time::Duration,
10};
11
12use iroh::{
13    endpoint::Connection,
14    protocol::{AcceptError, ProtocolHandler, RouterBuilder},
15};
16use iroh_gossip::Gossip;
17use iroh_live_node::Node;
18use iroh_smol_kv::ExpiryConfig;
19use n0_error::stack_error;
20use n0_future::{join_all, task::AbortOnDropHandle};
21use n0_watcher::Watchable;
22use tokio::sync::{OnceCell, mpsc};
23use tracing::{Instrument, debug, info, info_span, warn};
24
25use crate::{
26    actor::{Actor, EXPIRY_CHECK_INTERVAL, STATE_HORIZON},
27    room::{Inner, Room, RoomState, WeakRoom},
28    ticket::RoomTicket,
29};
30
31/// The ALPN rooms speak, iroh-gossip's.
32///
33/// [`Rooms::mount`] mounts the service under it.
34pub const ALPN: &[u8] = iroh_gossip::ALPN;
35
36/// An error from a room or the room service.
37#[stack_error(derive, add_meta, from_sources)]
38pub enum Error {
39    /// The room's gossip topic could not be joined.
40    #[error(transparent)]
41    Gossip(iroh_gossip::Error),
42    /// The node failed a publication, a subscription or a dial.
43    #[error(transparent)]
44    Node(iroh_live_node::Error),
45    /// A broadcast name that is empty or holds a slash.
46    #[error("invalid broadcast name {name:?}")]
47    InvalidName { name: String },
48    /// The room was left.
49    #[error("the room was left")]
50    Left,
51}
52
53/// Rooms on one endpoint.
54///
55/// Owns the gossip instance all rooms on the endpoint share. Cheap to clone,
56/// and [`shutdown`](Self::shutdown) ends it for every clone.
57///
58/// # Examples
59///
60/// ```no_run
61/// # async fn run(node: iroh_live_node::Node, ticket: iroh_live_rooms::RoomTicket)
62/// # -> Result<(), iroh_live_rooms::Error> {
63/// use iroh_live_rooms::Rooms;
64///
65/// let rooms = Rooms::new(&node);
66/// // Mount the service with `rooms.mount(router_builder)` to accept members.
67/// let room = rooms.join(&ticket, Some("ada".into())).await?;
68/// # drop(room);
69/// rooms.shutdown().await;
70/// # Ok(())
71/// # }
72/// ```
73#[derive(Debug, Clone)]
74pub struct Rooms {
75    node: Node,
76    gossip: Gossip,
77    /// Set once the gossip has shut down, so the router's shutdown does not repeat it.
78    shut_down: Arc<OnceCell<()>>,
79    /// Set when [`shutdown`](Self::shutdown) starts.
80    ///
81    /// The rooms joined here read it, so the gossip map ending under them is
82    /// a clean stop and not a failure.
83    closing: Arc<AtomicBool>,
84    /// Set once the service is mounted on a router.
85    mounted: Arc<AtomicBool>,
86    /// Set once a join has warned that the service is not mounted.
87    warned_unmounted: Arc<AtomicBool>,
88    /// The rooms joined here, for [`leave_all`](Self::leave_all).
89    joined: Arc<Mutex<Vec<WeakRoom>>>,
90}
91
92impl Rooms {
93    /// Creates the room service on `node`'s endpoint, with its own gossip.
94    ///
95    /// # Panics
96    ///
97    /// Panics when called outside a Tokio runtime.
98    #[must_use]
99    pub fn new(node: &Node) -> Self {
100        let gossip = Gossip::builder().spawn(node.endpoint().clone());
101        Self::with_gossip(node, gossip)
102    }
103
104    /// Creates the room service over an existing gossip instance.
105    ///
106    /// The service takes over the gossip: [`shutdown`](Self::shutdown) shuts
107    /// it down.
108    #[must_use]
109    pub fn with_gossip(node: &Node, gossip: Gossip) -> Self {
110        Self {
111            node: node.clone(),
112            gossip,
113            shut_down: Arc::default(),
114            closing: Arc::default(),
115            mounted: Arc::default(),
116            warned_unmounted: Arc::default(),
117            joined: Arc::default(),
118        }
119    }
120
121    /// Mounts the service's gossip protocol on `router` under [`ALPN`].
122    ///
123    /// Without it, other members cannot reach this one's gossip. The router's
124    /// shutdown calls [`shutdown`](Self::shutdown).
125    #[must_use]
126    pub fn mount(&self, router: RouterBuilder) -> RouterBuilder {
127        self.mounted.store(true, Ordering::Relaxed);
128        router.accept(ALPN, Handler(self.clone()))
129    }
130
131    /// Leaves every room joined here that a handle still holds.
132    ///
133    /// Tells the other members at once, as [`Room::leave`] does for one room.
134    /// The rooms are left concurrently. A room whose last handle dropped has
135    /// stopped already without telling anyone, so keep a handle until this
136    /// runs. Call it before [`shutdown`](Self::shutdown). Not cancellation
137    /// safe: call it again to finish.
138    pub async fn leave_all(&self) {
139        let rooms: Vec<Room> = {
140            let mut joined = self.joined.lock().expect("poisoned");
141            joined.retain(|room| room.upgrade().is_some());
142            joined.iter().filter_map(WeakRoom::upgrade).collect()
143        };
144        join_all(rooms.iter().map(Room::leave)).await;
145    }
146
147    /// Shuts the gossip down for every clone.
148    ///
149    /// Leaves every gossip topic, so the rooms joined here stop. Call
150    /// [`leave_all`](Self::leave_all) first to tell the other members at
151    /// once. Idempotent, and concurrent calls wait for the same shutdown.
152    pub async fn shutdown(&self) {
153        self.closing.store(true, Ordering::Relaxed);
154        self.shut_down
155            .get_or_init(|| async {
156                if let Err(err) = self.gossip.shutdown().await {
157                    warn!(error = %err, "failed to shut down the rooms' gossip");
158                }
159                debug!("rooms shut down");
160            })
161            .await;
162    }
163
164    /// Joins the room `ticket` names, as `display_name` if given.
165    ///
166    /// Subscribes to the room's gossip topic and starts announcing this
167    /// member.
168    ///
169    /// # Errors
170    ///
171    /// Fails if the gossip topic cannot be joined.
172    pub async fn join(
173        &self,
174        ticket: &RoomTicket,
175        display_name: Option<String>,
176    ) -> Result<Room, Error> {
177        if !self.mounted.load(Ordering::Relaxed)
178            && !self.warned_unmounted.swap(true, Ordering::Relaxed)
179        {
180            warn!("rooms are not mounted on a router: peers cannot reach this member's gossip");
181        }
182        let topic = ticket.topic_id();
183        let me = self.node.endpoint().id();
184        let gossip_topic = self
185            .gossip
186            .subscribe(topic, ticket.bootstrap().to_vec())
187            .await?;
188        let kv = iroh_smol_kv::Client::local(
189            gossip_topic,
190            iroh_smol_kv::Config {
191                anti_entropy_interval: Duration::from_secs(60),
192                fast_anti_entropy_interval: Duration::from_secs(1),
193                expiry: Some(ExpiryConfig {
194                    check_interval: EXPIRY_CHECK_INTERVAL,
195                    horizon: STATE_HORIZON,
196                }),
197            },
198        );
199        let writer = kv.write(self.node.endpoint().secret_key().clone());
200
201        let (leave, inbox) = mpsc::channel(1);
202        // Without `test-util` nothing keeps the sender, so the actor's
203        // restart branch never fires.
204        let (restart_map, restarts) = mpsc::channel(1);
205        #[cfg(not(feature = "test-util"))]
206        drop(restart_map);
207        let inner = Arc::new(Inner {
208            me,
209            ticket: ticket.clone(),
210            node: self.node.clone(),
211            state: Watchable::new(RoomState::default()),
212            members: Watchable::new(BTreeSet::new()),
213            leave,
214            local: Mutex::new(BTreeMap::new()),
215            local_changed: Watchable::new(0),
216            display_name: Watchable::new(display_name),
217            done: Watchable::new(false),
218            #[cfg(feature = "test-util")]
219            restart_map,
220        });
221        let actor = Actor {
222            inner: inner.clone(),
223            kv,
224            writer,
225            members: BTreeMap::new(),
226            sessions: BTreeSet::new(),
227            resync: None,
228            rooms_closing: self.closing.clone(),
229        };
230        let span = info_span!("room", topic = %topic.fmt_short(), me = %me.fmt_short());
231        let task = tokio::spawn(actor.run(inbox, restarts).instrument(span));
232        info!(topic = %topic.fmt_short(), "joined room");
233        let room = Room {
234            inner,
235            _actor: Arc::new(AbortOnDropHandle::new(task)),
236        };
237        let mut joined = self.joined.lock().expect("poisoned");
238        joined.retain(|room| room.upgrade().is_some());
239        joined.push(room.downgrade());
240        Ok(room)
241    }
242}
243
244/// The gossip handler of a [`Rooms`], which shuts the rooms down with the router.
245#[derive(Debug, Clone)]
246struct Handler(Rooms);
247
248impl ProtocolHandler for Handler {
249    async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
250        self.0.gossip.accept(connection).await
251    }
252
253    async fn shutdown(&self) {
254        self.0.shutdown().await;
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    use iroh::{Endpoint, protocol::Router};
261    use iroh_live_node::NodeConfig;
262
263    use super::*;
264
265    /// Mounting the service marks it mounted, which stops the unmounted warning.
266    #[tokio::test]
267    async fn mounting_marks_the_rooms_mounted() {
268        let endpoint = Endpoint::bind(iroh_live_node::MinimalPreset)
269            .await
270            .expect("binds");
271        let node = Node::new(endpoint.clone(), NodeConfig::default());
272        let rooms = Rooms::new(&node);
273        assert!(!rooms.mounted.load(Ordering::Relaxed));
274
275        let router = rooms.mount(Router::builder(endpoint)).spawn();
276        assert!(rooms.mounted.load(Ordering::Relaxed));
277        router.shutdown().await.expect("the router shuts down");
278    }
279}