Skip to main content

moq_mux/
follow.rs

1//! Following a catalog rendition's broadcast across the publisher identities that serve it.
2//!
3//! An announcement is the online and offline signal, so a reader that restarts on each identity
4//! follows [`Identities`] rather than pinning one broadcast as a [`Binding`](crate::Binding) does.
5
6use std::task::{Poll, ready};
7
8/// The publisher identities serving a rendition's broadcast, as each comes online, takes over,
9/// and goes. Created by [`Source::follow`](crate::Source::follow).
10///
11/// A sibling broadcast is followed through [`Following`](moq_net::origin::Following); the
12/// catalog's own broadcast is handed out once and its end never reported, since a reader
13/// follows its catalog's end itself.
14pub struct Identities(Feed);
15
16enum Feed {
17	/// Every identity announced at a path.
18	Following {
19		following: Box<moq_net::origin::Following>,
20		/// An identity was handed out and its end not reported yet.
21		live: bool,
22	},
23	/// One identity, handed out once.
24	Fixed(Option<moq_net::broadcast::Consumer>),
25}
26
27impl Identities {
28	/// Follow every identity announced at a path.
29	pub(crate) fn following(following: moq_net::origin::Following) -> Self {
30		Self(Feed::Following {
31			following: Box::new(following),
32			live: false,
33		})
34	}
35
36	pub(crate) fn fixed(broadcast: moq_net::broadcast::Consumer) -> Self {
37		Self(Feed::Fixed(Some(broadcast)))
38	}
39
40	/// The next change.
41	///
42	/// Returns each identity as it comes online or takes over, and `None` once the path goes
43	/// offline; see
44	/// [`Following::available`](moq_net::origin::Following::available). Fails once the origin
45	/// closes, and with any resolution failure, such as a handler refusing the path; the call
46	/// after a refusal waits for the serving route to change.
47	#[cfg_attr(feature = "async", kio::wrapper)]
48	pub fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<crate::Result<Option<moq_net::broadcast::Consumer>>> {
49		let (following, live) = match &mut self.0 {
50			Feed::Following { following, live } => (following, live),
51			Feed::Fixed(broadcast) => {
52				return match broadcast.take() {
53					Some(broadcast) => Poll::Ready(Ok(Some(broadcast))),
54					None => Poll::Pending,
55				};
56			}
57		};
58		loop {
59			if let Some(broadcast) = ready!(following.poll_available(waiter))? {
60				*live = true;
61				return Poll::Ready(Ok(Some(broadcast)));
62			}
63			// Report the end of what was handed out once.
64			if std::mem::take(live) {
65				return Poll::Ready(Ok(None));
66			}
67		}
68	}
69}
70
71#[cfg(test)]
72mod tests {
73	use super::*;
74	use crate::source::{produce_origin, resolved};
75	use moq_net::path::Relative;
76
77	/// Let the origin's driver run the fronts that announcements started.
78	async fn settle() {
79		for _ in 0..10 {
80			tokio::task::yield_now().await;
81		}
82	}
83
84	fn route(identity: &moq_net::Identity) -> moq_net::origin::RouteOptions {
85		moq_net::origin::RouteOptions::default().with_identity(identity.clone(), 0)
86	}
87
88	/// The next change a follower reports, which must arrive within the origin's update hold.
89	async fn followed(follow: &mut Identities) -> Option<moq_net::broadcast::Consumer> {
90		kio::clock::timeout(std::time::Duration::from_secs(1), follow.next())
91			.await
92			.expect("no change")
93			.expect("the follow failed")
94	}
95
96	/// The follower stays quiet past the origin's update hold.
97	async fn quiet(follow: &mut Identities) {
98		if kio::clock::timeout(std::time::Duration::from_secs(1), follow.next())
99			.await
100			.is_ok()
101		{
102			panic!("expected no change");
103		}
104	}
105
106	/// A sibling announced after the follow starts it, its end idles it, and its return starts
107	/// it again.
108	#[tokio::test(start_paused = true)]
109	async fn a_follow_starts_late_and_survives_an_end() {
110		let origin = produce_origin();
111		let _catalog = origin.route("a/pub", Default::default()).unwrap();
112		settle().await;
113		let source = resolved(&origin, "a/pub").await;
114		let mut follow = source.follow(Some(&Relative::new("./source").unwrap())).unwrap();
115		quiet(&mut follow).await;
116
117		let first = origin.route("a/source", Default::default()).unwrap();
118		let started = followed(&mut follow).await.expect("a start");
119		assert_eq!(started.info().path.as_str(), "a/source");
120
121		drop(first);
122		assert!(followed(&mut follow).await.is_none(), "an end");
123		quiet(&mut follow).await;
124
125		let _second = origin.route("a/source", Default::default()).unwrap();
126		let restarted = followed(&mut follow).await.expect("a start");
127		assert!(!restarted.is_clone(&started));
128	}
129
130	/// A replacement restarts the follow, and its end hands the old identity out again.
131	#[tokio::test(start_paused = true)]
132	async fn a_follow_restarts_on_a_replacement() {
133		let origin = produce_origin();
134		let (old_identity, new_identity) = (moq_net::Identity::random(), moq_net::Identity::random());
135		let _catalog = origin.route("a/pub", Default::default()).unwrap();
136		let _old = origin.route("a/source", route(&old_identity)).unwrap();
137		settle().await;
138		let source = resolved(&origin, "a/pub").await;
139		let rel = Relative::new("./source").unwrap();
140		let mut follow = source.follow(Some(&rel)).unwrap();
141		let old = followed(&mut follow).await.unwrap();
142		assert_eq!(old.info().identity.as_ref(), Some(&old_identity));
143
144		let new = origin.route("a/source", route(&new_identity)).unwrap();
145		let replaced = followed(&mut follow).await.unwrap();
146		assert_eq!(replaced.info().identity.as_ref(), Some(&new_identity));
147		// The old identity still serves the subscriptions already on it.
148		assert!(!old.is_closed());
149
150		// The replacement goes and the old identity wins again.
151		drop(new);
152		let back = followed(&mut follow).await.unwrap();
153		assert_eq!(back.info().identity.as_ref(), Some(&old_identity));
154	}
155
156	/// A self-reference reads only the catalog identity, whatever replaces it at the path.
157	#[tokio::test(start_paused = true)]
158	async fn a_follow_of_the_catalog_keeps_its_identity() {
159		let origin = produce_origin();
160		let old = origin.route("a/pub", Default::default()).unwrap();
161		settle().await;
162		let source = resolved(&origin, "a/pub").await;
163		let mut follow = source.follow(Some(&Relative::new("./pub").unwrap())).unwrap();
164		assert!(followed(&mut follow).await.unwrap().is_clone(&source.broadcast()));
165
166		let _new = origin.route("a/pub", Default::default()).unwrap();
167		quiet(&mut follow).await;
168		// Its end is the catalog's, which the catalog's reader sees.
169		drop(old);
170		quiet(&mut follow).await;
171	}
172}