Skip to main content

moq_wasm/media/
remote_broadcast.rs

1use std::{collections::VecDeque, sync::Arc, time::Duration};
2
3use moqt::{
4    client::{
5        self, GroupStartOptions, ReceivedObject, RequestError, SubscribeOptions, Subscription,
6    },
7    executor,
8};
9use msf::CATALOG_TRACK_NAME;
10use serde_json::Value;
11
12use super::catalog::Catalog;
13
14const RESUBSCRIBE_DELAY: Duration = Duration::from_secs(1);
15const FOLLOW_DELIVERY_TIMEOUT: Duration = Duration::from_secs(2);
16
17/// A namespace another publisher publishes, handed to a `watch_broadcasts`
18/// handler.
19#[derive(Clone)]
20pub struct RemoteBroadcast {
21    client: Arc<client::Session>,
22    namespace: Vec<String>,
23}
24
25/// How `RemoteBroadcast::follow` subscribes.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub struct FollowOptions {
28    /// The Subscriber Priority (draft-14 §7.1);
29    /// `SubscribeOptions::default().priority` by default.
30    pub priority: u8,
31    /// The DELIVERY TIMEOUT (draft-14 §9.2.1.2), 2 s by default: on a
32    /// congested link the relay drops an object that would arrive later.
33    /// `None` has every object sent.
34    pub delivery_timeout: Option<Duration>,
35}
36
37impl Default for FollowOptions {
38    fn default() -> Self {
39        Self {
40            priority: SubscribeOptions::default().priority,
41            delivery_timeout: Some(FOLLOW_DELIVERY_TIMEOUT),
42        }
43    }
44}
45
46/// How `RemoteBroadcast::event_timeline` subscribes. `delivery_timeout` is
47/// `None` by default, so every record arrives.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub struct EventTimelineOptions {
50    pub priority: u8,
51    pub delivery_timeout: Option<Duration>,
52}
53
54impl Default for EventTimelineOptions {
55    fn default() -> Self {
56        let defaults = GroupStartOptions::default();
57        Self {
58            priority: defaults.priority,
59            delivery_timeout: defaults.delivery_timeout,
60        }
61    }
62}
63
64impl RemoteBroadcast {
65    pub(super) fn new(client: Arc<client::Session>, namespace: Vec<String>) -> Self {
66        Self { client, namespace }
67    }
68
69    pub fn namespace(&self) -> &[String] {
70        &self.namespace
71    }
72
73    /// Each catalog the publisher writes, starting from the one the relay
74    /// holds (a joining FETCH). Fails when the SUBSCRIBE fails.
75    pub async fn catalogs(&self) -> Result<Catalogs, RequestError> {
76        let subscription = self
77            .client
78            .subscribe_current_group(
79                &self.namespace,
80                CATALOG_TRACK_NAME,
81                GroupStartOptions::default(),
82            )
83            .await?;
84        Ok(Catalogs {
85            subscription: ClosingSubscription(Some(subscription)),
86            track_namespace: self.namespace.join("/"),
87        })
88    }
89
90    /// The objects written after it subscribes. It subscribes again a second
91    /// after the track ends or its SUBSCRIBE fails, as when the publisher
92    /// leaves and another takes the track over.
93    pub fn follow(&self, name: &str, options: FollowOptions) -> FollowedTrack {
94        FollowedTrack {
95            resubscriber: Resubscriber::new(self, name, TrackStart::LargestObject(options)),
96        }
97    }
98
99    /// The records of an event timeline track (draft-ietf-moq-msf-02 §8),
100    /// starting from the first object of the current group (a Joining
101    /// FETCH), the whole timeline for one an `EventTimeline` writes, and
102    /// subscribing again as `follow` does.
103    pub fn event_timeline(&self, name: &str, options: EventTimelineOptions) -> RemoteEventTimeline {
104        RemoteEventTimeline {
105            resubscriber: Resubscriber::new(self, name, TrackStart::CurrentGroup(options)),
106            records: VecDeque::new(),
107            last: None,
108        }
109    }
110}
111
112/// The catalogs of a `RemoteBroadcast`; dropping it unsubscribes.
113pub struct Catalogs {
114    subscription: ClosingSubscription,
115    track_namespace: String,
116}
117
118impl Catalogs {
119    /// The next catalog; one that does not parse is logged and skipped.
120    /// `None` once the catalog track ends.
121    pub async fn next(&mut self) -> anyhow::Result<Option<Catalog>> {
122        let Some(subscription) = &self.subscription.0 else {
123            return Ok(None);
124        };
125        while let Some(object) = subscription.next().await? {
126            match Catalog::parse(&object.payload) {
127                Ok(catalog) => return Ok(Some(catalog)),
128                Err(error) => {
129                    tracing::warn!(%error, track_namespace = self.track_namespace, "catalog ignored")
130                }
131            }
132        }
133        Ok(None)
134    }
135}
136
137/// A followed track, read with `next`; dropping it unsubscribes.
138pub struct FollowedTrack {
139    resubscriber: Resubscriber,
140}
141
142impl FollowedTrack {
143    /// The next object. It never ends by itself.
144    pub async fn next(&mut self) -> ReceivedObject {
145        self.resubscriber.next().await
146    }
147}
148
149/// The records of an event timeline track, read with `next`; dropping it
150/// unsubscribes.
151pub struct RemoteEventTimeline {
152    resubscriber: Resubscriber,
153    records: VecDeque<Value>,
154    /// The group and object id of the last object read, so a resubscription
155    /// does not yield the records already read.
156    last: Option<(u64, u64)>,
157}
158
159impl RemoteEventTimeline {
160    /// The next record. An object that is not a JSON array is logged and
161    /// skipped. It never ends by itself.
162    pub async fn next(&mut self) -> Value {
163        loop {
164            if let Some(record) = self.records.pop_front() {
165                return record;
166            }
167            let object = self.resubscriber.next().await;
168            let location = (object.group_id, object.object_id);
169            if self.last.is_some_and(|last| location <= last) {
170                continue;
171            }
172            self.last = Some(location);
173            match serde_json::from_slice::<Vec<Value>>(&object.payload) {
174                Ok(records) => self.records.extend(records),
175                Err(error) => tracing::warn!(
176                    %error,
177                    track_namespace = self.resubscriber.track_namespace(),
178                    track_name = self.resubscriber.track_name,
179                    "event timeline object ignored"
180                ),
181            }
182        }
183    }
184}
185
186enum TrackStart {
187    LargestObject(FollowOptions),
188    CurrentGroup(EventTimelineOptions),
189}
190
191/// One track's subscription, made again a second after it ends or fails.
192struct Resubscriber {
193    client: Arc<client::Session>,
194    namespace: Vec<String>,
195    track_name: String,
196    start: TrackStart,
197    subscription: ClosingSubscription,
198}
199
200impl Resubscriber {
201    fn new(broadcast: &RemoteBroadcast, name: &str, start: TrackStart) -> Self {
202        Self {
203            client: broadcast.client.clone(),
204            namespace: broadcast.namespace.clone(),
205            track_name: name.to_string(),
206            start,
207            subscription: ClosingSubscription(None),
208        }
209    }
210
211    fn track_namespace(&self) -> String {
212        self.namespace.join("/")
213    }
214
215    async fn next(&mut self) -> ReceivedObject {
216        loop {
217            if self.subscription.0.is_none() {
218                match self.subscribe().await {
219                    Ok(subscription) => self.subscription.0 = Some(subscription),
220                    Err(error) => {
221                        tracing::info!(%error, track_namespace = self.track_namespace(), track_name = self.track_name, "SUBSCRIBE failed, subscribing again")
222                    }
223                }
224            }
225            if let Some(subscription) = &self.subscription.0 {
226                match subscription.next().await {
227                    Ok(Some(object)) => return object,
228                    end => {
229                        tracing::info!(error = ?end.err().map(|error| format!("{error:#}")), track_namespace = self.track_namespace(), track_name = self.track_name, "track ended, subscribing again")
230                    }
231                }
232            }
233            self.subscription = ClosingSubscription(None);
234            executor::sleep(RESUBSCRIBE_DELAY).await;
235        }
236    }
237
238    async fn subscribe(&self) -> Result<Subscription, RequestError> {
239        match self.start {
240            TrackStart::LargestObject(options) => {
241                let options = SubscribeOptions {
242                    priority: options.priority,
243                    delivery_timeout: options.delivery_timeout,
244                    ..SubscribeOptions::default()
245                };
246                self.client
247                    .subscribe(&self.namespace, &self.track_name, options)
248                    .await
249            }
250            TrackStart::CurrentGroup(options) => {
251                let options = GroupStartOptions {
252                    priority: options.priority,
253                    delivery_timeout: options.delivery_timeout,
254                    ..GroupStartOptions::default()
255                };
256                self.client
257                    .subscribe_current_group(&self.namespace, &self.track_name, options)
258                    .await
259            }
260        }
261    }
262}
263
264/// UNSUBSCRIBEs on a spawned task when dropped.
265struct ClosingSubscription(Option<Subscription>);
266
267impl Drop for ClosingSubscription {
268    fn drop(&mut self) {
269        let Some(subscription) = self.0.take() else {
270            return;
271        };
272        executor::spawn("moq-wasm-unsubscribe", async move {
273            if let Err(error) = subscription.close().await {
274                tracing::debug!(error = %format!("{error:#}"), "UNSUBSCRIBE failed");
275            }
276        });
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use serde_json::json;
283
284    use super::*;
285    use crate::test_support::{TEST_TIMEOUT, TestRelay};
286
287    fn remote(session: &crate::Session) -> RemoteBroadcast {
288        RemoteBroadcast::new(
289            session.client().clone(),
290            vec!["anon".into(), "remote".into()],
291        )
292    }
293
294    #[tokio::test]
295    async fn catalogs_start_from_the_one_the_relay_holds_and_skip_one_that_does_not_parse() {
296        // Arrange
297        let relay = TestRelay::spawn("catalogs");
298        let session = relay.connect().await;
299        let catalog = json!({"version": "draft-02", "tracks": []}).to_string();
300        relay
301            .write("anon/remote", "catalog", catalog.as_bytes(), true)
302            .await;
303        let mut catalogs = remote(&session).catalogs().await.unwrap();
304
305        // Act
306        let first = tokio::time::timeout(TEST_TIMEOUT, catalogs.next()).await;
307        relay
308            .write("anon/remote", "catalog", b"not json", true)
309            .await;
310        relay
311            .write("anon/remote", "catalog", catalog.as_bytes(), true)
312            .await;
313        let second = tokio::time::timeout(TEST_TIMEOUT, catalogs.next()).await;
314
315        // Assert
316        assert!(first.unwrap().unwrap().is_some());
317        assert!(second.unwrap().unwrap().is_some());
318    }
319
320    #[tokio::test]
321    async fn follow_yields_the_objects_written_after_it_subscribed() {
322        // Arrange
323        let relay = TestRelay::spawn("follow");
324        let session = relay.connect().await;
325        relay.write("anon/remote", "status", b"old", true).await;
326        let mut followed = remote(&session).follow("status", FollowOptions::default());
327
328        // Act: write until the subscription receives an object; it starts after the largest object
329        let object = tokio::time::timeout(TEST_TIMEOUT, async {
330            let next = followed.next();
331            tokio::pin!(next);
332            loop {
333                tokio::select! {
334                    object = &mut next => return object,
335                    _ = tokio::time::sleep(Duration::from_millis(50)) => {
336                        relay.write("anon/remote", "status", b"new", true).await;
337                    }
338                }
339            }
340        })
341        .await
342        .unwrap();
343
344        // Assert
345        assert_eq!(object.payload.as_ref(), b"new");
346    }
347
348    #[tokio::test]
349    async fn an_event_timeline_starts_with_the_records_the_relay_keeps() {
350        // Arrange
351        let relay = TestRelay::spawn("remote-event-timeline");
352        let session = relay.connect().await;
353        relay.write("anon/remote", "events", b"[]", true).await;
354        relay
355            .write("anon/remote", "events", br#"[{"T":1,"data":"a"}]"#, false)
356            .await;
357        let mut timeline =
358            remote(&session).event_timeline("events", EventTimelineOptions::default());
359
360        // Act
361        let kept = tokio::time::timeout(TEST_TIMEOUT, timeline.next())
362            .await
363            .unwrap();
364        relay
365            .write("anon/remote", "events", br#"[{"T":2,"data":"b"}]"#, false)
366            .await;
367        let later = tokio::time::timeout(TEST_TIMEOUT, timeline.next())
368            .await
369            .unwrap();
370
371        // Assert
372        assert_eq!(kept, json!({"T": 1, "data": "a"}));
373        assert_eq!(later, json!({"T": 2, "data": "b"}));
374    }
375}