Skip to main content

iroh_live_rooms/
chat.rs

1//! Room chat: one more broadcast every member publishes into the room.
2//!
3//! The broadcast is named [`NAME`] and carries a `chat` track, a JSON window
4//! of the last ten seconds of messages, which `@moq/room` reads too.
5//!
6//! [`Chat`] is the whole thing in one handle: it publishes this member's chat,
7//! reads every other member's, and hands their messages over through
8//! [`Chat::try_recv`] or [`Chat::recv`]. [`Chat::split`] parts it into the
9//! [`Writer`] and the [`Messages`], for an application that sends from one
10//! place and receives in another.
11
12use std::{collections::VecDeque, time::Duration};
13
14use iroh::EndpointId;
15use iroh_live_node::Subscription;
16use moq_json::window;
17use moq_net::{broadcast, track};
18use n0_error::{Result, StdResultExt};
19use n0_future::task::AbortOnDropHandle;
20use tokio::{sync::mpsc, time::Instant};
21use tracing::{debug, warn};
22
23use crate::{MemberSubscriptions, Room};
24
25/// The name of the track that carries the chat window.
26const TRACK: &str = "chat";
27
28/// The chat track's delivery priority, below audio and video.
29const PRIORITY: i8 = 10;
30
31/// How long a sent message stays in the window.
32const HISTORY: Duration = Duration::from_secs(10);
33
34/// A message entering, leaving or missed from the window.
35type Event = window::Event<String>;
36
37/// The name of the chat broadcast.
38pub const NAME: &str = "chat";
39
40/// How many typed messages wait for the writer task.
41const SEND_QUEUE: usize = 16;
42
43/// How many received messages wait for the application in [`Messages`].
44const RECV_QUEUE: usize = 64;
45
46/// How many delivered messages a reader remembers to skip replays.
47const REMEMBERED: usize = 64;
48
49/// A message another member sent.
50#[derive(Debug, Clone)]
51pub struct Message {
52    /// The member that sent it.
53    pub from: EndpointId,
54    /// The message text.
55    pub text: String,
56}
57
58/// This member's chat in a room, and every other member's.
59///
60/// Dropping it withdraws this member's chat and stops the readers. Neither
61/// keeps the room joined: the readers stop once its last handle drops.
62#[derive(Debug)]
63pub struct Chat {
64    writer: Writer,
65    messages: Messages,
66}
67
68impl Chat {
69    /// Publishes this member's chat into `room` and starts reading the others.
70    ///
71    /// Keeps one reader per member that publishes [`NAME`], as the
72    /// membership changes. A reader follows the member through
73    /// [`Room::subscriptions`], and a new subscription replays the member's
74    /// window without repeating the messages delivered already.
75    ///
76    /// # Errors
77    ///
78    /// Fails if the chat broadcast cannot be published.
79    ///
80    /// # Panics
81    ///
82    /// Panics when called outside a Tokio runtime.
83    pub fn new(room: &Room) -> Result<Self> {
84        let writer: Writer = room.publish(NAME)?;
85        let (tx, rx) = mpsc::channel(RECV_QUEUE);
86        let weak = room.downgrade();
87        let follow = room.for_each_member(NAME, move |from| {
88            let subscriptions = weak.upgrade().map(|room| room.subscriptions(from, NAME));
89            read(subscriptions, from, tx.clone())
90        });
91        Ok(Self {
92            writer,
93            messages: Messages {
94                rx,
95                _follow: follow,
96            },
97        })
98    }
99
100    /// Sends `text` to the room, unless the writer is backed up.
101    ///
102    /// Other members' copies come back through [`recv`](Self::recv), this
103    /// member's own do not.
104    pub fn send(&self, text: impl Into<String>) {
105        self.writer.send(text);
106    }
107
108    /// Returns the next received message, if one is waiting.
109    pub fn try_recv(&mut self) -> Option<Message> {
110        self.messages.try_recv()
111    }
112
113    /// Waits for the next received message.
114    ///
115    /// Returns `None` once the room was left. Cancel safe.
116    pub async fn recv(&mut self) -> Option<Message> {
117        self.messages.recv().await
118    }
119
120    /// Parts the chat into its writer and its received messages.
121    ///
122    /// Dropping the writer withdraws this member's chat, and dropping the
123    /// messages stops the readers.
124    #[must_use]
125    pub fn split(self) -> (Writer, Messages) {
126        (self.writer, self.messages)
127    }
128}
129
130/// The messages other members send, from [`Chat::split`].
131///
132/// Dropping it stops the readers.
133#[derive(Debug)]
134pub struct Messages {
135    rx: mpsc::Receiver<Message>,
136    _follow: AbortOnDropHandle<()>,
137}
138
139impl Messages {
140    /// Returns the next received message, if one is waiting.
141    pub fn try_recv(&mut self) -> Option<Message> {
142        self.rx.try_recv().ok()
143    }
144
145    /// Waits for the next received message.
146    ///
147    /// Returns `None` once the room was left. Cancel safe.
148    pub async fn recv(&mut self) -> Option<Message> {
149        self.rx.recv().await
150    }
151}
152
153/// This member's chat broadcast, and the task that writes and expires it.
154///
155/// Built by `room.publish::<Writer>(NAME)`, which creates the track before
156/// the room announces the broadcast, or taken from [`Chat::split`].
157#[derive(Debug)]
158pub struct Writer {
159    tx: mpsc::Sender<String>,
160    _task: AbortOnDropHandle<()>,
161}
162
163/// A broadcast that closes when dropped.
164struct ClosesOnDrop(broadcast::Producer);
165
166impl Drop for ClosesOnDrop {
167    fn drop(&mut self) {
168        self.0.close();
169    }
170}
171
172impl Writer {
173    /// Sends `text` to the room, unless the writer is backed up.
174    pub fn send(&self, text: impl Into<String>) {
175        if self.tx.try_send(text.into()).is_err() {
176            warn!("the chat writer is backed up, dropping a message");
177        }
178    }
179}
180
181impl TryFrom<broadcast::Producer> for Writer {
182    type Error = moq_net::Error;
183
184    /// Creates the chat track on `producer` and starts writing it.
185    ///
186    /// [`Room::publish`] builds a writer this way before it announces the
187    /// broadcast, so no member finds the broadcast without its track.
188    ///
189    /// # Errors
190    ///
191    /// Fails with [`moq_net::Error::Duplicate`] if `producer` has a chat
192    /// track already.
193    ///
194    /// # Panics
195    ///
196    /// Panics when called outside a Tokio runtime.
197    fn try_from(mut producer: broadcast::Producer) -> Result<Self, Self::Error> {
198        let mut publisher = Publisher::create(&mut producer)?;
199        let (tx, mut rx) = mpsc::channel::<String>(SEND_QUEUE);
200        let task = tokio::spawn(async move {
201            // Closed when the task ends, which withdraws the chat from the
202            // room: the room holds the broadcast open otherwise.
203            let _producer = ClosesOnDrop(producer);
204            loop {
205                let text = tokio::select! {
206                    text = rx.recv() => text,
207                    () = publisher.expiry() => match publisher.prune() {
208                        Ok(()) => continue,
209                        Err(err) => {
210                            warn!(error = %err, "the chat window failed");
211                            return;
212                        }
213                    },
214                };
215                let Some(text) = text else { return };
216                if let Err(err) = publisher.send(&text) {
217                    warn!(error = %err, "failed to send the chat message");
218                }
219            }
220        });
221        Ok(Self {
222            tx,
223            _task: AbortOnDropHandle::new(task),
224        })
225    }
226}
227
228/// Reads member `from`'s chat into `tx` from each of `subscriptions`, until they end or `tx` closes.
229///
230/// A new subscription replays the member's window, and messages delivered
231/// already are skipped. `None` for `subscriptions` stands for a room whose
232/// last handle dropped.
233async fn read(
234    subscriptions: Option<MemberSubscriptions>,
235    from: EndpointId,
236    tx: mpsc::Sender<Message>,
237) {
238    let Some(mut subscriptions) = subscriptions else {
239        return;
240    };
241    let mut delivered = VecDeque::new();
242    loop {
243        let subscription = tokio::select! {
244            subscription = subscriptions.next() => subscription,
245            () = tx.closed() => return,
246        };
247        let Some(subscription) = subscription else {
248            return;
249        };
250        if let Err(err) = read_once(&subscription, from, &mut delivered, &tx).await {
251            debug!(peer = %from.fmt_short(), error = %err, "chat read ended");
252        }
253        if tx.is_closed() {
254            return;
255        }
256    }
257}
258
259/// Reads member `from`'s chat from `subscription` until its broadcast ends or `tx` closes.
260async fn read_once(
261    subscription: &Subscription,
262    from: EndpointId,
263    delivered: &mut VecDeque<(u64, String)>,
264    tx: &mpsc::Sender<Message>,
265) -> Result<()> {
266    let broadcast = subscription.broadcast();
267    let mut chat = subscribe(&broadcast).await?;
268    loop {
269        // A broadcast whose session died does not always end its tracks.
270        let event = tokio::select! {
271            event = chat.next() => event.std_context("reading the chat")?,
272            _ = broadcast.closed() => None,
273            () = tx.closed() => None,
274        };
275        let Some(event) = event else {
276            return Ok(());
277        };
278        let Event::Push { index, value } = event.value else {
279            continue;
280        };
281        let Some(text) = remember(delivered, index, value) else {
282            continue;
283        };
284        if tx.send(Message { from, text }).await.is_err() {
285            return Ok(());
286        }
287    }
288}
289
290/// The writer of this member's chat window.
291///
292/// It retires each message once the window's history has passed.
293struct Publisher {
294    producer: window::Producer<String>,
295    /// When each message in the window expires, oldest first.
296    expires: VecDeque<Instant>,
297}
298
299impl Publisher {
300    /// Creates the chat track on `broadcast`, failing if it has one already.
301    fn create(broadcast: &mut broadcast::Producer) -> Result<Self, moq_net::Error> {
302        let info = track::Info::default()
303            .with_timescale(moq_net::Timescale::MILLI)
304            .with_priority(PRIORITY);
305        let track = broadcast
306            .create_track(TRACK, info)
307            .ok_or(moq_net::Error::Duplicate)?;
308        let config = window::Config::default().with_ops(false);
309        Ok(Self {
310            producer: window::Producer::new(track, config),
311            expires: VecDeque::new(),
312        })
313    }
314
315    /// Appends `text` to the window, retiring expired messages first.
316    fn send(&mut self, text: &str) -> Result<()> {
317        if text.is_empty() {
318            return Ok(());
319        }
320        self.prune()?;
321        let text = text.to_owned();
322        self.producer
323            .push(&text, track_time())
324            .std_context("writing the chat window")?;
325        self.expires.push_back(Instant::now() + HISTORY);
326        Ok(())
327    }
328
329    /// Waits until the oldest message expires, or forever with none.
330    async fn expiry(&self) {
331        match self.expires.front() {
332            Some(at) => tokio::time::sleep_until(*at).await,
333            None => std::future::pending().await,
334        }
335    }
336
337    /// Retires the messages whose history has passed.
338    fn prune(&mut self) -> Result<()> {
339        let now = Instant::now();
340        let count = self.expires.iter().take_while(|at| **at <= now).count();
341        if count == 0 {
342            return Ok(());
343        }
344        self.producer
345            .pop(count as u64, track_time())
346            .std_context("retiring chat messages")?;
347        self.expires.drain(..count);
348        Ok(())
349    }
350}
351
352/// The reader of a member's chat window, from its newest group.
353enum Subscriber {
354    /// Waiting for the track's newest group, which holds the whole window.
355    Positioning(Option<Box<track::Subscriber>>),
356    /// Reading the window from that group on.
357    Reading(Box<window::Consumer<String>>),
358}
359
360impl Subscriber {
361    /// Returns the next window event, or `None` once the track ends.
362    ///
363    /// Cancel safe: a cancelled read keeps its position.
364    async fn next(&mut self) -> moq_json::Result<Option<moq_json::Timed<Event>>> {
365        if let Self::Positioning(pending) = self {
366            let track = pending.as_mut().expect("positioning holds the track");
367            // Older groups only replay what the newest holds.
368            let largest = track.largest().await;
369            let mut track = *pending.take().expect("positioning holds the track");
370            if let Some(largest) = largest {
371                track = track.with_range(largest.group..);
372            }
373            *self = Self::Reading(Box::new(window::Consumer::new(track, Default::default())));
374        }
375        let Self::Reading(consumer) = self else {
376            unreachable!("positioned above");
377        };
378        consumer.next().await
379    }
380}
381
382/// Returns the current time on the chat track's millisecond scale.
383fn track_time() -> moq_net::Timestamp {
384    moq_net::Timestamp::from(moq_net::time::Instant::now())
385}
386
387/// Subscribes to the chat window of `broadcast`.
388async fn subscribe(broadcast: &broadcast::Consumer) -> Result<Subscriber> {
389    let track = broadcast
390        .track(TRACK)
391        .std_context("subscribing to the chat")?;
392    let subscriber = track
393        .subscribe(None)
394        .await
395        .std_context("subscribing to the chat")?;
396    Ok(Subscriber::Positioning(Some(Box::new(subscriber))))
397}
398
399/// Returns the message at `index` once, remembering that it was delivered.
400///
401/// Keyed by index and text: a member that restarted counts from zero again,
402/// with new text.
403fn remember(delivered: &mut VecDeque<(u64, String)>, index: u64, text: String) -> Option<String> {
404    let seen = (index, text);
405    if delivered.contains(&seen) {
406        return None;
407    }
408    let text = seen.1.clone();
409    delivered.push_back(seen);
410    if delivered.len() > REMEMBERED {
411        delivered.pop_front();
412    }
413    Some(text)
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419
420    /// A writer creates its track as it is built, so a second one on the same broadcast is refused.
421    #[tokio::test]
422    async fn a_writer_creates_its_track_as_it_is_built() {
423        let producer = broadcast::Info::new().produce();
424        let _writer = Writer::try_from(producer.clone()).expect("writer");
425        assert!(matches!(
426            Writer::try_from(producer.clone()),
427            Err(moq_net::Error::Duplicate)
428        ));
429    }
430
431    /// A message the writer sends reaches a subscriber of its broadcast.
432    #[tokio::test]
433    async fn a_message_reaches_a_subscriber() {
434        let producer = broadcast::Info::new().produce();
435        let writer = Writer::try_from(producer.clone()).expect("writer");
436        let mut chat = subscribe(&producer.consume()).await.expect("subscribe");
437        writer.send("hello");
438        let event = tokio::time::timeout(Duration::from_secs(5), chat.next())
439            .await
440            .expect("timed out")
441            .expect("read")
442            .expect("an event");
443        assert!(matches!(event.value, Event::Push { value, .. } if value == "hello"));
444    }
445
446    /// A replayed window is skipped, and a restarted member is heard.
447    #[test]
448    fn a_replay_is_skipped_and_a_restart_is_not() {
449        let mut delivered = VecDeque::new();
450        assert!(remember(&mut delivered, 0, "a".into()).is_some());
451        assert!(remember(&mut delivered, 1, "b".into()).is_some());
452        assert!(
453            remember(&mut delivered, 1, "b".into()).is_none(),
454            "a replay"
455        );
456        assert!(
457            remember(&mut delivered, 0, "again".into()).is_some(),
458            "a restart"
459        );
460    }
461}