Skip to main content

moq_wasm/media/
watch_broadcasts.rs

1use std::{collections::HashMap, future::Future, sync::Arc, time::Duration};
2
3use moqt::{
4    client::{self, NamespaceWatch},
5    executor::{self, JoinHandle},
6};
7use tokio::time::Instant;
8
9use super::remote_broadcast::RemoteBroadcast;
10use crate::Session;
11
12type NamespaceFilter = Arc<dyn Fn(&[String]) -> bool + Send + Sync>;
13
14#[derive(Clone, Default)]
15pub struct WatchOptions {
16    /// Takes only the namespaces it returns `true` for.
17    pub filter: Option<NamespaceFilter>,
18    /// `watch_broadcasts` returns once no namespace has been published for
19    /// this long, counted from the start or from the last withdrawal.
20    pub empty_timeout: Option<Duration>,
21}
22
23/// Runs `handler` on a task for each namespace published under `prefix`,
24/// including those published before the call, except this session's own.
25/// A withdrawal aborts the namespace's task; publishing it again starts a
26/// new one. A handler's `Err` is logged.
27///
28/// Returns when the session ends or `options.empty_timeout` passes, and
29/// aborts every task when it returns or is dropped. Fails when the relay
30/// refuses the SUBSCRIBE_NAMESPACE.
31pub async fn watch_broadcasts<H, F>(
32    session: &Session,
33    prefix: &[impl AsRef<str>],
34    options: WatchOptions,
35    handler: H,
36) -> anyhow::Result<()>
37where
38    H: Fn(RemoteBroadcast) -> F,
39    F: Future<Output = anyhow::Result<()>> + Send + 'static,
40{
41    let client = session.client().clone();
42    let watch = ClosingWatch(Some(client.watch_namespaces(prefix).await?));
43    let mut running: HashMap<Vec<String>, HandlerTask> = HashMap::new();
44    let empty_deadline = || {
45        options
46            .empty_timeout
47            .map(|timeout| Instant::now() + timeout)
48    };
49    let mut empty_until = empty_deadline();
50    loop {
51        let next = watch.next();
52        let event = match empty_until.filter(|_| running.is_empty()) {
53            Some(deadline) => match tokio::time::timeout_at(deadline, next).await {
54                Ok(event) => event,
55                Err(_) => return Ok(()),
56            },
57            None => next.await,
58        };
59        let Some(event) = event else {
60            return Ok(());
61        };
62        if skips(&client, &options, &event.namespace) {
63            continue;
64        }
65        running.remove(&event.namespace);
66        if event.active {
67            let broadcast = RemoteBroadcast::new(client.clone(), event.namespace.clone());
68            let task = HandlerTask::run(handler(broadcast), event.namespace.join("/"));
69            running.insert(event.namespace, task);
70        } else if running.is_empty() {
71            empty_until = empty_deadline();
72        }
73    }
74}
75
76fn skips(client: &client::Session, options: &WatchOptions, namespace: &[String]) -> bool {
77    client
78        .moqt_session()
79        .publishes_namespace(&namespace.join("/"))
80        || options
81            .filter
82            .as_ref()
83            .is_some_and(|filter| !filter(namespace))
84}
85
86/// One handler run, aborted when dropped.
87struct HandlerTask {
88    join_handle: JoinHandle,
89}
90
91impl HandlerTask {
92    fn run(
93        handler: impl Future<Output = anyhow::Result<()>> + Send + 'static,
94        track_namespace: String,
95    ) -> Self {
96        let join_handle = executor::spawn("moq-wasm-broadcast-handler", async move {
97            if let Err(error) = handler.await {
98                tracing::warn!(error = %format!("{error:#}"), track_namespace, "broadcast handler failed");
99            }
100        });
101        Self { join_handle }
102    }
103}
104
105impl Drop for HandlerTask {
106    fn drop(&mut self) {
107        self.join_handle.abort();
108    }
109}
110
111/// UNSUBSCRIBE_NAMESPACEs on a spawned task when dropped.
112struct ClosingWatch(Option<NamespaceWatch>);
113
114impl ClosingWatch {
115    async fn next(&self) -> Option<moqt::namespace::NamespaceEvent> {
116        self.0.as_ref()?.next().await
117    }
118}
119
120impl Drop for ClosingWatch {
121    fn drop(&mut self) {
122        let Some(watch) = self.0.take() else {
123            return;
124        };
125        executor::spawn("moq-wasm-unsubscribe-namespace", async move {
126            if let Err(error) = watch.close().await {
127                tracing::debug!(error = %format!("{error:#}"), "UNSUBSCRIBE_NAMESPACE failed");
128            }
129        });
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use tokio::sync::mpsc;
136
137    use super::*;
138    use crate::test_support::{TEST_TIMEOUT, TestRelay};
139
140    /// Sends `true` when the handler holding it is dropped, as when aborted.
141    struct Dropped(mpsc::UnboundedSender<bool>);
142
143    impl Drop for Dropped {
144        fn drop(&mut self) {
145            let _ = self.0.send(true);
146        }
147    }
148
149    #[tokio::test]
150    async fn a_handler_runs_for_each_namespace_but_the_sessions_own() {
151        // Arrange
152        let mut relay = TestRelay::spawn("watch-own");
153        let session = Arc::new(relay.connect().await);
154        let (namespace_sender, mut namespace_receiver) = mpsc::unbounded_channel();
155        let watching = session.clone();
156        let _watch = tokio::spawn(async move {
157            watch_broadcasts(&watching, &["anon"], WatchOptions::default(), |broadcast| {
158                let namespace_sender = namespace_sender.clone();
159                async move {
160                    let _ = namespace_sender.send(broadcast.namespace().join("/"));
161                    Ok(())
162                }
163            })
164            .await
165        });
166        assert_eq!(relay.next_request().await, "SUBSCRIBE_NAMESPACE anon");
167
168        // Act
169        let _own = session.announce(&["anon", "own"]).await.unwrap();
170        relay.next_request().await;
171        relay.publish_namespace("anon/remote").await;
172        let first = tokio::time::timeout(TEST_TIMEOUT, namespace_receiver.recv()).await;
173        let second =
174            tokio::time::timeout(Duration::from_millis(200), namespace_receiver.recv()).await;
175
176        // Assert: no handler ran for anon/own, which the relay echoed back
177        assert_eq!(first.unwrap().as_deref(), Some("anon/remote"));
178        assert!(second.is_err(), "{second:?}");
179    }
180
181    #[tokio::test]
182    async fn a_withdrawal_aborts_the_handler_and_the_empty_timeout_ends_the_watch() {
183        // Arrange
184        let mut relay = TestRelay::spawn("watch-withdraw");
185        let session = Arc::new(relay.connect().await);
186        let (dropped_sender, mut dropped_receiver) = mpsc::unbounded_channel();
187        let options = WatchOptions {
188            empty_timeout: Some(Duration::from_millis(300)),
189            ..WatchOptions::default()
190        };
191        let watching = session.clone();
192        let watch = tokio::spawn(async move {
193            watch_broadcasts(&watching, &["anon"], options, |_| {
194                let dropped = Dropped(dropped_sender.clone());
195                async move {
196                    let _dropped = dropped;
197                    std::future::pending::<()>().await;
198                    Ok(())
199                }
200            })
201            .await
202        });
203        relay.next_request().await;
204        relay.publish_namespace("anon/remote").await;
205
206        // Act
207        relay.publish_namespace_done("anon/remote").await;
208        let aborted = tokio::time::timeout(TEST_TIMEOUT, dropped_receiver.recv()).await;
209        let ended = tokio::time::timeout(TEST_TIMEOUT, watch).await;
210
211        // Assert
212        assert_eq!(aborted.unwrap(), Some(true));
213        assert!(ended.unwrap().unwrap().is_ok());
214    }
215}