Skip to main content

moq_net/model/
announced.rs

1//! The paths announced under a scope, each present or absent.
2
3use std::task::Poll;
4
5use super::origin_impl::{Announce, RouteEvent, RouteKind, Routes};
6use crate::{Error, Path};
7
8/// What an announcement listing reports for a path.
9#[derive(Clone, Debug)]
10#[non_exhaustive]
11pub enum AnnounceEvent {
12	/// A route now covers the path, which was absent. It may arrive unavailable; see
13	/// [`RouteInfo::available`](crate::origin::RouteInfo::available).
14	Present(Announce),
15	/// No route covers the path any more, whether its origin withdrew it or this side let
16	/// go of it. Carries its last advertised route.
17	Absent(Announce),
18}
19
20/// The paths announced in a scope, each reported as it becomes present or absent.
21///
22/// A path that another identity takes over stays present, and a route's metadata,
23/// availability included, changing is not reported: hold a
24/// [`follow`](crate::origin::Consumer::follow) to see the broadcast change. Created by
25/// [`Consumer::announced`](crate::origin::Consumer::announced). Drop to unregister.
26pub struct AnnounceConsumer {
27	routes: Routes,
28}
29
30impl AnnounceConsumer {
31	pub(super) fn new(routes: Routes) -> Self {
32		Self { routes }
33	}
34
35	/// What a route change means for the listing, if anything.
36	fn list(event: RouteEvent) -> Option<AnnounceEvent> {
37		let RouteEvent { kind, announce } = event;
38		match kind {
39			RouteKind::Start => Some(AnnounceEvent::Present(announce)),
40			RouteKind::Update | RouteKind::Restart => None,
41			RouteKind::End | RouteKind::Offline => Some(AnnounceEvent::Absent(announce)),
42		}
43	}
44
45	/// Returns the next path that became present or absent, relative to this listing's root.
46	///
47	/// Returns None once the origin closes. The consumer is also a [`futures::Stream`]
48	/// of the same events.
49	#[cfg(feature = "async")]
50	pub async fn next(&mut self) -> Option<AnnounceEvent> {
51		kio::wait(|waiter| self.poll_next(waiter)).await
52	}
53
54	/// Poll for the next event, registering `waiter` when there is none yet.
55	///
56	/// Returns `Poll::Ready(None)` once the origin closes.
57	pub fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<Option<AnnounceEvent>> {
58		loop {
59			let Some(event) = std::task::ready!(self.routes.poll_next(waiter)) else {
60				return Poll::Ready(None);
61			};
62			if let Some(event) = Self::list(event) {
63				return Poll::Ready(Some(event));
64			}
65		}
66	}
67
68	/// Returns the next event without blocking.
69	///
70	/// Returns None if there is no event available; NOT because the listing is closed.
71	/// Use [`Self::is_closed`] to check if the listing is closed.
72	pub fn try_next(&mut self) -> Option<AnnounceEvent> {
73		loop {
74			let event = self.routes.try_next()?;
75			if let Some(event) = Self::list(event) {
76				return Some(event);
77			}
78		}
79	}
80
81	/// Returns true if the listing is closed (no more events will arrive).
82	pub fn is_closed(&self) -> bool {
83		self.routes.is_closed()
84	}
85
86	/// Wait until this listing has synced with what its sources announced.
87	///
88	/// Synced means every session feeding this scope has delivered its peer's
89	/// announcements as of when it answered, and this listing has read every event
90	/// queued before then. A path not present by then is absent, rather than not heard
91	/// yet. A session joining the scope later, such as a reconnect, takes this back
92	/// until it syncs too; routes published on this origin itself never wait.
93	///
94	/// Level-triggered: ready whenever synced, and once the listing is closed.
95	pub fn poll_synced(&self, waiter: &kio::Waiter) -> Poll<()> {
96		self.routes.poll_synced(waiter)
97	}
98
99	/// Returns the root that is automatically stripped from reported paths.
100	pub fn root(&self) -> &Path {
101		self.routes.root()
102	}
103
104	/// Converts a reported path back to one rooted at the origin.
105	pub fn absolute(&self, prefix: impl TryInto<Path, Error: Into<Error>>) -> Result<Path, Error> {
106		self.routes.absolute(prefix)
107	}
108}
109
110#[cfg(feature = "async")]
111impl futures::Stream for AnnounceConsumer {
112	type Item = AnnounceEvent;
113
114	fn poll_next(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Option<Self::Item>> {
115		let this = self.get_mut();
116		loop {
117			let Some(event) = std::task::ready!(futures::Stream::poll_next(std::pin::Pin::new(&mut this.routes), cx))
118			else {
119				return Poll::Ready(None);
120			};
121			if let Some(event) = Self::list(event) {
122				return Poll::Ready(Some(event));
123			}
124		}
125	}
126}
127
128#[cfg(all(test, feature = "async"))]
129mod tests {
130	use std::time::Duration;
131
132	use super::super::ProduceTest;
133	use super::*;
134	use crate::{
135		Hop, Identity,
136		origin::{Cost, RouteInfo, RouteOptions},
137	};
138
139	/// The listing's next event as `present path` or `absent path`, within the update hold.
140	async fn listed(announced: &mut AnnounceConsumer) -> String {
141		let event = kio::clock::timeout(Duration::from_secs(1), announced.next())
142			.await
143			.expect("no event")
144			.expect("the origin closed");
145		match event {
146			AnnounceEvent::Present(announce) => format!("present {}", announce.prefix),
147			AnnounceEvent::Absent(announce) => format!("absent {}", announce.prefix),
148		}
149	}
150
151	/// The listing stays quiet past the origin's update hold.
152	async fn quiet(announced: &mut AnnounceConsumer) {
153		if let Ok(event) = kio::clock::timeout(Duration::from_secs(1), announced.next()).await {
154			panic!("expected nothing, got {event:?}");
155		}
156	}
157
158	fn route(identity: &Identity) -> RouteOptions {
159		RouteOptions::default().with_identity(identity.clone(), 0)
160	}
161
162	/// A path stays present while another identity takes it over or its route changes, and is
163	/// absent only once nothing covers it.
164	#[kio::test]
165	async fn a_path_stays_present_across_identities() {
166		let origin = Hop::new(1).unwrap().produce();
167		let mut announced = origin.consume().announced();
168		let mut routes = origin.consume().routes();
169
170		let first = origin.route("live", route(&Identity::random())).unwrap();
171		assert_eq!(listed(&mut announced).await, "present live");
172		assert!(matches!(
173			routes.next().await,
174			Some(RouteEvent {
175				kind: RouteKind::Start,
176				..
177			})
178		));
179
180		first
181			.announce_info(
182				RouteInfo::new()
183					.with_identity(Identity::random(), 0)
184					.with_cost(Cost::new(5)),
185			)
186			.unwrap();
187		quiet(&mut announced).await;
188		// The relay-level stream still reports the replacement.
189		assert!(matches!(
190			routes.next().await,
191			Some(RouteEvent {
192				kind: RouteKind::Restart,
193				..
194			})
195		));
196
197		let second = origin.route("live", route(&Identity::random())).unwrap();
198		drop(first);
199		quiet(&mut announced).await;
200
201		drop(second);
202		assert_eq!(listed(&mut announced).await, "absent live");
203	}
204
205	/// A held route keeps its path present and quiet as its availability flips; a session
206	/// letting go of a route and a peer withdrawing it both leave the path absent.
207	#[kio::test]
208	async fn availability_is_quiet_and_offline_is_absent() {
209		let origin = Hop::new(1).unwrap().produce();
210		let mut announced = origin.consume().announced();
211		let identity = Identity::random();
212		let held = RouteInfo::new()
213			.with_identity(identity.clone(), 0)
214			.with_available(false);
215
216		let lost = origin.forward("lost", held.clone()).unwrap();
217		assert_eq!(listed(&mut announced).await, "present lost");
218		lost.update(held.clone().with_cost(Cost::new(3))).unwrap();
219		quiet(&mut announced).await;
220		lost.update(held.clone().with_available(true)).unwrap();
221		quiet(&mut announced).await;
222		lost.update(held.clone()).unwrap();
223		quiet(&mut announced).await;
224		drop(lost);
225		assert_eq!(listed(&mut announced).await, "absent lost");
226
227		let ended = origin.forward("ended", held.with_available(true)).unwrap();
228		assert_eq!(listed(&mut announced).await, "present ended");
229		ended.withdrawn();
230		assert_eq!(listed(&mut announced).await, "absent ended");
231
232		// A route published here ends with its handle.
233		let local = origin.route("local", route(&identity)).unwrap();
234		assert_eq!(listed(&mut announced).await, "present local");
235		drop(local);
236		assert_eq!(listed(&mut announced).await, "absent local");
237	}
238}