Skip to main content

moq_mux/
linger.rs

1//! Keeping a cleanly ended broadcast up for subscribers that arrive late.
2
3use std::{pin::Pin, task::Poll, time::Duration};
4
5/// Keeps cleanly ended broadcasts announced, serving their finished tracks, for a fixed
6/// duration, then closes them.
7///
8/// Subscribers already reading a track get its tail when the broadcast closes; this serves
9/// the ones that arrive after the end, such as a relay or player that read the final catalog
10/// late. Finish the catalog and media tracks first, then hand over the broadcasts and
11/// `owner`, whatever holds their routes and track producers: a broadcast stays announced only
12/// while its [`Route`](moq_net::origin::Route) lives, and a finished track stops being served
13/// once its producers drop, so the owner drops only after the broadcasts close.
14///
15/// The deadline is fixed at [`new`](Self::new), however late [`poll_wait`](Self::poll_wait) is
16/// first polled. Dropping the handle closes the broadcasts at once, which is how an interrupt
17/// ends it. A newer publisher announced at the same path does not end it: that one wins the
18/// path while it is up, and readers that come back here find the finished catalog.
19#[must_use = "dropping a Linger closes its broadcasts at once"]
20pub struct Linger<T> {
21	broadcasts: Vec<moq_net::broadcast::Producer>,
22	// Dropped after `Drop::drop` closes the broadcasts.
23	_owner: T,
24	// `None` when the duration overflows the clock, so only an interrupt ends it.
25	deadline: Option<kio::clock::Instant>,
26	// Armed at the deadline, created on first poll.
27	timer: Option<kio::clock::Sleep>,
28}
29
30impl Linger<()> {
31	/// How long a publisher keeps a cleanly ended broadcast up unless configured otherwise.
32	///
33	/// Matches the default media max-age and a relay's idle track copy.
34	pub const DEFAULT: Duration = Duration::from_secs(30);
35}
36
37impl<T> Linger<T> {
38	/// Keep `broadcasts` up for `duration` from now, holding `owner` until they close.
39	///
40	/// A zero `duration` is due on the first poll.
41	pub fn new(
42		broadcasts: impl IntoIterator<Item = moq_net::broadcast::Producer>,
43		owner: T,
44		duration: Duration,
45	) -> Self {
46		Self {
47			broadcasts: broadcasts.into_iter().collect(),
48			_owner: owner,
49			deadline: kio::clock::now().checked_add(duration),
50			timer: None,
51		}
52	}
53
54	/// Poll until the deadline passes on the ambient clock; drop the handle then to close the
55	/// broadcasts.
56	pub fn poll_wait(&mut self, waiter: &kio::Waiter) -> Poll<()> {
57		let Some(deadline) = self.deadline else {
58			return Poll::Pending;
59		};
60		let timer = self.timer.get_or_insert_with(|| kio::clock::sleep_until(deadline));
61		waiter.poll_future(Pin::new(timer))
62	}
63
64	/// Wait for the deadline on the ambient clock, then close the broadcasts.
65	///
66	/// Hand-written rather than generated, since it consumes the handle to close them.
67	#[cfg(feature = "async")]
68	pub async fn wait(mut self) {
69		kio::wait(|waiter| self.poll_wait(waiter)).await
70	}
71}
72
73impl<T> Drop for Linger<T> {
74	fn drop(&mut self) {
75		// Closed before the owner drops, so no lookup finds the broadcast without its tracks.
76		for broadcast in &self.broadcasts {
77			broadcast.close();
78		}
79	}
80}
81
82#[cfg(test)]
83mod tests {
84	use super::*;
85	use moq_net::frame::Frame;
86
87	const PATH: &str = "live";
88
89	/// A broadcast at [`PATH`] whose one track, `video`, has three finished groups, and the
90	/// owner holding its route and track. It declares media's max age, so its superseded groups
91	/// stay fetchable as long as the default linger.
92	fn finished(
93		origin: &moq_net::origin::Producer,
94	) -> (
95		moq_net::broadcast::Producer,
96		(moq_net::origin::Route, moq_net::track::Finished),
97	) {
98		let route = origin.route(PATH, moq_net::origin::RouteOptions::default()).unwrap();
99		let info = moq_net::track::Info::default().with_max_age(hang::container::MAX_AGE);
100		let track = route.broadcast().create_track("video", info).unwrap();
101		for start in 0..3 {
102			let group = track
103				.append_group(Frame::new(
104					moq_net::Timestamp::unscaled(start),
105					bytes::Bytes::from_static(b"frame"),
106				))
107				.unwrap();
108			group.finish().unwrap();
109		}
110		let track = track.finish().unwrap();
111		(route.broadcast().clone(), (route, track))
112	}
113
114	/// Whether the origin has stopped routing [`PATH`].
115	async fn unroutable(origin: &moq_net::origin::Producer) -> bool {
116		matches!(
117			origin.consume().request(PATH, None).await,
118			Err(moq_net::Error::Unroutable)
119		)
120	}
121
122	/// A subscriber arriving just before the deadline gets every group, the latest by
123	/// subscribing and the earlier ones by fetching, and the path stops routing once it passes.
124	#[tokio::test(start_paused = true)]
125	async fn a_late_subscriber_drains_the_tail_until_the_deadline() {
126		let origin = crate::source::produce_origin();
127		let (broadcast, owner) = finished(&origin);
128		let start = kio::clock::now();
129		let linger = tokio::spawn(Linger::new([broadcast], owner, Duration::from_secs(30)).wait());
130
131		kio::clock::sleep(Duration::from_secs(29)).await;
132		let late = origin.consume().request(PATH, None).await.unwrap();
133		let video = late.track("video").unwrap();
134		for sequence in 0..3 {
135			let mut group = video.fetch_group(sequence, None).await.unwrap();
136			let frame = group.read_frame().await.unwrap().expect("a frame");
137			assert_eq!(frame.payload.as_ref(), b"frame");
138		}
139		let mut live = video.subscribe(None).await.unwrap();
140		assert!(live.recv_group().await.unwrap().is_some(), "the latest group");
141		assert!(
142			live.recv_group().await.unwrap().is_none(),
143			"the track ends after its tail"
144		);
145
146		linger.await.unwrap();
147		assert_eq!(kio::clock::now() - start, Duration::from_secs(30));
148		assert!(unroutable(&origin).await);
149	}
150
151	/// The deadline counts from the end of the content, not from when the wait is polled.
152	#[tokio::test(start_paused = true)]
153	async fn the_deadline_is_fixed_at_the_end() {
154		let origin = crate::source::produce_origin();
155		let (broadcast, owner) = finished(&origin);
156		let start = kio::clock::now();
157		let linger = Linger::new([broadcast], owner, Duration::from_secs(30));
158
159		kio::clock::sleep(Duration::from_secs(20)).await;
160		linger.wait().await;
161		assert_eq!(kio::clock::now() - start, Duration::from_secs(30));
162	}
163
164	/// Dropping the handle, as an interrupt does, closes the broadcast at once.
165	#[tokio::test(start_paused = true)]
166	async fn dropping_closes_at_once() {
167		let origin = crate::source::produce_origin();
168		let (broadcast, owner) = finished(&origin);
169		let linger = Linger::new([broadcast], owner, Duration::from_secs(30));
170		assert!(!unroutable(&origin).await);
171
172		drop(linger);
173		assert!(unroutable(&origin).await);
174	}
175}