moq_net/model/
announced.rs1use std::task::Poll;
4
5use super::origin_impl::{Announce, RouteEvent, RouteKind, Routes};
6use crate::{Error, Path};
7
8#[derive(Clone, Debug)]
10#[non_exhaustive]
11pub enum AnnounceEvent {
12 Present(Announce),
15 Absent(Announce),
18}
19
20pub struct AnnounceConsumer {
27 routes: Routes,
28}
29
30impl AnnounceConsumer {
31 pub(super) fn new(routes: Routes) -> Self {
32 Self { routes }
33 }
34
35 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 #[cfg(feature = "async")]
50 pub async fn next(&mut self) -> Option<AnnounceEvent> {
51 kio::wait(|waiter| self.poll_next(waiter)).await
52 }
53
54 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 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 pub fn is_closed(&self) -> bool {
83 self.routes.is_closed()
84 }
85
86 pub fn poll_synced(&self, waiter: &kio::Waiter) -> Poll<()> {
96 self.routes.poll_synced(waiter)
97 }
98
99 pub fn root(&self) -> &Path {
101 self.routes.root()
102 }
103
104 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 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 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 #[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 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 #[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 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}