Skip to main content

moq_net/model/
follow.rs

1use std::task::{Poll, ready};
2
3use super::WeakEntry;
4use super::origin_impl::{Announce, Consumer, Moved, Requesting, RouteEvent, RouteKind, Routes};
5use crate::{Error, Identity, Path, broadcast};
6
7/// The announcements covering one path, as one broadcast coming online, being replaced, and
8/// going offline. Created by [`Consumer::routes`].
9///
10/// Several routes can cover the path at once, such as the path itself and a prefix above it,
11/// and the cursor is rooted at the path, so it presents only the one a request resolves through,
12/// ranked as a request ranks them. Another route taking over is a
13/// [`Restart`](RouteKind::Restart), unless both carry the same identity: those serve one
14/// continuous stream, so it is an [`Update`](RouteKind::Update), as for a job's route
15/// continuing the prefix route it answered. An end followed by a start is a gap that ended any
16/// request on the old route, even when both routes carry one identity. Routes beneath the path
17/// serve other broadcasts and are ignored.
18pub(crate) struct Follow {
19	announced: Routes,
20	/// The route serving the path, as last reported.
21	serving: Option<Announce>,
22}
23
24impl Follow {
25	pub(super) fn new(announced: Routes) -> Self {
26		Self {
27			announced,
28			serving: None,
29		}
30	}
31
32	/// The next change to the route serving the path, or `None` once the origin closes.
33	#[cfg(all(test, feature = "async"))]
34	pub async fn next(&mut self) -> Option<RouteEvent> {
35		kio::wait(|waiter| self.poll_next(waiter)).await
36	}
37
38	/// Poll for the next change, registering `waiter` when there is none yet.
39	pub fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<Option<RouteEvent>> {
40		loop {
41			let Some(event) = ready!(self.announced.poll_next(waiter)) else {
42				return Poll::Ready(None);
43			};
44			if let Some(event) = self.fold(event) {
45				return Poll::Ready(Some(event));
46			}
47		}
48	}
49
50	/// Poll until every source feeding this follower has synced, registering `waiter` until
51	/// then. A path [`poll_next`](Self::poll_next) has not started by then is not announced,
52	/// rather than not heard yet. See [`Routes::poll_synced`].
53	pub fn poll_synced(&self, waiter: &kio::Waiter) -> Poll<()> {
54		self.announced.poll_synced(waiter)
55	}
56
57	/// The route serving the path, which is the one a request resolves.
58	fn serving(&self) -> Option<&Announce> {
59		self.serving.as_ref()
60	}
61
62	/// Apply one event of the cursor, returning what it means for the path, if anything.
63	fn fold(&mut self, event: RouteEvent) -> Option<RouteEvent> {
64		// Every claim covering the path presents at the cursor's root.
65		if !event.announce.prefix.is_empty() {
66			return None;
67		}
68		let kind = match (event.kind, &self.serving) {
69			(RouteKind::End | RouteKind::Offline, None) => return None,
70			(kind @ (RouteKind::End | RouteKind::Offline), Some(_)) => {
71				self.serving = None;
72				kind
73			}
74			(_, None) => RouteKind::Start,
75			(RouteKind::Start, Some(before)) => match before.route.identity == event.announce.route.identity {
76				true => RouteKind::Update,
77				false => RouteKind::Restart,
78			},
79			(kind, Some(_)) => kind,
80		};
81		if !matches!(kind, RouteKind::End | RouteKind::Offline) {
82			self.serving = Some(event.announce.clone());
83		}
84		Some(RouteEvent {
85			kind,
86			announce: event.announce,
87		})
88	}
89}
90
91/// Each identity serving one path, handed out as it takes over. Created by
92/// [`Consumer::follow`](crate::origin::Consumer::follow).
93pub struct Following {
94	consumer: Consumer,
95	path: Path,
96	/// The only identity handed out, if pinned.
97	identity: Option<Identity>,
98	follow: Follow,
99	/// An identity serves the path that was not handed out yet.
100	unseen: bool,
101	/// The resolution in flight, kept across a dropped wait so a retry picks it up.
102	resolving: Option<Requesting>,
103	/// The broadcast handed out last, until the path goes offline, the broadcast ends, or a
104	/// resolution is refused.
105	last: Option<Last>,
106	/// Whether the end of what was handed out is still to be reported.
107	handed: Handed,
108	/// The last resolution was refused: any change to the serving route, even the same
109	/// identity over another route, is worth asking again.
110	refused: bool,
111}
112
113/// The broadcast a [`Following`] handed out last, and what it waits on once that closes.
114struct Last {
115	/// Weak, so it never keeps one the caller let go of from retiring.
116	broadcast: broadcast::WeakConsumer,
117	/// Once the broadcast closed, waits for its identity to stop serving the path.
118	moved: Option<Moved>,
119	/// A change resolved to this broadcast while it was still open, so it counts as delivered
120	/// only until the broadcast closes.
121	absorbed: bool,
122}
123
124/// Whether a [`Following`] owes the end of the broadcast it handed out.
125#[derive(Clone, Copy, PartialEq, Eq)]
126enum Handed {
127	/// Nothing handed out, or its end already reported.
128	Nothing,
129	/// A broadcast was handed out and its end is not yet due, even if a refused takeover means
130	/// it no longer serves the path.
131	Live,
132	/// The broadcast handed out stopped serving the path, and its end is owed.
133	Ended,
134}
135
136impl Following {
137	pub(super) fn new(consumer: Consumer, path: Path, identity: Option<Identity>, follow: Follow) -> Self {
138		Self {
139			consumer,
140			path,
141			identity,
142			follow,
143			unseen: false,
144			resolving: None,
145			last: None,
146			handed: Handed::Nothing,
147			refused: false,
148		}
149	}
150
151	/// The next change to the identity serving the path; see
152	/// [`Consumer::follow`](crate::origin::Consumer::follow).
153	///
154	/// Returns the broadcast of each identity as it comes online or takes over, and `None`
155	/// once the path the one handed out last served goes offline, or, when pinned, another
156	/// identity takes it over. Returns [`Error::Closed`] once the origin closes, and any other
157	/// resolution failure as-is, such as a handler refusing the path; the next call then waits
158	/// for the serving route to change, even to another route of the same identity, instead of
159	/// asking the refusing route again. An abandoned wait keeps its progress for the next call.
160	#[cfg_attr(feature = "async", kio::wrapper)]
161	pub fn poll_available(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<broadcast::Consumer>, Error>> {
162		loop {
163			// Apply every change on hand before reading an answer, so a burst of them hands out
164			// only the identity serving the path now. A resolution in flight answers for the
165			// routes before the change, such as an end and a start for the identity it resolved,
166			// so it starts over.
167			if self.settle(waiter)? {
168				self.resolving = None;
169			}
170			// Report an end before whatever serves next, so a reader drops the old broadcast first.
171			if self.handed == Handed::Ended {
172				self.handed = Handed::Nothing;
173				return Poll::Ready(Ok(None));
174			}
175			// The broadcast handed out ended while the path is still served: its identity's
176			// routes may have gone, and another identity's, beneath the same announcement,
177			// taken the path over. It also ends once the caller lets go of it, so only its
178			// identity no longer serving the path makes whatever serves it now next, unless a
179			// change it absorbed is owed. A refusal forgets it, so only a route change asks again.
180			if !self.unseen
181				&& self.follow.serving().is_some()
182				&& let Some(last) = &mut self.last
183				&& let broadcast = last.broadcast.consume()
184				&& broadcast.poll_closed(waiter).is_ready()
185			{
186				let moved = match &broadcast.info().identity {
187					_ if last.absorbed => true,
188					Some(identity) => last
189						.moved
190						.get_or_insert_with(|| {
191							self.consumer
192								.moved(self.path.clone(), identity.clone(), self.identity.is_some())
193						})
194						.poll(waiter)
195						.is_ready(),
196					None => true,
197				};
198				if moved {
199					last.moved = None;
200					self.unseen = true;
201				}
202			}
203			if !self.unseen {
204				return Poll::Pending;
205			}
206
207			let resolving = self
208				.resolving
209				.get_or_insert_with(|| self.consumer.routing(self.path.clone(), self.identity.clone()));
210			let resolved = ready!(kio::Task::poll(resolving, waiter));
211			self.resolving = None;
212			// Handed out or refused, this announcement is settled: after a refusal, the next
213			// call waits for the serving route to change rather than asking it again. That
214			// includes the broadcast handed out last moving off the path, which led here.
215			self.unseen = false;
216			self.refused = resolved.is_err();
217			let broadcast = match resolved {
218				Ok(broadcast) => broadcast,
219				// `handed` stays: the end of what was handed out is still owed once the path goes
220				// offline.
221				Err(err) => {
222					self.last = None;
223					return Poll::Ready(Err(err));
224				}
225			};
226
227			// Resolving can run ahead of the follower: another identity resolves at once while
228			// the origin holds its restart, and that restart then names the identity handed
229			// out. The caller freeing it before reading the restart is owed it again.
230			let weak = broadcast.weak();
231			if let Some(last) = &mut self.last
232				&& last.broadcast.same_channel(&weak)
233			{
234				last.absorbed = true;
235				continue;
236			}
237			self.last = Some(Last {
238				broadcast: weak,
239				moved: None,
240				absorbed: false,
241			});
242			self.handed = Handed::Live;
243			return Poll::Ready(Ok(Some(broadcast)));
244		}
245	}
246
247	/// Apply every change on hand, returning whether any came through.
248	fn settle(&mut self, waiter: &kio::Waiter) -> Result<bool, Error> {
249		let mut changed = false;
250		while let Poll::Ready(event) = self.follow.poll_next(waiter) {
251			changed |= self.apply(event.ok_or(Error::Closed)?);
252		}
253		Ok(changed)
254	}
255
256	/// The broadcast handed out last stopped serving the path: owe its end, and hand out
257	/// whatever serves next, even the same identity coming back.
258	fn end(&mut self) {
259		if self.handed == Handed::Live {
260			self.handed = Handed::Ended;
261		}
262		self.last = None;
263	}
264
265	/// Apply one change to the path, returning whether it is one.
266	fn apply(&mut self, event: RouteEvent) -> bool {
267		match event {
268			// Another identity taking over ends a pinned follower's own stream, which is handed
269			// out again once it serves the path again.
270			RouteEvent {
271				kind: RouteKind::Restart,
272				announce,
273			} if self
274				.identity
275				.as_ref()
276				.is_some_and(|pin| announce.route.identity.as_ref() != Some(pin)) =>
277			{
278				self.end();
279				return false;
280			}
281			// A pinned resolution refuses any other identity, waiting until its own serves again.
282			RouteEvent {
283				kind: RouteKind::Start | RouteKind::Restart,
284				..
285			} => self.unseen = true,
286			// An end is a gap that ended every request on the old route, so whatever serves the
287			// path next is handed out, even the same identity coming back.
288			RouteEvent {
289				kind: RouteKind::End | RouteKind::Offline,
290				..
291			} => {
292				self.unseen = false;
293				self.end();
294			}
295			// After a refusal, another route may answer what the last one refused.
296			RouteEvent {
297				kind: RouteKind::Update,
298				..
299			} if self.refused => self.unseen = true,
300			// The same identity over another route, which its subscriptions ride out.
301			RouteEvent {
302				kind: RouteKind::Update,
303				..
304			} => return false,
305		}
306		true
307	}
308}
309
310#[cfg(all(test, feature = "async"))]
311mod tests {
312	use std::time::Duration;
313
314	use super::super::ProduceTest;
315	use super::*;
316	use crate::{
317		Error, Hop, Identity, Prefix, Prefixes,
318		origin::{Cost, RouteInfo, RouteOptions},
319	};
320
321	/// The follower's next event, which must arrive within a second, and the cost of the route
322	/// it names, which tells the tests' routes apart.
323	async fn followed(follow: &mut Follow) -> (&'static str, u64) {
324		let event = kio::clock::timeout(Duration::from_secs(1), follow.next())
325			.await
326			.expect("no event")
327			.expect("the origin closed");
328		let kind = match event.kind {
329			RouteKind::Start => "start",
330			RouteKind::Update => "update",
331			RouteKind::Restart => "restart",
332			RouteKind::End => "end",
333			RouteKind::Offline => "offline",
334		};
335		(kind, event.announce.route.cost.value())
336	}
337
338	/// The follower stays quiet for a second.
339	async fn quiet(follow: &mut Follow) {
340		if let Ok(event) = kio::clock::timeout(Duration::from_secs(1), follow.next()).await {
341			panic!("expected nothing, got {event:?}");
342		}
343	}
344
345	fn route(identity: &Identity) -> RouteInfo {
346		RouteInfo::new().with_identity(identity.clone(), 0)
347	}
348
349	fn options(identity: &Identity) -> RouteOptions {
350		RouteOptions::default().with_identity(identity.clone(), 0)
351	}
352
353	#[kio::test]
354	async fn follow_reports_the_route_serving_the_path() {
355		let origin = Hop::new(1).unwrap().produce();
356		let mut follow = origin.consume().path_routes("pool/job").unwrap();
357		let identity = Identity::random();
358
359		// A prefix above the path covers it.
360		let pool = origin.forward("pool", route(&identity).with_cost(1)).unwrap();
361		assert_eq!(followed(&mut follow).await, ("start", 1));
362
363		// A route beneath the path serves another broadcast.
364		let _beneath = origin.route("pool/job/thumbnail", RouteOptions::default()).unwrap();
365		quiet(&mut follow).await;
366
367		// The path itself, from the same identity, takes over without a restart.
368		let exact = origin.route("pool/job", options(&identity).with_cost(2)).unwrap();
369		assert_eq!(followed(&mut follow).await, ("update", 2));
370
371		// The covering prefix no longer serves the path, so its changes are not seen.
372		pool.update(pool.route().unwrap().with_cost(5)).unwrap();
373		quiet(&mut follow).await;
374
375		// Another identity at the path.
376		exact.announce_info(route(&Identity::random()).with_cost(2)).unwrap();
377		assert_eq!(followed(&mut follow).await, ("restart", 2));
378
379		// It goes, so the prefix serves the path again: another identity.
380		drop(exact);
381		assert_eq!(followed(&mut follow).await, ("restart", 5));
382
383		pool.update(pool.route().unwrap().with_cost(9)).unwrap();
384		assert_eq!(followed(&mut follow).await, ("update", 9));
385
386		drop(pool);
387		assert_eq!(followed(&mut follow).await, ("offline", 9));
388	}
389
390	/// A follower that joins late starts on the route serving the path, not on whichever
391	/// covering route the replay happened to reach first.
392	#[kio::test]
393	async fn follow_starts_on_the_serving_route_when_joining_late() {
394		let origin = Hop::new(1).unwrap().produce();
395		let _pool = origin.forward("pool", RouteInfo::new().with_cost(1)).unwrap();
396		let _exact = origin.route("pool/job", RouteOptions::default().with_cost(2)).unwrap();
397
398		let mut follow = origin.consume().path_routes("pool/job").unwrap();
399		assert_eq!(followed(&mut follow).await, ("start", 2));
400		quiet(&mut follow).await;
401	}
402
403	/// A gap with nothing serving the path ends any request on it, so a covering route that
404	/// arrives after it is a start of its own, even under the same identity.
405	#[kio::test]
406	async fn follow_keeps_a_gap_between_routes_of_one_identity() {
407		let origin = Hop::new(1).unwrap().produce();
408		let identity = Identity::random();
409		let exact = origin.route("pool/job", options(&identity).with_cost(2)).unwrap();
410		let mut follow = origin.consume().path_routes("pool/job").unwrap();
411		assert_eq!(followed(&mut follow).await, ("start", 2));
412
413		// Both land before the follower reads again, but the path went unserved in between.
414		drop(exact);
415		let _pool = origin.forward("pool", route(&identity).with_cost(1)).unwrap();
416		assert_eq!(followed(&mut follow).await, ("end", 2));
417		assert_eq!(followed(&mut follow).await, ("start", 1));
418
419		// A prefix standing while the path's route goes takes over in place.
420		let exact = origin.route("pool/job", options(&identity).with_cost(2)).unwrap();
421		assert_eq!(followed(&mut follow).await, ("update", 2));
422		drop(exact);
423		assert_eq!(followed(&mut follow).await, ("update", 1));
424	}
425
426	/// A prefix that started before the serving route's last change stood before the route's
427	/// end, so it takes over in place even when the follower never read in between.
428	#[kio::test]
429	async fn follow_hands_over_to_a_prefix_that_started_before_the_last_change() {
430		let origin = Hop::new(1).unwrap().produce();
431		let exact = origin.route("pool/job", RouteOptions::default().with_cost(2)).unwrap();
432		let mut follow = origin.consume().path_routes("pool/job").unwrap();
433		assert_eq!(followed(&mut follow).await, ("start", 2));
434
435		let identity = Identity::random();
436		let _pool = origin.forward("pool", route(&identity).with_cost(1)).unwrap();
437		exact.announce_info(route(&identity).with_cost(2)).unwrap();
438		assert_eq!(followed(&mut follow).await, ("restart", 2));
439
440		drop(exact);
441		assert_eq!(followed(&mut follow).await, ("update", 1));
442	}
443
444	/// Under another identity nothing says two routes serve the same bytes.
445	#[kio::test]
446	async fn follow_restarts_onto_a_more_specific_route_under_another_identity() {
447		let origin = Hop::new(1).unwrap().produce();
448		let mut follow = origin.consume().path_routes("pool/job").unwrap();
449
450		let _pool = origin.forward("pool", RouteInfo::new().with_cost(1)).unwrap();
451		assert_eq!(followed(&mut follow).await, ("start", 1));
452
453		let _exact = origin.route("pool/job", RouteOptions::default().with_cost(2)).unwrap();
454		assert_eq!(followed(&mut follow).await, ("restart", 2));
455	}
456
457	/// A route whose claim covers only paths beneath the followed one never serves it, so it
458	/// cannot mask the route that does, even when it would win the prefix on cost.
459	#[kio::test]
460	async fn follow_ignores_a_route_scoped_beneath_the_path() {
461		let origin = Hop::new(1).unwrap().produce();
462		let chat = Prefixes::from(Prefix::try_from("room/alice/chat").unwrap());
463		let _chat = origin
464			.scope("", &chat)
465			.unwrap()
466			.forward("room/alice", RouteInfo::new())
467			.unwrap();
468		let mut follow = origin.consume().path_routes("room/alice").unwrap();
469
470		let first = origin
471			.route("room/alice", RouteOptions::default().with_cost(5))
472			.unwrap();
473		let event = kio::clock::timeout(Duration::from_secs(1), follow.next())
474			.await
475			.unwrap()
476			.unwrap();
477		assert!(
478			matches!(&event, RouteEvent { kind: RouteKind::Start, announce } if announce.route.cost == Cost::new(5)),
479			"{event:?}"
480		);
481
482		// A republish is another identity of the route that serves the path.
483		let _second = origin
484			.route("room/alice", RouteOptions::default().with_cost(5))
485			.unwrap();
486		drop(first);
487		let event = kio::clock::timeout(Duration::from_secs(1), follow.next())
488			.await
489			.unwrap()
490			.unwrap();
491		assert!(
492			matches!(&event, RouteEvent { kind: RouteKind::Restart, announce } if announce.route.cost == Cost::new(5)),
493			"{event:?}"
494		);
495	}
496
497	/// The next change handed out, which must arrive within a second.
498	async fn changed(announced: &mut Following) -> Option<broadcast::Consumer> {
499		kio::clock::timeout(Duration::from_secs(1), announced.available())
500			.await
501			.expect("no change")
502			.expect("the wait failed")
503	}
504
505	/// The next identity handed out, which must arrive within a second.
506	async fn available(announced: &mut Following) -> broadcast::Consumer {
507		changed(announced).await.expect("an end, not an identity")
508	}
509
510	/// The broadcast handed out last stops serving, with nothing in its place.
511	async fn ended(announced: &mut Following) {
512		if let Some(broadcast) = changed(announced).await {
513			panic!("expected an end, got {:?}", broadcast.info().identity);
514		}
515	}
516
517	/// Nothing more is handed out for a second.
518	async fn none(announced: &mut Following) {
519		if let Ok(result) = kio::clock::timeout(Duration::from_secs(1), announced.available()).await {
520			panic!(
521				"expected nothing, got {:?}",
522				result.map(|broadcast| broadcast.map(|broadcast| broadcast.info().identity.clone()))
523			);
524		}
525	}
526
527	/// The next request a dynamic route receives for its path.
528	async fn requested(dynamic: &crate::origin::Claim) -> crate::origin::Request {
529		kio::clock::timeout(Duration::from_secs(1), dynamic.requested())
530			.await
531			.expect("never asked")
532			.expect("the route closed")
533	}
534
535	/// Another identity taking over while a wait resolves is the one it hands out, so the
536	/// restart that announced it must not hand it out again while the caller holds it.
537	/// `dynamic_at` is where the route the wait first resolves through covers the path: above
538	/// it, the takeover's restart lands while resolving; at it, the origin holds that restart.
539	async fn hands_out_a_takeover_once(dynamic_at: &str) {
540		let origin = Hop::new(1).unwrap().produce();
541		let dynamic = origin.claim(dynamic_at, RouteOptions::default()).unwrap();
542		let mut announced = origin.consume().follow("live", None).unwrap();
543
544		// The wait is on the dynamic route's answer when the exact path takes over under another identity.
545		let (_takeover, _publish) = futures::join!(available(&mut announced), async {
546			let _unanswered = requested(&dynamic).await;
547			origin.route("live", RouteOptions::default()).unwrap()
548		});
549		none(&mut announced).await;
550	}
551
552	#[kio::test]
553	async fn announced_hands_out_a_takeover_once_while_resolving() {
554		hands_out_a_takeover_once("").await;
555	}
556
557	#[kio::test]
558	async fn announced_hands_out_a_held_takeover_once() {
559		hands_out_a_takeover_once("live").await;
560	}
561
562	/// Dropping a handed-out takeover changes nothing about the path, so the follower hands
563	/// out nothing until another identity takes over. The takeover's restart reached the
564	/// follower before its resolution handed it out, so no restart is owed.
565	#[kio::test]
566	async fn announced_waits_for_another_identity_after_a_dropped_takeover() {
567		let origin = Hop::new(1).unwrap().produce();
568		let dynamic = origin.claim("live", RouteOptions::default()).unwrap();
569		let mut announced = origin.consume().follow("live", None).unwrap();
570
571		let (takeover, _publish) = futures::join!(available(&mut announced), async {
572			let _unanswered = requested(&dynamic).await;
573			origin.route("live", RouteOptions::default()).unwrap()
574		});
575		drop(takeover);
576		none(&mut announced).await;
577
578		let next = origin.route("live", RouteOptions::default()).unwrap();
579		assert_eq!(available(&mut announced).await.info().identity, Some(next.identity()));
580	}
581
582	/// The route a wait resolves through leaving, and another identity arriving before it
583	/// resolves, reach the follower as an end and a start alongside the answer. That start must
584	/// not hand the newcomer out again.
585	#[kio::test]
586	async fn announced_hands_out_a_gap_while_resolving_once() {
587		let origin = Hop::new(1).unwrap().produce();
588		let dynamic = origin.claim("", RouteOptions::default()).unwrap();
589		let mut announced = origin.consume().follow("live", None).unwrap();
590
591		let (_arrival, _publish) = futures::join!(available(&mut announced), async {
592			let _unanswered = requested(&dynamic).await;
593			drop(dynamic);
594			// A gap, well inside the second `available` waits.
595			kio::clock::sleep(Duration::from_millis(600)).await;
596			origin.route("live", RouteOptions::default()).unwrap()
597		});
598		none(&mut announced).await;
599	}
600
601	/// An end is a gap that ended every request on the old route, even when a route above the
602	/// path with the same identity carries the identity on. So the identity serving the path
603	/// afterwards is handed out again, though it is the one the caller still holds.
604	#[kio::test]
605	async fn announced_hands_out_the_identity_again_after_an_end() {
606		let origin = Hop::new(1).unwrap().produce();
607		let identity = Identity::random();
608		let mut announced = origin.consume().follow("live", None).unwrap();
609		let exact = origin.route("live", options(&identity)).unwrap();
610		let first = available(&mut announced).await;
611
612		exact.withdraw();
613		ended(&mut announced).await;
614		let dynamic = origin.forward("", route(&identity)).unwrap();
615		let served = broadcast::Info::new().produce();
616		let (again, ()) = futures::join!(available(&mut announced), async {
617			requested(&dynamic).await.serve(&served);
618		});
619		assert!(again.is_clone(&first), "the route above did not carry the identity on");
620	}
621
622	/// An announced request that pins an identity ends when another identity takes over instead of
623	/// following it.
624	#[kio::test]
625	async fn announced_pinned_refuses_another_identity() {
626		let origin = Hop::new(1).unwrap().produce();
627		let identity = Identity::random();
628		let _first = origin.route("live", options(&identity)).unwrap();
629		let mut announced = origin.consume().follow("live", identity.clone()).unwrap();
630		let pinned = available(&mut announced).await;
631		assert_eq!(pinned.info().identity.as_ref(), Some(&identity));
632
633		let second = origin.route("live", RouteOptions::default()).unwrap();
634		ended(&mut announced).await;
635		none(&mut announced).await;
636
637		// Unpinned, the same takeover is followed.
638		let mut unpinned = origin.consume().follow("live", None).unwrap();
639		let current = available(&mut unpinned).await;
640		assert_ne!(current.info().identity.as_ref(), Some(&identity));
641
642		// The pinned identity serves again once the other goes, and is handed out again.
643		drop(second);
644		assert_eq!(
645			available(&mut announced).await.info().identity.as_ref(),
646			Some(&identity)
647		);
648		assert_eq!(available(&mut unpinned).await.info().identity.as_ref(), Some(&identity));
649	}
650
651	/// A follower started before anything serves the path waits for it, reports its end, and
652	/// hands out what serves it next.
653	#[kio::test]
654	async fn announced_reports_the_path_going_offline() {
655		let origin = Hop::new(1).unwrap().produce();
656		let mut announced = origin.consume().follow("live", None).unwrap();
657		none(&mut announced).await;
658
659		let first = origin.route("live", RouteOptions::default()).unwrap();
660		let started = available(&mut announced).await;
661		drop(first);
662		ended(&mut announced).await;
663		none(&mut announced).await;
664
665		let _second = origin.route("live", RouteOptions::default()).unwrap();
666		assert!(!available(&mut announced).await.is_clone(&started));
667	}
668
669	#[kio::test]
670	async fn announced_pinned_hands_out_its_identity_after_a_gap() {
671		let origin = Hop::new(1).unwrap().produce();
672		let identity = Identity::random();
673		let first = origin.route("live", options(&identity)).unwrap();
674		let mut announced = origin.consume().follow("live", identity.clone()).unwrap();
675		assert_eq!(
676			available(&mut announced).await.info().identity.as_ref(),
677			Some(&identity)
678		);
679		first.withdraw();
680		ended(&mut announced).await;
681		none(&mut announced).await;
682		first.announce().unwrap();
683		assert_eq!(
684			available(&mut announced).await.info().identity.as_ref(),
685			Some(&identity)
686		);
687	}
688
689	#[kio::test]
690	async fn announced_reports_a_dropped_prepared_answer() {
691		let origin = Hop::new(1).unwrap().produce();
692		let claim = origin.claim("live", RouteOptions::default()).unwrap();
693		let mut announced = origin.consume().follow("live", None).unwrap();
694		let (result, ()) = futures::join!(
695			kio::clock::timeout(Duration::from_secs(1), announced.available()),
696			async {
697				let prepared = requested(&claim).await.route(RouteOptions::hidden()).unwrap();
698				drop(prepared);
699			}
700		);
701		assert!(matches!(
702			result.expect("the selected refusal must answer"),
703			Err(Error::Unroutable)
704		));
705		// The refusing route is not asked again, and the next announcement is handed out.
706		let ((), again) = futures::join!(
707			none(&mut announced),
708			kio::clock::timeout(Duration::from_secs(1), claim.requested())
709		);
710		assert!(again.is_err(), "the refusing route was asked again");
711		drop(claim);
712		let identity = Identity::random();
713		let _published = origin.route("live", options(&identity)).unwrap();
714		assert_eq!(
715			available(&mut announced).await.info().identity.as_ref(),
716			Some(&identity)
717		);
718	}
719
720	/// A refusal is asked again once the same identity serves the path over another route.
721	#[kio::test]
722	async fn announced_retries_a_refusal_on_another_route_of_the_identity() {
723		let origin = Hop::new(1).unwrap().produce();
724		let identity = Identity::random();
725		let claim = origin.claim("", options(&identity)).unwrap();
726		let mut announced = origin.consume().follow("live", None).unwrap();
727		let (result, ()) = futures::join!(
728			kio::clock::timeout(Duration::from_secs(1), announced.available()),
729			async {
730				requested(&claim).await.reject(Error::Unroutable);
731			}
732		);
733		assert!(matches!(
734			result.expect("the refusal must answer"),
735			Err(Error::Unroutable)
736		));
737		let _exact = origin.route("live", options(&identity)).unwrap();
738		assert_eq!(
739			available(&mut announced).await.info().identity.as_ref(),
740			Some(&identity)
741		);
742	}
743
744	/// A refusal is asked again once a covering claim takes over from the refusing one, even when
745	/// the two announce alike.
746	#[kio::test]
747	async fn announced_retries_a_refusal_on_a_covering_claim_announced_alike() {
748		let origin = Hop::new(1).unwrap().produce();
749		let identity = Identity::random();
750		let above = origin.claim("", options(&identity)).unwrap();
751		let exact = origin.claim("live", options(&identity)).unwrap();
752		let mut announced = origin.consume().follow("live", None).unwrap();
753		let (result, ()) = futures::join!(
754			kio::clock::timeout(Duration::from_secs(1), announced.available()),
755			async {
756				requested(&exact).await.reject(Error::Unroutable);
757			}
758		);
759		assert!(matches!(
760			result.expect("the refusal must answer"),
761			Err(Error::Unroutable)
762		));
763
764		drop(exact);
765		let served = broadcast::Info::new().produce();
766		let (_again, ()) = futures::join!(available(&mut announced), async {
767			requested(&above).await.serve(&served);
768		});
769	}
770
771	/// A refusal is asked again once another handler at the same filing takes over, even when the
772	/// two announce alike.
773	#[kio::test]
774	async fn announced_retries_a_refusal_on_another_handler_announced_alike() {
775		let origin = Hop::new(1).unwrap().produce();
776		let identity = Identity::random();
777		let first = origin.claim("live", options(&identity)).unwrap();
778		let second = origin.claim("live", options(&identity)).unwrap();
779		let mut announced = origin.consume().follow("live", None).unwrap();
780		let (result, ()) = futures::join!(
781			kio::clock::timeout(Duration::from_secs(1), announced.available()),
782			async {
783				requested(&second).await.reject(Error::Unroutable);
784			}
785		);
786		assert!(matches!(
787			result.expect("the refusal must answer"),
788			Err(Error::Unroutable)
789		));
790
791		drop(second);
792		let served = broadcast::Info::new().produce();
793		let (_again, ()) = futures::join!(available(&mut announced), async {
794			requested(&first).await.serve(&served);
795		});
796	}
797
798	/// A refusal is reported once, and the follower then waits for the serving route to change
799	/// rather than asking the refusing handler again.
800	#[kio::test]
801	async fn announced_waits_for_a_route_change_after_a_refusal() {
802		let origin = Hop::new(1).unwrap().produce();
803		let claim = origin.claim("live", RouteOptions::default()).unwrap();
804		let mut announced = origin.consume().follow("live", None).unwrap();
805		let (result, ()) = futures::join!(
806			kio::clock::timeout(Duration::from_secs(1), announced.available()),
807			async { requested(&claim).await.reject(Error::NotFound) }
808		);
809		assert!(matches!(result.expect("the refusal answers"), Err(Error::NotFound)));
810		none(&mut announced).await;
811		let again = kio::clock::timeout(Duration::from_secs(1), claim.requested()).await;
812		assert!(again.is_err(), "the refusing handler was asked again");
813
814		// A publisher takes the path over from the claim, and is handed out.
815		let _publisher = origin.route("live", options(&Identity::random())).unwrap();
816		let _served = available(&mut announced).await;
817	}
818
819	/// A refusal by the route that took over from a closed broadcast is not retried when that
820	/// broadcast's movement is seen: the follower waits for the serving route to change, and
821	/// still reports the end of what it handed out once the path goes offline.
822	#[kio::test]
823	async fn announced_does_not_retry_a_refusal_after_a_takeover() {
824		let origin = Hop::new(1).unwrap().produce();
825		let dynamic = origin.claim("", options(&Identity::random())).unwrap();
826		let exact = origin.route("live", options(&Identity::random())).unwrap();
827		let mut announced = origin.consume().follow("live", None).unwrap();
828		let _first = available(&mut announced).await;
829
830		drop(exact);
831		let (result, ()) = futures::join!(
832			kio::clock::timeout(Duration::from_secs(1), announced.available()),
833			async { requested(&dynamic).await.reject(Error::NotFound) }
834		);
835		assert!(matches!(result.expect("the refusal answers"), Err(Error::NotFound)));
836		none(&mut announced).await;
837		let again = kio::clock::timeout(Duration::from_secs(1), dynamic.requested()).await;
838		assert!(again.is_err(), "the refusing handler was asked again");
839
840		// The broadcast handed out before the refusal is still owed its end once the path goes
841		// offline.
842		drop(dynamic);
843		ended(&mut announced).await;
844	}
845
846	/// A path the consumer's scope can never cover fails at once instead of waiting forever.
847	#[test]
848	fn follow_refuses_a_path_outside_the_scope() {
849		let origin = Hop::new(1).unwrap().produce();
850		let scope = Prefixes::from(Prefix::try_from("pool/job/cam").unwrap());
851		let scoped = origin.consume().scope("", &scope).unwrap();
852		assert!(matches!(scoped.path_routes("pool/job"), Err(Error::Unauthorized)));
853	}
854}