Skip to main content

moq_net/model/
origin.rs

1use crate::{broadcast, cache, stats, track};
2use kio::Task;
3use std::{
4	cmp::Reverse,
5	collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque},
6	fmt,
7	num::{NonZeroU64, NonZeroUsize},
8	sync::Arc,
9	sync::atomic::{AtomicU64, AtomicUsize, Ordering},
10	task::{Context, Poll, Wake, Waker, ready},
11	time::Duration,
12};
13
14use rand::RngExt;
15
16use super::{
17	RequestQueue, WeakCache, WeakEntry,
18	announced::AnnounceConsumer,
19	follow::{Follow, Following},
20	front::{Action, Candidate, Event, Front, Refusal},
21};
22use crate::{
23	Error, Identity, Path, Prefixes,
24	coding::{BoundsExceeded, Decode, DecodeError, Decoder, Encode, EncodeError, Encoder, Form, varint},
25	path,
26	time::{Deadlines, Instant},
27	util::{Keepalive, SendCell, TaskSet, Tasks, TasksWeak},
28};
29
30/// One relay's identity in a broadcast's hop chain: any 64-bit id.
31///
32/// Names a *hop*, not an [`origin::Producer`](Producer): a relay's routing table is the
33/// origin, and this is the id it stamps into a route's hop chain as an announcement
34/// passes through, so a receiver can spot its own id and reject a loop.
35///
36/// A transit fact the origin and the relays fill in: applications read them back
37/// ([`RouteInfo::hops`]).
38///
39/// Local hops come from a [`NonZeroU64`] or [`Hop::random`], so loop detection can work.
40/// Remote peers may still send `0`; it is legal on the wire, names nobody, and marks the
41/// chain anonymous for route selection.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub(crate) struct Hop {
44	id: u64,
45}
46
47impl Hop {
48	/// The reserved id 0: no identity.
49	///
50	/// It stands in for an endpoint that never declared one, and for Lite03 hop-count
51	/// placeholders. Any number of endpoints can be 0, so it identifies nothing: it is
52	/// never a loop, never a publisher two chains have in common, and a chain that
53	/// holds one anywhere is anonymous for route selection.
54	pub const UNKNOWN: Self = Self { id: 0 };
55
56	/// A local hop from a stable id, or `None` for 0, which cannot be excluded for loop
57	/// detection.
58	#[cfg(any(test, feature = "fuzz"))]
59	pub(crate) fn new(id: u64) -> Option<Self> {
60		NonZeroU64::new(id).map(Self::from)
61	}
62
63	/// Generate a fresh hop with a random non-zero id; see [`random_id`].
64	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
65	pub(crate) fn random() -> Self {
66		Self::from(random_id())
67	}
68
69	/// Return the hop's wire id.
70	pub(crate) fn id(self) -> u64 {
71		self.id
72	}
73
74	/// Build a hop from an id read off the wire, where 0 is legal.
75	pub(crate) const fn from_wire(id: u64) -> Self {
76		Self { id }
77	}
78
79	/// The id this hop carries on a wire whose varints use `form`.
80	///
81	/// A QUIC varint stops at 2^62 - 1, so a larger id travels as [`Self::UNKNOWN`]:
82	/// the route still reaches the peer, losing loop detection through this hop on
83	/// that link only.
84	pub(crate) fn wire_id(self, form: Form) -> u64 {
85		match form {
86			Form::Quic if self.id > varint::MAX_QUIC => Self::UNKNOWN.id,
87			_ => self.id,
88		}
89	}
90}
91
92/// An origin's identity plus the cache pool its broadcasts inherit.
93///
94/// Construction config for an [origin `Producer`](Producer). The origin passes its
95/// [`cache::Pool`] to every broadcast it creates, so every track and group beneath it
96/// shares one budget. Defaults to no byte target and the cache's standard idle expiry.
97#[derive(Clone, Debug)]
98#[non_exhaustive]
99pub struct Config {
100	/// The origin's Node ID: its identity on every wire, appended to broadcast hop chains
101	/// for loop detection and declared as the Relay ID on moq-lite-07, which also names it
102	/// in the hops of each route it forwards there. `None` mints a random one as each
103	/// [`Producer`] is built, so a config reused or cloned still makes a new node: lite-07
104	/// floors trust that a Relay ID names one run, numbering its sessions upward.
105	pub(crate) node: Option<NonZeroU64>,
106
107	/// Longest hop path a session using this origin accepts or forwards (default 32).
108	///
109	/// Legacy: applies to moq-lite-03 through 06 and the negotiated MoQ Cluster extension
110	/// on moq-transport, and leaves with moq-lite-06. A moq-lite-07 route's own hops stop
111	/// at 32 whatever this is, but a route that crossed into moq-lite-07 from moq-lite-06
112	/// still carries that chain: with its publisher's hop appended it must fit this
113	/// bound, or the route is dropped (logged at debug). A forwarded path counts this origin's own hop too, including
114	/// when the receiving peer reconstructs that hop from the announce handshake.
115	/// Protocols without a hop path cannot reveal or bound the depth they hide. No wire
116	/// carries a path longer than 32, so a larger value acts as 32.
117	pub max_hops: NonZeroUsize,
118
119	/// The cache pool broadcasts under this origin charge their groups into. It flows
120	/// down the ownership chain (origin -> broadcast -> track -> group): a track opens
121	/// an account against it, and its groups charge through that. It has no byte target
122	/// and uses [`cache::DEFAULT_EXPIRY`] by default; a relay sets a shared configured
123	/// pool (assign [`Self::pool`]) so cached groups across the whole process share
124	/// one policy.
125	pub pool: cache::Pool,
126
127	/// Local ceiling on each track's max age under this origin.
128	/// This caps how long a superseded group stays fresh here, and the delivery budget,
129	/// without changing the publisher's [`max_age`](track::Info::max_age) metadata. Wall-clock
130	/// reclamation of idle content is separate: [`Self::pool`]'s
131	/// [`expiry`](cache::Pool::expiry) window. `None` (the default) imposes no ceiling,
132	/// leaving each track's own window in force.
133	pub cache_duration: Option<Duration>,
134
135	/// Whether a moq-lite-07 session on this origin carries its peer's traffic to other
136	/// origins: off (the default), a peer is sent only the routes to this node's own
137	/// claims; on, the routes it learned from other peers too.
138	///
139	/// A relay turns it on. An application publishing its own broadcasts leaves it off,
140	/// so a peer never routes through it to reach anyone else. On a proxying origin, a
141	/// [`Link::Upstream`] session still gets routes learned from peers, just none from
142	/// other upstreams; a session that must forward nothing needs its own origin with
143	/// this off. Older versions advertise everything either way, since their hop chains
144	/// cannot tell this node's claims from what it forwards.
145	pub proxy: bool,
146
147	/// How long an announce cursor holds a changed route that arrived over a hop chain
148	/// before delivering it: a [`lite06_churn`] mitigation. A moq-lite-07 route and one
149	/// published here never wait.
150	///
151	/// A new route, a removed one, and another identity are delivered at once; only an
152	/// update waits, and a newer change during the wait replaces it. A hop-chain wire
153	/// carries no identity, so each session mints its own, and a fall back onto another
154	/// session's worse path to the same publisher (first hop) reads as another identity:
155	/// it waits like an update. When a publisher withdraws, a relay that loses its best
156	/// route but still holds routes derived from the withdrawn one sends nothing while
157	/// the withdrawal wave removes them, then one retraction, instead of advertising
158	/// each stale path in turn. It must outlast
159	/// the wave's spread across the mesh. Defaults to 300 ms, longer than a withdrawal
160	/// takes to cross a global mesh, with margin; zero delivers updates at once.
161	///
162	/// A relay further out can still pass a stale path to a cursor that already
163	/// retracted the prefix, which would announce it anew. So for two seconds after
164	/// a retraction, an announcement from the same publisher (first hop, identity and
165	/// epoch, or any session's identity for a hop chain) on a strictly worse route waits.
166	/// A republish ranks the same and a restart carries a new identity, epoch, or
167	/// publisher, so neither waits. Zero disables this too.
168	pub(crate) update_hold: Duration,
169}
170
171/// Lite-06 churn: the mitigations an announce cursor applies while a withdrawal hunts
172/// through a lite-06 mesh's hop-chain paths, which go with lite-06. They are the update
173/// hold and the retraction quarantine ([`Config::update_hold`]) and the same-clock dedup
174/// of a retraction's queue entry ([`Routes::quarantine`]). The cursor every version
175/// shares applies them, to the routes [`hunts`](lite06_churn::hunts) picks out alone, so
176/// a reader of a lite-06 mesh keeps them whatever version it speaks; each site names this
177/// module, so deleting it finds them all.
178pub(super) mod lite06_churn {
179	use std::time::Duration;
180
181	/// The default [`Config::update_hold`](super::Config::update_hold).
182	pub(crate) const DEFAULT_UPDATE_HOLD: Duration = Duration::from_millis(300);
183
184	/// How long a cursor holds back a stale path to a prefix it retracted; see
185	/// [`Config::update_hold`](super::Config::update_hold). Path hunting after a
186	/// withdrawal settles within it on random meshes with links of up to 250 ms.
187	pub(super) const RETRACT_QUARANTINE: Duration = Duration::from_secs(2);
188
189	/// Whether a route arrived over a hop chain (moq-lite-03 to 06, or moq-transport),
190	/// whose withdrawals hunt through stale paths: the only routes these mitigations
191	/// hold. A moq-lite-07 route names the node claiming it, whose withdrawal is final,
192	/// and one published here crossed no hop.
193	pub(super) fn hunts(hops: &super::Hops, node: Option<crate::route::NodeId>) -> bool {
194		node.is_none() && !hops.is_empty()
195	}
196
197	/// The publisher a hop chain starts at, if it names one.
198	pub(super) fn publisher(hops: &super::Hops) -> Option<super::Hop> {
199		hops.iter().next().copied().filter(|hop| *hop != super::Hop::UNKNOWN)
200	}
201
202	/// Whether `identity` and `other` may be one broadcast that reached here over two
203	/// sessions: each session mints its own identity for a hop chain, which carries none.
204	pub(super) fn same_stream(identity: &crate::Identity, other: &crate::Identity) -> bool {
205		identity == other || (identity.is_minted() && other.is_minted())
206	}
207
208	/// Whether a restart onto `meta` may be a fall back from the `delivered` route onto
209	/// a worse path to its publisher, which a withdrawal hunts through: the update hold
210	/// waits it out as it does an update. A replacement session ranks the same and
211	/// another publisher's broadcast names another first hop, so neither waits.
212	pub(super) fn falls_back(delivered: &super::Delivered, meta: &super::RouteMeta) -> bool {
213		hunts(&meta.0, meta.6)
214			&& delivered.publisher.is_some()
215			&& delivered.publisher == publisher(&meta.0)
216			&& same_stream(&delivered.identity, &meta.3)
217			&& (meta.1, meta.0.len()) > delivered.rank
218	}
219}
220use lite06_churn::{DEFAULT_UPDATE_HOLD, RETRACT_QUARANTINE};
221
222impl Default for Config {
223	/// A node minted per origin, with no byte target and the default idle expiry.
224	fn default() -> Self {
225		let pool = cache::Pool::new(cache::Config::default().with_expiry(cache::DEFAULT_EXPIRY));
226		Self {
227			node: None,
228			max_hops: MAX_HOP_LIMIT,
229			pool,
230			cache_duration: None,
231			proxy: false,
232			update_hold: DEFAULT_UPDATE_HOLD,
233		}
234	}
235}
236
237impl Config {
238	/// Config for the given origin node with no byte target and the default idle expiry.
239	///
240	/// Behind the `test-support` feature: a test's door, not an API. A Node ID kept across
241	/// runs would merge them on lite-07.
242	#[cfg(any(test, feature = "test-support"))]
243	pub fn new(node: NonZeroU64) -> Self {
244		Self {
245			node: Some(node),
246			..Self::default()
247		}
248	}
249
250	/// Hold route updates for `hold` rather than the default; see the field's notes.
251	///
252	/// Behind the `test-support` feature: a test's door, not an API.
253	#[cfg(feature = "test-support")]
254	pub fn with_update_hold(mut self, hold: Duration) -> Self {
255		self.update_hold = hold;
256		self
257	}
258
259	/// How long announce cursors hold a changed route; see [`Self::with_update_hold`].
260	///
261	/// Behind the `test-support` feature: a test's door, not an API.
262	#[cfg(feature = "test-support")]
263	pub fn update_hold(&self) -> Duration {
264		self.update_hold
265	}
266}
267
268/// A fresh random hop id, which names one run of an origin or peer.
269///
270/// Older `@moq/lite` clients decode the exclude hop as a JavaScript number and reject
271/// values above 2^53-1, so generated ids stay in that range.
272pub(crate) fn random_id() -> NonZeroU64 {
273	NonZeroU64::MIN.saturating_add(kio::clock::rng().random_range(0..(1u64 << 53) - 1))
274}
275
276impl From<NonZeroU64> for Hop {
277	/// A local hop: its non-zero id can be excluded for loop detection.
278	fn from(id: NonZeroU64) -> Self {
279		Self { id: id.get() }
280	}
281}
282
283impl fmt::Display for Hop {
284	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285		self.id.fmt(f)
286	}
287}
288
289impl<V> Encode<V> for Hop {
290	fn encode(&self, w: &mut Encoder<'_>, _: V) -> Result<(), EncodeError> {
291		w.varint(self.wire_id(w.form()))
292	}
293}
294
295impl<'a, V> Decode<'a, V> for Hop {
296	fn decode(r: &mut Decoder<'a>, _: V) -> Result<Self, DecodeError> {
297		Ok(Self::from_wire(r.varint()?))
298	}
299}
300
301/// Maximum number of origins (hops) an [`Hops`] can hold.
302///
303/// Caps pathological or loop-induced announcements at a reasonable cluster
304/// diameter; appending past this limit returns [`InvalidHop::TooMany`] rather than
305/// silently truncating.
306pub(super) const MAX_HOPS: usize = 32;
307
308/// The default and highest [`Config::max_hops`].
309const MAX_HOP_LIMIT: NonZeroUsize = NonZeroUsize::new(MAX_HOPS).unwrap();
310
311/// Bounded, loop-free list of [`Hop`] entries: the hop chain of a broadcast.
312///
313/// Guarantees `len() <= MAX_HOPS` and that no non-zero [`Hop`] appears twice. Both
314/// are wire rules, and both hold wherever a list exists rather than only where one was
315/// parsed, so a chain that a conforming receiver would reject cannot be built and sent.
316/// Construct via [`Hops::new`] + [`Hops::push`], or fall back to the
317/// fallible [`TryFrom<Vec<Hop>>`].
318#[derive(Debug, Clone, Default, PartialEq, Eq)]
319pub(crate) struct Hops(Vec<Hop>);
320
321/// Why a [`Hop`] cannot join a [`Hops`] chain.
322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323pub(crate) enum InvalidHop {
324	/// The list is already at its hop-count cap, which a real path never reaches and a
325	/// loop does.
326	TooMany,
327
328	/// The id is already in the list. A chain that revisits a hop looped, which every
329	/// receiver of it must reject, so it must not be built in the first place. The
330	/// reserved id 0 identifies nothing and may repeat.
331	Duplicate,
332}
333
334impl fmt::Display for InvalidHop {
335	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
336		match self {
337			Self::TooMany => write!(f, "too many hops (max {MAX_HOPS})"),
338			Self::Duplicate => write!(f, "hop already in the chain"),
339		}
340	}
341}
342
343impl std::error::Error for InvalidHop {}
344
345impl From<InvalidHop> for DecodeError {
346	fn from(err: InvalidHop) -> Self {
347		match err {
348			InvalidHop::TooMany => DecodeError::BoundsExceeded,
349			InvalidHop::Duplicate => DecodeError::InvalidValue,
350		}
351	}
352}
353
354impl Hops {
355	/// Create an empty list.
356	pub fn new() -> Self {
357		Self(Vec::new())
358	}
359
360	/// Append an [`Hop`], rejecting anything a conforming receiver would.
361	///
362	/// Fails with [`InvalidHop::TooMany`] once the list is full, and with
363	/// [`InvalidHop::Duplicate`] for an id already in the chain, which is a loop. The
364	/// reserved id 0 identifies nothing, so it may repeat.
365	pub fn push(&mut self, hop: Hop) -> Result<(), InvalidHop> {
366		if self.0.len() >= MAX_HOPS {
367			return Err(InvalidHop::TooMany);
368		}
369		if hop != Hop::UNKNOWN && self.0.contains(&hop) {
370			return Err(InvalidHop::Duplicate);
371		}
372		self.0.push(hop);
373		Ok(())
374	}
375
376	/// Returns true if any entry matches `hop`.
377	pub fn contains(&self, hop: &Hop) -> bool {
378		self.0.contains(hop)
379	}
380
381	/// Number of entries currently in the list (always `<= MAX_HOPS`).
382	pub fn len(&self) -> usize {
383		self.0.len()
384	}
385
386	/// Whether the list contains no entries.
387	pub fn is_empty(&self) -> bool {
388		self.0.is_empty()
389	}
390
391	/// Iterate over the entries in hop order (oldest first).
392	pub fn iter(&self) -> std::slice::Iter<'_, Hop> {
393		self.0.iter()
394	}
395
396	/// Borrow the entries as a slice.
397	#[cfg(test)]
398	pub fn as_slice(&self) -> &[Hop] {
399		&self.0
400	}
401
402	/// The entries' ids, in hop order, reusing the list's allocation.
403	#[cfg(all(feature = "async", any(test, feature = "fuzz")))]
404	pub(crate) fn into_ids(self) -> Vec<u64> {
405		self.0.into_iter().map(|hop| hop.id).collect()
406	}
407}
408
409impl TryFrom<Vec<Hop>> for Hops {
410	type Error = InvalidHop;
411
412	fn try_from(v: Vec<Hop>) -> Result<Self, Self::Error> {
413		if v.len() > MAX_HOPS {
414			return Err(InvalidHop::TooMany);
415		}
416		// MAX_HOPS is 32, so the quadratic scan is cheaper than allocating a set.
417		for (i, hop) in v.iter().enumerate() {
418			if *hop != Hop::UNKNOWN && v[i + 1..].contains(hop) {
419				return Err(InvalidHop::Duplicate);
420			}
421		}
422		Ok(Self(v))
423	}
424}
425
426impl<'a> IntoIterator for &'a Hops {
427	type Item = &'a Hop;
428	type IntoIter = std::slice::Iter<'a, Hop>;
429
430	fn into_iter(self) -> Self::IntoIter {
431		self.iter()
432	}
433}
434
435impl<V: Copy> Encode<V> for Hops {
436	fn encode(&self, w: &mut Encoder<'_>, version: V) -> Result<(), EncodeError> {
437		w.varint(self.0.len() as u64)?;
438		for origin in &self.0 {
439			origin.encode(w, version)?;
440		}
441		Ok(())
442	}
443}
444
445impl<'a, V: Copy> Decode<'a, V> for Hops {
446	fn decode(r: &mut Decoder<'a>, version: V) -> Result<Self, DecodeError> {
447		let count = r.varint()? as usize;
448		if count > MAX_HOPS {
449			return Err(DecodeError::BoundsExceeded);
450		}
451		// Through `push`, so a chain that revisits a hop is rejected here rather than
452		// entering the model and being forwarded on to a receiver that must close on it.
453		let mut list = Self(Vec::with_capacity(count));
454		for _ in 0..count {
455			list.push(Hop::decode(r, version)?)?;
456		}
457		Ok(list)
458	}
459}
460
461/// The highest route cost, shared by every wire version.
462const MAX_COST: u64 = (1 << 62) - 1;
463
464/// The static cost of pulling content through a route; lower wins.
465#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
466pub struct Cost(u64);
467
468impl Cost {
469	/// Price a route, saturating at the wire ceiling.
470	pub const fn new(cost: u64) -> Self {
471		Self(if cost > MAX_COST { MAX_COST } else { cost })
472	}
473
474	/// The accumulated route price.
475	pub const fn value(self) -> u64 {
476		self.0
477	}
478
479	/// The wire ceiling every price saturates at.
480	pub(crate) const MAX: Self = Self(MAX_COST);
481
482	/// A peer without a wire cost: the same as [`Cost::default`], so only the
483	/// local link price counts.
484	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
485	pub(crate) const UNKNOWN: Self = Self(0);
486
487	/// Add a link's static price without overflowing the wire ceiling.
488	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
489	pub(crate) fn charged(self, link_cost: u64) -> Self {
490		Self::new(self.0.saturating_add(link_cost))
491	}
492}
493
494impl From<u64> for Cost {
495	fn from(cost: u64) -> Self {
496		Self::new(cost)
497	}
498}
499
500/// How much an endpoint prefers a link over its others; higher wins.
501///
502/// Every link starts at the neutral [`Priority::default`] (0), which is also what
503/// a broadcast published locally ranks. A positive value promotes a link and a
504/// negative one demotes it. See [`Producer::with_priority`].
505///
506/// This ranks a route's link, as a Route Offer's priority does. A
507/// [`track::Subscription`](crate::track::Subscription)'s `priority` ranks one
508/// subscription against the others sharing a connection.
509#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
510pub struct Priority(i8);
511
512impl Priority {
513	/// Rank a link.
514	pub const fn new(priority: i8) -> Self {
515		Self(priority)
516	}
517
518	/// The rank.
519	pub const fn value(self) -> i8 {
520		self.0
521	}
522}
523
524impl From<i8> for Priority {
525	fn from(priority: i8) -> Self {
526		Self::new(priority)
527	}
528}
529
530/// The stream a received route serves and what using it costs: read-only facts on an
531/// announcement.
532///
533/// Carried by [`Announce::route`]. A route claims capability, not inventory: it says
534/// paths under its prefix are servable, never that any specific broadcast exists. The
535/// common convention is that a publisher announces each broadcast's exact path with
536/// [`Producer::route`], so subscribers can enumerate broadcasts; a service instead
537/// announces one short prefix with [`Producer::claim`] and answers whatever is
538/// requested beneath it.
539///
540/// Applications never build one: a [`Route`] takes [`RouteOptions`], and the origin
541/// and the relays fill in the rest.
542#[derive(Clone, Debug, PartialEq, Eq)]
543pub struct RouteInfo {
544	/// The stream the route serves; see [`Self::identity`]. Always set on a route the
545	/// origin delivers. Given to a route a session lands, `None` mints one.
546	pub(crate) identity: Option<Identity>,
547
548	/// Orders the incarnations of one identity: among its routes at one prefix only the
549	/// highest epoch is eligible. Never compared across identities, and never shown to
550	/// readers.
551	pub(crate) epoch: u64,
552
553	/// The chain of origins the route has traversed, oldest first. Each relay appends its
554	/// own hop when forwarding; used for loop detection and as the selection tie-break. A
555	/// 0 entry is the anonymous mark and travels unchanged, ranking the route below every
556	/// fully identified one. A route announced on this origin has none.
557	pub(crate) hops: Hops,
558
559	/// What pulling content via this route costs; see [`Self::cost`].
560	pub(crate) cost: Cost,
561
562	/// The credential the request advertising this route carries, from
563	/// `auth::Handle::add`, or `None` for the session's scope.
564	///
565	/// Only a session built on the handle that issued it carries it, as the token on its
566	/// moq-transport PUBLISH_NAMESPACE: any other session, the inline NAMESPACE answering a
567	/// solicited SUBSCRIBE_NAMESPACE, and moq-lite (which rides the session's scope)
568	/// advertise the route unnamed. Swapping it is an update that renews the request with
569	/// REQUEST_UPDATE. A handle passed to
570	/// `Client::with_auth` presents it on every session it backs, so the route keeps it
571	/// across a reconnect. Local, like [`Self::source`]: a relay never forwards it.
572	pub(crate) auth: Option<crate::auth::Credential>,
573
574	/// The announcing session's declared or assigned identity.
575	///
576	/// Local selection state: split-horizon matches this as well as the chain, so a
577	/// route is never advertised back to the session it came from even when that
578	/// session withheld an identity (hop 0). Never forwarded.
579	pub(crate) via: Hop,
580
581	/// Where the route entered this origin; see [`Self::source`]. Never forwarded.
582	pub(crate) source: Source,
583
584	/// The forwarding node whose claim the route follows, for a route the lite-07 route
585	/// layer serves: a request resolved through it reaches that node's claim. `None`
586	/// for a route this node serves itself, published here or learned over an older
587	/// version.
588	pub(crate) node: Option<crate::route::NodeId>,
589
590	/// How the route layer ranks the route among those of its claim; see [`Lane`].
591	pub(crate) lane: Lane,
592
593	/// The session it arrived on is going away (the peer sent a GOAWAY): it ranks below
594	/// every other available route, whatever its priority or cost, yet above one held
595	/// unavailable, and still serves when nothing else does.
596	///
597	/// A ranking state, never a saturated metric. Never in an announcement, so a relay
598	/// advertises a draining route at its real cost and its readers never see the flag; only
599	/// the lite-07 route layer hears it, which drains the claim it makes for the route.
600	pub(crate) draining: bool,
601
602	/// Whether a usable path reaches the route's origin; see [`Self::available`].
603	pub(crate) available: bool,
604
605	/// The lite-07 route layer reached it across a marked link, though the session it
606	/// arrived on is not one: it is hidden from an upstream reader, as a route learned on
607	/// a [`Link::Upstream`] handle is, so this origin never carries it between two
608	/// upstreams. Local, like [`Self::via`]: never forwarded.
609	pub(crate) marked: bool,
610}
611
612impl RouteInfo {
613	/// No route yet: no identity, hops, cost or credential, entered here. Crate-private
614	/// because a delivered route always names an identity.
615	pub(crate) fn new() -> Self {
616		Self {
617			identity: None,
618			epoch: 0,
619			hops: Hops::new(),
620			cost: Cost::default(),
621			auth: None,
622			via: Hop::UNKNOWN,
623			source: Source::Local,
624			node: None,
625			lane: Lane::default(),
626			draining: false,
627			available: true,
628			marked: false,
629		}
630	}
631}
632
633/// How the lite-07 route layer ranks a route it serves: one per forwarding node claiming
634/// the broadcast that a route reaches. Only the closest is primary, which a reader here
635/// follows; a request a peer forwards follows the one it names.
636#[derive(Clone, Debug, PartialEq, Eq, Hash)]
637pub(crate) struct Lane {
638	pub primary: bool,
639	/// The lowest priority of a link on the way to the publisher, which ranks the route
640	/// where a session's priority does, or `None` for a route the route layer does not
641	/// serve.
642	pub priority: Option<i8>,
643	/// How many segments the claim's own prefix lacks of the path it entered at, which a
644	/// stream presenting a broader claim at a narrower request reports: 0 for a claim
645	/// exactly there. The longer prefix wins, so a claim at 0 outranks every broader one.
646	/// A path has at most 32 segments, so a byte holds it, and the route entry stays small.
647	pub above: u8,
648	/// Which showing of the claim the route layer serves: a new one each time the claim
649	/// is shown again after every copy of it left, so a copy retired late never retires
650	/// the copies a later showing serves. See [`Claim::retire`].
651	pub lifecycle: u64,
652}
653
654impl Default for Lane {
655	fn default() -> Self {
656		Self {
657			primary: true,
658			priority: None,
659			above: 0,
660			lifecycle: 0,
661		}
662	}
663}
664
665/// Where a route entered an origin: here, or from a cluster peer.
666///
667/// Origin bookkeeping, not a chain fact: the hop chain cannot say it, since a
668/// client and a peer relay each append one hop. The origin records it from the
669/// handle that announced the route; see [`Producer::with_link`].
670#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
671pub(crate) enum Source {
672	/// Announced on this origin: by an in-process producer or a client session.
673	#[default]
674	Local,
675	/// Learned from a cluster peer, named by the hop id the announcing session declared
676	/// or was assigned. 0 when the announcing handle named none: a peer handle in-process,
677	/// or a session whose peer declared no hop and was assigned none.
678	Peer(u64),
679}
680
681impl RouteInfo {
682	/// The stream the route serves: routes with one identity serve one continuous
683	/// key space, so a subscription resumes from one to another. Pass it to
684	/// [`Consumer::request`] to pin this stream.
685	pub fn identity(&self) -> &Identity {
686		self.identity.as_ref().expect("a delivered route has an identity")
687	}
688
689	/// What pulling content via this route costs, accumulated per link: lower wins
690	/// among routes of the same link priority and anonymity, with ties broken by a
691	/// broadcast published on this origin, then hop length, then a hash of the identity
692	/// and the requested path (except for a route that entered here, at its own path),
693	/// and finally the most recently announced route. See [`Cost`].
694	pub fn cost(&self) -> Cost {
695		self.cost
696	}
697
698	/// Whether a usable path reaches the route's origin. An unavailable route is held:
699	/// the network lost every path to it but may recover one, so the announcement stays.
700	/// It ranks below every available claim of its prefix, a draining one included, though a
701	/// more specific claim still shadows a broader one, and requests through it may fail until
702	/// it recovers: request again once it turns available.
703	pub fn available(&self) -> bool {
704		self.available
705	}
706
707	/// Serve a stable `identity` at `epoch`; see [`RouteOptions::with_identity`].
708	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
709	pub(crate) fn with_identity(mut self, identity: Identity, epoch: u64) -> Self {
710		self.identity = Some(identity);
711		self.epoch = epoch;
712		self
713	}
714
715	/// Replace the hop chain.
716	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
717	pub(crate) fn with_hops(mut self, hops: Hops) -> Self {
718		self.hops = hops;
719		self
720	}
721
722	/// Set the cost: lower wins among routes covering the same prefix and anonymity.
723	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
724	pub(crate) fn with_cost(mut self, cost: impl Into<Cost>) -> Self {
725		self.cost = cost.into();
726		self
727	}
728
729	/// Set the credential the advertising request carries; see [`Self::auth`].
730	#[cfg(all(test, feature = "async"))]
731	pub(crate) fn with_auth(mut self, auth: crate::auth::Credential) -> Self {
732		self.auth = Some(auth);
733		self
734	}
735
736	/// The announcing session's declared or assigned identity, for split-horizon.
737	///
738	/// Not part of the advertised route: an assigned identity is private selection
739	/// state and must not be forwarded.
740	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
741	pub(crate) fn with_via(mut self, via: Hop) -> Self {
742		self.via = via;
743		self
744	}
745
746	/// The forwarding node whose claim a route-layer route follows.
747	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
748	pub(crate) fn with_node(mut self, node: Option<crate::route::NodeId>) -> Self {
749		self.node = node;
750		self
751	}
752
753	/// Follow the route layer's route `lane`; see [`Self::lane`].
754	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
755	pub(crate) fn with_lane(mut self, lane: Lane) -> Self {
756		self.lane = lane;
757		self
758	}
759
760	/// Rank the route last, or not; see [`Self::draining`].
761	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
762	pub(crate) fn with_draining(mut self, draining: bool) -> Self {
763		self.draining = draining;
764		self
765	}
766
767	/// Mark whether a usable path reaches the route's origin; see [`Self::available`].
768	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
769	pub(crate) fn with_available(mut self, available: bool) -> Self {
770		self.available = available;
771		self
772	}
773
774	/// Hide the route from upstream readers, or not; see [`Self::marked`].
775	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
776	pub(crate) fn with_marked(mut self, marked: bool) -> Self {
777		self.marked = marked;
778		self
779	}
780
781	/// Whether this route passed through an anonymous hop.
782	///
783	/// True when the chain holds a 0 anywhere, including Lite03 hop-count
784	/// placeholders. An anonymous route ranks below every fully identified one,
785	/// whatever the costs say. An empty chain is a local announcement, not the
786	/// anonymous mark; ingress fills a received empty list with 0 before it
787	/// enters the table.
788	#[cfg(test)]
789	pub(crate) fn is_anonymous(&self) -> bool {
790		self.hops.iter().any(|hop| *hop == Hop::UNKNOWN)
791	}
792
793	/// Where the route entered this origin.
794	#[cfg(test)]
795	pub(crate) fn source(&self) -> Source {
796		self.source
797	}
798
799	/// The hop id of the session the route entered this origin from, 0 when that session
800	/// named none, or `None` for a route announced here.
801	///
802	/// Behind the `test-support` feature: a test's door, not an API.
803	#[cfg(feature = "test-support")]
804	pub fn entered_from(&self) -> Option<u64> {
805		match self.source {
806			Source::Local => None,
807			Source::Peer(hop) => Some(hop),
808		}
809	}
810}
811
812/// How an application advertises a [`Route`]: its visibility at creation, its price,
813/// its credential, and, rarely, a stable identity.
814///
815/// The default announces at once, at cost 0, under the session's scope, serving a
816/// fresh random identity minted when the route is created.
817#[derive(Clone, Debug, Default)]
818pub struct RouteOptions {
819	hidden: bool,
820	cost: Cost,
821	auth: Option<crate::auth::Credential>,
822	identity: Option<(Identity, u64)>,
823}
824
825impl RouteOptions {
826	/// Create the route hidden: it exists for nobody until [`Route::announce`].
827	///
828	/// For a publisher that fills its catalog first, or answers a negotiation, before
829	/// readers may find it.
830	pub fn hidden() -> Self {
831		Self {
832			hidden: true,
833			..Self::default()
834		}
835	}
836
837	/// Set the cost: lower wins among routes covering the same prefix and anonymity.
838	/// A publisher prices content it already produces at zero, and content it would
839	/// have to start producing on demand higher.
840	pub fn with_cost(mut self, cost: impl Into<Cost>) -> Self {
841		self.cost = cost.into();
842		self
843	}
844
845	/// Set the credential the advertising request carries, from `auth::Handle::add`.
846	///
847	/// Only a session built on the handle that issued it presents it, as the token on
848	/// its moq-transport PUBLISH_NAMESPACE; every other session advertises the route
849	/// under its own scope.
850	pub fn with_auth(mut self, auth: crate::auth::Credential) -> Self {
851		self.auth = Some(auth);
852		self
853	}
854
855	/// Serve a stable `identity` at `epoch`, in place of a freshly minted one.
856	///
857	/// Only for a publisher that continues the identity's key space across restarts,
858	/// announcing a higher `epoch` each time, such as a counter persisted on disk. Readers
859	/// stitch every route of one identity together, so a publisher that restarts its
860	/// group keys under an old identity splices unrelated groups into their tracks.
861	/// The highest epoch wins over every older one of the identity, cheaper or not.
862	/// Naming an identity grants nothing: publishing still needs the path's grant.
863	pub fn with_identity(mut self, identity: Identity, epoch: u64) -> Self {
864		self.identity = Some((identity, epoch));
865		self
866	}
867
868	/// The route metadata these options advertise, under `identity` at `epoch`.
869	/// The price and credential to advertise, naming no identity.
870	fn info(&self) -> RouteInfo {
871		RouteInfo {
872			cost: self.cost,
873			auth: self.auth.clone(),
874			..RouteInfo::new()
875		}
876	}
877}
878
879static NEXT_CONSUMER_ID: AtomicU64 = AtomicU64::new(0);
880
881#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
882struct ConsumerId(u64);
883
884impl ConsumerId {
885	fn new() -> Self {
886		Self(NEXT_CONSUMER_ID.fetch_add(1, Ordering::Relaxed))
887	}
888}
889
890/// FNV-1a 64 of `path`, then `bytes`, from the offset basis `seed`.
891///
892/// FNV-1a, not the std hasher: its output is fixed across Rust versions and
893/// builds, which matters when nodes run mismatched binaries during a rolling
894/// deploy and still need to agree on the same route. Mixing the path in spreads
895/// equal routes across different paths rather than funneling onto one.
896fn fnv(seed: u64, path: &str, bytes: impl IntoIterator<Item = u8>) -> u64 {
897	const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
898
899	let mut hash = seed;
900	for byte in path.as_bytes().iter().copied().chain(bytes) {
901		hash = (hash ^ u64::from(byte)).wrapping_mul(FNV_PRIME);
902	}
903	hash
904}
905
906/// The draft's Rendezvous Hash: standard FNV-1a 64 of the requested path, then the
907/// identity, which reads the same on every node, so every relay picks the same one.
908fn rendezvous(path: &str, identity: &Identity) -> u64 {
909	fnv(0xcbf2_9ce4_8422_2325, path, identity.as_str().bytes())
910}
911
912/// The hash that spreads a pool's named identities over `path`s: a named identity reads
913/// the same on every node, so every relay picks the same one. Its basis is
914/// `spreadHash`'s in `js/net`.
915fn identity_key(path: &str, identity: &Identity) -> u64 {
916	fnv(0x420C0DECB00B, path, identity.as_str().bytes())
917}
918
919/// The highest epoch each identity reaches among a set of candidates, per claim: an older
920/// incarnation of an identity is never eligible, however cheap, since its publisher was
921/// replaced. A claim is its own prefix ([`RouteEntry::claimed`]), wherever it is filed, so a
922/// broader claim shown at a prefix is another claim than the one made there, and its epoch
923/// supersedes nothing of it. Built in one pass, so ranking N candidates stays linear. Only
924/// epochs above 0 are kept, since nothing is below 0: the common case, where every identity
925/// announces epoch 0, allocates nothing.
926struct Epochs<'a>(HashMap<(&'a str, &'a Identity), u64>);
927
928impl<'a> Epochs<'a> {
929	fn of(candidates: impl Iterator<Item = &'a RouteEntry>) -> Self {
930		let mut highest = HashMap::new();
931		for entry in candidates.filter(|entry| entry.epoch > 0) {
932			let epoch = highest.entry((entry.claimed(), &entry.identity)).or_insert(0);
933			*epoch = (*epoch).max(entry.epoch);
934		}
935		Self(highest)
936	}
937
938	/// Whether a candidate carries `entry`'s identity at a higher epoch on the same claim.
939	fn superseded(&self, entry: &RouteEntry) -> bool {
940		// Checked first, so the common case never walks the entry's prefix for its claim.
941		!self.0.is_empty()
942			&& self
943				.0
944				.get(&(entry.claimed(), &entry.identity))
945				.is_some_and(|&highest| highest > entry.epoch)
946	}
947}
948
949/// Ordering key for an eligible route entry resolving `path` (see [`Epochs`]), among the
950/// candidates of one claim tier: its [`route_rank`], then how a tie between equally ranked
951/// routes breaks, then the newest announcement. Lower wins. A caller ranks claims by
952/// specificity first (see [`RouteEntry::specificity`]), since the most specific claim wins
953/// outright, however far its route's cost or state ranks below a broader one. `path` is what
954/// is being resolved: the requested path for a request, the prefix itself for an
955/// advertisement.
956///
957/// A tie between two lite-07 claims goes by a rendezvous hash of the identity and `path`,
958/// then the node claiming it, as every node that knows the claim ranks it. Any other tie
959/// beneath `path` goes first by a hash of a named identity and `path`, which spreads a pool
960/// of identities at one prefix: each path picks its own winner, and a named identity reads
961/// alike on every node, so every node picks the same one. Then, between the routes of one
962/// identity, or of identities a session minted (which no other node shares, so a hash of
963/// them agrees with nothing), the route that has held its rank longest
964/// ([`RouteEntry::since`]): a route of equal rank that arrives later never displaces the
965/// one in use, which would restart it downstream, and in turn at every relay downstream
966/// that ranks it alike. When the route in use leaves, the next oldest takes over. The hop
967/// chain refuses loops, not this order, so keeping a route forms none.
968///
969/// A route that entered here for exactly `path` ties to the newest announcement: no other
970/// node ranks it, and a restarted publisher announces under a new identity, so the restart
971/// takes over at once instead of after the transport retires its old session.
972fn route_order(path: &Path, entry: &RouteEntry) -> RouteOrder {
973	let tie = match (entry.node, entry.link == Link::Local && entry.prefix == *path) {
974		(_, true) => (0, 0),
975		// Every node that knows the claim ranks its identity alike, and then the nodes
976		// claiming it: one publisher reaches several over several sessions.
977		(Some(node), false) => (rendezvous(path.as_str(), &entry.identity), node.relay),
978		(None, false) => match entry.identity.is_minted() {
979			true => (0, entry.since),
980			false => (identity_key(path.as_str(), &entry.identity), entry.since),
981		},
982	};
983	(route_rank(entry), tie, Reverse(entry.id))
984}
985
986/// The key [`route_order`] ranks an entry by: lower wins.
987type RouteOrder = (RouteRank, (u64, u64), Reverse<u64>);
988
989/// How good a route is, ties aside: lower wins. First a route that reaches its origin (see
990/// [`RouteInfo::available`]), then one that is not draining (see [`RouteInfo::draining`]), so
991/// a peer that sent a GOAWAY ranks below every live route yet above one held unavailable,
992/// which may serve nothing. Then the route layer's closest way to a broadcast ahead of its
993/// others ([`Lane::primary`]). Then the higher link [`Priority`], so metrics from different
994/// operators are never compared. Then an identified chain (no 0) outranks an anonymous one
995/// regardless of cost, then the cheapest cost, then a broadcast published on this origin (it
996/// serves what is here, not a claim that has to ask), then the shortest hop chain. The
997/// availability, drain, priority and cost tiers are the draft's (Resolution), as the route
998/// layer ranks the claims of one filing ([`crate::route::relay::claim_order`]).
999fn route_rank(entry: &RouteEntry) -> RouteRank {
1000	// A lite-07 claim ranks as the one hop to its origin node: the rest of its hops are
1001	// the moq-lite-06 chain it carries only for loop detection and translation.
1002	let (anonymous, hops) = match entry.node {
1003		Some(_) => (false, 1),
1004		None => (entry.is_anonymous(), entry.hops.len()),
1005	};
1006	(
1007		!entry.available,
1008		entry.draining,
1009		// The route layer's closest way ahead of its others to the same broadcast. Below
1010		// availability, since the route layer marks every way to a broadcast available or
1011		// none: a live identity's other way outranks a dead one held unavailable while a
1012		// route change moves its closest way to another session. Below the drain, since the
1013		// route layer ranks a draining claim below every other, so its closest way drains
1014		// only once every way does.
1015		!entry.lane.primary,
1016		Reverse(entry.link_priority()),
1017		anonymous,
1018		entry.cost,
1019		!entry.local,
1020		hops,
1021	)
1022}
1023
1024/// The key [`route_rank`] ranks an entry by: lower wins.
1025type RouteRank = (bool, bool, bool, Reverse<Priority>, bool, Cost, bool, usize);
1026
1027/// The `(hops, cost, source, identity, epoch, auth, node, available, above, standing)`
1028/// metadata an announce cursor delivers alongside a prefix.
1029type RouteMeta = (
1030	Hops,
1031	Cost,
1032	Source,
1033	Identity,
1034	u64,
1035	Option<crate::auth::Credential>,
1036	Option<crate::route::NodeId>,
1037	bool,
1038	u8,
1039	Option<Standing>,
1040);
1041
1042/// A route's drain and link priority, which a ranked cursor ([`NodeFilter::Own`]) delivers as
1043/// well: they change how the route layer ranks the claim it is fed, but nothing a reader
1044/// sees, so no other cursor carries them (see [`RouteInfo::draining`]).
1045type Standing = (bool, Priority);
1046
1047/// The earlier of two optional deadlines.
1048fn earliest(a: Option<Instant>, b: Option<Instant>) -> Option<Instant> {
1049	match (a, b) {
1050		(Some(a), Some(b)) => Some(a.min(b)),
1051		(a, b) => a.or(b),
1052	}
1053}
1054
1055/// A retraction's quarantine, keyed by prefix in its [`Routes`]: the
1056/// retracted route's publisher (none for an anonymous route, which holds
1057/// nothing), identity, epoch, and rank, and when the quarantine ends.
1058#[derive(Clone)]
1059struct Quarantine {
1060	held: Held,
1061	publisher: Option<Hop>,
1062	identity: (Identity, u64),
1063	rank: (Cost, usize),
1064}
1065
1066impl Quarantine {
1067	/// Whether `meta` could be a stale path to the retracted publisher: the same
1068	/// first hop, identity (see [`lite06_churn::same_stream`]) and epoch, ranked
1069	/// strictly worse. A republish ranks the same and a restart carries a new identity
1070	/// or epoch, so neither waits.
1071	fn holds(&self, meta: &RouteMeta) -> bool {
1072		lite06_churn::hunts(&meta.0, meta.6)
1073			&& self.publisher.is_some_and(|hop| meta.0.iter().next() == Some(&hop))
1074			&& lite06_churn::same_stream(&meta.3, &self.identity.0)
1075			&& meta.4 == self.identity.1
1076			&& (meta.1, meta.0.len()) > self.rank
1077	}
1078}
1079
1080/// What a [`Routes`] last delivered as an announce at a prefix.
1081struct Delivered {
1082	identity: Identity,
1083	/// The publisher and rank, which tell a hop chain's fall back onto a worse session's
1084	/// path from a restart; see [`lite06_churn::falls_back`].
1085	publisher: Option<Hop>,
1086	rank: (Cost, usize),
1087	/// Whether a ranked cursor delivered the route draining; see [`Delivered::drains`].
1088	draining: bool,
1089}
1090
1091impl Delivered {
1092	fn new(meta: &RouteMeta) -> Self {
1093		Self {
1094			identity: meta.3.clone(),
1095			publisher: lite06_churn::publisher(&meta.0),
1096			rank: (meta.1, meta.0.len()),
1097			draining: draining(meta),
1098		}
1099	}
1100
1101	/// Whether `meta` is the route starting to drain, which the update hold never delays: it
1102	/// damps path hunting, which a drain is not, and a peer closing within the hold would
1103	/// end the route before a ranked cursor's reader learned it drains.
1104	fn drains(&self, meta: &RouteMeta) -> bool {
1105		!self.draining && draining(meta)
1106	}
1107}
1108
1109/// Whether a ranked cursor delivers `meta` draining.
1110fn draining(meta: &RouteMeta) -> bool {
1111	meta.9.is_some_and(|(draining, _)| draining)
1112}
1113
1114/// A pending update's hold, kept with it in its [`Routes`]'s queue.
1115///
1116/// A consumer reads the origin's clock outside the driver, where it holds the
1117/// driver's last reading, not the time the update arrived. So a hold first waits
1118/// for the driver's next reading (armed a nanosecond past the stale one, which
1119/// wakes the driver at once), and counts from there.
1120#[derive(Clone, Copy, PartialEq)]
1121enum Held {
1122	Anchoring(Instant),
1123	Until(Instant),
1124}
1125
1126/// One coalesced update queued for an `Routes`.
1127///
1128/// At most one entry exists per prefix, so a slow consumer's pending set is
1129/// bounded by the number of distinct prefixes. A metadata change on a live route
1130/// overwrites the pending `Announce` (or is delivered as another active update),
1131/// a pending `Restart` stays one until delivered whatever metadata follows it,
1132/// and `UnannounceAnnounce` preserves a real retract-then-announce key.
1133enum PendingUpdate {
1134	Announce(RouteMeta),
1135	/// Another identity replaces the one the consumer holds (`old`), and a retraction before
1136	/// delivery retracts `old`. `lost` records that `old` was lost when it was replaced, the
1137	/// only reason a replacement knows for sure: a route merely outranked leaves no reason, so
1138	/// the retraction then takes the last route's.
1139	Restart {
1140		old: RouteMeta,
1141		lost: bool,
1142		new: RouteMeta,
1143	},
1144	Unannounce(RouteMeta, Gone),
1145	UnannounceAnnounce {
1146		old: RouteMeta,
1147		gone: Gone,
1148		new: RouteMeta,
1149	},
1150}
1151
1152/// How a route left a cursor: the origin ended it, or this node lost it.
1153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1154enum Gone {
1155	/// Its origin withdrew it, as far as this node knows: [`RouteKind::End`].
1156	End,
1157	/// This node let go of it, such as the session it arrived on closing:
1158	/// [`RouteKind::Offline`].
1159	Offline,
1160}
1161
1162impl Gone {
1163	fn kind(self) -> RouteKind {
1164		match self {
1165			Self::End => RouteKind::End,
1166			Self::Offline => RouteKind::Offline,
1167		}
1168	}
1169}
1170
1171// An update is taken only while collapsing it under the cursor state lock.
1172struct Pending {
1173	update: Option<PendingUpdate>,
1174	// A later live event must not consume an earlier snapshot entry's debt.
1175	owed: bool,
1176	/// The entry's place in delivery order: when it was queued.
1177	seq: u64,
1178	/// When a poll looks at the entry again, in [`OriginConsumerState::parked`],
1179	/// or `None` while it is in [`OriginConsumerState::due`].
1180	wake: Option<Instant>,
1181	/// The update hold, from the first poll that saw the entry as one.
1182	held: Option<Held>,
1183}
1184
1185impl Pending {
1186	/// When a poll at `now` looks at this held entry again, or `None` once its hold ended.
1187	fn hold(&mut self, now: Instant, hold: Duration) -> Option<Instant> {
1188		// The clock reads the driver's last advance, which may be stale: anchor the hold
1189		// on the first advance after the update arrived, by waking the driver.
1190		match self.held {
1191			None => {
1192				self.held = Some(Held::Anchoring(now));
1193				Some(now.saturating_add(Duration::from_nanos(1)))
1194			}
1195			Some(Held::Anchoring(seen)) if now <= seen => Some(seen.saturating_add(Duration::from_nanos(1))),
1196			Some(Held::Anchoring(_)) => {
1197				self.held = Some(Held::Until(now.saturating_add(hold)));
1198				Some(now.saturating_add(hold))
1199			}
1200			Some(Held::Until(until)) => Some(until).filter(|until| *until > now),
1201		}
1202	}
1203}
1204
1205/// Pending updates keep their insertion order when metadata changes. Fully removing
1206/// cancelled entries bounds memory by prefixes with outstanding work.
1207///
1208/// Every entry sits in exactly one of `due` and `parked`, so a poll touches only
1209/// what changed or came due since the last one, never the entries it holds back.
1210#[derive(Default)]
1211struct OriginConsumerState {
1212	pending: HashMap<Path, Pending>,
1213	/// The entries a poll looks at next, in delivery order: queued or changed since,
1214	/// or come due.
1215	due: BTreeMap<u64, Path>,
1216	/// The entries held back, by when a poll looks at them again.
1217	parked: BTreeMap<(Instant, u64), Path>,
1218	next_seq: u64,
1219	/// Prefixes whose most recently delivered update was an announce, with the
1220	/// identity it named. A pending `Announce` is ambiguous on its own: it is an
1221	/// unseen initial announce (a retraction cancels it entirely) or a metadata
1222	/// update on a route the consumer already observed (a retraction must still be
1223	/// delivered). The identity tells a restart back to it from one onto another.
1224	delivered: BTreeMap<Path, Delivered>,
1225	/// Set by the origin's teardown: the cursor drains `pending`, then reports
1226	/// the end instead of parking forever on a table that can never fire again.
1227	ended: bool,
1228	/// Snapshots in flight that can present on this consumer's cursors, counted
1229	/// once per cursor they touch. See [`Routes::poll_synced`].
1230	///
1231	/// Changed through a read guard, so a session joining wakes none of the cursors it
1232	/// holds back (nothing waits on losing sync), except the last landing, which
1233	/// takes the write guard to owe the queue too. Only the table lock changes it.
1234	waiting: AtomicUsize,
1235	/// Pending entries from before the last snapshot landed. Synced at zero
1236	/// when no source is `waiting`; held metadata changes are not counted.
1237	owed: usize,
1238	/// Entries the polls have looked at, which the CPU a poll costs follows.
1239	#[cfg(test)]
1240	steps: usize,
1241}
1242
1243impl OriginConsumerState {
1244	/// Whether the consumer has read everything its sources announced before they
1245	/// synced. A torn-down origin has no sources left to wait on.
1246	fn synced(&self) -> bool {
1247		(self.waiting.load(Ordering::Relaxed) == 0 || self.ended) && self.owed == 0
1248	}
1249
1250	/// Owe every pending update that changes which prefixes are announced: a start
1251	/// the consumer has not seen, or an end. A re-price or restart of a delivered
1252	/// route leaves the set as it is, and may be held, so it is not owed.
1253	fn owe(&mut self) {
1254		self.owed = 0;
1255		for (prefix, pending) in &mut self.pending {
1256			pending.owed = !self.delivered.contains_key(prefix)
1257				|| matches!(
1258					pending.update,
1259					Some(PendingUpdate::Unannounce(..) | PendingUpdate::UnannounceAnnounce { .. })
1260				);
1261			self.owed += usize::from(pending.owed);
1262		}
1263	}
1264
1265	/// Queue `update` at `prefix`, or replace the one queued there in its place. A
1266	/// replaced entry is looked at again on the next poll.
1267	fn put(&mut self, prefix: Path, update: PendingUpdate) {
1268		let Some(pending) = self.pending.get_mut(&prefix) else {
1269			self.insert(prefix, update, false);
1270			return;
1271		};
1272		pending.update = Some(update);
1273		if let Some(wake) = pending.wake.take() {
1274			self.parked.remove(&(wake, pending.seq));
1275			self.due.insert(pending.seq, prefix);
1276		}
1277	}
1278
1279	/// Queue `update` at `prefix`, which has nothing queued, last in delivery order.
1280	fn insert(&mut self, prefix: Path, update: PendingUpdate, owed: bool) {
1281		let seq = self.next_seq;
1282		self.next_seq += 1;
1283		self.due.insert(seq, prefix.clone());
1284		self.pending.insert(
1285			prefix,
1286			Pending {
1287				update: Some(update),
1288				owed,
1289				seq,
1290				wake: None,
1291				held: None,
1292			},
1293		);
1294	}
1295
1296	/// Unqueue the entry at `prefix`.
1297	fn remove(&mut self, prefix: &Path) -> Option<Pending> {
1298		let pending = self.pending.remove(prefix)?;
1299		match pending.wake {
1300			Some(wake) => self.parked.remove(&(wake, pending.seq)),
1301			None => self.due.remove(&pending.seq),
1302		};
1303		Some(pending)
1304	}
1305
1306	/// The origin tore down: drain everything queued, holds and all, then end.
1307	fn end(&mut self) {
1308		self.ended = true;
1309		for ((_, seq), prefix) in std::mem::take(&mut self.parked) {
1310			self.pending.get_mut(&prefix).unwrap().wake = None;
1311			self.due.insert(seq, prefix);
1312		}
1313	}
1314
1315	fn apply_announce(&mut self, prefix: Path, meta: RouteMeta) {
1316		let new = match self.pending.get_mut(&prefix).and_then(|pending| pending.update.take()) {
1317			// First announce, a stale announce being replaced, or a metadata update.
1318			None | Some(PendingUpdate::Announce(_)) => PendingUpdate::Announce(meta),
1319			// The consumer still owes the restart; this only moves its metadata.
1320			Some(PendingUpdate::Restart { old, lost, .. }) => PendingUpdate::Restart { old, lost, new: meta },
1321			// Consumer needs to observe the retraction before this announce.
1322			Some(PendingUpdate::Unannounce(old, gone) | PendingUpdate::UnannounceAnnounce { old, gone, .. }) => {
1323				PendingUpdate::UnannounceAnnounce { old, gone, new: meta }
1324			}
1325		};
1326		self.put(prefix, new);
1327	}
1328
1329	/// Another identity replaces the route at `prefix`, `old`, which was `lost` if it went
1330	/// offline, or announces it afresh when the consumer never saw the old one.
1331	fn apply_restart(&mut self, prefix: Path, old: RouteMeta, lost: bool, meta: RouteMeta) {
1332		let new = match self.pending.get_mut(&prefix).and_then(|pending| pending.update.take()) {
1333			Some(PendingUpdate::Unannounce(old, gone) | PendingUpdate::UnannounceAnnounce { old, gone, .. }) => {
1334				PendingUpdate::UnannounceAnnounce { old, gone, new: meta }
1335			}
1336			// Back to the identity the consumer holds, before it saw the restart away:
1337			// one continuous stream, so a metadata update.
1338			_ if self
1339				.delivered
1340				.get(&prefix)
1341				.is_some_and(|delivered| delivered.identity == meta.3) =>
1342			{
1343				PendingUpdate::Announce(meta)
1344			}
1345			// The consumer still holds the identity the first restart replaced.
1346			Some(PendingUpdate::Restart { old, lost, .. }) => PendingUpdate::Restart { old, lost, new: meta },
1347			_ if self.delivered.contains_key(&prefix) => PendingUpdate::Restart { old, lost, new: meta },
1348			// The consumer never saw the old identity, so this is its first announce.
1349			_ => PendingUpdate::Announce(meta),
1350		};
1351		self.put(prefix, new);
1352	}
1353
1354	fn apply_unannounce(&mut self, prefix: Path, last: RouteMeta, gone: Gone) {
1355		match self.pending.get_mut(&prefix).and_then(|pending| pending.update.take()) {
1356			// The pending announce was never delivered and neither was any earlier
1357			// one, so the pair cancels entirely, and nothing is owed for it.
1358			Some(PendingUpdate::Announce(_)) if !self.delivered.contains_key(&prefix) => {
1359				let pending = self.remove(&prefix).unwrap();
1360				self.owed -= usize::from(pending.owed);
1361			}
1362			// Either nothing is pending or the pending announce was a metadata
1363			// update on a delivered route; the consumer still owes a retraction.
1364			None | Some(PendingUpdate::Announce(_) | PendingUpdate::Unannounce(..)) => {
1365				self.put(prefix, PendingUpdate::Unannounce(last, gone));
1366			}
1367			// The replacement was never delivered: retract the identity the consumer
1368			// holds, offline if it was lost, and otherwise for the last route's reason.
1369			Some(PendingUpdate::Restart { old, lost, .. }) => {
1370				let gone = if lost { Gone::Offline } else { gone };
1371				self.put(prefix, PendingUpdate::Unannounce(old, gone));
1372			}
1373			// The embedded announce cancels with this retraction; the consumer still
1374			// needs the leading one. Its reason is the later one only when both carry
1375			// one identity; otherwise the later reason is for a route never delivered.
1376			Some(PendingUpdate::UnannounceAnnounce { old, gone: prior, new }) => {
1377				let gone = if old.3 == new.3 { gone } else { prior };
1378				self.put(prefix, PendingUpdate::Unannounce(old, gone));
1379			}
1380		}
1381	}
1382
1383	/// Whether a poll at `now` has an entry to look at: one queued, changed, or come
1384	/// due since the last, or the end of a torn-down origin.
1385	fn due(&self, now: Instant) -> bool {
1386		!self.due.is_empty()
1387			|| self.parked.first_key_value().is_some_and(|((wake, _), _)| *wake <= now)
1388			|| (self.ended && self.pending.is_empty())
1389	}
1390
1391	/// When the next held entry is due, if any is held.
1392	fn wake(&self) -> Option<Instant> {
1393		self.parked.first_key_value().map(|((wake, _), _)| *wake)
1394	}
1395
1396	/// The first pending prefix ready to deliver at `now`, or when the next held one
1397	/// is. Each entry looked at is either ready or parked until it could be.
1398	///
1399	/// A metadata change to a route the consumer holds waits out the update hold
1400	/// (see [`Config::update_hold`]), which starts the first time a poll sees it. A
1401	/// restart onto another identity goes at once. A stale path to a retracted
1402	/// publisher waits out its quarantine in `retracted`, settled against `now`.
1403	fn scan(
1404		&mut self,
1405		retracted: &HashMap<Path, Quarantine>,
1406		now: Instant,
1407		hold: Duration,
1408	) -> Result<Path, Option<Instant>> {
1409		while let Some(entry) = self.parked.first_entry()
1410			&& entry.key().0 <= now
1411		{
1412			let ((_, seq), prefix) = entry.remove_entry();
1413			self.pending.get_mut(&prefix).unwrap().wake = None;
1414			self.due.insert(seq, prefix);
1415		}
1416		while let Some(entry) = self.due.first_entry() {
1417			#[cfg(test)]
1418			{
1419				self.steps += 1;
1420			}
1421			let prefix = entry.get();
1422			if hold.is_zero() || self.ended {
1423				return Ok(prefix.clone());
1424			}
1425			let pending = self.pending.get_mut(prefix).unwrap();
1426			let wake = match pending.update.as_ref().unwrap() {
1427				PendingUpdate::Announce(meta)
1428					if self
1429						.delivered
1430						.get(prefix)
1431						.is_some_and(|delivered| !delivered.drains(meta))
1432						&& lite06_churn::hunts(&meta.0, meta.6) =>
1433				{
1434					pending.hold(now, hold)
1435				}
1436				PendingUpdate::Restart { new: meta, .. }
1437					if self
1438						.delivered
1439						.get(prefix)
1440						.is_some_and(|delivered| lite06_churn::falls_back(delivered, meta)) =>
1441				{
1442					pending.hold(now, hold)
1443				}
1444				PendingUpdate::Announce(meta) => match retracted.get(prefix).filter(|q| q.holds(meta)) {
1445					Some(Quarantine {
1446						held: Held::Anchoring(seen),
1447						..
1448					}) => Some(seen.saturating_add(Duration::from_nanos(1))),
1449					Some(Quarantine {
1450						held: Held::Until(until),
1451						..
1452					}) => Some(*until).filter(|until| *until > now),
1453					None => None,
1454				},
1455				_ => None,
1456			};
1457			let Some(wake) = wake else {
1458				return Ok(prefix.clone());
1459			};
1460			pending.wake = Some(wake);
1461			let (seq, prefix) = entry.remove_entry();
1462			self.parked.insert((wake, seq), prefix);
1463		}
1464		Err(self.wake())
1465	}
1466
1467	/// Take the pending update at `prefix` for delivery.
1468	fn take_prefix(&mut self, prefix: Path) -> RouteEvent {
1469		let (event, owed) = self.take_update(prefix);
1470		// A trailing announce left pending is still owed.
1471		if owed && !self.pending.contains_key(&event.announce.prefix) {
1472			self.owed -= 1;
1473		}
1474		event
1475	}
1476
1477	fn take_update(&mut self, prefix: Path) -> (RouteEvent, bool) {
1478		let pending = self.remove(&prefix).unwrap();
1479		let owed = pending.owed;
1480		let (meta, kind) = match pending.update.unwrap() {
1481			PendingUpdate::Announce(meta) => {
1482				// The consumer has seen this prefix before, so it is a metadata update.
1483				let kind = match self.delivered.insert(prefix.clone(), Delivered::new(&meta)) {
1484					None => RouteKind::Start,
1485					Some(_) => RouteKind::Update,
1486				};
1487				(meta, kind)
1488			}
1489			PendingUpdate::Restart { new: meta, .. } => {
1490				self.delivered.insert(prefix.clone(), Delivered::new(&meta));
1491				(meta, RouteKind::Restart)
1492			}
1493			PendingUpdate::Unannounce(meta, gone) => {
1494				self.delivered.remove(&prefix);
1495				(meta, gone.kind())
1496			}
1497			PendingUpdate::UnannounceAnnounce { old, gone, new } => {
1498				// Deliver the retraction now; leave the trailing announce pending so
1499				// the next take returns it for the same prefix.
1500				self.delivered.remove(&prefix);
1501				self.insert(prefix.clone(), PendingUpdate::Announce(new), owed);
1502				(old, gone.kind())
1503			}
1504		};
1505		let announce = Announce {
1506			prefix,
1507			route: RouteInfo {
1508				hops: meta.0,
1509				cost: meta.1,
1510				via: Hop::UNKNOWN,
1511				source: meta.2,
1512				identity: Some(meta.3),
1513				epoch: meta.4,
1514				auth: meta.5,
1515				node: meta.6,
1516				draining: meta.9.is_some_and(|(draining, _)| draining),
1517				available: meta.7,
1518				// A ranked cursor's link priority rides the lane's, which
1519				// [`OwnClaims::apply`] reads: it ranks the route where the route layer's would.
1520				lane: Lane {
1521					above: meta.8,
1522					priority: meta.9.map(|(_, priority)| priority.value()),
1523					..Lane::default()
1524				},
1525				marked: false,
1526			},
1527		};
1528		(RouteEvent { kind, announce }, owed)
1529	}
1530}
1531
1532/// One announced route in the origin's table, absolute prefix.
1533struct RouteEntry {
1534	id: u64,
1535	/// When the entry last became [live](Self::live), changed its [`route_rank`], or moved to
1536	/// another identity or epoch, from the counter [`Self::id`] comes from: of equally ranked
1537	/// routes, the one held longest keeps winning (see [`route_order`]).
1538	since: u64,
1539	/// The stream this route serves; see [`RouteInfo::identity`].
1540	identity: Identity,
1541	/// Which incarnation of the identity; see [`RouteInfo::epoch`].
1542	epoch: u64,
1543	/// Where the entry is filed: the prefix it was announced at, or one of its producer's
1544	/// grant prefixes beneath it, so the entry may serve its whole subtree.
1545	prefix: Path,
1546	/// How many segments [`Self::prefix`] lies beneath the prefix it was announced at,
1547	/// which [`Lane::above`] already counts: what an update adds to the route it is given.
1548	below: u8,
1549	/// Every prefix the announcement is filed at, this one included: one claim, whose
1550	/// identity moves to a fresh one at each together (see [`OriginState::advance`]).
1551	filed: Arc<[Path]>,
1552	/// The absolute subtrees the announcing producer may not serve, even beneath
1553	/// a covering prefix.
1554	excluded: Arc<[Path]>,
1555	hops: Hops,
1556	cost: Cost,
1557	/// The auth the request advertising the route carries; see [`RouteInfo::auth`].
1558	auth: Option<crate::auth::Credential>,
1559	/// The rank of the link the entry arrived on; see [`Producer::with_priority`].
1560	priority: Priority,
1561	/// The announcing session's declared or assigned identity. Split-horizon
1562	/// matches this as well as [`Self::hops`], so an anonymous hop 0 still
1563	/// cannot echo back to the session it came from.
1564	via: Hop,
1565	/// Whether this is a broadcast published on this origin, which wins a cost tie and
1566	/// keeps its own cache.
1567	local: bool,
1568	/// The link the entry arrived on, from the handle that inserted it.
1569	link: Link,
1570	/// The route crossed a marked link before it; see [`RouteInfo::marked`].
1571	marked: bool,
1572	/// The forwarding node whose claim the route follows; see [`RouteInfo::node`].
1573	node: Option<crate::route::NodeId>,
1574	/// The route layer's route it follows; see [`RouteInfo::lane`].
1575	lane: Lane,
1576	/// Whether the route ranks below every other available one; see [`RouteInfo::draining`].
1577	/// Only a ranked cursor's [`Self::meta`] carries it, for the route layer.
1578	draining: bool,
1579	/// Whether a usable path reaches the route's origin; see [`RouteInfo::available`].
1580	available: bool,
1581	/// The queue requests under this route are served from, when the announcer
1582	/// serves content on demand (a [`Claim`]). `None` for an advertise-only
1583	/// announcement ([`Producer::announce`]) and for a local broadcast.
1584	server: Option<kio::Shared<ServeState>>,
1585	/// The broadcast published on this origin at exactly `prefix`, when the
1586	/// entry is one: requests resolve to it directly, and the newest one at a
1587	/// path wins through [`route_order`].
1588	source: Option<broadcast::Consumer>,
1589	/// Whether the entry exists for anyone: cursors see it and requests resolve
1590	/// through it. A broadcast is in the table from creation but serves nobody,
1591	/// locally or remotely, until it announces.
1592	advertised: bool,
1593	/// Whether a peer the chain passes through has since withdrawn this prefix.
1594	/// The route was derived from that peer's advertisement, so it serves nobody
1595	/// until the peer announces again. See [`Claim::withdrawn`].
1596	stale: bool,
1597	/// The route layer let go of the claim this entry follows through another of its
1598	/// copies, whose own retraction is on its way. See [`Claim::retire`].
1599	retired: bool,
1600	/// Whether the job routes answering this prefix route take its identity, which it
1601	/// minted rather than was given: their readers continue on the job's route. It moves
1602	/// to a fresh one as each job carrying it stops serving; see [`OriginState::advance`].
1603	lends: bool,
1604	/// The prefix route, by prefix and id, whose identity this job's route took.
1605	lent: Option<(Path, u64)>,
1606}
1607
1608impl RouteEntry {
1609	/// How many segments the claim's own prefix has: the entry's, less how far above it the
1610	/// claim was shown. The most specific claim covering a path wins, however deep the entry
1611	/// that shows it is filed.
1612	fn specificity(&self) -> usize {
1613		(self.prefix.parts().count()).saturating_sub(usize::from(self.lane.above))
1614	}
1615
1616	/// The lowest priority of a link on the way to the publisher: the link the entry arrived
1617	/// on, and for a lite-07 route, every link the route layer counted before it.
1618	fn link_priority(&self) -> Priority {
1619		match self.lane.priority {
1620			Some(priority) => self.priority.min(Priority::new(priority)),
1621			None => self.priority,
1622		}
1623	}
1624
1625	/// The claim's own prefix: the entry's, less how far above it the claim was shown. Claims
1626	/// of one prefix form one tier, whichever prefix each is filed at.
1627	fn claimed(&self) -> &str {
1628		let len = (self.prefix.head_len(self.specificity())).expect("a claim is no deeper than its entry");
1629		&self.prefix.as_str()[..len]
1630	}
1631
1632	/// Whether the announcing producer may serve the absolute `path` beneath the entry: its
1633	/// grant covers the entry's whole subtree, less what it excludes.
1634	fn authorizes(&self, path: &Path) -> bool {
1635		!self.excluded.iter().any(|excluded| path.has_prefix(excluded))
1636	}
1637
1638	/// Whether cursors see the entry and requests resolve through it.
1639	fn live(&self) -> bool {
1640		self.advertised && !self.stale && !self.retired
1641	}
1642
1643	fn is_anonymous(&self) -> bool {
1644		self.hops.iter().any(|hop| *hop == Hop::UNKNOWN)
1645	}
1646
1647	/// Where the entry entered this origin.
1648	fn entered(&self) -> Source {
1649		match self.link {
1650			Link::Local => Source::Local,
1651			Link::Peer | Link::Upstream => Source::Peer(self.via.id()),
1652		}
1653	}
1654
1655	/// The metadata an announce cursor delivers for this entry, its [`Standing`] too when the
1656	/// cursor is `ranked`.
1657	fn meta(&self, ranked: bool) -> RouteMeta {
1658		(
1659			self.hops.clone(),
1660			self.cost,
1661			self.entered(),
1662			self.identity.clone(),
1663			self.epoch,
1664			self.auth.clone(),
1665			self.node,
1666			self.available,
1667			self.lane.above,
1668			self.standing(ranked),
1669		)
1670	}
1671
1672	/// What a `ranked` cursor delivers of the entry's drain and link priority.
1673	fn standing(&self, ranked: bool) -> Option<Standing> {
1674		ranked.then(|| (self.draining, self.link_priority()))
1675	}
1676
1677	/// Whether [`Self::meta`] would equal `meta`, without building it.
1678	fn delivers(&self, meta: &RouteMeta, ranked: bool) -> bool {
1679		let (hops, cost, source, identity, epoch, auth, node, available, above, standing) = meta;
1680		*hops == self.hops
1681			&& *cost == self.cost
1682			&& *source == self.entered()
1683			&& *identity == self.identity
1684			&& *epoch == self.epoch
1685			&& *auth == self.auth
1686			&& *node == self.node
1687			&& *available == self.available
1688			&& *above == self.lane.above
1689			&& *standing == self.standing(ranked)
1690	}
1691
1692	/// Whether a request for `path` can be served through this entry. A served
1693	/// route covers everything beneath its prefix; a broadcast published here
1694	/// is only itself, so it serves its exact path and shadows what is beneath.
1695	fn serves(&self, path: &Path) -> bool {
1696		self.server.is_some() || (self.source.is_some() && self.prefix == *path)
1697	}
1698
1699	/// Whether this entry may be observed or served to a requester excluding `peer`.
1700	///
1701	/// A non-zero peer is hidden when it is the announcing session (`via`) or
1702	/// appears in the chain. Hop 0 identifies nobody, so it is never excluded.
1703	fn visible_to(&self, exclude: Option<Hop>) -> bool {
1704		match exclude {
1705			Some(peer) if peer != Hop::UNKNOWN => self.via != peer && !self.hops.contains(&peer),
1706			_ => true,
1707		}
1708	}
1709}
1710
1711// Published names are literal coordinates. Navigation belongs to Relative,
1712// resolved before publication, so a name remains stable when carried by a URL.
1713fn publish_path(path: &Path) -> Result<(), Error> {
1714	nameable(path)?;
1715	if path.parts().any(|segment| matches!(segment, "." | "..")) {
1716		return Err(Error::NavigationSegment);
1717	}
1718	Ok(())
1719}
1720
1721// A `*` stays out of every path while a prefix refuses one (so a pattern written where a
1722// prefix belongs fails loudly): a broadcast no listing can root at, and that pre-0.22
1723// subscribers read as a wildcard, is refused before it is published or watched.
1724fn nameable(path: &Path) -> Result<(), Error> {
1725	if path.as_str().contains('*') {
1726		return Err(Error::InvalidPath);
1727	}
1728	Ok(())
1729}
1730
1731/// Where a claim at the absolute `requested` prefix is filed under `scope`, so each place
1732/// serves its whole subtree: the prefix itself when the scope covers it, and otherwise each
1733/// of the scope's prefixes beneath it that `publishes` admits, with how many segments
1734/// beneath the requested prefix it lies. Empty when the scope reaches nothing beneath it.
1735pub(crate) fn filed(scope: &Prefixes, requested: &Path, publishes: impl Fn(&Path) -> bool) -> Vec<(Path, u8)> {
1736	if scope.matches(requested.as_str()) {
1737		return vec![(requested.clone(), 0)];
1738	}
1739	// Count segments, not every `/` as the wire limit does: an escaped `/` must not push the
1740	// claim's own prefix (`RouteEntry::claimed`) above the requested one.
1741	let segments = requested.parts().count();
1742	(scope.iter())
1743		// A prefix too long for a path holds nothing a request could name.
1744		.filter_map(|prefix| Path::new(prefix.as_str()).ok())
1745		.filter(|prefix| prefix.has_prefix(requested) && prefix.depth() <= Path::MAX_PARTS && publishes(prefix))
1746		.map(|prefix| {
1747			let below = u8::try_from(prefix.parts().count() - segments).expect("a path has at most 32 segments");
1748			(prefix, below)
1749		})
1750		.collect()
1751}
1752
1753/// A served route's request queue: what materializes a requested path on demand.
1754///
1755/// Shared by every requester resolving through the owning route and the
1756/// [`Claim`] draining it, so both sides work under one lock.
1757#[derive(Default)]
1758pub(super) struct ServeState {
1759	// Result channels for pending requests, keyed by absolute path so concurrent
1760	// `request` calls for the same path coalesce onto one channel.
1761	requests: RequestQueue<Path, kio::Producer<PendingBroadcast>>,
1762
1763	// Broadcasts the handler has already served, kept weakly so a repeat request for the
1764	// same path resolves to a shared clone instead of re-invoking the handler (which would
1765	// open a duplicate upstream subscription). Weak so a served broadcast still closes once
1766	// its real consumers drop. The cache reclaims closed entries incrementally on insert, so a
1767	// long-lived origin serving many distinct one-shot paths stays bounded by the live count.
1768	served: WeakCache<Path, broadcast::WeakConsumer>,
1769
1770	// How many times the route changed identity: a front compares it to the count when
1771	// it asked to tell a released request from an answered one without taking this lock.
1772	renewals: Arc<AtomicU64>,
1773
1774	// Set when the announcement is retracted or the origin tears down: new requests
1775	// fail immediately and the handler observes the end instead of parking forever.
1776	closed: bool,
1777}
1778
1779/// Key of a remotely-served front: the absolute path and the requester's
1780/// [`Horizon::effective`] horizon. Requesters excluding a peer some covering
1781/// route passes through get a front of their own, so its failover never adopts
1782/// a route flowing back through one of its readers, nor a local view a peer's
1783/// route. Every other requester shares the plain front, so fronts scale with
1784/// the peers in the path's route chains rather than with viewer sessions. A
1785/// request naming an identity other than the path's winner, such as a relay
1786/// forwarding toward the pool member its own route names, follows that
1787/// identity's routes on a front of its own.
1788type FrontKey = (Path, Horizon, Option<Identity>);
1789
1790/// Which routes a reader sees: the split-horizon exclusion and the local-only view.
1791#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1792struct Horizon {
1793	/// Routes whose hop chain or announcing session (`via`) is this peer are
1794	/// hidden. `Some(UNKNOWN)` marks an anonymous peer: no hop is excluded, but
1795	/// local-only broadcasts are not advertised. `None` is a local reader.
1796	exclude: Option<Hop>,
1797	/// Hide the routes that entered from a cluster peer ([`Consumer::local`]).
1798	local: bool,
1799	/// Hide the routes learned on an upstream link, because this reader is one
1800	/// ([`Link::Upstream`]): a relay never transits between two upstreams.
1801	upstream: bool,
1802	/// Hide the routes with no room for our hop under this cap, because this reader
1803	/// forwards them ([`Consumer::forwardable`]). Selection then falls back to a
1804	/// shorter route instead of withdrawing a prefix an in-cap path still reaches.
1805	max_hops: Option<NonZeroUsize>,
1806	/// Which origin nodes' routes this reader sees ([`Consumer::with_node`]).
1807	node: NodeFilter,
1808}
1809
1810/// Which origin nodes' routes a reader sees: a request naming a node resolves only
1811/// through that node's routes.
1812#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1813pub(crate) enum NodeFilter {
1814	/// Every route. Of the route layer's, the most specific claim ranks first and then each
1815	/// broadcast's closest way (see [`Lane`]).
1816	#[default]
1817	Any,
1818	/// Only the routes this node serves itself, which the route layer is fed as this node's
1819	/// own claims: a cursor delivers each one's [`Standing`] too, since the claim carries it.
1820	Own,
1821	/// Only the route layer's route following the forwarding node `node`'s claim.
1822	#[cfg_attr(
1823		not(feature = "async"),
1824		allow(dead_code, reason = "only the async session names a node")
1825	)]
1826	Route { node: crate::route::NodeId },
1827}
1828
1829impl NodeFilter {
1830	fn admits(self, node: Option<crate::route::NodeId>) -> bool {
1831		match self {
1832			Self::Any => true,
1833			Self::Own => node.is_none(),
1834			Self::Route { node: id } => node == Some(id),
1835		}
1836	}
1837}
1838
1839impl Horizon {
1840	/// Whether `entry` may be observed or served through this horizon.
1841	fn admits(&self, entry: &RouteEntry) -> bool {
1842		self.admits_link(entry.link)
1843			&& !(self.upstream && entry.marked)
1844			&& entry.visible_to(self.exclude)
1845			&& self.max_hops.is_none_or(|max| entry.hops.len() < max.get())
1846			&& self.node.admits(entry.node)
1847	}
1848
1849	/// Whether routes arriving on `link` may be observed through this horizon.
1850	fn admits_link(&self, link: Link) -> bool {
1851		!(self.local && link != Link::Local) && !(self.upstream && link == Link::Upstream)
1852	}
1853
1854	/// This horizon as it applies to the routes covering `path`: an excluded peer
1855	/// that none of them passes through hides nothing, so it excludes nothing. Every
1856	/// session carries a hop of its own, and a viewer's never shows up in a chain, so
1857	/// this is what lets viewers share a front.
1858	///
1859	/// Decided per request: a peer whose hop joins a chain later gets the filtered
1860	/// front on its next request, while what it already reads stays on the plain
1861	/// front. That cannot loop, since the peer serves our requests through its own
1862	/// split horizon, which never routes back through us.
1863	///
1864	/// The hop cap bounds what is advertised, not what serves a request, so it never
1865	/// applies here.
1866	fn effective(self, routes: &RouteTable, path: &Path) -> Self {
1867		let horizon = Self { max_hops: None, ..self };
1868		match horizon.exclude {
1869			Some(peer) if routes.covering(path).any(|entry| !entry.visible_to(Some(peer))) => horizon,
1870			_ => Self {
1871				exclude: None,
1872				..horizon
1873			},
1874		}
1875	}
1876}
1877
1878/// The link a handle's routes arrive on; see [`Producer::with_link`].
1879///
1880/// The hop chain cannot say it, since a client and a peer relay each append one hop.
1881#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1882pub enum Link {
1883	/// Here: an in-process producer or a client session.
1884	#[default]
1885	Local,
1886	/// A cluster peer: the routes it announces entered from a peer, not here.
1887	Peer,
1888	/// An upstream peer: a [`Self::Peer`] whose routes are never offered to another
1889	/// upstream, so this origin never carries traffic between two upstreams.
1890	Upstream,
1891}
1892
1893/// One remotely-served front in [`OriginState::fronts`]: the shared broadcast at a
1894/// path plus the channel requesters resolve through.
1895#[derive(Clone)]
1896struct RemoteFront {
1897	/// Resolves requesters with the front's verdict. The producer lives here so the
1898	/// teardown can reject requesters still parked on a front whose watcher was
1899	/// cancelled.
1900	request: kio::Producer<PendingFront>,
1901	/// The front's broadcast, weak: dead once the front ends, so a
1902	/// later request re-creates the front instead of joining a corpse.
1903	broadcast: broadcast::WeakConsumer,
1904}
1905
1906/// The last route a cursor observed at a presented prefix.
1907struct CursorRoute {
1908	/// The stream it serves.
1909	identity: Identity,
1910	/// What the cursor delivered with it.
1911	meta: RouteMeta,
1912	/// Whether it serves requests: part of the dedupe key, but never delivered.
1913	served: bool,
1914	/// The absolute prefix it was announced at.
1915	prefix: Path,
1916	/// The route entry that won, which a lookup reports a change of.
1917	id: u64,
1918}
1919
1920impl WeakEntry for RemoteFront {
1921	fn is_closed(&self) -> bool {
1922		self.broadcast.is_closed()
1923	}
1924
1925	fn same_channel(&self, other: &Self) -> bool {
1926		self.broadcast.same_channel(&other.broadcast)
1927	}
1928}
1929
1930/// One registered announce cursor: which prefixes it may see, how prefixes are
1931/// re-rooted, and the per-cursor delivery buffer.
1932struct TableCursor {
1933	/// The prefix stripped from every delivered path.
1934	root: Path,
1935	/// The absolute prefixes this cursor is scoped to (its token / scope).
1936	allowed: Prefixes,
1937	/// Where the cursor hangs in the [`RouteTable`]: the members of `allowed`, or for a
1938	/// lookup its root. A route the cursor can see sits at or under one of them, or on
1939	/// the walk down to one.
1940	heads: Vec<Path>,
1941	/// The routes this cursor may see (control-plane split horizon).
1942	horizon: Horizon,
1943	/// Which routes beneath a hidden segment are reported.
1944	hidden: Hidden,
1945	/// Whether a route whose subtree only overlaps the scope is reported too, not just
1946	/// one whose literal name matches it.
1947	covering: bool,
1948	/// The delivery buffer, drained by the cursor's `poll_next`. A mounted
1949	/// consumer's cursors share one.
1950	state: kio::Producer<OriginConsumerState>,
1951	/// Where this cursor's presented prefixes land in the delivery buffer: empty,
1952	/// or the mount the cursor reads for, relative to the consumer's root.
1953	under: Path,
1954	/// The absolute prefixes a mount shadows: routes at or beneath them are not
1955	/// this cursor's to present.
1956	holes: Vec<Path>,
1957	/// For a cursor reading through a mount: the mount, which must be able to name what
1958	/// it presents.
1959	mount: Option<Mount>,
1960	/// Whether the cursor counts an [`Interest`] at each of its heads.
1961	interested: bool,
1962	/// The last delivered best route per presented (relative) prefix, for change
1963	/// detection. Servability is part of the dedupe key but never leaves the model.
1964	current: HashMap<Path, CursorRoute>,
1965	/// Whether the cursor delivers each route's [`Standing`], and a change to it.
1966	ranked: bool,
1967	/// Whether the cursor serves a path lookup ([`Consumer::path_routes`]), which reads only
1968	/// what serves its root: the entry [`RouteTable::best_route`] picks for it, as a request
1969	/// does. It sees only the routes covering its root, so one claiming only paths beneath it
1970	/// never masks the one that serves it, and it reports any change of the entry serving the
1971	/// root, which a refused request asks again.
1972	lookup: bool,
1973}
1974
1975impl TableCursor {
1976	/// Whether a route at the absolute `prefix` could serve something this cursor lists: its
1977	/// subtree overlaps the scope, or for a lookup, covers the root.
1978	fn reaches(&self, prefix: &Path) -> bool {
1979		match self.lookup {
1980			true => self.root.has_prefix(prefix),
1981			false => self.allowed.overlaps(prefix.as_str()),
1982		}
1983	}
1984
1985	/// Where `prefix` presents on this cursor, named relative to the cursor root.
1986	/// The prefix stays a prefix; the scope only decides visibility.
1987	fn presented(&self, prefix: &Path) -> Option<Path> {
1988		if !self.reaches(prefix) {
1989			return None;
1990		}
1991
1992		if let Some(relative) = prefix.strip_prefix(&self.root) {
1993			return Some(relative);
1994		}
1995		self.root.has_prefix(prefix).then(Path::default)
1996	}
1997
1998	/// Whether this cursor waits on `snapshot`: what it delivers could present here,
1999	/// as [`Self::visible`] judges a route at or beneath its prefix.
2000	fn awaits(&self, snapshot: &SnapshotEntry) -> bool {
2001		self.horizon.admits_link(snapshot.link)
2002			&& self.reaches(&snapshot.prefix)
2003			&& self.hidden.reaches(&self.heads, &snapshot.prefix)
2004			&& !self.holes.iter().any(|hole| snapshot.prefix.has_prefix(hole))
2005			// Too deep for the mount to name means everything beneath is too.
2006			&& self.mount.as_ref().is_none_or(|mount| mount.names(&snapshot.prefix))
2007	}
2008
2009	/// Whether this cursor may observe `entry` at all: advertised, not behind
2010	/// the excluded peer (split horizon), within the cursor's prefixes, and
2011	/// nameable through its mount.
2012	fn visible(&self, entry: &RouteEntry) -> bool {
2013		entry.live()
2014			&& self.horizon.admits(entry)
2015			&& self.reaches(&entry.prefix)
2016			&& (self.covering || self.allowed.matches(entry.prefix.as_str()))
2017			&& self.discovers(&entry.prefix)
2018			&& !self.holes.iter().any(|hole| entry.prefix.has_prefix(hole))
2019			&& self.mount.as_ref().is_none_or(|mount| mount.names(&entry.prefix))
2020	}
2021
2022	/// Deliver a changed winner at this presented prefix, reporting a route left with
2023	/// none as `gone`.
2024	fn update(&mut self, presented: &Path, best: Option<&RouteEntry>, gone: Gone) {
2025		let Some(entry) = best else {
2026			if let Some(last) = self.current.remove(presented)
2027				&& let Ok(mut state) = self.state.write()
2028			{
2029				state.apply_unannounce(self.under.rejoin(presented), last.meta, gone);
2030			}
2031			return;
2032		};
2033		let served = entry.server.is_some();
2034		let previous = self.current.get(presented);
2035		// Compared in place first: most visits find the winner unchanged, and building
2036		// what it delivers allocates.
2037		if previous.is_some_and(|previous| {
2038			previous.identity == entry.identity
2039				&& previous.prefix == entry.prefix
2040				&& (!self.lookup || previous.id == entry.id)
2041				&& previous.served == served
2042				&& entry.delivers(&previous.meta, self.ranked)
2043		}) {
2044			return;
2045		}
2046
2047		let meta = entry.meta(self.ranked);
2048		let previous = self.current.insert(
2049			presented.clone(),
2050			CursorRoute {
2051				identity: entry.identity.clone(),
2052				meta: meta.clone(),
2053				served,
2054				prefix: entry.prefix.clone(),
2055				id: entry.id,
2056			},
2057		);
2058		match previous {
2059			// Another identity: whatever was resolved under the prefix is another stream.
2060			Some(previous) if previous.identity != entry.identity => {
2061				if let Ok(mut state) = self.state.write() {
2062					state.apply_restart(self.under.rejoin(presented), previous.meta, gone == Gone::Offline, meta);
2063				}
2064			}
2065			// Unchanged metadata and servability: nothing the consumer could
2066			// act on, even if the winning entry itself changed (a failover
2067			// between routes of one identity and epoch is invisible, which is the point).
2068			// A servability flip is delivered: a request that failed Unroutable
2069			// under an advertise-only route retries on the update, and hiding
2070			// it would park that waiter forever. So is another entry serving a
2071			// lookup, which a refusal by the one before asks again.
2072			Some(previous)
2073				if previous.meta == meta && previous.served == served && !(self.lookup && previous.id != entry.id) => {}
2074			_ => {
2075				if let Ok(mut state) = self.state.write() {
2076					state.apply_announce(self.under.rejoin(presented), meta);
2077				}
2078			}
2079		}
2080	}
2081
2082	/// The visible entry among `candidates` that presents at the absolute `at`: the most
2083	/// specific claim, then the first eligible one in [`route_order`] resolving `at`, wherever
2084	/// each claim of that tier is filed, so the stream advertises what a request for `at`
2085	/// resolves to. One whose producer may not serve `at` is no candidate, as in
2086	/// [`RouteTable::best_route`]; one that cannot serve `at`, such as a broadcast published
2087	/// above it, still shadows broader claims but ranks behind every tier-mate that can.
2088	fn best<'a>(&self, at: &Path, candidates: impl Iterator<Item = &'a RouteEntry> + Clone) -> Option<&'a RouteEntry> {
2089		let visible = candidates.filter(|entry| self.visible(entry) && entry.authorizes(at));
2090		let epochs = Epochs::of(visible.clone());
2091		visible
2092			.clone()
2093			.filter(|entry| !epochs.superseded(entry))
2094			.min_by_key(|entry| (Reverse(entry.specificity()), !entry.serves(at), route_order(at, entry)))
2095	}
2096
2097	/// Whether the hidden rule lets this cursor discover a route at `prefix`.
2098	fn discovers(&self, prefix: &Path) -> bool {
2099		self.hidden.reaches(&self.heads, prefix)
2100	}
2101}
2102
2103/// A handle's view of an origin: the absolute prefixes it may reach, and the
2104/// subtrees it reads from elsewhere on the origin.
2105#[derive(Clone)]
2106struct OriginScope {
2107	// The paths this handle may reach, absolute, named as the handle sees them:
2108	// a path under a mount is authorized here, before it is resolved.
2109	allowed: Prefixes,
2110	// The subtrees that resolve elsewhere; see [`Producer::mount`]. Disjoint.
2111	mounts: Arc<[Mount]>,
2112	// The subtrees this handle never reaches despite `allowed`, absolute and
2113	// named as the handle sees them; see [`Consumer::exclude`].
2114	excluded: Arc<[Path]>,
2115}
2116
2117/// A subtree a handle reads from elsewhere on the origin: `at/rest` resolves at
2118/// `target/rest`. Both absolute.
2119#[derive(Clone, Debug, PartialEq, Eq)]
2120struct Mount {
2121	at: Path,
2122	target: Path,
2123}
2124
2125/// A mount as a reader of a prefix sees it through a handle: where the origin holds
2126/// what it presents, and how the handle names that.
2127#[derive(Clone, Debug, PartialEq, Eq)]
2128#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2129pub(crate) struct Mounted {
2130	mount: Mount,
2131	/// The absolute, origin-side prefix to read: the target, or beneath it for a
2132	/// reader's prefix beneath the mount point.
2133	pub interest: Path,
2134}
2135
2136#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2137impl Mounted {
2138	/// How the handle names a claim at the absolute, origin-side `path`, which lies at
2139	/// or beneath the interest: at or beneath the mount point.
2140	pub fn name(&self, path: &Path) -> Option<Path> {
2141		self.mount.name(path)
2142	}
2143
2144	/// How many segments the handle-side `path` lies beneath the mount point: the most a
2145	/// claim read through the mount can be above it. A claim covering the whole target, which
2146	/// is broader than the mount point as the handle sees it, covers no more than that.
2147	pub fn beneath(&self, path: &Path) -> u64 {
2148		path.parts().count().saturating_sub(self.mount.at.parts().count()) as u64
2149	}
2150}
2151
2152impl Mount {
2153	/// Where the handle-side absolute `path` resolves, when it is under this mount
2154	/// and the result fits the wire limits.
2155	fn resolve(&self, path: &Path) -> Option<Path> {
2156		let resolved = self.target.join(&path.strip_prefix(&self.at)?).ok()?;
2157		(resolved.depth() <= Path::MAX_PARTS).then_some(resolved)
2158	}
2159
2160	/// Where the origin-side absolute `path` shows on the handle, when it is at or
2161	/// beneath the target. A route covering the target has no handle-side name.
2162	fn name(&self, path: &Path) -> Option<Path> {
2163		self.at.join(&path.strip_prefix(&self.target)?).ok()
2164	}
2165
2166	/// Whether the origin-side absolute `path` has a handle-side name within the
2167	/// wire limits, so a reader could ask for it. A route covering the target always does.
2168	fn names(&self, path: &Path) -> bool {
2169		path.strip_prefix(&self.target).is_none_or(|rest| {
2170			self.at.depth() + rest.depth() <= Path::MAX_PARTS
2171				&& self.at.len() + usize::from(!self.at.is_empty() && !rest.is_empty()) + rest.len() <= Path::MAX_BYTES
2172		})
2173	}
2174
2175	/// The handle-side absolute `prefixes` beneath this mount, as origin-side prefixes
2176	/// beneath its target. A member too deep to root covers no valid path and drops.
2177	fn translate(&self, prefixes: &Prefixes) -> Prefixes {
2178		let target = self.target.as_str();
2179		(prefixes.rebase(self.at.as_str()).iter())
2180			.filter_map(|member| member.rooted(target).ok())
2181			.collect()
2182	}
2183
2184	/// A handle-side interest head as an origin-side one: a head beneath the mount
2185	/// moves under the target, and one above it hangs at the target itself.
2186	fn translate_head(&self, head: &Path) -> Option<Path> {
2187		match head.strip_prefix(&self.at) {
2188			Some(rest) => self.target.join(&rest).ok(),
2189			None => self.at.has_prefix(head).then(|| self.target.clone()),
2190		}
2191	}
2192}
2193
2194impl OriginScope {
2195	/// A view that reaches nothing.
2196	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2197	fn empty() -> Self {
2198		Self {
2199			allowed: Prefixes::new(),
2200			mounts: Arc::from([]),
2201			excluded: Arc::from([]),
2202		}
2203	}
2204
2205	/// This view narrowed to the absolute `prefixes`: the paths in both.
2206	fn narrow(&self, prefixes: &Prefixes) -> Option<Self> {
2207		let allowed = self.allowed.intersect(prefixes);
2208		if allowed.is_empty() {
2209			None
2210		} else {
2211			Some(Self {
2212				allowed,
2213				..self.clone()
2214			})
2215		}
2216	}
2217
2218	/// The mount the absolute `path` is under, if any.
2219	fn mount(&self, path: &Path) -> Option<&Mount> {
2220		self.mounts.iter().find(|mount| path.has_prefix(&mount.at))
2221	}
2222
2223	/// Where the absolute `path` resolves on the origin: itself, or its mount
2224	/// target. `None` when the mount would resolve it past the wire limits.
2225	fn resolve(&self, path: &Path) -> Option<Path> {
2226		match self.mount(path) {
2227			Some(mount) => mount.resolve(path),
2228			None => Some(path.clone()),
2229		}
2230	}
2231
2232	/// Whether this view may publish at the absolute `prefix`: a mount is read-only,
2233	/// so nothing is published at or beneath one, nor in an excluded subtree.
2234	fn publishes(&self, prefix: &Path) -> bool {
2235		self.mount(prefix).is_none() && !self.excluded.iter().any(|excluded| prefix.has_prefix(excluded))
2236	}
2237
2238	/// Whether this view reaches the absolute `path`.
2239	fn permits(&self, path: &Path) -> bool {
2240		self.allowed.matches(path.as_str()) && !self.excluded.iter().any(|excluded| path.has_prefix(excluded))
2241	}
2242
2243	/// The excluded subtrees a cursor must not present, in the space it reads: the
2244	/// origin's own, or `mount`'s target. `None` when an exclusion covers the whole mount.
2245	fn holes(&self, mount: Option<&Mount>) -> Option<Vec<Path>> {
2246		let Some(mount) = mount else {
2247			return Some(self.excluded.to_vec());
2248		};
2249		let mut holes = Vec::new();
2250		for excluded in self.excluded.iter() {
2251			if mount.at.has_prefix(excluded) {
2252				return None;
2253			}
2254			if excluded.has_prefix(&mount.at) {
2255				// Too deep for the mount to resolve, nothing beneath is nameable anyway.
2256				holes.extend(mount.resolve(excluded));
2257			}
2258		}
2259		Some(holes)
2260	}
2261
2262	/// What this view reaches, named from `root`.
2263	fn relative(&self, root: &Path) -> Prefixes {
2264		self.allowed.rebase(root.as_str())
2265	}
2266}
2267
2268impl Default for OriginScope {
2269	fn default() -> Self {
2270		Self {
2271			allowed: Prefixes::all(),
2272			mounts: Arc::from([]),
2273			excluded: Arc::from([]),
2274		}
2275	}
2276}
2277
2278/// Where a cursor listing `allowed` hangs: each member as a path. A member too long for a
2279/// path covers none and asks for nothing.
2280fn heads(allowed: &Prefixes) -> Vec<Path> {
2281	allowed
2282		.iter()
2283		.filter_map(|prefix| Path::new(prefix.as_str()).ok())
2284		.collect()
2285}
2286
2287/// Which routes beneath a hidden segment an announce cursor reports.
2288///
2289/// A route is hidden when a segment below the cursor's requested prefix (its
2290/// interest head) starts with `.`; a prefix that names the dot segment itself
2291/// lists what is under it. Only discovery is affected: a request by exact path
2292/// resolves either way.
2293#[derive(Clone, Debug, Default, PartialEq, Eq)]
2294pub(super) struct Hidden {
2295	/// Report hidden routes too.
2296	include: bool,
2297	/// Measure visibility from the request prefix instead of authorization heads.
2298	from: Option<Path>,
2299}
2300
2301impl Hidden {
2302	/// Whether a cursor hanging at `heads` reports a route at or beneath `prefix`. A hidden
2303	/// segment hides everything beneath it.
2304	fn reaches(&self, heads: &[Path], prefix: &Path) -> bool {
2305		self.include || !hides(self.from.as_ref().map(std::slice::from_ref).unwrap_or(heads), prefix)
2306	}
2307
2308	/// This rule for a cursor reading through `mount`, whose heads sit on the target.
2309	fn translate(&self, mount: &Mount) -> Self {
2310		Self {
2311			include: self.include,
2312			from: self.from.as_ref().and_then(|head| mount.translate_head(head)),
2313		}
2314	}
2315}
2316
2317/// Whether a segment of `prefix` below the head it sits under starts with `.`.
2318/// A route at or above a head has nothing below it, so it never hides.
2319fn hides(heads: &[Path], prefix: &Path) -> bool {
2320	heads
2321		.iter()
2322		.any(|head| prefix.strip_prefix(head).is_some_and(|below| below.is_hidden()))
2323}
2324
2325/// What a [`Routes`] yields: how the route covering a prefix changed, and that route.
2326#[derive(Clone, Debug)]
2327#[non_exhaustive]
2328pub struct RouteEvent {
2329	/// How the route changed.
2330	pub kind: RouteKind,
2331	/// The route; for [`RouteKind::End`], its last advertised route.
2332	pub announce: Announce,
2333}
2334
2335/// How the route covering a prefix changed.
2336#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2337#[non_exhaustive]
2338pub enum RouteKind {
2339	/// A route now covers the prefix; the cursor had none there.
2340	Start,
2341	/// The route covering the prefix changed hops, cost, epoch or
2342	/// [availability](RouteInfo::available), with the same identity; it is delivered in
2343	/// place.
2344	Update,
2345	/// The origin withdrew the route, as far as this origin knows, and no other covers
2346	/// the prefix.
2347	End,
2348	/// This origin let go of the route, and no other covers the prefix: the session it
2349	/// arrived on closed, or the route layer lost every path to it. Its origin may still
2350	/// serve it; only an [`End`](Self::End) says it stopped.
2351	Offline,
2352	/// Another [`Identity`] now serves the prefix: another stream, such as a publisher
2353	/// that restarted, a redundant ingest switching, or a pool failing over.
2354	///
2355	/// Whatever was resolved under the prefix before is the old stream: drop it and
2356	/// request afresh to follow the new one. Subscriptions already open stay on the old
2357	/// one until dropped or its route goes.
2358	Restart,
2359}
2360
2361/// A route over a prefix, as an announcement listing or a [`Routes`] stream reports it.
2362///
2363/// An announcement is always a prefix, never a broadcast: it advertises that
2364/// [`prefix`](Self::prefix) and every path beneath it are servable. A broadcast
2365/// announces its own path, so the prefix usually names one, but resolve it with
2366/// [`Consumer::request`]; the application decides which paths name
2367/// broadcasts, and filters them locally when it wants a subset.
2368#[derive(Clone, Debug)]
2369#[non_exhaustive]
2370pub struct Announce {
2371	/// The prefix the route covers, relative to the consuming cursor's root.
2372	pub prefix: Path,
2373	/// The route serving the prefix. On a retraction this carries its last
2374	/// advertised metadata.
2375	pub route: RouteInfo,
2376}
2377
2378/// Publishes broadcasts and announces routes into an origin.
2379#[derive(Clone)]
2380pub struct Producer {
2381	// Identity for this origin. Appended to route hops when re-announcing so
2382	// downstream relays can detect loops and prefer the shortest path.
2383	node: NonZeroU64,
2384	max_hops: NonZeroUsize,
2385
2386	// The absolute patterns this handle may publish under.
2387	scope: OriginScope,
2388
2389	// The prefix that is automatically stripped from all paths.
2390	root: Path,
2391
2392	// The origin's shared state: the route table, announce cursors, and the
2393	// remotely-served fronts. Shared with every derived consumer.
2394	shared: SendCell<kio::Shared<OriginState>>,
2395
2396	// The cache pool inherited by broadcasts created under this origin (sessions
2397	// mint their remote broadcasts with it). Unbounded by default.
2398	pool: cache::Pool,
2399
2400	// Max age ceiling inherited by broadcasts created under this origin (see
2401	// [`Config::cache_duration`]). No ceiling by default.
2402	cache_duration: Option<Duration>,
2403
2404	// Ingress stats context. Broadcasts created through this producer are attributed
2405	// to it (writes counted on the subscriber/ingress side). Empty (no-op) unless a
2406	// session tagged this handle via [`Self::with_stats`].
2407	stats: stats::Session,
2408
2409	// The link routes announced through this handle arrive on (see
2410	// [`Self::with_link`]).
2411	link: Link,
2412
2413	// The rank of that link; see [`Self::with_priority`].
2414	priority: Priority,
2415
2416	// Whether this origin forwards; see [`Config::proxy`].
2417	proxy: bool,
2418
2419	// Submission handle to the origin's [`Driver`]: source watchers, fronts, and
2420	// serve tasks queued here run when the driver is polled. Closed once the
2421	// driver drops, which is what makes later mutations fail with `Closed`.
2422	tasks: Tasks,
2423
2424	// The clock advanced by the origin driver.
2425	timers: Deadlines,
2426
2427	// What the frames written through this handle may allocate up front, shared by every
2428	// broadcast it creates.
2429	frames: super::frame::Budget,
2430
2431	// What the live edges of the tracks written through this handle may hold, shared by
2432	// every broadcast it creates.
2433	edges: super::cache::Edges,
2434}
2435
2436impl Producer {
2437	/// Build a producer from a [`Config`] (identity + cache pool) with no scoped
2438	/// prefix and no pre-existing broadcasts, paired with the [`Driver`] that runs
2439	/// the origin's lifecycle work.
2440	///
2441	/// Poll the driver with caller-supplied time for the origin to make progress.
2442	/// `moq_tokio::origin::spawn` wraps this for tokio callers.
2443	pub fn new(config: Config) -> (Self, Driver) {
2444		let (tasks, set) = TaskSet::new();
2445		let scope = OriginScope::default();
2446		let timers = Deadlines::new(Instant::ZERO);
2447		let shared = SendCell::new(kio::Shared::new(OriginState::new(config.update_hold)));
2448		let pool = config.pool.clone();
2449		let producer = Self {
2450			node: config.node.unwrap_or_else(random_id),
2451			max_hops: config.max_hops.min(MAX_HOP_LIMIT),
2452			scope: scope.clone(),
2453			root: Path::default(),
2454			shared: shared.clone(),
2455			pool: config.pool,
2456			cache_duration: config.cache_duration,
2457			stats: stats::Session::default(),
2458			link: Link::Local,
2459			priority: Priority::default(),
2460			proxy: config.proxy,
2461			tasks,
2462			timers: timers.clone(),
2463			frames: Default::default(),
2464			edges: Default::default(),
2465		};
2466		let driver = Driver {
2467			state: DriverState {
2468				set,
2469				shared,
2470				done: false,
2471			},
2472			timers,
2473			pool,
2474		};
2475		(producer, driver)
2476	}
2477
2478	/// Give this handle budgets of its own, so what one session allocates up front never
2479	/// crowds out another's, and its tracks' live edges hold at most `live_edges` bytes.
2480	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2481	pub(crate) fn with_own_budgets(mut self, live_edges: Option<u64>) -> Self {
2482		self.frames = Default::default();
2483		self.edges = super::cache::Edges::new(live_edges);
2484		self
2485	}
2486
2487	/// The ingress stats context this handle was tagged with.
2488	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2489	pub(crate) fn stats(&self) -> &stats::Session {
2490		&self.stats
2491	}
2492
2493	/// Attach an ingress stats context: broadcasts created through this handle (and
2494	/// any handle derived from it) are attributed to `session` on the subscriber
2495	/// (ingress) side. Pass [`stats::Session::default`] to opt out.
2496	pub fn with_stats(mut self, session: stats::Session) -> Self {
2497		self.stats = session;
2498		self
2499	}
2500
2501	/// Set the link this handle (and any handle derived from it) is given to.
2502	///
2503	/// Hand a session with another relay a [`Link::Peer`] handle, so this origin can
2504	/// tell what entered here from what a peer forwarded. Hand a [`Link::Upstream`]
2505	/// handle to a session with a peer that should reach everything here without this
2506	/// relay carrying its traffic to other upstreams, such as an edge's link to a core
2507	/// or a drone's link to its CDN: a [`Consumer`] taken from it hides every route an
2508	/// upstream handle announced.
2509	pub fn with_link(mut self, link: Link) -> Self {
2510		self.link = link;
2511		self
2512	}
2513
2514	/// Rank the link this handle (and any handle derived from it) is given to:
2515	/// higher wins, and every handle starts at the neutral [`Priority::default`].
2516	///
2517	/// Applies to the routes a session lands from its peer through this handle, not to
2518	/// a route created here. Only an identity's newest epoch is
2519	/// eligible, but among eligible routes priority decides before cost, so links to different
2520	/// operators rank by this instead of comparing their metrics. Hand each CDN's
2521	/// session its own rank to use the primary while it has a route and fail over to
2522	/// the next.
2523	///
2524	/// A moq-lite-07 route ranks by the lowest priority of any link on its path, so
2525	/// two relays never prefer each other's paths forever. A link promoted above the
2526	/// links before it gains nothing there: demote the fallbacks instead.
2527	pub fn with_priority(mut self, priority: Priority) -> Self {
2528		self.priority = priority;
2529		self
2530	}
2531
2532	/// Whether this origin forwards what it learns; see [`Config::proxy`].
2533	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2534	pub(crate) fn proxy(&self) -> bool {
2535		self.proxy
2536	}
2537
2538	/// The rank of the link this handle is given to; see [`Self::with_priority`].
2539	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2540	pub(crate) fn priority(&self) -> Priority {
2541		self.priority
2542	}
2543
2544	/// The link this handle's routes arrive on; see [`Self::with_link`].
2545	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2546	pub(crate) fn link(&self) -> Link {
2547		self.link
2548	}
2549
2550	/// The route layer node every lite-07 session on this origin shares; see
2551	/// [`Consumer::route_node`].
2552	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2553	pub(crate) fn route_node(&self) -> crate::route::Node {
2554		self.consume().route_node()
2555	}
2556
2557	/// This origin's construction config, less its Node ID: an origin built from it is a
2558	/// new node.
2559	pub fn config(&self) -> Config {
2560		let shared = self.shared.lock();
2561		Config {
2562			node: None,
2563			max_hops: self.max_hops,
2564			pool: self.pool.clone(),
2565			cache_duration: self.cache_duration,
2566			proxy: self.proxy,
2567			update_hold: shared.update_hold,
2568		}
2569	}
2570
2571	/// This origin's Node ID, random for each run.
2572	pub fn node(&self) -> NonZeroU64 {
2573		self.node
2574	}
2575
2576	/// Whether `id`, as a peer declared it, names this origin: its node id, which is also
2577	/// the relay its moq-lite-07 Node ID names.
2578	pub fn is_own(&self, id: NonZeroU64) -> bool {
2579		id == self.node
2580	}
2581
2582	// Sessions enforce the policy configured once on the origin.
2583	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2584	pub(crate) fn max_hops(&self) -> NonZeroUsize {
2585		self.max_hops
2586	}
2587
2588	/// A producer with *no* allowed prefixes: it can't publish anything and
2589	/// advertises no subscribe interest (its `allowed()` is empty, so the
2590	/// subscriber issues no ANNOUNCE_PLEASE). Used to fill an unset session half
2591	/// so both the publisher and subscriber loops still run.
2592	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2593	pub(crate) fn empty() -> Self {
2594		// No allowed prefixes means no broadcast is ever created, so nothing will
2595		// ever be queued on the detached submission handle.
2596		let (tasks, _) = TaskSet::new();
2597		Self {
2598			node: random_id(),
2599			scope: OriginScope::empty(),
2600			max_hops: MAX_HOP_LIMIT,
2601			root: Path::default(),
2602			shared: SendCell::new(kio::Shared::new(OriginState::new(DEFAULT_UPDATE_HOLD))),
2603			pool: cache::Pool::default(),
2604			cache_duration: None,
2605			stats: stats::Session::default(),
2606			link: Link::Local,
2607			priority: Priority::default(),
2608			proxy: false,
2609			tasks,
2610			timers: Deadlines::new(Instant::ZERO),
2611			frames: Default::default(),
2612			edges: Default::default(),
2613		}
2614	}
2615
2616	/// Create a route at exactly `path`, owning a new broadcast to fill.
2617	///
2618	/// This is how local content enters an origin. Fill the broadcast through
2619	/// [`Route::broadcast`]. The route serves a fresh random identity, minted here and
2620	/// kept for its lifetime, across [`Route::withdraw`] and [`Route::announce`], since
2621	/// its keys continue: a new route is a new stream that never splices into an
2622	/// old one. A publisher that continues one key space across restarts may name
2623	/// a stable identity instead ([`RouteOptions::with_identity`]).
2624	///
2625	/// Announced at once unless created [`RouteOptions::hidden`]. A hidden route exists
2626	/// for nobody until [`Route::announce`]: until then no announce cursor lists it and
2627	/// a request for its path fails with [`Error::Unroutable`], for a consumer of this
2628	/// origin exactly as for a peer. Create it hidden when the tracks a subscriber needs
2629	/// first, such as a catalog, are not there yet. To serve paths on demand without
2630	/// publishing each one, use [`Self::claim`].
2631	///
2632	/// Announcing is visible to local consumers before it returns; only lifecycle work
2633	/// (track serving, teardown) waits for the [`Driver`] to be polled. Register a
2634	/// [`broadcast::Producer::requests`] handler before announcing, so the first
2635	/// consumer finds the tracks it serves.
2636	///
2637	/// Dropping the last clone of the route retracts it, as does closing its broadcast.
2638	///
2639	/// Fails with [`Error::Unauthorized`] if `path` is outside the prefixes this
2640	/// producer may publish under (after [`scope`](Self::scope)) or beneath a
2641	/// [`mount`](Self::mount),
2642	/// [`Error::BoundsExceeded`] if the full rooted path exceeds
2643	/// [`Path::MAX_PARTS`] or [`Path::MAX_BYTES`], [`Error::InvalidPath`] if it holds a `*`,
2644	/// [`Error::NavigationSegment`] for a literal `.` or `..`, or [`Error::Closed`] once the origin's
2645	/// [`Driver`] has been dropped.
2646	pub fn route(&self, path: impl TryInto<Path, Error: Into<Error>>, options: RouteOptions) -> Result<Route, Error> {
2647		let full = self.root.join(&path::convert(path)?)?;
2648		self.exact(full, options, None)
2649	}
2650
2651	/// Whether this handle could publish a route at the absolute `full` prefix: its
2652	/// scope overlaps the subtree (as a forwarded claim is admitted, a covering prefix
2653	/// serving the permitted descendants), and no mount or excluded subtree covers it.
2654	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2655	pub(crate) fn publishable(&self, full: &Path) -> bool {
2656		self.scope.allowed.overlaps(full.as_str()) && self.scope.publishes(full)
2657	}
2658
2659	/// An exact route at the absolute `full` path, answering `request` on its first
2660	/// announce when it is a job's.
2661	fn exact(&self, full: Path, options: RouteOptions, request: Option<Request>) -> Result<Route, Error> {
2662		publish_path(&full)?;
2663		if !self.scope.permits(&full) || !self.scope.publishes(&full) {
2664			return Err(Error::Unauthorized);
2665		}
2666		// A decoded prefix and suffix are each within the wire limit, but their
2667		// join might not be. Enforcing here bounds the table depth and guarantees the
2668		// path can be re-encoded when forwarded.
2669		if full.depth() > Path::MAX_PARTS {
2670			return Err(BoundsExceeded.into());
2671		}
2672		// Resolve the ingress counters once, keyed by the absolute broadcast path.
2673		let ingress = self.stats.ingress(&full);
2674
2675		// The broadcast is a route table entry at its exact path from the start,
2676		// hidden from cursors and requests until it announces. The entry lives
2677		// as long as the route, or until the broadcast closes.
2678		let announcing = Announcing {
2679			hop: Hop::from(self.node),
2680			shared: self.shared.clone(),
2681			requested: full.clone(),
2682			prefixes: vec![(full.clone(), 0)],
2683			excluded: self.scope.excluded.clone(),
2684			local: true,
2685			link: self.link,
2686			priority: Priority::default(),
2687			stats: self.stats.clone(),
2688		};
2689		let info = broadcast::Info {
2690			pool: self.pool.clone(),
2691			cache_duration: self.cache_duration,
2692			path: full,
2693			identity: None,
2694			frames: self.frames.clone(),
2695			edges: self.edges.clone(),
2696		};
2697		let source = info.produce().with_stats(ingress);
2698		// A job's route naming no identity takes its prefix route's, held in the table
2699		// until it first announces; see [`Request::route`].
2700		let lender = request
2701			.as_ref()
2702			.filter(|_| options.identity.is_none())
2703			.map(|request| request.home.clone());
2704		let identity = match (&options.identity, &lender) {
2705			(None, None) => Some((Identity::random(), 0)),
2706			(named, _) => named.clone(),
2707		};
2708		let entry = announcing.announce(
2709			RouteInfo {
2710				identity: identity.as_ref().map(|(identity, _)| identity.clone()),
2711				epoch: identity.as_ref().map_or(0, |(_, epoch)| *epoch),
2712				..options.info()
2713			},
2714			Serving {
2715				server: None,
2716				source: Some(source.consume()),
2717				advertised: false,
2718				lends: false,
2719			},
2720			lender.as_ref(),
2721		)?;
2722		let hidden = options.hidden;
2723		let control = RouteControl::new(options, &entry, request);
2724		let route = Route {
2725			state: Arc::new(RouteState {
2726				announcement: entry,
2727				control: kio::Lock::new(control),
2728				forwarded: false,
2729				keepalive: std::sync::Mutex::new(Some(self.tasks.keepalive())),
2730			}),
2731			broadcast: source.clone(),
2732		};
2733		// Closing the broadcast retracts the route, and refuses the request a job's route
2734		// has not answered yet. The broadcast holds only a weak reference, so it never
2735		// keeps the route alive.
2736		let weak = Arc::downgrade(&route.state);
2737		source.on_close(Box::new(move || {
2738			if let Some(state) = weak.upgrade() {
2739				state.ended();
2740			}
2741		}));
2742		if !hidden {
2743			route.announce()?;
2744		}
2745		Ok(route)
2746	}
2747
2748	/// Mint a standalone source broadcast for a served-route request: it carries
2749	/// this origin's cache policy and ingress attribution, but
2750	/// is *not* entered into the route table. Sessions answer
2751	/// a prefix route's requests with one of these; the requester already holds
2752	/// the request's result channel, so the table never needs to resolve it.
2753	/// The source takes new tracks only while `validity` holds.
2754	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2755	pub(crate) fn create_source(
2756		&self,
2757		path: Path,
2758		validity: crate::model::broadcast::RequestValidity,
2759	) -> broadcast::Producer {
2760		// The path came off a served request, whose root join already fit.
2761		let full = self.root.join(&path).expect("request path fits");
2762		let ingress = self.stats.ingress(&full);
2763		broadcast::Info {
2764			pool: self.pool.clone(),
2765			cache_duration: self.cache_duration,
2766			path: full,
2767			identity: None,
2768			frames: self.frames.clone(),
2769			edges: self.edges.clone(),
2770		}
2771		.produce()
2772		.with_stats(ingress)
2773		.with_validity(validity)
2774	}
2775
2776	/// Advertise a route without serving it: a claim that paths under `prefix`
2777	/// can be served, answered by nothing.
2778	///
2779	/// A request under an advertise-only route resolves [`Error::Unroutable`]
2780	/// unless an announced broadcast or a prefix route ([`Self::claim`]) covers
2781	/// the path too. Tests use it to shape the route table; everything else
2782	/// advertises through a [`Route`] or [`Claim`], which serves what it claims.
2783	#[cfg(test)]
2784	pub(crate) fn announce(
2785		&self,
2786		prefix: impl TryInto<Path, Error: Into<Error>>,
2787		route: RouteInfo,
2788	) -> Result<AnnounceProducer, Error> {
2789		Announcing::new(self, prefix)?.announce(
2790			route,
2791			Serving {
2792				server: None,
2793				source: None,
2794				advertised: true,
2795				lends: false,
2796			},
2797			None,
2798		)
2799	}
2800
2801	/// Start a [`Snapshot`] under `prefix`: the announce consumers it overlaps are not
2802	/// synced until the returned guard drops. Taken before the request goes out, so
2803	/// nothing reads as synced in between.
2804	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2805	pub(crate) fn snapshot(&self, prefix: impl TryInto<Path, Error: std::fmt::Debug>) -> Snapshot {
2806		let prefix = self
2807			.root
2808			.join(&prefix.try_into().expect("snapshot prefix"))
2809			.expect("snapshot prefix fits");
2810		self.shared.lock().snapshot(&self.shared, prefix, self.link)
2811	}
2812
2813	/// Hear what this handle's session should ask its peer about: the broadest
2814	/// prefixes readers of the origin want discovered, mapped onto this handle's
2815	/// scope, starting with the current ones.
2816	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2817	pub(crate) fn interests(&self) -> Interests {
2818		let queue = kio::Queue::new();
2819		let mut state = self.shared.lock();
2820		let id = state.next_listener;
2821		state.next_listener += 1;
2822		let listener = Listener {
2823			id,
2824			root: self.root.clone(),
2825			heads: (self.allowed().iter())
2826				.filter_map(|prefix| Path::new(prefix.as_str()).ok())
2827				.collect(),
2828			allowed: self.scope.allowed.clone(),
2829			link: self.link,
2830			queue: queue.clone(),
2831		};
2832		match state.closed {
2833			true => queue.close(),
2834			false => {
2835				for prefix in state.routes.interests_from(&Path::empty()) {
2836					for relative in listener.asks(&prefix) {
2837						// A head too long to root covers no path, so nothing reads it.
2838						let Ok(absolute) = self.root.join(&relative) else {
2839							continue;
2840						};
2841						let snapshot = state.snapshot(&self.shared, absolute, self.link);
2842						let _ = queue.try_push(InterestChange {
2843							prefix: relative,
2844							wanted: true,
2845							snapshot: Some(snapshot),
2846						});
2847					}
2848				}
2849				state.listeners.push(listener);
2850			}
2851		}
2852		Interests {
2853			shared: self.shared.clone(),
2854			id,
2855			queue,
2856		}
2857	}
2858
2859	/// Whether routes arrive here on a link between relays ([`Link::Peer`] or
2860	/// [`Link::Upstream`]), whose sessions discover everything they may.
2861	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2862	pub(crate) fn relays(&self) -> bool {
2863		self.link != Link::Local
2864	}
2865
2866	/// Create a [`Claim`] over `prefix` that serves the requests beneath it.
2867	///
2868	/// A route is always a prefix on the wire: a claim covers `prefix` and every path
2869	/// beneath it (the empty prefix claims every path). A service that only serves some of
2870	/// them, say `pid/*.hang`, advertises the covering prefix and refuses the
2871	/// rest as they are requested; consumers narrow what they list locally.
2872	/// This is the one shape every wire carries, so a route means the same
2873	/// thing on every hop.
2874	///
2875	/// A consumer resolving a path under it through this route is handed to
2876	/// [`Claim::poll_requested`] as a [`Request`]: answer it by serving a broadcast already
2877	/// held ([`Request::serve`]), under this route's identity, or by creating the path's
2878	/// own exact route ([`Request::route`]). This is how a service answers a whole
2879	/// subtree without publishing each path ahead of time; a publisher that
2880	/// knows its broadcasts creates each one's exact route with [`Self::route`]
2881	/// instead, so subscribers can enumerate them.
2882	///
2883	/// Unless `options` names an identity, the route lends the one it mints to the exact
2884	/// routes answering its requests, so a reader that resolved a path through it
2885	/// continues on that path's answer rather than restarting. Once an exact route holding
2886	/// the lent identity stops serving it (withdrawn, closed, or renamed), this route moves
2887	/// to a fresh identity, as a restarted job's keys are another stream: see
2888	/// [`Claim::identity`]. A claim naming a stable identity lends nothing, and its
2889	/// answers each mint their own.
2890	///
2891	/// The claim is priced, credentialed and shown like an exact route. It is visible
2892	/// for as long as the returned [`Claim`] (and every clone) lives, unless withdrawn.
2893	///
2894	/// The prefix must overlap this producer's scope. Individual requests remain
2895	/// authoritative and are refused when the scope does not cover them.
2896	pub fn claim(&self, prefix: impl TryInto<Path, Error: Into<Error>>, options: RouteOptions) -> Result<Claim, Error> {
2897		// A minted identity lives in the table, which moves it on as its jobs end; see
2898		// [`OriginState::advance`].
2899		let info = RouteInfo {
2900			identity: options.identity.as_ref().map(|(identity, _)| identity.clone()),
2901			epoch: options.identity.as_ref().map_or(0, |(_, epoch)| *epoch),
2902			..options.info()
2903		};
2904		let advertised = !options.hidden;
2905		let lends = options.identity.is_none();
2906		self.serving_route(prefix, info, Some(self.clone()), advertised, lends, options)
2907	}
2908
2909	/// Land a peer's route with its wire metadata.
2910	#[cfg(any(feature = "async", test))]
2911	pub(crate) fn forward(
2912		&self,
2913		prefix: impl TryInto<Path, Error: Into<Error>>,
2914		mut info: RouteInfo,
2915	) -> Result<Claim, Error> {
2916		// A handle that names no identity serves one of its own.
2917		let identity = info.identity.get_or_insert_with(Identity::random).clone();
2918		let options = RouteOptions {
2919			hidden: false,
2920			cost: info.cost,
2921			auth: info.auth.clone(),
2922			identity: Some((identity, info.epoch)),
2923		};
2924		self.serving_route(prefix, info, None, true, false, options)
2925	}
2926
2927	fn serving_route(
2928		&self,
2929		prefix: impl TryInto<Path, Error: Into<Error>>,
2930		info: RouteInfo,
2931		publisher: Option<Producer>,
2932		advertised: bool,
2933		lends: bool,
2934		options: RouteOptions,
2935	) -> Result<Claim, Error> {
2936		let announcing = Announcing::new(self, prefix)?;
2937		let serve = kio::Shared::<ServeState>::default();
2938		serve.lock().requests.add_handler();
2939		let announcement = announcing.announce(
2940			info,
2941			Serving {
2942				server: Some(serve.clone()),
2943				source: None,
2944				advertised,
2945				lends,
2946			},
2947			None,
2948		)?;
2949		let control = RouteControl::new(options, &announcement, None);
2950		// A session's route outlives nothing it was given: dropping it means the session lost it.
2951		let forwarded = publisher.is_none();
2952		Ok(Claim {
2953			state: Arc::new(RouteState {
2954				announcement,
2955				control: kio::Lock::new(control),
2956				forwarded,
2957				keepalive: std::sync::Mutex::new(Some(self.tasks.keepalive())),
2958			}),
2959			server: serve,
2960			publisher,
2961		})
2962	}
2963
2964	/// Returns a producer rooted at `root` and restricted to `prefixes`, each covering
2965	/// its whole subtree.
2966	///
2967	/// `root` is relative to this producer's root, and `prefixes` are relative to
2968	/// the new root. Returns [`Error::Unauthorized`] when the requested scope has
2969	/// no overlap with this producer's scope, or [`Error::BoundsExceeded`] when
2970	/// rooting the prefixes would exceed the path limit or the root holds a `*`.
2971	pub fn scope(&self, root: impl TryInto<Path, Error: Into<Error>>, prefixes: &Prefixes) -> Result<Producer, Error> {
2972		let root = self.root.join(&path::convert(root)?)?;
2973		let rooted = prefixes.rooted(root.as_str()).map_err(|_| BoundsExceeded)?;
2974		let scope = self.scope.narrow(&rooted).ok_or(Error::Unauthorized)?;
2975		Ok(Producer {
2976			node: self.node,
2977			max_hops: self.max_hops,
2978			scope,
2979			root,
2980			shared: self.shared.clone(),
2981			pool: self.pool.clone(),
2982			cache_duration: self.cache_duration,
2983			stats: self.stats.clone(),
2984			link: self.link,
2985			priority: self.priority,
2986			proxy: self.proxy,
2987			tasks: self.tasks.clone(),
2988			timers: self.timers.clone(),
2989			frames: self.frames.clone(),
2990			edges: self.edges.clone(),
2991		})
2992	}
2993
2994	/// A clone that never reaches the subtree at `prefix`, relative to this root:
2995	/// nothing is published or announced at or beneath it, and a consumer derived
2996	/// from the result does not see it. [`allowed`](Self::allowed) is unchanged.
2997	pub fn exclude(&self, prefix: impl TryInto<Path, Error: Into<Error>>) -> Result<Self, Error> {
2998		let prefix = self.root.join(&path::convert(prefix)?)?;
2999		let mut producer = self.clone();
3000		producer.scope.excluded = self.scope.excluded.iter().cloned().chain([prefix]).collect();
3001		Ok(producer)
3002	}
3003
3004	/// Returns a producer that reads the subtree at `at` from `target` instead.
3005	///
3006	/// Both are relative to this producer's root. A consumer derived from the
3007	/// result resolves `at/rest` at `target/rest`, through the one front serving
3008	/// that path, and presents the routes under `target` (or covering it) under
3009	/// `at`. Permissions stay named from the handle's side: a later
3010	/// [`scope`](Self::scope) authorizes `at/rest` as written. The mount is
3011	/// read-only: nothing is published at or beneath `at`, so what a reader finds
3012	/// there is only ever `target`'s. Whatever the origin holds at `at` itself is
3013	/// hidden from the mounted handle.
3014	///
3015	/// Returns [`Error::Unauthorized`] unless this producer reaches all of
3016	/// `target`, none of it [excluded](Self::exclude), so a mount never widens a scope, and [`Error::Duplicate`] when
3017	/// `at` or `target` overlaps a mount point this producer already has, or `at`
3018	/// overlaps an existing target or its own: mounts never chain, in whatever order they are added,
3019	/// so a target is always read as the origin holds it. Mounts may share a target.
3020	/// [`Error::BoundsExceeded`] if either rooted path exceeds [`Path::MAX_PARTS`] or [`Path::MAX_BYTES`],
3021	/// and [`Error::InvalidPath`] if `at` holds a `*`.
3022	pub fn mount(
3023		&self,
3024		at: impl TryInto<Path, Error: Into<Error>>,
3025		target: impl TryInto<Path, Error: Into<Error>>,
3026	) -> Result<Producer, Error> {
3027		let at = self.root.join(&path::convert(at)?)?;
3028		let target = self.root.join(&path::convert(target)?)?;
3029		if at.depth() > Path::MAX_PARTS || target.depth() > Path::MAX_PARTS {
3030			return Err(BoundsExceeded.into());
3031		}
3032		nameable(&at)?;
3033		let overlaps = |a: &Path, b: &Path| a.has_prefix(b) || b.has_prefix(a);
3034		// An excluded subtree at, above, or beneath the target would be read under `at`.
3035		if !self.scope.allowed.matches(target.as_str())
3036			|| self.scope.excluded.iter().any(|excluded| overlaps(&target, excluded))
3037		{
3038			return Err(Error::Unauthorized);
3039		}
3040		// Symmetric, so the order mounts are added never changes which sets are accepted:
3041		// no mount point overlaps any mount's point or target, its own included.
3042		// Targets may overlap.
3043		if overlaps(&at, &target)
3044			|| self
3045				.scope
3046				.mounts
3047				.iter()
3048				.any(|mount| overlaps(&at, &mount.at) || overlaps(&target, &mount.at) || overlaps(&at, &mount.target))
3049		{
3050			return Err(Error::Duplicate);
3051		}
3052		let mounts = self
3053			.scope
3054			.mounts
3055			.iter()
3056			.cloned()
3057			.chain([Mount { at, target }])
3058			.collect();
3059		Ok(Producer {
3060			scope: OriginScope {
3061				mounts,
3062				..self.scope.clone()
3063			},
3064			..self.clone()
3065		})
3066	}
3067
3068	/// Cheap read handle over this origin's route table.
3069	///
3070	/// Use [`Consumer::announced`] to register interest and start receiving
3071	/// announcement events; the consumer itself does not allocate any channels.
3072	pub fn consume(&self) -> Consumer {
3073		// Untagged: a session tags the egress consumer separately via
3074		// `origin::Consumer::with_stats` (ingress and egress are distinct sides).
3075		Consumer::from_producer(self, stats::Session::default())
3076	}
3077
3078	/// Returns the root that is automatically stripped from all paths.
3079	pub fn root(&self) -> &Path {
3080		&self.root
3081	}
3082
3083	/// The prefixes this producer may publish under, relative to its root.
3084	pub fn allowed(&self) -> Prefixes {
3085		self.scope.relative(&self.root)
3086	}
3087
3088	/// Converts a relative path to an absolute path.
3089	pub fn absolute(&self, path: impl TryInto<Path, Error: Into<Error>>) -> Result<Path, Error> {
3090		Ok(self.root.join(&path::convert(path)?)?)
3091	}
3092}
3093
3094/// What it takes to insert a route: the prefixes it covers and the origin table
3095/// to insert them into. Built by [`Producer::route`], [`Producer::claim`]
3096/// and the advertise-only test helper.
3097struct Announcing {
3098	hop: Hop,
3099	shared: SendCell<kio::Shared<OriginState>>,
3100	/// The absolute advertised prefix, which also keys the ingress announce counters.
3101	requested: Path,
3102	/// Where the route is filed in the table (see [`filed`]), each with how many segments
3103	/// beneath the advertised prefix it lies.
3104	prefixes: Vec<(Path, u8)>,
3105	/// The absolute subtrees the producer may not serve.
3106	excluded: Arc<[Path]>,
3107	local: bool,
3108	/// The link the producer's routes arrive on.
3109	link: Link,
3110	/// The rank of that link; a broadcast published here is on none, so it ranks at the default.
3111	priority: Priority,
3112	stats: stats::Session,
3113}
3114
3115impl Announcing {
3116	/// The requested prefix, filed where the scope lets it serve (see [`filed`]), refused
3117	/// when its subtree does not overlap the scope.
3118	fn new(producer: &Producer, prefix: impl TryInto<Path, Error: Into<Error>>) -> Result<Self, Error> {
3119		let requested = producer.root.join(&path::convert(prefix)?)?;
3120		publish_path(&requested)?;
3121		if requested.depth() > Path::MAX_PARTS {
3122			return Err(BoundsExceeded.into());
3123		}
3124		if !producer.scope.publishes(&requested) {
3125			return Err(Error::Unauthorized);
3126		}
3127		let scope = &producer.scope;
3128		let prefixes = filed(&scope.allowed, &requested, |prefix| scope.publishes(prefix));
3129		if prefixes.is_empty() {
3130			return Err(Error::Unauthorized);
3131		}
3132		Ok(Self {
3133			hop: Hop::from(producer.node),
3134			shared: producer.shared.clone(),
3135			requested,
3136			prefixes,
3137			excluded: producer.scope.excluded.clone(),
3138			local: false,
3139			link: producer.link,
3140			priority: producer.priority,
3141			stats: producer.stats.clone(),
3142		})
3143	}
3144
3145	/// Insert the route. A job's route naming no identity reads as its `lender`'s, the
3146	/// prefix route its request came through, until it binds one as it announces.
3147	fn announce(
3148		&self,
3149		route: RouteInfo,
3150		serving: Serving,
3151		lender: Option<&kio::Shared<ServeState>>,
3152	) -> Result<AnnounceProducer, Error> {
3153		debug_assert!(
3154			!route.hops.contains(&self.hop),
3155			"announce called with a looping hop chain",
3156		);
3157
3158		let via = route.via;
3159
3160		let mut shared = self.shared.lock();
3161		if shared.closed {
3162			return Err(Error::Closed);
3163		}
3164
3165		// A handle that names no identity serves one of its own.
3166		let minted = route.identity.clone().unwrap_or_else(Identity::random);
3167		let filed: Arc<[Path]> = self.prefixes.iter().map(|(prefix, ..)| prefix.clone()).collect();
3168		let mut entries = Vec::with_capacity(self.prefixes.len());
3169		for (prefix, below) in &self.prefixes {
3170			shared.reannounced(prefix, &route.hops);
3171			let id = shared.next_route;
3172			shared.next_route += 1;
3173			let stale = shared.withdrawn_through(prefix, &route.hops);
3174			let (identity, epoch) = match lender.and_then(|server| shared.lender(prefix, server)) {
3175				Some(lent) => (lent.identity, lent.epoch),
3176				None => (minted.clone(), route.epoch),
3177			};
3178			shared.routes.insert(RouteEntry {
3179				id,
3180				since: id,
3181				identity,
3182				epoch,
3183				prefix: prefix.clone(),
3184				below: *below,
3185				filed: filed.clone(),
3186				excluded: self.excluded.clone(),
3187				hops: route.hops.clone(),
3188				cost: route.cost,
3189				auth: route.auth.clone(),
3190				priority: self.priority,
3191				via,
3192				local: self.local,
3193				link: self.link,
3194				marked: route.marked,
3195				node: route.node,
3196				lane: Lane {
3197					above: route.lane.above.saturating_add(*below),
3198					..route.lane.clone()
3199				},
3200				draining: route.draining,
3201				available: route.available,
3202				server: serving.server.clone(),
3203				source: serving.source.clone(),
3204				advertised: serving.advertised,
3205				stale,
3206				retired: false,
3207				lends: serving.lends,
3208				lent: None,
3209			});
3210			shared.sync_route(prefix, Gone::End);
3211			entries.push((prefix.clone(), id));
3212		}
3213		drop(shared);
3214
3215		// Ingress announce guard: held while the route is advertised.
3216		let ingress = self.stats.ingress(&self.requested);
3217		let guard = serving.advertised.then(|| ingress.announce());
3218
3219		Ok(AnnounceProducer {
3220			shared: self.shared.clone(),
3221			entries,
3222			ingress,
3223			guard: kio::Lock::new(guard),
3224		})
3225	}
3226}
3227
3228/// What a route entry serves and whether cursors see it.
3229struct Serving {
3230	server: Option<kio::Shared<ServeState>>,
3231	source: Option<broadcast::Consumer>,
3232	advertised: bool,
3233	/// Whether the job routes answering it take its identity; see [`RouteEntry::lends`].
3234	lends: bool,
3235}
3236
3237/// An exact route on an origin: one path, owning the broadcast published there.
3238///
3239/// On the publishing side ownership runs origin → route → broadcast → track → group →
3240/// frame. Created by [`Producer::route`], or by [`Request::route`] to answer a request
3241/// with the path's own route. A prefix served on demand is a [`Claim`] instead.
3242///
3243/// A route mints its identity when it is created and keeps it for its lifetime, across
3244/// [`withdraw`](Self::withdraw), [`announce`](Self::announce) and reconnects, since it
3245/// owns the same broadcast and its keys continue. A new run is a new route.
3246///
3247/// ```
3248/// # fn run(origin: moq_net::origin::Producer) -> Result<(), moq_net::Error> {
3249/// use moq_net::origin::RouteOptions;
3250///
3251/// // Fill the catalog before readers can find it.
3252/// let route = origin.route("live/alice", RouteOptions::hidden())?;
3253/// let _catalog = route.broadcast().create_track("catalog.json", None).ok_or(moq_net::Error::Duplicate)?;
3254/// route.announce()?; // visible now, same identity
3255/// route.set_cost(5)?; // re-prices in place
3256/// route.withdraw(); // hidden; announce() again continues the same stream
3257/// # Ok(())
3258/// # }
3259/// ```
3260///
3261/// Clones share one route. Dropping the last clone retracts it, and so does closing
3262/// its broadcast. The broadcast lives on for the subscriptions already on it for as
3263/// long as another of its producer handles does. The route keeps the origin's
3264/// [`Driver`] running, so a publisher can drop every [`Producer`] and keep serving.
3265#[derive(Clone)]
3266#[must_use = "dropping the last clone of a route retracts it"]
3267pub struct Route {
3268	// Declared first so the advertisement retracts before the broadcast handle drops.
3269	state: Arc<RouteState>,
3270	broadcast: broadcast::Producer,
3271}
3272
3273/// A prefix route on an origin: a claim that every path beneath a prefix can be served,
3274/// answering each request as it arrives.
3275///
3276/// Created by [`Producer::claim`]. Requests arrive on [`Self::poll_requested`]; answer
3277/// each by serving a broadcast already held or by creating the path's own [`Route`].
3278///
3279/// Clones share one claim. Dropping the last clone retracts it and refuses the requests
3280/// still waiting. The claim keeps the origin's [`Driver`] running.
3281#[derive(Clone)]
3282#[must_use = "dropping the last clone of a claim retracts it"]
3283pub struct Claim {
3284	state: Arc<RouteState>,
3285	/// The queue requests arrive on.
3286	server: kio::Shared<ServeState>,
3287	/// Present for an application's claim, whose requests may create their own exact
3288	/// routes. A session-forwarded request can only serve its peer's broadcast.
3289	publisher: Option<Producer>,
3290}
3291
3292/// What a [`Route`] and a [`Claim`] share: the advertisement and how it is changed.
3293struct RouteState {
3294	/// The advertisement, retracted on drop.
3295	announcement: AnnounceProducer,
3296	control: kio::Lock<RouteControl>,
3297	/// Whether a session landed it for its peer, so dropping it means the session lost
3298	/// the route ([`RouteKind::Offline`]), not that its origin ended it.
3299	forwarded: bool,
3300	/// A route is lifecycle work: the origin's driver keeps running for as long as one
3301	/// lives, even once every producer handle is gone. `None` once [`Claim::disown`]ed.
3302	keepalive: std::sync::Mutex<Option<Keepalive>>,
3303}
3304
3305/// What a route advertises when it announces, changed under one lock so concurrent
3306/// announces, withdrawals and re-prices land in order.
3307struct RouteControl {
3308	options: RouteOptions,
3309	/// The identity and epoch the route advertises, as last seen when [`Self::held`].
3310	identity: (Identity, u64),
3311	/// Whether the table entry holds the identity: a prefix route that lends its own, which
3312	/// moves on as its jobs end (see [`OriginState::advance`]), or a job's route taking one
3313	/// from it. An update then names none, leaving the entry's as it is.
3314	held: bool,
3315	/// Whether a job's route read its identity before it first announced: it then announces
3316	/// under that one or not at all, so whatever was built from it, such as a signer, stays
3317	/// valid.
3318	bound: bool,
3319	/// The request a job's route answers when it first announces.
3320	request: Option<Request>,
3321}
3322
3323impl RouteControl {
3324	fn new(options: RouteOptions, announcement: &AnnounceProducer, request: Option<Request>) -> Self {
3325		let held = options.identity.is_none();
3326		let identity = announcement
3327			.identity(None)
3328			.expect("a route just inserted has its entries");
3329		Self {
3330			options,
3331			identity,
3332			held,
3333			bound: false,
3334			request,
3335		}
3336	}
3337
3338	/// What to advertise.
3339	fn info(&self) -> RouteInfo {
3340		let (identity, epoch) = &self.identity;
3341		RouteInfo {
3342			identity: (!self.held).then(|| identity.clone()),
3343			epoch: *epoch,
3344			..self.options.info()
3345		}
3346	}
3347}
3348
3349impl RouteState {
3350	/// The broadcast closed: retract the route for good and refuse a job's unanswered
3351	/// request.
3352	fn ended(&self) {
3353		// Retracted under the control lock, so an announce racing the close either lands
3354		// first or finds the entries gone, never advertises after it.
3355		let mut control = self.control.lock();
3356		let request = control.request.take();
3357		self.announcement.retract(Retract::Ended);
3358		drop(control);
3359		// Dropped outside every lock: refusing it wakes the requesters.
3360		drop(request);
3361	}
3362}
3363
3364impl RouteState {
3365	/// See [`Route::identity`] and [`Claim::identity`].
3366	fn identity(&self) -> Identity {
3367		let mut control = self.control.lock();
3368		if control.held && !control.bound {
3369			let lender = control.request.as_ref().map(|request| &request.home);
3370			if let Some(current) = self.announcement.identity(lender) {
3371				control.identity = current;
3372			}
3373			control.bound = control.request.is_some();
3374		}
3375		control.identity.0.clone()
3376	}
3377
3378	/// See [`Route::withdraw`] and [`Claim::withdraw`].
3379	fn withdraw(&self) {
3380		let _control = self.control.lock();
3381		self.announcement.withdraw();
3382	}
3383
3384	/// See [`Route::is_announced`] and [`Claim::is_announced`].
3385	fn is_announced(&self) -> bool {
3386		self.announcement.route().is_some()
3387	}
3388
3389	/// Apply `update` to the options, re-advertising a visible route in place. A failed
3390	/// change keeps the options as they were, so a closed route holds nothing it was given.
3391	fn change(&self, update: impl FnOnce(&mut RouteOptions)) -> Result<(), Error> {
3392		let mut control = self.control.lock();
3393		let previous = control.options.clone();
3394		update(&mut control.options);
3395		// One rollback for both failures: closed before the check, or between it and the update.
3396		let result = match self.announcement.is_live() {
3397			Ok(true) => self.announcement.update_if(control.info(), None, |_| true).map(drop),
3398			Ok(false) => Ok(()),
3399			Err(err) => Err(err),
3400		};
3401		if result.is_err() {
3402			control.options = previous;
3403		}
3404		result
3405	}
3406}
3407
3408impl Route {
3409	/// The broadcast this route owns, to fill with tracks.
3410	pub fn broadcast(&self) -> &broadcast::Producer {
3411		&self.broadcast
3412	}
3413
3414	/// The stream this route serves, minted when it was created unless
3415	/// [`RouteOptions::with_identity`] named one.
3416	///
3417	/// A job's route ([`Request::route`]) naming none takes its claim's current one when it
3418	/// first announces, or when this reads it first. Read before announcing, it is the one
3419	/// the job announces under, and [`Self::announce`] fails with [`Error::Unroutable`] once
3420	/// the claim has moved past it.
3421	pub fn identity(&self) -> Identity {
3422		self.state.identity()
3423	}
3424
3425	/// Make the route visible, or keep it so. Idempotent.
3426	///
3427	/// Visible to local consumers before it returns. A job's route ([`Request::route`])
3428	/// also answers the requesters waiting on its path.
3429	///
3430	/// Fails with [`Error::Closed`] once the route's broadcast closed or the origin's
3431	/// [`Driver`] was dropped, and with [`Error::Unroutable`], announcing nothing, when a
3432	/// job's request was released or its claim retracted meanwhile, or when the job read
3433	/// its [`identity`](Self::identity) and its claim has moved past it since: that route
3434	/// can never announce. In that last case the request goes back to the claim's handler,
3435	/// its requesters still waiting.
3436	pub fn announce(&self) -> Result<(), Error> {
3437		let mut control = self.state.control.lock();
3438		let info = control.info();
3439		let Some(mut request) = control.request.take() else {
3440			return self.state.announcement.update_if(info, None, |_| true).map(|_| ());
3441		};
3442		let bound = std::mem::take(&mut control.bound).then(|| control.identity.0.clone());
3443		let mut moved = false;
3444		let answer = self.broadcast.consume();
3445		let mut resolved = None;
3446		// Answered under the table lock that every release takes first, so the route
3447		// lands only for a request still pending and no release can slip in between.
3448		// A job's route naming no identity takes its claim's current one as it lands, so
3449		// whatever resolved through the claim for the path continues on it rather than
3450		// restarting.
3451		let lender = control.held.then_some(&request.home);
3452		let admitted = self.state.announcement.update_if(info, lender, |table| {
3453			// The claim's entries leave the table before its retraction releases the
3454			// request, so one gone from it no longer answers, even before that release.
3455			let home = table.routes.covering(&request.path).any(|entry| {
3456				entry
3457					.server
3458					.as_ref()
3459					.is_some_and(|server| server.is_clone(&request.home))
3460			});
3461			if !home {
3462				return false;
3463			}
3464			// A job that read its identity announces under it or not at all. A claim that
3465			// lends nothing never moves, and one no longer serving released the request.
3466			if let Some(bound) = &bound
3467				&& table
3468					.lender(&request.path, &request.home)
3469					.is_some_and(|lent| lent.identity != *bound)
3470			{
3471				moved = true;
3472				return false;
3473			}
3474			// The exact route owns this answer's availability. Caching it under the
3475			// claim would keep serving it after this route is withdrawn.
3476			resolved = request
3477				.home
3478				.lock()
3479				.take(&request.path, &request.producer)
3480				.map(|()| Ok(answer));
3481			resolved.is_some()
3482		});
3483		let Some(resolved) = resolved.filter(|_| matches!(admitted, Ok(true))) else {
3484			// A failed answer can never announce. Retracted under the control lock, as
3485			// `ended` does, so a clone's racing announce finds the entries gone rather than
3486			// advertising through the ordinary branch now that the request is taken.
3487			self.state.announcement.retract(Retract::Ended);
3488			drop(control);
3489			// The claim moved past the identity the job read: its requesters wait on for
3490			// the handler to prepare the job again under the new one.
3491			request.requeue = moved;
3492			drop(request);
3493			return Err(admitted.err().unwrap_or(Error::Unroutable));
3494		};
3495		drop(control);
3496		// Woken outside every lock: a front re-entering the table must not find it held.
3497		if let Ok(mut pending) = request.producer.write() {
3498			pending.resolved.get_or_insert(resolved);
3499		}
3500		Ok(())
3501	}
3502
3503	/// Hide the route from everyone, local and remote alike, keeping its broadcast and
3504	/// identity: [`Self::announce`] brings the same stream back. Requests for the path
3505	/// fail with [`Error::Unroutable`] meanwhile, while tracks already in flight carry
3506	/// on to their own end. Idempotent.
3507	pub fn withdraw(&self) {
3508		self.state.withdraw()
3509	}
3510
3511	/// Whether the route is visible.
3512	pub fn is_announced(&self) -> bool {
3513		self.state.is_announced()
3514	}
3515
3516	/// Re-price the route: lower wins among routes covering the same prefix and anonymity.
3517	/// A visible route changes in place, as an update to its readers; a hidden one
3518	/// keeps the price for when it next announces.
3519	///
3520	/// Fails with [`Error::Closed`] once the route's broadcast closed or the origin's
3521	/// [`Driver`] was dropped.
3522	pub fn set_cost(&self, cost: impl Into<Cost>) -> Result<(), Error> {
3523		let cost = cost.into();
3524		self.state.change(|options| options.cost = cost)
3525	}
3526
3527	/// Swap the credential the advertising request carries; see [`RouteOptions::with_auth`].
3528	/// `None` advertises under the session's scope.
3529	///
3530	/// Fails with [`Error::Closed`] once the route's broadcast closed or the origin's
3531	/// [`Driver`] was dropped.
3532	pub fn set_auth(&self, auth: Option<crate::auth::Credential>) -> Result<(), Error> {
3533		self.state.change(|options| options.auth = auth)
3534	}
3535
3536	/// The route metadata as advertised, or `None` while hidden.
3537	#[cfg(test)]
3538	pub(crate) fn route(&self) -> Option<RouteInfo> {
3539		self.state.announcement.route()
3540	}
3541
3542	/// Announce with `info` as given, identity included when it names one, as a
3543	/// session's update does: for tests that shape an exact route's metadata.
3544	#[cfg(all(test, feature = "async"))]
3545	pub(crate) fn announce_info(&self, mut info: RouteInfo) -> Result<(), Error> {
3546		let mut control = self.state.control.lock();
3547		match &info.identity {
3548			Some(identity) => {
3549				control.identity = (identity.clone(), info.epoch);
3550				control.held = false;
3551			}
3552			None => {
3553				info.identity = Some(control.identity.0.clone());
3554				info.epoch = control.identity.1;
3555			}
3556		}
3557		control.options.cost = info.cost;
3558		control.options.auth = info.auth.clone();
3559		self.state.announcement.update_if(info, None, |_| true).map(|_| ())
3560	}
3561}
3562
3563impl Claim {
3564	/// The stream this claim serves, minted when it was created unless
3565	/// [`RouteOptions::with_identity`] named one.
3566	///
3567	/// Unnamed, it can change: the claim moves to a fresh identity each time an answer
3568	/// holding its current one ends. See [`Producer::claim`].
3569	pub fn identity(&self) -> Identity {
3570		self.state.identity()
3571	}
3572
3573	/// Make the claim visible, or keep it so. Idempotent. Visible to local consumers
3574	/// before it returns.
3575	///
3576	/// Fails with [`Error::Closed`] once the origin's [`Driver`] was dropped.
3577	pub fn announce(&self) -> Result<(), Error> {
3578		let control = self.state.control.lock();
3579		self.state
3580			.announcement
3581			.update_if(control.info(), None, |_| true)
3582			.map(|_| ())
3583	}
3584
3585	/// Hide the claim from everyone, local and remote alike, keeping its identity:
3586	/// [`Self::announce`] brings it back. Requests beneath it fail with
3587	/// [`Error::Unroutable`] meanwhile. Idempotent.
3588	pub fn withdraw(&self) {
3589		self.state.withdraw()
3590	}
3591
3592	/// Whether the claim is visible.
3593	pub fn is_announced(&self) -> bool {
3594		self.state.is_announced()
3595	}
3596
3597	/// Re-price the claim: lower wins among routes covering the same prefix and anonymity.
3598	/// A visible claim changes in place, as an update to its readers; a hidden one
3599	/// keeps the price for when it next announces.
3600	///
3601	/// Fails with [`Error::Closed`] once the origin's [`Driver`] was dropped.
3602	pub fn set_cost(&self, cost: impl Into<Cost>) -> Result<(), Error> {
3603		let cost = cost.into();
3604		self.state.change(|options| options.cost = cost)
3605	}
3606
3607	/// Swap the credential the advertising request carries; see [`RouteOptions::with_auth`].
3608	/// `None` advertises under the session's scope.
3609	///
3610	/// Fails with [`Error::Closed`] once the origin's [`Driver`] was dropped.
3611	pub fn set_auth(&self, auth: Option<crate::auth::Credential>) -> Result<(), Error> {
3612		self.state.change(|options| options.auth = auth)
3613	}
3614
3615	/// The next path a consumer requests beneath this claim, as a [`Request`] to answer.
3616	///
3617	/// Takes `&self` so a handler can answer from one task while another re-prices the
3618	/// claim; concurrent callers each receive distinct requests. Returns `None` once the
3619	/// claim is retracted or the origin's [`Driver`] was dropped, so handler loops end.
3620	#[cfg_attr(feature = "async", kio::wrapper)]
3621	pub fn poll_requested(&self, waiter: &kio::Waiter) -> Poll<Option<Request>> {
3622		let mut state = ready!(self.server.poll(waiter, |state| {
3623			if state.closed || state.requests.has_queued() {
3624				Poll::Ready(())
3625			} else {
3626				Poll::Pending
3627			}
3628		}));
3629
3630		// The teardown already drained the queue, so there is nothing left to pop.
3631		if state.closed {
3632			return Poll::Ready(None);
3633		}
3634
3635		let path = state.requests.pop().expect("predicate guaranteed a request");
3636		// The popped request stays pending, so a repeat request in the window between
3637		// hand-off and answer coalesces onto it instead of re-invoking the handler. The
3638		// producer is a shared clone; answering or dropping the `Request` removes the
3639		// entry. This mirrors how `poll_requested_track` keeps a served track
3640		// discoverable via the weak cache across the same window.
3641		let producer = state.requests.get(&path).expect("popped key must be pending").clone();
3642		Poll::Ready(Some(Request {
3643			path,
3644			producer,
3645			home: self.server.clone(),
3646			publisher: self.publisher.clone(),
3647			requeue: false,
3648		}))
3649	}
3650
3651	/// The claim metadata as advertised, or `None` while hidden.
3652	#[cfg(test)]
3653	pub(crate) fn route(&self) -> Option<RouteInfo> {
3654		self.state.announcement.route()
3655	}
3656
3657	/// The queue the claim's requests arrive on, for tests that inspect it.
3658	#[cfg(test)]
3659	fn server(&self) -> &kio::Shared<ServeState> {
3660		&self.server
3661	}
3662
3663	/// Replace a forwarded claim's metadata in place, taken as given.
3664	///
3665	/// A claim naming no [`RouteInfo::identity`], or the same one, re-prices: consumers
3666	/// observe an update and every handle survives. Another identity is another stream:
3667	/// consumers see a restart, and a re-request never joins what was resolved under the
3668	/// old one. Requests still waiting on this handle carry over: the handler is asked
3669	/// again under the new identity, and its answer to a request asked before the change
3670	/// is dropped, never served under the new one. A request pinned to the old identity
3671	/// is refused with [`Error::Unroutable`]. The answers already served are forgotten,
3672	/// so the next request for one of those paths asks the handler again too. The
3673	/// broadcasts it served keep running for the subscriptions already on them.
3674	///
3675	/// Fails with [`Error::Closed`] once the origin's [`Driver`] has been dropped.
3676	#[cfg(any(feature = "async", test))]
3677	pub(crate) fn update(&self, info: RouteInfo) -> Result<(), Error> {
3678		let mut control = self.state.control.lock();
3679		if let Some(identity) = &info.identity {
3680			control.identity = (identity.clone(), info.epoch);
3681			control.held = false;
3682		}
3683		control.options.cost = info.cost;
3684		control.options.auth = info.auth.clone();
3685		self.state.announcement.update(info)
3686	}
3687
3688	/// Retire an explicit peer withdrawal, hiding derived paths only once its
3689	/// last live advertisement at the prefix is gone. Readers see it end. A lost
3690	/// session just drops, and readers see it go offline.
3691	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
3692	pub(crate) fn withdrawn(self) {
3693		self.state.announcement.retract(Retract::Withdrawn);
3694	}
3695
3696	/// The route layer let go of the claim this follows: every copy of it the table holds,
3697	/// each of the same node, identity and [`Lane::lifecycle`] at any epoch, goes with this one
3698	/// under one lock, rather than readers seeing the rest in turn as their sessions
3699	/// retract them. They end with `ended`, else go offline.
3700	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
3701	pub(crate) fn retire(self, ended: bool) {
3702		self.state.announcement.retract(Retract::Retired { ended });
3703	}
3704
3705	/// Retire a route its announcer ended without a hop chain to stale, such as a
3706	/// moq-transport PUBLISH_NAMESPACE_DONE: readers see it end, not go offline.
3707	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
3708	pub(crate) fn ended(self) {
3709		self.state.announcement.retract(Retract::Ended);
3710	}
3711}
3712
3713impl Drop for RouteState {
3714	fn drop(&mut self) {
3715		// Retract before a job's unanswered request drops, so its requesters are refused
3716		// rather than asked again through this route.
3717		self.announcement.retract(match self.forwarded {
3718			true => Retract::Lost,
3719			false => Retract::Ended,
3720		});
3721	}
3722}
3723
3724/// Why an advertisement leaves the table.
3725#[derive(Clone, Copy, PartialEq, Eq)]
3726enum Retract {
3727	/// The session it arrived on lost it: readers see it go offline.
3728	Lost,
3729	/// Its announcer ended it: readers see it end.
3730	Ended,
3731	/// A peer withdrew it, which also stales the routes derived through that peer.
3732	Withdrawn,
3733	/// The route layer let go of the claim it follows: see [`Claim::retire`]. Ended, it
3734	/// stales as [`Self::Withdrawn`] does.
3735	Retired { ended: bool },
3736}
3737
3738/// The write half of an advertisement: a live claim that paths under a prefix can be
3739/// served.
3740///
3741/// Held by a [`Route`]; dropping it retracts the route, which [`Routes`]s
3742/// observe and sessions withdraw from their peers.
3743#[must_use = "dropping an announcement retracts the route"]
3744pub(crate) struct AnnounceProducer {
3745	shared: SendCell<kio::Shared<OriginState>>,
3746	/// The table entries this advertisement created, by prefix and id. A prefix
3747	/// remains unchanged; scopes only filter its visibility and requests.
3748	entries: Vec<(Path, u64)>,
3749	/// The ingress counters an advertised interval's announce guard comes from.
3750	ingress: stats::Scope,
3751	/// Ingress announce stats guard, held only while the entries are advertised.
3752	guard: kio::Lock<Option<stats::Announce>>,
3753}
3754
3755impl AnnounceProducer {
3756	/// Replace the route in place, identity included when it names one; see
3757	/// [`Claim::update`].
3758	///
3759	/// The prefix is fixed at announce time and a [`RouteInfo`] cannot name one: to
3760	/// move an advertisement, drop this and announce again. Fails with
3761	/// [`Error::Closed`] once the origin's [`Driver`] has been dropped.
3762	#[cfg(any(feature = "async", test))]
3763	pub fn update(&self, route: RouteInfo) -> Result<(), Error> {
3764		self.update_if(route, None, |_| true).map(|_| ())
3765	}
3766
3767	/// [`Self::update`] once `admit` agrees, returning whether it did. `admit` runs
3768	/// under the table lock, so nothing ordered after that lock (a release, a
3769	/// retraction, the teardown) can change its answer before the route lands.
3770	///
3771	/// A job's route answering its request through `lender`, a prefix route that lends
3772	/// its identity, takes that route's identity and epoch as of now.
3773	fn update_if(
3774		&self,
3775		route: RouteInfo,
3776		lender: Option<&kio::Shared<ServeState>>,
3777		admit: impl FnOnce(&OriginState) -> bool,
3778	) -> Result<bool, Error> {
3779		let mut shared = self.shared.lock();
3780		if shared.closed {
3781			return Err(Error::Closed);
3782		}
3783		if !self
3784			.entries
3785			.iter()
3786			.all(|(prefix, id)| shared.routes.entry(prefix, *id).is_some())
3787		{
3788			return Err(Error::Closed);
3789		}
3790		if !admit(&shared) {
3791			return Ok(false);
3792		}
3793		// The requests an identity change released, refused once the table lock is gone: the
3794		// refusal wakes their fronts, which read the table.
3795		let mut released = Vec::new();
3796		for (prefix, id) in &self.entries {
3797			shared.reannounced(prefix, &route.hops);
3798			let stale = shared.withdrawn_through(prefix, &route.hops);
3799			let lent = lender.and_then(|server| shared.lender(prefix, server));
3800			let stamp = shared.next_route;
3801			shared.next_route += 1;
3802			// Each entry keeps its advertised prefix; only the metadata moves.
3803			let Some(entry) = shared.routes.entry_mut(prefix, *id) else {
3804				return Err(Error::Closed);
3805			};
3806			let held = (
3807				entry.live(),
3808				entry.specificity(),
3809				route_rank(entry),
3810				entry.identity.clone(),
3811				entry.epoch,
3812			);
3813			let next = match &lent {
3814				Some(lent) => Some((lent.identity.clone(), lent.epoch)),
3815				None => route.identity.clone().map(|identity| (identity, route.epoch)),
3816			};
3817			let mut spent = None;
3818			if let Some((identity, epoch)) = next {
3819				if identity != entry.identity {
3820					// Another stream: what its server was asked, or answered, for the old one
3821					// is not its own. Under the table lock, so no front sees the new identity
3822					// while an old answer can still land. A higher epoch of the same one
3823					// continues it.
3824					if let Some(server) = &entry.server {
3825						released.extend(server.lock().renew());
3826					}
3827					// The identity it took stops serving here.
3828					if entry.advertised {
3829						spent = entry.lent.take().map(|lender| (lender, entry.identity.clone()));
3830					}
3831				}
3832				entry.identity = identity;
3833				entry.epoch = epoch;
3834			}
3835			if let Some(lent) = lent {
3836				entry.lent = Some((lent.prefix, lent.id));
3837			}
3838			entry.hops = route.hops.clone();
3839			entry.stale = stale;
3840			entry.cost = route.cost;
3841			entry.auth = route.auth.clone();
3842			entry.via = route.via;
3843			entry.node = route.node;
3844			entry.lane = Lane {
3845				above: route.lane.above.saturating_add(entry.below),
3846				..route.lane.clone()
3847			};
3848			entry.draining = route.draining;
3849			entry.available = route.available;
3850			entry.marked = route.marked;
3851			entry.advertised = true;
3852			if held
3853				!= (
3854					true,
3855					entry.specificity(),
3856					route_rank(entry),
3857					entry.identity.clone(),
3858					entry.epoch,
3859				) {
3860				entry.since = stamp;
3861			}
3862			shared.sync_route(prefix, Gone::End);
3863			if let Some(((lender, lender_id), identity)) = spent {
3864				shared.advance(&lender, lender_id, &identity);
3865			}
3866			shared.prune_withdrawn(prefix);
3867		}
3868		// Under the table lock, as withdrawing and retracting clear it, so a racing one
3869		// never leaves the guard held for entries no longer advertised.
3870		self.guard.lock().get_or_insert_with(|| self.ingress.announce());
3871		drop(shared);
3872		for producer in released {
3873			if let Ok(mut request) = producer.write() {
3874				request.resolved.get_or_insert(Err(Error::Unroutable));
3875			}
3876		}
3877		Ok(true)
3878	}
3879
3880	/// The identity and epoch the entries carry, or `None` once they are gone. A job's
3881	/// route not yet announced reads its `lender`'s current one, which it would bind now.
3882	fn identity(&self, lender: Option<&kio::Shared<ServeState>>) -> Option<(Identity, u64)> {
3883		let shared = self.shared.lock();
3884		let (prefix, id) = self.entries.first()?;
3885		let entry = shared.routes.entry(prefix, *id)?;
3886		if let Some(lent) = lender.and_then(|server| shared.lender(prefix, server)) {
3887			return Some((lent.identity, lent.epoch));
3888		}
3889		Some((entry.identity.clone(), entry.epoch))
3890	}
3891
3892	/// Whether the entries are advertised, or [`Error::Closed`] once they are gone.
3893	fn is_live(&self) -> Result<bool, Error> {
3894		let shared = self.shared.lock();
3895		if shared.closed {
3896			return Err(Error::Closed);
3897		}
3898		let mut advertised = false;
3899		for (prefix, id) in &self.entries {
3900			advertised |= shared.routes.entry(prefix, *id).ok_or(Error::Closed)?.advertised;
3901		}
3902		Ok(advertised)
3903	}
3904
3905	/// The route as last given, while advertised: every entry carries the same one.
3906	pub(crate) fn route(&self) -> Option<RouteInfo> {
3907		let shared = self.shared.lock();
3908		let (prefix, id) = self.entries.first()?;
3909		let entry = shared.routes.entry(prefix, *id).filter(|entry| entry.advertised)?;
3910		Some(RouteInfo {
3911			identity: Some(entry.identity.clone()),
3912			epoch: entry.epoch,
3913			hops: entry.hops.clone(),
3914			cost: entry.cost,
3915			auth: entry.auth.clone(),
3916			via: entry.via,
3917			source: entry.entered(),
3918			node: entry.node,
3919			lane: Lane {
3920				above: entry.lane.above.saturating_sub(entry.below),
3921				..entry.lane.clone()
3922			},
3923			draining: entry.draining,
3924			available: entry.available,
3925			marked: entry.marked,
3926		})
3927	}
3928
3929	/// Hide the entries from everyone, local and remote alike: cursors see a
3930	/// retraction and requests stop resolving through them. The entries stay,
3931	/// so announcing again restores the same route. What [`Route::withdraw`] does.
3932	///
3933	/// A prefix route's pending requests, queued or handed to a handler, are released
3934	/// under the table lock, so an answer prepared for one, such as a hidden job route,
3935	/// can no longer land once the route is withdrawn.
3936	fn withdraw(&self) {
3937		let mut shared = self.shared.lock();
3938		let guard = self.guard.lock().take();
3939		let mut released = Vec::new();
3940		for (prefix, id) in &self.entries {
3941			let Some(entry) = shared.routes.entry_mut(prefix, *id) else {
3942				continue;
3943			};
3944			if !entry.advertised {
3945				continue;
3946			}
3947			entry.advertised = false;
3948			if let Some(server) = &entry.server {
3949				released.extend(server.lock().renew());
3950			}
3951			let spent = entry.lent.take().map(|lender| (lender, entry.identity.clone()));
3952			shared.sync_route(prefix, Gone::End);
3953			if let Some(((lender, lender_id), identity)) = spent {
3954				shared.advance(&lender, lender_id, &identity);
3955			}
3956		}
3957		drop(shared);
3958		drop(guard);
3959		// Refused once the table lock is gone: the refusal wakes their fronts, which read
3960		// the table.
3961		for producer in released {
3962			if let Ok(mut request) = producer.write() {
3963				request.resolved.get_or_insert(Err(Error::Unroutable));
3964			}
3965		}
3966	}
3967
3968	/// Retract the route now: remove its table entries and reject anything still
3969	/// waiting on its queue. Idempotent, and what dropping the advertisement does.
3970	fn retract(&self, how: Retract) {
3971		let mut shared = self.shared.lock();
3972		let guard = self.guard.lock().take();
3973		let mut servers = Vec::new();
3974		for (prefix, id) in &self.entries {
3975			let Some(entry) = shared.routes.remove(prefix, *id) else {
3976				continue;
3977			};
3978			servers.extend(entry.server.clone());
3979			if let Retract::Retired { .. } = how {
3980				shared.retire_copies(&entry);
3981			}
3982			// A peer remains reachable while any of its sessions advertises this
3983			// prefix. Remove this session's route before testing the remaining
3984			// claims, under the same lock, so overlapping withdrawals cannot
3985			// invalidate a newer advertisement or miss the last withdrawal. A live copy
3986			// of the same lite-07 claim, such as one a later showing serves over another
3987			// chain, says its claimant still advertises it too.
3988			let same_claim = |other: &RouteEntry| {
3989				entry.node.is_some() && other.node == entry.node && other.identity == entry.identity
3990			};
3991			if matches!(how, Retract::Withdrawn | Retract::Retired { ended: true })
3992				&& let Some(&peer) = entry.hops.iter().last()
3993				&& peer != Hop::UNKNOWN
3994				&& !shared
3995					.routes
3996					.at(prefix)
3997					.any(|other| other.live() && (other.hops.iter().last() == Some(&peer) || same_claim(other)))
3998			{
3999				shared.withdrawn.entry(prefix.clone()).or_default().insert(peer);
4000				shared.restale(prefix);
4001			}
4002			let gone = match how {
4003				Retract::Lost | Retract::Retired { ended: false } => Gone::Offline,
4004				Retract::Ended | Retract::Withdrawn | Retract::Retired { ended: true } => Gone::End,
4005			};
4006			shared.sync_route(&entry.prefix, gone);
4007			if entry.advertised
4008				&& let Some((lender, lender_id)) = &entry.lent
4009			{
4010				shared.advance(lender, *lender_id, &entry.identity);
4011			}
4012			shared.prune_withdrawn(&entry.prefix);
4013		}
4014		drop(shared);
4015		drop(guard);
4016		// Reject anything still waiting on this route's server; a request already
4017		// handed to the handler resolves through its own `Request`. Closing wakes
4018		// the server's waiters, so it runs after the table unlocks; the entries
4019		// already left it, so nothing new routes here meanwhile, and a job route
4020		// answering one of them finds its prefix route gone (see [`Route::announce`]).
4021		for server in servers {
4022			let released = {
4023				let mut server = server.lock();
4024				server.closed = true;
4025				server.requests.drain_all()
4026			};
4027			for producer in released {
4028				if let Ok(mut request) = producer.write() {
4029					request.resolved.get_or_insert(Err(Error::Unroutable));
4030				}
4031			}
4032		}
4033	}
4034}
4035
4036impl Drop for AnnounceProducer {
4037	fn drop(&mut self) {
4038		self.retract(Retract::Ended);
4039	}
4040}
4041
4042/// Feeds a route layer node the routes this node serves itself, best per prefix,
4043/// for as long as the origin lives.
4044struct OwnClaims {
4045	routes: Routes,
4046	/// The same routes, less those learned on an upstream link.
4047	downstream: Routes,
4048	/// The claim fed at each prefix: its identity, and whether another node announced it.
4049	best: HashMap<Path, (Identity, crate::route::node::Claim, bool)>,
4050	/// The identity at each prefix that a route not learned upstream serves.
4051	local: HashMap<Path, Identity>,
4052	/// Claims that left since the last feed, told after it: a successor at the same
4053	/// prefix must reach the node first, or a peer reading the two apart sees an end.
4054	gone: BTreeMap<crate::route::node::Broadcast, crate::route::node::Change>,
4055	/// Whether the origin forwards. One that does not tells no peer a claim it learned.
4056	proxy: bool,
4057	node: crate::route::Node,
4058}
4059
4060/// The driver's task feeding [`OwnClaims`], which [`Consumer::route_node`] also catches up.
4061/// It ends once nothing owns the origin, after feeding the withdrawals still queued: its
4062/// cursors end only in the driver's teardown, which waits for this task.
4063struct FeedOwnClaims {
4064	claims: Arc<std::sync::Mutex<OwnClaims>>,
4065	origin: TasksWeak,
4066}
4067
4068impl kio::Task for FeedOwnClaims {
4069	type Output = ();
4070
4071	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> {
4072		// Wakes wait for the feeder's lock, which drops before the hold; see
4073		// `Consumer::route_node`.
4074		let _hold = kio::hold();
4075		let mut claims = lock_own(&self.claims);
4076		if self.origin.poll_orphaned(waiter).is_ready() {
4077			claims.catch_up();
4078			return Poll::Ready(());
4079		}
4080		claims.poll(waiter)
4081	}
4082}
4083
4084/// The driver's task firing the route node's timers on the origin's clock: a claim no
4085/// route reaches going offline. It ends once nothing owns the origin, letting go of what
4086/// closed sessions left behind, since no timer would take it offline after.
4087struct RouteTimer {
4088	node: crate::route::Node,
4089	deadline: crate::time::Deadline,
4090	origin: TasksWeak,
4091}
4092
4093impl kio::Task for RouteTimer {
4094	type Output = ();
4095
4096	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> {
4097		if self.origin.poll_orphaned(waiter).is_ready() {
4098			self.node.release_orphans();
4099			return Poll::Ready(());
4100		}
4101		loop {
4102			if let Poll::Ready(at) = self.node.poll_deadline(self.deadline.deadline(), waiter) {
4103				self.deadline.set(at);
4104				continue;
4105			}
4106			ready!(self.deadline.poll(waiter));
4107			// Firing moves the deadline past now, which the next pass arms.
4108			self.node.timeout();
4109			if self.node.poll_deadline(self.deadline.deadline(), waiter).is_pending() {
4110				// It stayed put: wait for it to move rather than fire it again.
4111				return Poll::Pending;
4112			}
4113		}
4114	}
4115}
4116
4117fn lock_own(own: &std::sync::Mutex<OwnClaims>) -> std::sync::MutexGuard<'_, OwnClaims> {
4118	own.lock().unwrap_or_else(|poison| poison.into_inner())
4119}
4120
4121impl OwnClaims {
4122	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> {
4123		let mut changed = Vec::new();
4124		let mut open = true;
4125		// One change to the table reaches both cursors, so neither is read without the
4126		// other: a claim fed between the two would be filed as one that crossed a marked
4127		// link, or as one that did not, for no longer than that, and a peer shown the
4128		// difference sees the claim lost.
4129		loop {
4130			let mut progressed = false;
4131			while open && let Poll::Ready(event) = self.downstream.poll_next(waiter) {
4132				match event {
4133					Some(event) => changed.push(self.local(event)),
4134					None => open = false,
4135				}
4136				progressed = true;
4137			}
4138			while open && let Poll::Ready(event) = self.routes.poll_next(waiter) {
4139				match event {
4140					Some(event) => changed.extend(self.apply(event)),
4141					None => open = false,
4142				}
4143				progressed = true;
4144			}
4145			if !open || !progressed {
4146				break;
4147			}
4148		}
4149		self.feed(changed);
4150		match open {
4151			true => Poll::Pending,
4152			false => Poll::Ready(()),
4153		}
4154	}
4155}
4156
4157impl OwnClaims {
4158	/// Feed the node every change the table already holds, so a stream registered next
4159	/// sees them without waiting for the driver.
4160	fn catch_up(&mut self) {
4161		let mut changed = Vec::new();
4162		while let Some(event) = self.downstream.try_next() {
4163			changed.push(self.local(event));
4164		}
4165		while let Some(event) = self.routes.try_next() {
4166			changed.extend(self.apply(event));
4167		}
4168		self.feed(changed);
4169	}
4170
4171	/// The best route at a prefix changed: the prefix whose claim is to be fed again, if
4172	/// one is left there.
4173	fn apply(&mut self, event: RouteEvent) -> Option<Path> {
4174		use crate::route::node::{Attr, Change, Claim};
4175		let announce = match event {
4176			RouteEvent {
4177				kind: RouteKind::Start | RouteKind::Update | RouteKind::Restart,
4178				announce,
4179			} => announce,
4180			RouteEvent { kind, announce } => {
4181				if let Some((identity, ..)) = self.best.remove(&announce.prefix) {
4182					let change = match kind {
4183						RouteKind::End => Change::Ended,
4184						_ => Change::Lost,
4185					};
4186					self.gone.insert((announce.prefix, identity), change);
4187				}
4188				return None;
4189			}
4190		};
4191		let route = announce.route;
4192		let identity = route.identity?;
4193		// Only a route published here has crossed no node.
4194		let learned = !route.hops.is_empty();
4195		let claim = Claim {
4196			item: Attr {
4197				epoch: route.epoch,
4198				// Filed at a grant prefix beneath the prefix it claims, it is shown no higher.
4199				above: route.lane.above.into(),
4200			},
4201			cost: route.cost.value(),
4202			// A publisher's own claim carries the highest priority; a learned one the lowest
4203			// of a link on its way here, which the ranked cursor delivers.
4204			priority: match learned {
4205				true => route.lane.priority.unwrap_or_default(),
4206				false => i8::MAX,
4207			},
4208			draining: route.draining,
4209			unavailable: false,
4210			// Kept, so the claim that crossed into lite-07 here is still recognized
4211			// wherever it leaves for lite-06 again. A hop that names nobody says nothing.
4212			chain: route.hops.iter().map(|hop| hop.id()).filter(|id| *id != 0).collect(),
4213			marked: false,
4214		};
4215		let was = self
4216			.best
4217			.insert(announce.prefix.clone(), (identity.clone(), claim, learned));
4218		// Another identity took the prefix: the one it served before is gone.
4219		if let Some((was, ..)) = was.filter(|(was, ..)| *was != identity) {
4220			self.gone.insert((announce.prefix.clone(), was), Change::Ended);
4221		}
4222		Some(announce.prefix)
4223	}
4224
4225	/// The route not learned upstream changed at a prefix, which is returned: whether
4226	/// the claim there may go to an upstream peer follows it.
4227	fn local(&mut self, event: RouteEvent) -> Path {
4228		match event {
4229			RouteEvent {
4230				kind: RouteKind::End | RouteKind::Offline,
4231				announce,
4232			} => {
4233				self.local.remove(&announce.prefix);
4234				announce.prefix
4235			}
4236			RouteEvent {
4237				kind: RouteKind::Start | RouteKind::Update | RouteKind::Restart,
4238				announce,
4239			} => {
4240				if let Some(identity) = announce.route.identity {
4241					self.local.insert(announce.prefix.clone(), identity);
4242				}
4243				announce.prefix
4244			}
4245		}
4246	}
4247
4248	/// Feed the node the claim at each of `prefixes`, marked unless a route not learned
4249	/// upstream serves the same identity there, and unless this origin forwards what it
4250	/// learned. Then end the claims that left, less any that came back since.
4251	fn feed(&mut self, mut prefixes: Vec<Path>) {
4252		prefixes.sort();
4253		prefixes.dedup();
4254		for prefix in prefixes {
4255			let Some((identity, claim, learned)) = self.best.get(&prefix) else {
4256				continue;
4257			};
4258			let marked = (*learned && !self.proxy) || self.local.get(&prefix) != Some(identity);
4259			let change = crate::route::node::Change::Live(claim.clone());
4260			self.node.own(marked, (prefix, identity.clone()), change);
4261		}
4262		for ((prefix, identity), change) in std::mem::take(&mut self.gone) {
4263			if self.best.get(&prefix).is_some_and(|(best, ..)| *best == identity) {
4264				continue;
4265			}
4266			self.node.own(false, (prefix, identity), change);
4267		}
4268	}
4269}
4270
4271/// Drives origin lifecycle work and cache expiration with caller-supplied time.
4272///
4273/// Returned by [`Producer::new`]. Poll on external activity or at the deadline
4274/// it returns, supplying nondecreasing instants. RouteInfo changes, track serving, linger,
4275/// failover, and teardown run here; the route table and announce cursors update
4276/// synchronously when a route is announced or retracted.
4277///
4278/// It holds no [`Producer`] clone, so it never keeps the origin alive. It
4279/// finishes once every owner is gone: each [`Producer`] clone and [`Route`]. Read handles ([`Consumer`], [`Routes`])
4280/// are not owners. Dropping it aborts active fronts, rejects pending requests,
4281/// ends announcements, and makes subsequent producer mutations fail with
4282/// [`Error::Closed`].
4283/// `moq_tokio::origin::spawn` handles construction and driving for Tokio callers.
4284#[must_use = "poll the driver or the origin makes no progress"]
4285pub struct Driver {
4286	state: DriverState,
4287	// Shared by this origin's lifecycle tasks; advanced only when polled.
4288	timers: Deadlines,
4289	// The cache pool this origin's groups charge into, swept on a wall-clock
4290	// cadence so its idle window binds a track whose publisher stopped writing, and
4291	// collected at its reads' wall-clock deadlines.
4292	pool: cache::Pool,
4293}
4294
4295/// Lifecycle work and the state it tears down.
4296struct DriverState {
4297	/// The front drivers: producers submit, this polls.
4298	set: TaskSet,
4299	/// The route table, announce cursors, and the remotely-served fronts, for
4300	/// ending everything on drop.
4301	shared: SendCell<kio::Shared<OriginState>>,
4302	/// Cached completion so a poll after `Ready` doesn't re-poll the drained set.
4303	done: bool,
4304}
4305
4306impl Driver {
4307	/// Process ready origin work using caller-supplied monotonic time.
4308	///
4309	/// See [`crate::time::Driver`] for the contract. Finishes with
4310	/// [`Error::Closed`] once every owner (a [`Producer`] clone or [`Route`]) has dropped and the remaining lifecycle work
4311	/// has drained.
4312	pub fn poll(&mut self, now: Instant, waiter: &kio::Waiter) -> Result<Option<Instant>, Error> {
4313		waiter.batch(|| {
4314			self.timers.advance(now);
4315			let result = self.state.poll(waiter);
4316			let gc = self.pool.poll(now, waiter);
4317			if result.is_ready() {
4318				return Err(Error::Closed);
4319			}
4320			Ok(self.timers.park(waiter).into_iter().chain(gc).min())
4321		})
4322	}
4323}
4324
4325impl crate::time::Driver for Driver {
4326	fn poll(&mut self, now: Instant, waiter: &kio::Waiter) -> Result<Option<Instant>, Error> {
4327		self.poll(now, waiter)
4328	}
4329}
4330
4331/// What an origin holds on behalf of its sessions and readers, for the session fuzz target's
4332/// leak check.
4333#[cfg(all(feature = "async", any(test, feature = "fuzz")))]
4334#[derive(Clone, Debug, PartialEq, Eq)]
4335pub(crate) struct Footprint {
4336	tasks: usize,
4337	routes: usize,
4338	cursors: usize,
4339	listeners: usize,
4340	withdrawn: usize,
4341}
4342
4343#[cfg(all(feature = "async", any(test, feature = "fuzz")))]
4344impl Driver {
4345	/// Count what this origin holds; see [`Footprint`].
4346	pub(crate) fn footprint(&self) -> Footprint {
4347		let shared = self.state.shared.lock();
4348		Footprint {
4349			tasks: self.state.set.len(),
4350			routes: shared.routes.entries().count(),
4351			cursors: shared.cursors.len(),
4352			listeners: shared.listeners.len(),
4353			withdrawn: shared.withdrawn.len(),
4354		}
4355	}
4356}
4357
4358impl DriverState {
4359	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> {
4360		// Never gates completion: the pool outlives this origin (a relay shares one
4361		// across every origin), so a sweep that is still due must not keep the driver
4362		// alive after its lifecycle work has drained.
4363		if !self.done {
4364			ready!(self.set.poll(waiter));
4365			self.done = true;
4366		}
4367		Poll::Ready(())
4368	}
4369
4370	/// Tear the origin down: cancel the lifecycle work, abort and unpublish every
4371	/// front, retract every route, end announcement cursors, and reject pending
4372	/// requests.
4373	fn teardown(&mut self) {
4374		// Cancel queued and running lifecycle work first, so no front serves
4375		// while the table is ended below.
4376		drop(std::mem::replace(&mut self.set, TaskSet::owned()));
4377
4378		// Refuse new work and take the pending requests, under the same lock
4379		// `route` holds across its attach: a concurrent create either
4380		// finishes before this (the walk below cleans its entry up) or observes
4381		// `closed` and fails with `Closed`.
4382		let (servers, cursors, fronts, route_node) = {
4383			let mut shared = self.shared.lock();
4384			shared.closed = true;
4385			// Fronts and parked requesters observe `closed` on their next pass.
4386			shared.routes.poke_all();
4387			let servers: Vec<_> = shared
4388				.routes
4389				.entries()
4390				.filter_map(|entry| entry.server.clone())
4391				.collect();
4392			let cursors: Vec<_> = shared.cursors.values().map(|cursor| cursor.state.clone()).collect();
4393			let fronts: Vec<_> = shared.fronts.values().map(|front| front.request.clone()).collect();
4394			// Sessions stop hearing interests; their queued snapshots release as they drop.
4395			for listener in &shared.listeners {
4396				listener.queue.close();
4397			}
4398			// The node holds what closed sessions left behind, and each of those holds this
4399			// state: let go of it, or the two keep each other alive. Dropped outside the
4400			// lock, since an orphan's release takes it.
4401			(servers, cursors, fronts, shared.route_node.take())
4402		};
4403		drop(route_node);
4404
4405		// Reject requesters still parked on a remote front's channel: its watcher
4406		// was cancelled above and will never resolve them.
4407		for producer in fronts {
4408			if let Ok(mut request) = producer.write() {
4409				request.resolved.get_or_insert(Err(Error::Closed));
4410			}
4411		}
4412		// Reject every pending route request, including those already handed to a
4413		// handler: the teardown is terminal, so a handler resolving late must not
4414		// beat it (resolution is first-write-wins).
4415		for server in servers {
4416			let released = {
4417				let mut server = server.lock();
4418				server.closed = true;
4419				server.requests.drain_all()
4420			};
4421			for producer in released {
4422				if let Ok(mut request) = producer.write() {
4423					request.resolved.get_or_insert(Err(Error::Closed));
4424				}
4425			}
4426		}
4427
4428		// End the announce cursors: each drains its pending updates, then reports
4429		// the end. Registrations stay (the cursors remove themselves on drop). A
4430		// snapshot still in flight is released like a landing, owing what is queued.
4431		for state in cursors {
4432			if let Ok(mut state) = state.write() {
4433				state.end();
4434				if state.waiting.swap(0, Ordering::Relaxed) > 0 {
4435					state.owe();
4436				}
4437			}
4438		}
4439	}
4440}
4441
4442impl Drop for DriverState {
4443	fn drop(&mut self) {
4444		self.teardown();
4445	}
4446}
4447
4448/// Everything [`FrontServeRun`] owns, queued by [`Consumer::request`].
4449struct FrontTask {
4450	/// The route table the front selects from.
4451	shared: SendCell<kio::Shared<OriginState>>,
4452	/// The broadcast the front serves.
4453	broadcast: broadcast::Producer,
4454	/// Absolute path of the front.
4455	path: Path,
4456	/// The requesters' horizon, applied to every (re)selection.
4457	horizon: Horizon,
4458	/// The identity the front serves from the start, for requests naming another one than
4459	/// the path's winner; see [`FrontKey`].
4460	pin: Option<Identity>,
4461	/// Wakes the front when a route covering its path changes.
4462	watch: Watch,
4463	/// Resolves the requesters parked on the front's channel.
4464	request: kio::Producer<PendingFront>,
4465	timers: Deadlines,
4466}
4467
4468/// A route asked for its copy of a track: the copy, its info once its query
4469/// resolved, and a subscription with what the readers want.
4470struct Asked {
4471	source: u64,
4472	/// The track instance the query reached, whatever its source serves under the name later.
4473	copy: track::Consumer,
4474	/// The front's own demand on the copy, held for as long as the front holds the copy: a
4475	/// bare handle is no demand, so this stands in for the readers' queries and fetches.
4476	query: track::Resolving,
4477	info: Option<track::Info>,
4478	/// Some sessions only learn a track's info by subscribing (moq-transport's
4479	/// SUBSCRIBE_OK), and read the demand only then, so the readers' demand rides the
4480	/// query. Kept once spliced until the last reader leaves, so the copy is never left
4481	/// with nobody subscribed while readers are still subscribing to it on their own.
4482	sub: Option<super::resume::Held>,
4483	/// The copy staged for fetches while its info is in flight, withdrawn if it is never
4484	/// spliced.
4485	staged: super::resume::Staged,
4486}
4487
4488/// The driver's side of one logical track: the handles behind the names the
4489/// machine uses.
4490struct TrackIo {
4491	/// Queues just this track when a resource it watches changes.
4492	ready: Arc<crate::util::QueueWake<track::Key>>,
4493	park: kio::Park,
4494	logical: Logical,
4495	/// Whether anyone reads the logical track.
4496	weak: track::TrackWeak,
4497	/// Which copy serves the track, and how it ends; see [`super::resume`].
4498	routes: super::resume::Producer,
4499	/// A copy whose info is still in flight.
4500	query: Option<Asked>,
4501	/// The copy whose info resolved, waiting for the machine to splice it.
4502	staged: Option<Asked>,
4503	/// The source whose copy serves the track, the copy, and the query holding it; plus the
4504	/// subscription that query made.
4505	copy: Option<(u64, track::Consumer, track::Resolving)>,
4506	held: Option<super::resume::Held>,
4507	/// Whether the track had a reader as of the last demand edge.
4508	wanted: bool,
4509}
4510
4511/// The logical track the front answers its readers with.
4512enum Logical {
4513	/// Until the first copy says what it is.
4514	Requested(track::Request),
4515	/// Accepted with that copy's info. Nothing writes it: its readers read the serving
4516	/// route's copy through `routes`.
4517	Accepted(track::Producer),
4518	/// Finished, aborted, or refused.
4519	Ended,
4520}
4521
4522impl Logical {
4523	/// Accept a request still waiting, with the first copy's `info`.
4524	fn accept(&mut self, info: track::Info) {
4525		if let Self::Requested(_) = self
4526			&& let Self::Requested(request) = std::mem::replace(self, Self::Ended)
4527		{
4528			*self = Self::Accepted(request.accept(info));
4529		}
4530	}
4531
4532	/// The accepted track, whose readers' demand the copy follows.
4533	fn accepted(&mut self) -> Option<&mut track::Producer> {
4534		match self {
4535			Self::Accepted(accepted) => Some(accepted),
4536			_ => None,
4537		}
4538	}
4539}
4540
4541impl TrackIo {
4542	/// Whether anyone reads the track: a reader of the open track, or anything still holding
4543	/// a finished one whose reads move with the front, such as a fetch of a group below its
4544	/// end. A track that failed or concluded owes its holders nothing.
4545	fn read(&self) -> bool {
4546		match self.routes.moves() {
4547			true => self.weak.is_held(),
4548			false => self.weak.is_wanted(),
4549		}
4550	}
4551
4552	/// Serve the track from `asked`'s copy, accepting it with that copy's info first.
4553	fn splice(&mut self, asked: Asked) {
4554		self.ready.wake_by_ref();
4555		if let Some(info) = asked.info.clone() {
4556			self.logical.accept(info);
4557		}
4558		self.routes.splice(asked.copy.clone(), asked.staged);
4559		self.copy = Some((asked.source, asked.copy, asked.query));
4560		self.held = asked.sub;
4561	}
4562
4563	/// End the track: cleanly with `Ok`, or failed for good. Readers drain what the
4564	/// serving copy still holds. A request still waiting is refused with `retry`, the Retry
4565	/// Interval an upstream refusal asked for, when there is one.
4566	fn end(&mut self, result: Result<(), Error>, retry: Option<Duration>) {
4567		self.ready.wake_by_ref();
4568		self.query = None;
4569		self.staged = None;
4570		self.copy = None;
4571		self.held = None;
4572		match std::mem::replace(&mut self.logical, Logical::Ended) {
4573			// Ended before any route served it: nothing to read, nor to fetch.
4574			Logical::Requested(request) => {
4575				self.routes.end(result.clone());
4576				let err = result.err().unwrap_or(Error::NotFound);
4577				match retry {
4578					Some(retry) => request.refuse(err, retry),
4579					None => request.reject(err),
4580				}
4581			}
4582			Logical::Accepted(accepted) => {
4583				let _ = match &result {
4584					Ok(()) => accepted.finish().map(drop),
4585					// A failed track refuses newcomers too, so they ask afresh.
4586					Err(err) => accepted.abort(err.clone()),
4587				};
4588				self.routes.end(result);
4589			}
4590			Logical::Ended => self.routes.end(result),
4591		}
4592	}
4593}
4594
4595/// The front's answer to listings of its broadcast: the serving source's listing,
4596/// forwarded through the front's [`broadcast::Lister`].
4597#[derive(Default)]
4598struct FrontListing {
4599	/// The source being read.
4600	source: Option<u64>,
4601	reader: Option<broadcast::Tracks>,
4602	/// Every track the front lists, by kind and name.
4603	listed: HashSet<(broadcast::Kind, Arc<str>)>,
4604	/// Tracks an earlier source listed that the current one has yet to list. A source of the
4605	/// same identity lists the same tracks, so its readers see no churn: what it still lacks
4606	/// at its SYNCED is gone.
4607	stale: HashSet<(broadcast::Kind, Arc<str>)>,
4608}
4609
4610/// A track the ended front left in flight, held until its last reader leaves. It
4611/// keeps none of the driver's wake state, which would queue its name for a driver
4612/// that is gone.
4613struct InFlight {
4614	weak: track::TrackWeak,
4615	routes: super::resume::Producer,
4616	/// Why the front ended, used if its pending copy cannot answer.
4617	end: Error,
4618	// Kept for its readers: the logical track, still owed an answer when the front ended
4619	// before the copy's info arrived, the query holding its copy, and the copy's
4620	// subscription, which follows their demand as it did while the front served it.
4621	logical: Logical,
4622	query: track::Resolving,
4623	held: Option<super::resume::Held>,
4624}
4625
4626/// Keep the query's subscription on a copy following the readers' demand, and let it go
4627/// with the last reader. Left behind, its first preferences would mask a later, lower
4628/// aggregate from the copy's source: a shorter budget, or a demoted priority. With `copy`,
4629/// a reader arriving subscribes it too.
4630fn follow_demand(
4631	held: &mut Option<super::resume::Held>,
4632	copy: Option<&track::Consumer>,
4633	accepted: Option<&mut track::Producer>,
4634	weak: &track::TrackWeak,
4635	routes: &super::resume::Producer,
4636	waiter: &kio::Waiter,
4637) {
4638	if held.is_none() && copy.is_none() {
4639		return;
4640	}
4641	// Woken by the demand changing, which `follow` reads from each reader's own edits.
4642	if let Some(accepted) = accepted {
4643		accepted.watch_subscription(waiter);
4644	}
4645	match held {
4646		Some(hold) => {
4647			if !routes.follow(hold, weak) {
4648				*held = None;
4649			}
4650		}
4651		None => {
4652			*held = weak
4653				.subscription()
4654				.and_then(|(subscription, subscribers)| Some(routes.subscribe(copy?, subscription, subscribers)));
4655		}
4656	}
4657}
4658
4659impl InFlight {
4660	/// Let go once its last reader left. Nobody reads the logical track any more, so it ends
4661	/// as a cancel rather than as a producer dropped unfinished.
4662	fn release(self) {
4663		self.routes.release();
4664		match self.logical {
4665			Logical::Requested(request) => request.reject(Error::Cancel),
4666			Logical::Accepted(accepted) => {
4667				let _ = accepted.abort(Error::Cancel);
4668			}
4669			Logical::Ended => {}
4670		}
4671	}
4672}
4673
4674/// Drives one front until it ends, then holds the tracks it left in flight until
4675/// their last reader leaves, or until nothing owns the origin: a reader never keeps
4676/// the driver from finishing.
4677struct FrontServeRun {
4678	state: FrontRunState,
4679	origin: TasksWeak,
4680}
4681
4682#[allow(clippy::large_enum_variant, reason = "a machine's enum is its storage")]
4683enum FrontRunState {
4684	/// Not polled yet: the front starts serving on its first poll, so a set that drops
4685	/// it unpolled never starts it.
4686	Start(FrontTask),
4687	Serve(FrontServe),
4688	/// Each keeps its copy for the readers still on their way, then lets go as an unread
4689	/// track parks, so the copy never keeps its source subscribed for nobody. Unread once
4690	/// is unread for good: the front closed its broadcast, which refuses every lookup, so
4691	/// no reader can arrive once the last one left.
4692	InFlight(Vec<InFlight>),
4693}
4694
4695impl FrontServeRun {
4696	fn new(task: FrontTask, origin: TasksWeak) -> Self {
4697		Self {
4698			state: FrontRunState::Start(task),
4699			origin,
4700		}
4701	}
4702}
4703
4704/// A front dropped before it ended, as when its origin is torn down, ends the logical tracks it
4705/// was serving as closed, rather than leave them to warn as producers dropped unfinished.
4706impl Drop for FrontServeRun {
4707	fn drop(&mut self) {
4708		let close = |logical: &mut Logical| {
4709			if let Logical::Accepted(accepted) = std::mem::replace(logical, Logical::Ended) {
4710				let _ = accepted.abort(Error::Closed);
4711			}
4712		};
4713		match &mut self.state {
4714			FrontRunState::Start(_) => {}
4715			FrontRunState::Serve(serve) => serve.tracks.values_mut().for_each(|io| close(&mut io.logical)),
4716			FrontRunState::InFlight(in_flight) => in_flight.iter_mut().for_each(|io| close(&mut io.logical)),
4717		}
4718	}
4719}
4720
4721impl kio::Task for FrontServeRun {
4722	type Output = ();
4723
4724	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> {
4725		let in_flight = loop {
4726			match &mut self.state {
4727				FrontRunState::Start(_) => {
4728					let FrontRunState::Start(task) =
4729						std::mem::replace(&mut self.state, FrontRunState::InFlight(Vec::new()))
4730					else {
4731						unreachable!("matched above");
4732					};
4733					self.state = FrontRunState::Serve(FrontServe::new(task));
4734				}
4735				FrontRunState::Serve(serve) => {
4736					let in_flight = ready!(serve.poll(waiter));
4737					self.state = FrontRunState::InFlight(in_flight);
4738				}
4739				FrontRunState::InFlight(in_flight) => break in_flight,
4740			}
4741		};
4742		// Dropped without a release, so a reader on its way keeps the copy; it stays held
4743		// only while the logical track's state does, for an origin nobody owns.
4744		if self.origin.poll_orphaned(waiter).is_ready() {
4745			for io in in_flight.iter_mut() {
4746				if let Logical::Requested(_) = io.logical
4747					&& let Logical::Requested(request) = std::mem::replace(&mut io.logical, Logical::Ended)
4748				{
4749					request.reject(io.end.clone());
4750				}
4751			}
4752			return Poll::Ready(());
4753		}
4754		for mut io in std::mem::take(in_flight) {
4755			if let Logical::Requested(request) = &mut io.logical {
4756				request.watch_subscription(waiter);
4757				match io.query.poll_ok(waiter) {
4758					Poll::Ready(Ok(info)) => io.logical.accept(info),
4759					Poll::Ready(Err(err)) => {
4760						// No metadata ever arrived: a lost route cannot answer the request.
4761						let err = match err.retryable() {
4762							true => io.end.clone(),
4763							false => err,
4764						};
4765						if let Logical::Requested(request) = std::mem::replace(&mut io.logical, Logical::Ended) {
4766							request.reject(err.clone());
4767						}
4768						io.routes.end(Err(err));
4769						continue;
4770					}
4771					Poll::Pending => {}
4772				}
4773			}
4774			follow_demand(&mut io.held, None, io.logical.accepted(), &io.weak, &io.routes, waiter);
4775			match io.weak.poll_unwanted(waiter) {
4776				Poll::Pending => in_flight.push(io),
4777				Poll::Ready(_) => io.release(),
4778			}
4779		}
4780		match in_flight.is_empty() {
4781			true => Poll::Ready(()),
4782			false => Poll::Pending,
4783		}
4784	}
4785}
4786
4787/// The route a front may serve from. `resolved` is the identity the front first
4788/// resolved, once it has. Its routes serve one continuous key space, so any of them
4789/// at its newest epoch may take over. The front stays until those routes go, even once
4790/// another identity wins the path: its subscriptions are sticky, and new requests
4791/// resolve the winner on a fresh front.
4792fn pick<'a>(
4793	table: &'a OriginState,
4794	path: &Path,
4795	horizon: Horizon,
4796	front: &Front,
4797	resolved: Option<&Identity>,
4798) -> Option<&'a RouteEntry> {
4799	let excluded = front.excluded_routes();
4800	match resolved {
4801		None => table.best_route(path, horizon, excluded, |_| true),
4802		Some(identity) => table.best_route(path, horizon, excluded, |entry| entry.identity == *identity),
4803	}
4804}
4805
4806/// What [`FrontServe::poll_step`] returns: one thing that happened.
4807enum FrontStep {
4808	/// Boxed, as it dwarfs every other step.
4809	Assigned(Box<track::Request>),
4810	Resolved(Result<broadcast::Consumer, Error>),
4811	SourceClosed(u64),
4812	Info(track::Key, u64, Result<track::Info, Error>),
4813	Ended(track::Key, u64, Result<(), Error>, bool),
4814	Demand(track::Key),
4815	Holders,
4816	/// The broadcast closed: nobody can hold it again.
4817	Closed,
4818	Deadline,
4819	Table,
4820	/// Someone lists the broadcast, or the serving source changed: read its listing.
4821	Listing,
4822	/// Nobody lists the broadcast any more.
4823	Unlisted,
4824	Listed(Result<Option<broadcast::TracksEvent>, Error>),
4825}
4826
4827/// A front's in-flight upstream request.
4828struct FrontUpstream {
4829	route: u64,
4830	/// The route's identity and epoch when asked.
4831	asked: (Identity, u64),
4832	pending: kio::Consumer<PendingBroadcast>,
4833	/// The queue's [`ServeState::renewals`], and its count when asked: a renewal
4834	/// since released the request, whatever it resolved to and whenever.
4835	renewals: Arc<AtomicU64>,
4836	asked_renewals: u64,
4837}
4838
4839/// Feeds the world's events to a [`Front`] and performs the actions it returns,
4840/// until the front ends; resolves to the tracks it ended in flight. The decisions live
4841/// in the machine; this only waits and executes, so nothing here decides anything
4842/// twice.
4843///
4844/// Declared in drop order: the state the front builds goes before the task's handles it
4845/// is built from, the newest first.
4846struct FrontServe {
4847	/// The current wait's waiter. Each wait gets a fresh one: a reused waiter keeps the
4848	/// registrations an earlier wait left, which wake the front spuriously.
4849	park: kio::Park,
4850	/// The source the broadcast's datagram lookups go to, as last handed over: datagram
4851	/// tracks are live only, so a lookup joins the serving source's own track rather than a
4852	/// copy the front would splice.
4853	datagram_source: Option<u64>,
4854	/// Once the front picks a route a session received, it asks sessions to keep
4855	/// discovering its path for as long as it lives, so the route outlives whatever
4856	/// reader found it, such as a listing that has since closed.
4857	discovered: Option<Interest>,
4858	events: VecDeque<Event>,
4859	/// Whether a consumer held the broadcast as of the last edge fed to the machine,
4860	/// starting with the request that minted the front.
4861	held: bool,
4862	/// What the front first resolved; see [`pick`].
4863	resolved: Option<Identity>,
4864	/// The watch generation the last selection saw.
4865	seen: u64,
4866	deadline: crate::time::Deadline,
4867	ready: kio::Queue<track::Key>,
4868	tracks: HashMap<track::Key, TrackIo>,
4869	upstream: Option<FrontUpstream>,
4870	next_source: u64,
4871	/// The identity and epoch each source's route served when it was asked: what its
4872	/// content is from.
4873	identities: HashMap<u64, (Identity, u64)>,
4874	sources: HashMap<u64, broadcast::Consumer>,
4875	front: Front,
4876	listing: Option<FrontListing>,
4877	lister: broadcast::Lister,
4878	/// The front serves its broadcast on demand: every track a reader names is
4879	/// handed here, and its readers read it from whichever source serves the path.
4880	dynamic: broadcast::Requests,
4881	timers: Deadlines,
4882	request: kio::Producer<PendingFront>,
4883	watch: Watch,
4884	pin: Option<Identity>,
4885	horizon: Horizon,
4886	path: Path,
4887	broadcast: broadcast::Producer,
4888	shared: SendCell<kio::Shared<OriginState>>,
4889}
4890
4891/// The copy of `key` a front's source serves: its metadata copy where it keeps one apart,
4892/// and otherwise its payload copy, whose headers a metadata reader takes.
4893fn source_track(source: &broadcast::Consumer, key: &track::Key) -> Result<track::Consumer, Error> {
4894	match key.meta {
4895		true => source.track_meta(&key.name),
4896		false => source.track(&key.name),
4897	}
4898}
4899
4900impl FrontServe {
4901	fn new(task: FrontTask) -> Self {
4902		let FrontTask {
4903			shared,
4904			broadcast,
4905			path,
4906			horizon,
4907			pin,
4908			watch,
4909			request,
4910			timers,
4911		} = task;
4912		let dynamic = broadcast.requests();
4913		let lister = dynamic
4914			.lister()
4915			.expect("only the front answers its broadcast's listings");
4916		let deadline = crate::time::Deadline::new(&timers);
4917		broadcast.serve_datagrams_from(None);
4918		let mut serve = Self {
4919			park: kio::Park::default(),
4920			datagram_source: None,
4921			discovered: None,
4922			events: VecDeque::new(),
4923			held: true,
4924			resolved: None,
4925			seen: 0,
4926			deadline,
4927			ready: kio::Queue::new(),
4928			tracks: HashMap::new(),
4929			upstream: None,
4930			next_source: 0,
4931			identities: HashMap::new(),
4932			sources: HashMap::new(),
4933			front: Front::new(track::IDLE_LINGER),
4934			listing: None,
4935			lister,
4936			dynamic,
4937			timers,
4938			request,
4939			watch,
4940			pin,
4941			horizon,
4942			path,
4943			broadcast,
4944			shared,
4945		};
4946		let event = serve.select();
4947		serve.events.push_back(event);
4948		serve
4949	}
4950
4951	/// Read the table for the machine: the best route and whether
4952	/// the serving source is on its way out. Also what the watch wakes for.
4953	fn select(&mut self) -> Event {
4954		let mut table = self.shared.lock();
4955		if table.closed {
4956			return Event::Closed;
4957		}
4958		// Read alongside the decision, under the lock a poke takes first.
4959		self.seen = self.watch.seen();
4960		self.front.retain_routes(|route| table.routes.covers(&self.path, route));
4961		let best = pick(
4962			&table,
4963			&self.path,
4964			self.horizon,
4965			&self.front,
4966			self.resolved.as_ref().or(self.pin.as_ref()),
4967		);
4968		// Under the table's lock, which a request reads it under too: a request that
4969		// sees another winner from here on mints its own front rather than join this one.
4970		if self.resolved.is_none()
4971			&& let Some(entry) = best
4972			&& let Ok(mut pending) = self.request.write()
4973		{
4974			if pending.selected != entry.identity {
4975				pending.selected = entry.identity.clone();
4976			}
4977			if pending.epoch != entry.epoch {
4978				pending.epoch = entry.epoch;
4979			}
4980		}
4981		// Whether another identity than the front's wins the path, with no node named: a request
4982		// naming the claim's node still resolves the winner on its own front. A pinned front
4983		// serves the identity its requests named, so another winning supersedes it too.
4984		let everyone = Horizon {
4985			node: NodeFilter::Any,
4986			..self.horizon
4987		};
4988		let superseded = (self.resolved.as_ref().or(self.pin.as_ref())).is_some_and(|identity| {
4989			table
4990				.best_route(&self.path, everyone, &HashSet::new(), |_| true)
4991				.is_some_and(|winner| winner.identity != *identity)
4992		});
4993		// Only a received route carries a hop chain or a claiming node: a local one needs
4994		// no discovery.
4995		let received = best.is_some_and(|entry| !entry.hops.is_empty() || entry.node.is_some());
4996		let best = best.map(|entry| Candidate {
4997			route: entry.id,
4998			local: entry.local,
4999			carried: !entry.identity.is_minted(),
5000			claim: entry.node.is_some(),
5001		});
5002		// No candidate irreversibly ends this front, unless it waits on a claim. Leave the
5003		// cache under the same lock a lookup takes, before a route can return and a newcomer
5004		// join the broadcast the end actions are about to close. Existing requesters keep
5005		// their original verdict.
5006		if best.is_none() && !self.front.waiting() {
5007			table
5008				.fronts
5009				.remove_if(&(self.path.clone(), self.horizon, self.pin.clone()), |front| {
5010					front.request.is_clone(&self.request)
5011				});
5012		}
5013		let serving_closing = self
5014			.front
5015			.serving()
5016			.and_then(|id| self.sources.get(&id))
5017			.is_some_and(|source| source.is_closing());
5018		drop(table);
5019		if received && self.discovered.is_none() {
5020			let mut table = self.shared.lock();
5021			self.discovered = Some(Interest::new(&mut table, &self.shared, self.path.clone()));
5022		}
5023		Event::Selected {
5024			best,
5025			serving_closing,
5026			superseded,
5027		}
5028	}
5029
5030	/// Whether a route's refusal is the answer: only the current winner speaks for the
5031	/// path. A retraction resolves like a rejection, and a route beaten while its
5032	/// request was pending speaks for nobody, so either one re-selects instead.
5033	fn standing(&self, route: u64) -> bool {
5034		let table = self.shared.read();
5035		pick(
5036			&table,
5037			&self.path,
5038			self.horizon,
5039			&self.front,
5040			self.resolved.as_ref().or(self.pin.as_ref()),
5041		)
5042		.is_some_and(|best| best.id == route)
5043	}
5044
5045	/// Whether an answer `route` gave for `asked` (an identity and its epoch) would serve
5046	/// another identity than the front's, or an epoch of it that no longer stands: the route
5047	/// has since moved off it, before the front resolved another identity won the path while
5048	/// the request was in flight, or a higher epoch of the route's claim did, including one
5049	/// that replaced the route in the table.
5050	fn stale(&self, route: u64, asked: &(Identity, u64)) -> bool {
5051		let table = self.shared.read();
5052		let entry = table.routes.covering(&self.path).find(|entry| entry.id == route);
5053		if let Some(entry) = entry
5054			&& (entry.identity != asked.0 || self.resolved.as_ref().is_some_and(|resolved| *resolved != asked.0))
5055		{
5056			return true;
5057		}
5058		let best = pick(
5059			&table,
5060			&self.path,
5061			self.horizon,
5062			&self.front,
5063			self.resolved.as_ref().or(self.pin.as_ref()),
5064		);
5065		best.is_some_and(|best| match entry {
5066			Some(entry) => best.identity != asked.0 || (best.claimed() == entry.claimed() && best.epoch > entry.epoch),
5067			// The route left the table: its answer still serves its identity, unless another
5068			// identity or a higher epoch of it wins now.
5069			None => best.identity != asked.0 || best.epoch > asked.1,
5070		})
5071	}
5072
5073	/// Wait for the next thing to happen, the one place the front parks.
5074	fn poll_step(&mut self, waiter: &kio::Waiter) -> Poll<FrontStep> {
5075		if let Poll::Ready(Ok(request)) = self.dynamic.poll_requested_track(waiter) {
5076			return Poll::Ready(FrontStep::Assigned(Box::new(request)));
5077		}
5078		if let Some(upstream) = &self.upstream
5079			&& let Poll::Ready(result) = upstream.pending.poll(waiter, |p| match &p.resolved {
5080				Some(result) => Poll::Ready(result.clone()),
5081				None => Poll::Pending,
5082			}) {
5083			return Poll::Ready(FrontStep::Resolved(match result {
5084				Ok(resolved) => resolved,
5085				// The queue died unresolved (its handler dropped): the route
5086				// could not serve.
5087				Err(_closed) => Err(Error::Unroutable),
5088			}));
5089		}
5090		// The listing first: a source ends its listing before it closes, so this forwards
5091		// the tracks it finished last before its close detaches it.
5092		match &mut self.listing {
5093			None => {
5094				if self.front.serving().is_some() && matches!(self.lister.poll_wanted(waiter), Poll::Ready(Ok(()))) {
5095					return Poll::Ready(FrontStep::Listing);
5096				}
5097			}
5098			Some(state) => {
5099				if self.lister.poll_unwanted(waiter).is_ready() {
5100					return Poll::Ready(FrontStep::Unlisted);
5101				}
5102				if state.source != self.front.serving() {
5103					return Poll::Ready(FrontStep::Listing);
5104				}
5105				if let Some(reader) = &mut state.reader
5106					&& let Poll::Ready(result) = reader.poll_next(waiter)
5107				{
5108					return Poll::Ready(FrontStep::Listed(result));
5109				}
5110			}
5111		}
5112		if let Some(id) = self.front.serving()
5113			&& let Some(source) = self.sources.get(&id)
5114			&& source.poll_closed(waiter).is_ready()
5115		{
5116			return Poll::Ready(FrontStep::SourceClosed(id));
5117		}
5118		while let Poll::Ready(Ok(name)) = self.ready.poll_pop(waiter) {
5119			let Some(io) = self.tracks.get_mut(&name) else { continue };
5120			io.ready.popped();
5121			let waker = Waker::from(io.ready.clone());
5122			let waiter = io.park.hold(&Context::from_waker(&waker));
5123			let step = (|| {
5124				if let Some(asked) = &mut io.query {
5125					if asked.info.is_none()
5126						&& let Poll::Ready(result) = asked.query.poll(waiter)
5127					{
5128						match result {
5129							Ok(info) => asked.info = Some(info),
5130							Err(err) => return Some(FrontStep::Info(name.clone(), asked.source, Err(err))),
5131						}
5132					}
5133					// An awaited copy follows the readers, or it may never send the group
5134					// they now want. The readers of an ended track stay on the copy it ended
5135					// on, so one rerouted for its group reads subscribes nothing.
5136					if asked.info.is_some() && !matches!(io.logical, Logical::Ended) {
5137						follow_demand(
5138							&mut asked.sub,
5139							Some(&asked.copy),
5140							io.logical.accepted(),
5141							&io.weak,
5142							&io.routes,
5143							waiter,
5144						);
5145					}
5146					// While another copy may still deliver, a matching replacement answers only
5147					// once it delivers or ends: one failing first refuses, and that copy keeps
5148					// serving. Different metadata is refused at once. An ended track's readers
5149					// stay on its last copy, so a copy rerouted for its group reads answers with
5150					// its info alone: it may never deliver anything unasked.
5151					if let Some(info) = &asked.info
5152						&& (matches!(io.logical, Logical::Ended)
5153							|| io
5154								.copy
5155								.as_ref()
5156								.is_none_or(|(_, copy, _)| copy.poll_complete(waiter).is_ready())
5157							|| matches!(&io.logical, Logical::Accepted(accepted) if accepted.info() != info)
5158							|| asked.copy.poll_grouped(waiter).is_ready()
5159							|| asked.copy.poll_complete(waiter).is_ready())
5160					{
5161						return Some(FrontStep::Info(name.clone(), asked.source, Ok(info.clone())));
5162					}
5163				}
5164				follow_demand(&mut io.held, None, io.logical.accepted(), &io.weak, &io.routes, waiter);
5165				// Settled once the copy closes: a group still open below a declared end is
5166				// owed until then, and a session closing first means it never came.
5167				if let Some((source, copy, _)) = &io.copy
5168					&& copy.poll_closed(waiter).is_ready()
5169				{
5170					let result = match copy.poll_complete(&kio::Waiter::noop()) {
5171						Poll::Ready(result) => result,
5172						Poll::Pending => {
5173							// A channel cannot reopen after poll_closed reported its end.
5174							debug_assert!(false, "closed copy did not report completion");
5175							Err(Error::Cancel)
5176						}
5177					};
5178					let delivered = copy.latest_key().is_some();
5179					return Some(FrontStep::Ended(name.clone(), *source, result, delivered));
5180				}
5181				// Watch the demand edge in whichever direction is unmet (`TrackIo::read`).
5182				// Only `Pending` parks, so an answer steps and the handler looks again,
5183				// polling anew when nothing changed. Any other closed track is unread: it owes
5184				// one `Unwanted` if recorded read, and is no edge after.
5185				let edge = match (io.routes.moves(), io.wanted) {
5186					(true, wanted) => io.weak.poll_held_changed(waiter, wanted).is_ready(),
5187					(false, true) => io.weak.poll_unwanted(waiter).is_ready(),
5188					(false, false) => matches!(io.weak.poll_wanted(waiter), Poll::Ready(Ok(()))),
5189				};
5190				if edge {
5191					return Some(FrontStep::Demand(name.clone()));
5192				}
5193				None
5194			})();
5195			if let Some(step) = step {
5196				// A ready answer did not park on its next edge. Revisit this track
5197				// once the machine has consumed the event and applied its actions.
5198				io.ready.wake_by_ref();
5199				return Poll::Ready(step);
5200			}
5201		}
5202		// The same for whoever holds the broadcast itself.
5203		let edge = match self.held {
5204			true => self.broadcast.poll_unheld(waiter),
5205			false => self.broadcast.poll_held(waiter),
5206		};
5207		match edge {
5208			Poll::Ready(Ok(())) => return Poll::Ready(FrontStep::Holders),
5209			// Answers at once from here on, so it must end the front, not be polled again.
5210			Poll::Ready(Err(_)) => return Poll::Ready(FrontStep::Closed),
5211			Poll::Pending => {}
5212		}
5213		if self.deadline.poll(waiter).is_ready() {
5214			return Poll::Ready(FrontStep::Deadline);
5215		}
5216		self.watch.poll_changed(waiter, self.seen).map(|()| FrontStep::Table)
5217	}
5218}
5219
5220impl kio::Task for FrontServe {
5221	type Output = Vec<InFlight>;
5222
5223	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Vec<InFlight>> {
5224		loop {
5225			while let Some(event) = self.events.pop_front() {
5226				let refused = matches!(
5227					&event,
5228					Event::Resolved {
5229						result: Err(Refusal { standing: true, .. }),
5230						..
5231					}
5232				);
5233				let answered = match &event {
5234					Event::TrackInfo { track, source, .. } => Some((track.clone(), *source)),
5235					_ => None,
5236				};
5237				// Every transition, for telling how a front ended a track in a run that failed.
5238				let traced = tracing::enabled!(tracing::Level::DEBUG).then(|| format!("{event:?}"));
5239				let actions = self.front.step(event);
5240				if let Some(event) = traced {
5241					tracing::debug!(path = %self.path, %event, ?actions, "front step");
5242				}
5243				for action in actions {
5244					match action {
5245						Action::Reselect => {
5246							let event = self.select();
5247							self.events.push_back(event);
5248						}
5249						Action::Request { route } => {
5250							// The entry and what it serves.
5251							let found = {
5252								let table = self.shared.read();
5253								table
5254									.routes
5255									.covering(&self.path)
5256									.find(|entry| entry.id == route && entry.live())
5257									.map(|entry| {
5258										let identity = (entry.identity.clone(), entry.epoch);
5259										(entry.source.clone(), entry.server.clone(), identity)
5260									})
5261							};
5262							let Some((source, server, identity)) = found else {
5263								self.events.push_back(Event::Resolved {
5264									route,
5265									result: Err(Refusal {
5266										err: Error::Unroutable,
5267										standing: false,
5268									}),
5269								});
5270								continue;
5271							};
5272							if let Some(source) = source {
5273								let id = self.next_source;
5274								self.next_source += 1;
5275								self.sources.insert(id, source);
5276								self.identities.insert(id, identity);
5277								self.events.push_back(Event::Resolved { route, result: Ok(id) });
5278								continue;
5279							}
5280							let Some(server) = server else {
5281								self.events.push_back(Event::Resolved {
5282									route,
5283									result: Err(Refusal {
5284										err: Error::Unroutable,
5285										standing: self.standing(route),
5286									}),
5287								});
5288								continue;
5289							};
5290							let mut serve = server.lock();
5291							if serve.closed {
5292								// Retracted under us, or its handler dropped while the
5293								// announcement stands: it cannot serve. A retraction
5294								// leaves the table before it closes the server, so the
5295								// table tells the two apart.
5296								drop(serve);
5297								self.events.push_back(Event::Resolved {
5298									route,
5299									result: Err(Refusal {
5300										err: Error::Unroutable,
5301										standing: self.standing(route),
5302									}),
5303								});
5304								continue;
5305							}
5306							// A source this route already materialized for the path
5307							// attaches without another upstream round trip. Its session
5308							// retires a source nothing holds, atomically with this mint, so
5309							// one found closed is gone and the route is asked afresh.
5310							if let Some(source) = serve
5311								.served
5312								.get(&self.path)
5313								.map(|weak| weak.consume())
5314								.filter(|source| !source.is_closed())
5315							{
5316								drop(serve);
5317								let id = self.next_source;
5318								self.next_source += 1;
5319								self.sources.insert(id, source);
5320								self.identities.insert(id, identity);
5321								self.events.push_back(Event::Resolved { route, result: Ok(id) });
5322								continue;
5323							}
5324							// A request nobody waits on any more is final: its claimant may
5325							// already be skipping it, so ask afresh rather than revive it.
5326							// `join` refuses atomically, since its last reader leaves outside
5327							// this lock.
5328							let pending = match serve.requests.join(&self.path).map(|producer| producer.join()) {
5329								Some(Some(consumer)) => consumer,
5330								stale => {
5331									if stale.is_some() {
5332										serve.requests.take(&self.path);
5333									}
5334									let producer = kio::Producer::<PendingBroadcast>::default();
5335									let consumer = producer.consume();
5336									match serve.requests.insert(self.path.clone(), producer) {
5337										Ok(()) => consumer,
5338										// No live handler behind the route: it cannot
5339										// serve, whatever the table says.
5340										Err(_) => {
5341											drop(serve);
5342											self.events.push_back(Event::Resolved {
5343												route,
5344												result: Err(Refusal {
5345													err: Error::Unroutable,
5346													standing: self.standing(route),
5347												}),
5348											});
5349											continue;
5350										}
5351									}
5352								}
5353							};
5354							self.upstream = Some(FrontUpstream {
5355								route,
5356								asked: identity,
5357								pending,
5358								renewals: serve.renewals.clone(),
5359								asked_renewals: serve.renewals.load(Ordering::Acquire),
5360							});
5361						}
5362						Action::Detach { source, drain } => {
5363							self.sources.remove(&source);
5364							self.identities.remove(&source);
5365							for io in self.tracks.values_mut() {
5366								if !drain && io.query.as_ref().is_some_and(|asked| asked.source == source) {
5367									io.query = None;
5368								}
5369								if !drain && io.staged.as_ref().is_some_and(|asked| asked.source == source) {
5370									io.staged = None;
5371								}
5372								// Any source leaving is rare: drop every parked shortcut rather
5373								// than track which source each came from.
5374								io.routes.unpark();
5375							}
5376						}
5377						Action::Resolve => {
5378							// The broadcast is whatever its first source serves, from the identity
5379							// its route had when asked.
5380							let Some(source) = self.front.serving() else {
5381								continue;
5382							};
5383							let Some((identity, epoch)) = self.identities.get(&source).cloned() else {
5384								continue;
5385							};
5386							// Route datagram lookups before a requester can see the broadcast,
5387							// which would otherwise find no source to ask.
5388							if self.datagram_source != Some(source) {
5389								self.datagram_source = Some(source);
5390								self.broadcast.serve_datagrams_from(self.sources.get(&source).cloned());
5391							}
5392							self.resolved = Some(identity.clone());
5393							if let Ok(mut pending) = self.request.write() {
5394								pending.resolved.get_or_insert(Ok(identity));
5395								pending.epoch = epoch;
5396							}
5397						}
5398						Action::Query { track: name, source } => {
5399							let Some(io) = self.tracks.get_mut(&name) else { continue };
5400							io.ready.wake_by_ref();
5401							let closing = self.sources.get(&source).is_some_and(|s| s.is_closing());
5402							match self.sources.get(&source).map(|s| source_track(s, &name)) {
5403								Some(Ok(lookup)) => {
5404									// Subscribe before the query exposes upstream demand, and query
5405									// that same identity even if the broadcast changes meanwhile.
5406									let sub = io
5407										.weak
5408										.subscription()
5409										.map(|(demand, subscribers)| io.routes.subscribe(&lookup, demand, subscribers));
5410									let query = match &sub {
5411										Some(sub) => sub.info(),
5412										None => lookup.info().into_inner(),
5413									};
5414									let copy = query.track();
5415									io.query = Some(Asked {
5416										source,
5417										staged: io.routes.stage(copy.clone()),
5418										copy,
5419										query,
5420										info: None,
5421										sub,
5422									});
5423								}
5424								Some(Err(err)) => self.events.push_back(Event::TrackInfo {
5425									track: name,
5426									source,
5427									closing,
5428									result: Err(err),
5429									retry: None,
5430								}),
5431								None => {}
5432							}
5433						}
5434						Action::Reroute { track: name, source } => {
5435							let Some(io) = self.tracks.get_mut(&name) else { continue };
5436							// Nothing reads it any more, so nothing would continue on the copy.
5437							if !io.weak.is_held() {
5438								continue;
5439							}
5440							io.ready.wake_by_ref();
5441							let closing = self.sources.get(&source).is_some_and(|s| s.is_closing());
5442							let lookup = match self.sources.get(&source).map(|s| source_track(s, &name)) {
5443								Some(Ok(lookup)) => lookup,
5444								// Refused before any lookup, as a query would be: the front judges
5445								// it the same way, so a held fetch is not left waiting on it.
5446								Some(Err(err)) => {
5447									self.events.push_back(Event::TrackInfo {
5448										track: name,
5449										source,
5450										closing,
5451										result: Err(err),
5452										retry: None,
5453									});
5454									continue;
5455								}
5456								None => continue,
5457							};
5458							// No subscription: the track is over, and a read that continues on the
5459							// copy asks it for what it needs.
5460							let query = lookup.info().into_inner();
5461							let copy = query.track();
5462							io.query = Some(Asked {
5463								source,
5464								staged: io.routes.stage(copy.clone()),
5465								copy,
5466								query,
5467								info: None,
5468								sub: None,
5469							});
5470						}
5471						Action::Conclude { track: name } => {
5472							let Some(io) = self.tracks.get_mut(&name) else { continue };
5473							io.ready.wake_by_ref();
5474							io.routes.conclude();
5475							io.query = None;
5476							io.staged = None;
5477						}
5478						Action::Splice { track: name, source } => {
5479							let Some(io) = self.tracks.get_mut(&name) else { continue };
5480							let Some(asked) = io.staged.take() else {
5481								continue;
5482							};
5483							if asked.source != source {
5484								continue;
5485							}
5486							io.splice(asked);
5487						}
5488						Action::Park { track: name } => {
5489							let Some(io) = self.tracks.get_mut(&name) else { continue };
5490							io.ready.wake_by_ref();
5491							// Drop the copy so its source goes idle at once. A returning
5492							// reader gets a fresh one, so nothing cached can be stale.
5493							io.routes.park();
5494							io.query = None;
5495							io.staged = None;
5496							io.copy = None;
5497							io.held = None;
5498						}
5499						Action::Forget { track: name } => {
5500							// A reader that looked the track up since the machine decided keeps
5501							// it, as does one still holding it once it finished. Feed its `Wanted`
5502							// edge here: the demand poll only sees the current level, so a reader
5503							// gone before the next poll would otherwise leave the track unread
5504							// with no linger armed.
5505							if let Some(io) = self.tracks.get_mut(&name)
5506								&& (!io.weak.abort_unwanted(Error::Cancel) || io.read())
5507							{
5508								if !io.wanted {
5509									io.wanted = true;
5510									self.events.push_back(Event::Wanted { track: name });
5511								}
5512								continue;
5513							}
5514							// Nobody reads it, so nobody follows its copy: let the route go idle.
5515							if let Some(io) = self.tracks.remove(&name) {
5516								io.routes.park();
5517							}
5518							self.events.push_back(Event::Forgotten { track: name });
5519						}
5520						Action::Finish { track: name } => {
5521							if let Some(io) = self.tracks.get_mut(&name) {
5522								io.end(Ok(()), None);
5523							}
5524						}
5525						Action::Abort {
5526							track: name,
5527							err,
5528							retry,
5529						} => {
5530							if let Some(io) = self.tracks.get_mut(&name) {
5531								tracing::debug!(name = %name, %err, "aborting track");
5532								io.end(Err(err), retry);
5533							}
5534						}
5535						Action::Arm { at } => self.deadline.set(at),
5536						Action::Retire => {
5537							// Closing refuses every holder from here on, atomically with minting
5538							// one: a request that joined first keeps the front, and one after
5539							// finds it closed and mints a fresh one.
5540							let event = match self.broadcast.close_unheld() {
5541								true => Event::Retired,
5542								false => {
5543									self.held = true;
5544									Event::Held
5545								}
5546							};
5547							self.events.push_back(event);
5548						}
5549						Action::End { err } => {
5550							// Leave the table before anything shows the end, whatever ended the
5551							// front: a requester seeing it re-requests, and must mint a fresh
5552							// front rather than join this one again. A successor already in the
5553							// slot stays.
5554							self.shared
5555								.lock()
5556								.fronts
5557								.remove_if(&(self.path.clone(), self.horizon, self.pin.clone()), |front| {
5558									front.request.is_clone(&self.request)
5559								});
5560							if let Ok(mut pending) = self.request.write() {
5561								pending.refused = refused;
5562								pending.resolved.get_or_insert(Err(err.clone()));
5563							}
5564							// Ending the broadcast only retracts it: no new requesters or
5565							// tracks, and a newcomer at the path gets a fresh front. Tracks
5566							// in flight carry on (moq-lite: retraction does not disturb
5567							// subscriptions already in flight): their readers follow the copy
5568							// they read to its end, since no front is left to replace it.
5569							self.broadcast.close();
5570							let mut in_flight = Vec::new();
5571							for (name, mut io) in self.tracks.drain() {
5572								let wanted = io.weak.is_wanted();
5573								let err = self.front.lost(&name).unwrap_or_else(|| err.clone());
5574								// A reader still waiting on its source's answer is in flight
5575								// too: serve it the copy it asked, so it ends as that copy does.
5576								let waiting = io.staged.take().or_else(|| io.query.take());
5577								if io.copy.is_none()
5578									&& wanted && let Some(asked) = waiting
5579								{
5580									io.splice(asked);
5581								}
5582								let (_, _, query) = match io.copy.take() {
5583									Some(copy) if wanted => copy,
5584									// Nothing in flight: unread, or nothing serving it.
5585									copy => {
5586										io.copy = copy;
5587										// A track that already ended keeps its copy, which subscribes
5588										// nothing any more, so a fetch still reads what it cached.
5589										let ended = io.routes.ended();
5590										io.end(Err(err.clone()), None);
5591										// An unread track the front has not parked yet still holds
5592										// its copy, which would keep its source subscribed.
5593										if !wanted && !ended {
5594											io.routes.release();
5595										}
5596										continue;
5597									}
5598								};
5599								io.routes.conclude();
5600								let TrackIo {
5601									weak,
5602									routes,
5603									logical,
5604									held,
5605									..
5606								} = io;
5607								in_flight.push(InFlight {
5608									weak,
5609									routes,
5610									end: err.clone(),
5611									logical,
5612									query,
5613									held,
5614								});
5615							}
5616							return Poll::Ready(in_flight);
5617						}
5618					}
5619				}
5620				// The machine stopped asking the route this request went to, by asking another or
5621				// giving the switch up: drop it, so its claimant learns nobody waits on it.
5622				if self
5623					.upstream
5624					.as_ref()
5625					.is_some_and(|asked| self.front.asking() != Some(asked.route))
5626				{
5627					self.upstream = None;
5628				}
5629				// A staged copy the machine did not splice was refused or is no longer wanted:
5630				// let it go, or its source stays subscribed for nobody.
5631				if let Some((name, source)) = answered
5632					&& let Some(io) = self.tracks.get_mut(&name)
5633					&& io.staged.as_ref().is_some_and(|asked| asked.source == source)
5634				{
5635					io.staged = None;
5636				}
5637			}
5638
5639			if self.front.serving() != self.datagram_source {
5640				self.datagram_source = self.front.serving();
5641				self.broadcast
5642					.serve_datagrams_from(self.datagram_source.and_then(|id| self.sources.get(&id)).cloned());
5643				// A switch to another epoch of the identity admits the requests that select it.
5644				if let Some((_, epoch)) = self.datagram_source.and_then(|id| self.identities.get(&id))
5645					&& let Ok(mut pending) = self.request.write()
5646				{
5647					pending.epoch = *epoch;
5648				}
5649			}
5650
5651			let mut park = std::mem::take(&mut self.park);
5652			let Poll::Ready(step) = self.poll_step(park.hold(&waiter.context())) else {
5653				self.park = park;
5654				return Poll::Pending;
5655			};
5656			// Before the step runs, so nothing it touches wakes the front for a wait that
5657			// is over.
5658			drop(park);
5659
5660			let event = match step {
5661				FrontStep::Assigned(request) => {
5662					let request = *request;
5663					let name = track::Key {
5664						name: request.name().into(),
5665						meta: request.meta(),
5666					};
5667					let track_ready = crate::util::QueueWake::new(name.clone(), self.ready.clone());
5668					track_ready.wake_by_ref();
5669					let routes = super::resume::Producer::new();
5670					self.tracks.insert(
5671						name.clone(),
5672						TrackIo {
5673							ready: track_ready,
5674							park: Default::default(),
5675							weak: request.weak(),
5676							logical: Logical::Requested(request.routes(routes.consume())),
5677							routes,
5678							query: None,
5679							staged: None,
5680							copy: None,
5681							held: None,
5682							wanted: false,
5683						},
5684					);
5685					Event::TrackAssigned {
5686						track: name,
5687						now: self.timers.now(),
5688					}
5689				}
5690				FrontStep::Resolved(result) => {
5691					let Some(FrontUpstream {
5692						route,
5693						asked,
5694						renewals,
5695						asked_renewals,
5696						..
5697					}) = self.upstream.take()
5698					else {
5699						continue;
5700					};
5701					// Counted rather than read off the request, which an answer just before
5702					// the change already took out of the queue, and rather than compared by
5703					// identity, which may have come back since.
5704					let released = renewals.load(Ordering::Acquire) != asked_renewals;
5705					match result {
5706						// An identity change released the request, the route moved to another
5707						// identity, or another won the path, while the request was in flight:
5708						// ask again rather than resolve requesters onto a broadcast that is
5709						// already replaced.
5710						_ if released => Event::Resolved {
5711							route,
5712							result: Err(Refusal {
5713								err: Error::Unroutable,
5714								standing: false,
5715							}),
5716						},
5717						Ok(_) if self.stale(route, &asked) => Event::Resolved {
5718							route,
5719							result: Err(Refusal {
5720								err: Error::Unroutable,
5721								standing: false,
5722							}),
5723						},
5724						Ok(source) => {
5725							let id = self.next_source;
5726							self.next_source += 1;
5727							self.sources.insert(id, source);
5728							self.identities.insert(id, asked);
5729							Event::Resolved { route, result: Ok(id) }
5730						}
5731						Err(err) => Event::Resolved {
5732							route,
5733							result: Err(Refusal {
5734								err,
5735								standing: self.standing(route),
5736							}),
5737						},
5738					}
5739				}
5740				FrontStep::SourceClosed(source) => Event::SourceClosed { source },
5741				FrontStep::Info(name, source, result) => {
5742					let Some(io) = self.tracks.get_mut(&name) else { continue };
5743					let Some(asked) = io.query.take() else { continue };
5744					let retry = asked.query.retry();
5745					// An aborted copy with history still splices, so its readers drain that
5746					// history before the outcome, as local readers do. One that delivered
5747					// nothing is a refusal, which leaves a draining incumbent serving.
5748					let result = match result {
5749						Ok(info) => match asked.copy.poll_complete(&kio::Waiter::noop()) {
5750							Poll::Ready(Err(err)) if asked.copy.latest_key().is_none() => Err(err),
5751							_ => Ok(info),
5752						},
5753						Err(err) => Err(err),
5754					};
5755					// Read after the copy's outcome: a subscriber closes a source before it fails
5756					// that source's copies, so a failure seen above is already reflected here.
5757					let closing = self.sources.get(&source).is_some_and(|s| s.is_closing());
5758					// Staged only while the track has a reader, or a read holds the finished
5759					// track: without one the machine will not splice, and a held copy would
5760					// keep the source subscribed.
5761					if let Ok(info) = &result
5762						&& (io.wanted || io.routes.ended())
5763					{
5764						io.staged = Some(Asked {
5765							info: Some(info.clone()),
5766							..asked
5767						});
5768					}
5769					Event::TrackInfo {
5770						track: name,
5771						source,
5772						closing,
5773						retry: result.as_ref().err().and(retry),
5774						result,
5775					}
5776				}
5777				FrontStep::Ended(name, source, result, delivered) => {
5778					let closing = self.sources.get(&source).is_some_and(|s| s.is_closing());
5779					let Some(io) = self.tracks.get_mut(&name) else { continue };
5780					io.copy = None;
5781					io.held = None;
5782					// A copy that failed may have failed with its route, which the table can
5783					// already have replaced: the front takes that change first, so it fails over
5784					// to the replacement rather than giving up on the route that died.
5785					if result.is_err() && self.watch.poll_changed(&kio::Waiter::noop(), self.seen).is_ready() {
5786						let selected = self.select();
5787						self.events.push_back(selected);
5788					}
5789					Event::TrackEnded {
5790						track: name,
5791						source,
5792						closing,
5793						result,
5794						delivered,
5795					}
5796				}
5797				FrontStep::Demand(name) => {
5798					let Some(io) = self.tracks.get_mut(&name) else { continue };
5799					// Read again: the edge may have flipped back since it fired, and the next
5800					// wait parks on it.
5801					if io.read() == io.wanted {
5802						continue;
5803					}
5804					io.wanted = !io.wanted;
5805					// Nothing will be spliced now: let go of the copies a query holds, or the
5806					// source stays subscribed with nobody reading. An ended track's query is a
5807					// reroute for the reads still holding it, which subscribes nothing: finishing
5808					// is what closes the track, so its edge may come only after the reroute.
5809					if !io.wanted && !io.routes.ended() {
5810						io.query = None;
5811						io.staged = None;
5812					}
5813					match io.wanted {
5814						true => Event::Wanted { track: name },
5815						false => Event::Unwanted {
5816							track: name,
5817							now: self.timers.now(),
5818						},
5819					}
5820				}
5821				FrontStep::Holders => {
5822					// Read again: the edge may have flipped back since it fired.
5823					if self.broadcast.is_held() == self.held {
5824						continue;
5825					}
5826					self.held = !self.held;
5827					match self.held {
5828						true => Event::Held,
5829						false => Event::Unheld,
5830					}
5831				}
5832				FrontStep::Closed => Event::Retired,
5833				FrontStep::Deadline => {
5834					// Cleared here so a fired deadline cannot keep firing; the machine
5835					// re-arms what is still parked.
5836					self.deadline.set(None);
5837					Event::Deadline { now: self.timers.now() }
5838				}
5839				FrontStep::Table => self.select(),
5840				FrontStep::Listing => {
5841					// A route claiming a prefix names no broadcast, so a path it serves on request
5842					// has no inventory to list.
5843					let covering = self.front.serving_route().is_some_and(|route| {
5844						self.shared
5845							.read()
5846							.routes
5847							.covering(&self.path)
5848							.find(|entry| entry.id == route)
5849							.is_some_and(|entry| entry.prefix != self.path)
5850					});
5851					if covering {
5852						self.listing = None;
5853						self.lister.abort(Error::NotFound);
5854						continue;
5855					}
5856					let state = self.listing.get_or_insert_default();
5857					state.source = self.front.serving();
5858					state.stale = state.listed.clone();
5859					// A closing source lists nothing more; the front moves off it soon.
5860					state.reader = state
5861						.source
5862						.and_then(|id| self.sources.get(&id))
5863						.and_then(|source| source.tracks().ok());
5864					continue;
5865				}
5866				FrontStep::Unlisted => {
5867					self.listing = None;
5868					self.lister.clear();
5869					continue;
5870				}
5871				FrontStep::Listed(result) => {
5872					let Some(state) = &mut self.listing else { continue };
5873					// The lister refuses only once the broadcast ended, which ends the front too.
5874					match result {
5875						Ok(Some(broadcast::TracksEvent::Added { name, info })) => {
5876							let key = (info.kind(), name);
5877							if !state.stale.remove(&key) && state.listed.insert(key.clone()) {
5878								let _ = self.lister.add(key.1, info);
5879							}
5880						}
5881						// Forwarded as the source reported it, finished or not.
5882						Ok(Some(broadcast::TracksEvent::Removed { kind, name })) => {
5883							let key = (kind, name);
5884							state.stale.remove(&key);
5885							if state.listed.remove(&key) {
5886								let _ = self.lister.remove(kind, key.1);
5887							}
5888						}
5889						Ok(Some(broadcast::TracksEvent::Finished { kind, name })) => {
5890							let key = (kind, name);
5891							state.stale.remove(&key);
5892							if state.listed.remove(&key) {
5893								let _ = self.lister.finish(kind, key.1);
5894							}
5895						}
5896						Ok(Some(broadcast::TracksEvent::Synced)) => {
5897							for (kind, name) in state.stale.drain() {
5898								state.listed.remove(&(kind, name.clone()));
5899								let _ = self.lister.remove(kind, name);
5900							}
5901							self.lister.synced();
5902						}
5903						// The source ended: the front moves to another source, or ends with it.
5904						Ok(None)
5905							if state
5906								.source
5907								.and_then(|id| self.sources.get(&id))
5908								.is_none_or(|source| source.is_closing()) =>
5909						{
5910							state.reader = None
5911						}
5912						// The source's handler ended the listing on a live source, as a peer does
5913						// once its broadcast ended: so does the front's, and a later reader asks again.
5914						Ok(None) => {
5915							self.listing = None;
5916							self.lister.end();
5917						}
5918						Err(err) => {
5919							// Its readers fail, and a later reader asks again.
5920							self.listing = None;
5921							self.lister.abort(err);
5922						}
5923					}
5924					continue;
5925				}
5926			};
5927			self.events.push_back(event);
5928		}
5929	}
5930}
5931
5932/// The announced routes, keyed by prefix: a trie with one node per path
5933/// segment. Every question about a path walks its segments, so the cost of an
5934/// announcement, a cursor registration, or a request is bounded by the tree
5935/// around that path and never by the size of the table.
5936#[derive(Default)]
5937struct RouteTable {
5938	root: RouteNode,
5939}
5940
5941/// One prefix in the [`RouteTable`]: what is announced exactly there, which
5942/// cursors hang there, and the prefixes one segment below.
5943#[derive(Default)]
5944struct RouteNode {
5945	/// Routes announced exactly at this prefix.
5946	entries: Vec<RouteEntry>,
5947	/// Cursors with an interest head at this prefix (see [`TableCursor::heads`]).
5948	cursors: Vec<ConsumerId>,
5949	/// Cursors at this node or below. An announcement walks only the subtrees
5950	/// that hold one, so a deep table of routes nobody watches costs nothing.
5951	cursors_below: usize,
5952	/// Who is waiting on the routes covering this prefix: the fronts serving it
5953	/// and the requesters parked on it (see [`Watch`]).
5954	watches: Vec<(u64, WatchProducer)>,
5955	/// Watches at this node or below, so a route change walks only the subtrees
5956	/// holding one.
5957	watches_below: usize,
5958	/// Snapshots in flight at exactly this prefix; see [`Snapshot`].
5959	snapshots: Vec<SnapshotEntry>,
5960	/// Snapshots at this node or below, so a cursor registering walks only the
5961	/// subtrees holding one.
5962	snapshots_below: usize,
5963	/// Readers asking sessions to discover routes at or beneath exactly this
5964	/// prefix; see [`Interest`].
5965	interests: usize,
5966	/// Interests at this node or below, so finding the narrower ones a change
5967	/// covers or uncovers walks only the subtrees holding one.
5968	interests_below: usize,
5969	children: HashMap<String, RouteNode>,
5970}
5971
5972/// What a [`Watch`] observes: bumped by every change to a route covering its
5973/// path (a broadcast published here is one) and by the origin's teardown.
5974#[derive(Default)]
5975struct Watched {
5976	generation: u64,
5977}
5978
5979enum WatchProducer {
5980	Changes(kio::Producer<Watched>),
5981	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
5982	Selection(kio::Producer<Selected>),
5983}
5984
5985struct Selected {
5986	path: Path,
5987	via: Hop,
5988	identity: Identity,
5989	/// The selection period, closed when the peer stops selecting the identity.
5990	current: Option<kio::Producer<()>>,
5991	/// Open until another identity of the peer takes the path, which may answer a
5992	/// request still unanswered. A withdrawal alone leaves it open, and a period the
5993	/// identity wins again keeps it.
5994	answering: Option<kio::Producer<()>>,
5995}
5996
5997/// How a [`Selected`] period changes.
5998enum Change {
5999	/// A new period: nothing refused in the last one revives.
6000	Start,
6001	/// The peer no longer selects the identity.
6002	End,
6003	/// Another identity of the peer took the path.
6004	Replace,
6005}
6006
6007impl Selected {
6008	/// How the period changes now that the peer's best route is `best`, if it does.
6009	fn change(&self, best: Option<&RouteEntry>) -> Option<Change> {
6010		let Some(best) = best else {
6011			self.current.as_ref()?;
6012			return Some(Change::End);
6013		};
6014		if best.identity == self.identity {
6015			return self.current.is_none().then_some(Change::Start);
6016		}
6017		if self.current.is_none() {
6018			// Withdrawn earlier: the identity taking the path now may answer what is left.
6019			return self.answering.is_some().then_some(Change::Replace);
6020		}
6021		Some(Change::Replace)
6022	}
6023
6024	fn apply(&mut self, change: Change) {
6025		match change {
6026			Change::Start => {
6027				if self.answering.is_none() {
6028					self.answering = Some(kio::Producer::default());
6029				}
6030				self.current = Some(kio::Producer::default());
6031			}
6032			Change::End => self.current = None,
6033			Change::Replace => {
6034				self.current = None;
6035				self.answering = None;
6036			}
6037		}
6038	}
6039}
6040
6041/// The lifetime of path requests while this peer still selects the held identity.
6042#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
6043pub(crate) struct Selection {
6044	shared: SendCell<kio::Shared<OriginState>>,
6045	path: Path,
6046	id: u64,
6047	signal: kio::Consumer<Selected>,
6048}
6049
6050impl Selection {
6051	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
6052	pub(super) fn current(&self) -> kio::Consumer<()> {
6053		self.signal
6054			.read()
6055			.current
6056			.as_ref()
6057			.map(kio::Producer::consume)
6058			.unwrap_or_else(|| kio::Producer::new(()).consume())
6059	}
6060
6061	/// Closed once another identity takes the path, for a request already sent.
6062	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
6063	pub(super) fn answering(&self) -> kio::Consumer<()> {
6064		self.signal
6065			.read()
6066			.answering
6067			.as_ref()
6068			.map(kio::Producer::consume)
6069			.unwrap_or_else(|| kio::Producer::new(()).consume())
6070	}
6071}
6072
6073impl Drop for Selection {
6074	fn drop(&mut self) {
6075		self.shared.lock().routes.remove_watch(&self.path, self.id);
6076	}
6077}
6078
6079/// A registration in the route table for changes to the routes covering one
6080/// path. The table pokes it; the holder waits on it, so an announcement wakes
6081/// only the fronts and requesters it can affect rather than every one of them.
6082/// Dropping it unregisters, which takes the table lock: never drop one while
6083/// holding it.
6084struct Watch {
6085	shared: SendCell<kio::Shared<OriginState>>,
6086	path: Path,
6087	id: u64,
6088	signal: kio::Consumer<Watched>,
6089}
6090
6091impl Watch {
6092	/// The generation to wait past with [`Self::poll_changed`]. Read under the
6093	/// table lock, alongside the decision it guards, so a poke between the two
6094	/// cannot be missed: a poke takes that same lock first.
6095	fn seen(&self) -> u64 {
6096		self.signal.read().generation
6097	}
6098
6099	/// Ready once the routes covering the path moved past `seen`.
6100	fn poll_changed(&self, waiter: &kio::Waiter, seen: u64) -> Poll<()> {
6101		self.signal
6102			.poll(waiter, |watched| match watched.generation != seen {
6103				true => Poll::Ready(()),
6104				false => Poll::Pending,
6105			})
6106			.map(|_| ())
6107	}
6108}
6109
6110impl Drop for Watch {
6111	fn drop(&mut self) {
6112		self.shared.lock().routes.remove_watch(&self.path, self.id);
6113	}
6114}
6115
6116/// A snapshot in flight, as the route table holds it.
6117struct SnapshotEntry {
6118	id: u64,
6119	/// The link its routes arrive on, so a horizon hiding them never waits on it.
6120	link: Link,
6121	/// The absolute prefix, so a cursor that could see nothing at or beneath it never waits
6122	/// on it.
6123	prefix: Path,
6124}
6125
6126/// A session still delivering its peer's initial announcements under a prefix.
6127///
6128/// Every announce consumer whose scope the prefix overlaps is unsynced
6129/// (see [`Routes::poll_synced`]) until this drops: once the session
6130/// has inserted the announcements its peer counted, or it gave up on them.
6131pub(crate) struct Snapshot {
6132	shared: Option<SendCell<kio::Shared<OriginState>>>,
6133	prefix: Path,
6134	id: u64,
6135}
6136
6137impl Snapshot {
6138	/// A snapshot nothing waits on.
6139	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
6140	pub(crate) fn landed() -> Self {
6141		Self {
6142			shared: None,
6143			prefix: Path::default(),
6144			id: 0,
6145		}
6146	}
6147}
6148
6149impl Drop for Snapshot {
6150	fn drop(&mut self) {
6151		if let Some(shared) = self.shared.take() {
6152			shared.lock().remove_snapshot(&self.prefix, self.id);
6153		}
6154	}
6155}
6156
6157/// Counts an absolute prefix as one readers want discovered until dropped: a
6158/// session fed into the origin asks its peer about the broadest such prefixes.
6159/// Dropping it takes the table lock: never drop one while holding it.
6160struct Interest {
6161	shared: SendCell<kio::Shared<OriginState>>,
6162	prefix: Path,
6163}
6164
6165impl Interest {
6166	/// Count `prefix` under the held table lock.
6167	fn new(state: &mut OriginState, shared: &SendCell<kio::Shared<OriginState>>, prefix: Path) -> Self {
6168		state.add_interest(shared, &prefix);
6169		Self {
6170			shared: shared.clone(),
6171			prefix,
6172		}
6173	}
6174}
6175
6176impl Drop for Interest {
6177	fn drop(&mut self) {
6178		self.shared.lock().remove_interest(&self.shared, &self.prefix);
6179	}
6180}
6181
6182/// A session registered for [`Interests`], as the table holds it.
6183struct Listener {
6184	id: u64,
6185	/// The session's root, absolute: what it asks about is named relative to it.
6186	root: Path,
6187	/// The broadest prefixes the session may ask about, relative to `root`.
6188	heads: Vec<Path>,
6189	/// The absolute prefixes the session may publish under.
6190	allowed: Prefixes,
6191	/// The link the session's routes arrive on, which its snapshots wait for.
6192	link: Link,
6193	queue: kio::Queue<InterestChange>,
6194}
6195
6196impl Listener {
6197	/// What the session asks about, relative to its root, for an interest at the
6198	/// absolute `prefix`: each head an interest above it covers, since the scope
6199	/// may ask for no more, or the prefix itself inside a head.
6200	fn asks(&self, prefix: &Path) -> Vec<Path> {
6201		let Some(relative) = prefix.strip_prefix(&self.root) else {
6202			return match self.root.has_prefix(prefix) {
6203				true => self.heads.clone(),
6204				false => Vec::new(),
6205			};
6206		};
6207		let mut out = Vec::new();
6208		for head in &self.heads {
6209			if head.has_prefix(&relative) {
6210				out.push(head.clone());
6211			} else if relative.has_prefix(head) {
6212				return match self.allowed.overlaps(prefix.as_str()) {
6213					true => vec![relative],
6214					false => Vec::new(),
6215				};
6216			}
6217		}
6218		out
6219	}
6220}
6221
6222/// What a session asks its peer about, as it changes: the broadest prefixes
6223/// readers of the origin want discovered, mapped onto the session's scope.
6224pub(crate) struct Interests {
6225	shared: SendCell<kio::Shared<OriginState>>,
6226	id: u64,
6227	queue: kio::Queue<InterestChange>,
6228}
6229
6230impl Interests {
6231	/// The next change, or `None` once the origin closed.
6232	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
6233	pub(crate) fn poll_next(&self, waiter: &kio::Waiter) -> Poll<Option<InterestChange>> {
6234		Poll::Ready(ready!(self.queue.poll_pop(waiter)).ok())
6235	}
6236}
6237
6238impl Drop for Interests {
6239	fn drop(&mut self) {
6240		// Only the table's copy of the queue goes here; the changes still queued drop with
6241		// this handle's, after the lock is released, since each may hold a snapshot.
6242		self.shared.lock().listeners.retain(|listener| listener.id != self.id);
6243	}
6244}
6245
6246/// One change to what a session asks its peer about; see [`Interests`].
6247#[cfg_attr(
6248	not(feature = "async"),
6249	expect(dead_code, reason = "only async sessions consume discovery changes")
6250)]
6251pub(crate) struct InterestChange {
6252	/// The prefix, relative to the session's root.
6253	pub prefix: Path,
6254	/// Whether readers now want the prefix discovered, or no longer do.
6255	pub wanted: bool,
6256	/// Set when wanted: holds the readers under the prefix short of synced from
6257	/// the moment they asked, until the request the session opens for it
6258	/// delivers the peer's initial set, or the session drops it unasked.
6259	pub snapshot: Option<Snapshot>,
6260}
6261
6262/// What a registration adds to the subtree counts on its walk.
6263#[derive(Clone, Copy)]
6264struct Below {
6265	cursors: usize,
6266	watches: usize,
6267	snapshots: usize,
6268	interests: usize,
6269}
6270
6271impl Below {
6272	const NONE: Self = Self {
6273		cursors: 0,
6274		watches: 0,
6275		snapshots: 0,
6276		interests: 0,
6277	};
6278	const CURSOR: Self = Self {
6279		cursors: 1,
6280		..Self::NONE
6281	};
6282	const WATCH: Self = Self {
6283		watches: 1,
6284		..Self::NONE
6285	};
6286	const SNAPSHOT: Self = Self {
6287		snapshots: 1,
6288		..Self::NONE
6289	};
6290	const INTEREST: Self = Self {
6291		interests: 1,
6292		..Self::NONE
6293	};
6294}
6295
6296impl RouteNode {
6297	/// Nothing here and nothing below: the node can be pruned.
6298	fn is_empty(&self) -> bool {
6299		self.entries.is_empty()
6300			&& self.cursors.is_empty()
6301			&& self.watches.is_empty()
6302			&& self.snapshots.is_empty()
6303			&& self.interests == 0
6304			&& self.children.is_empty()
6305	}
6306
6307	/// The node `parts` below this one, if the table has it.
6308	fn find<'a>(&self, mut parts: impl Iterator<Item = &'a str>) -> Option<&Self> {
6309		match parts.next() {
6310			None => Some(self),
6311			Some(part) => self.children.get(part)?.find(parts),
6312		}
6313	}
6314
6315	/// The node `parts` below this one, created along the way when missing.
6316	/// `below` is added to the subtree counts at every node on the walk.
6317	fn reach<'a>(&mut self, mut parts: impl Iterator<Item = &'a str>, below: Below) -> &mut Self {
6318		self.cursors_below += below.cursors;
6319		self.watches_below += below.watches;
6320		self.snapshots_below += below.snapshots;
6321		self.interests_below += below.interests;
6322		match parts.next() {
6323			None => self,
6324			Some(part) => self.children.entry(part.to_string()).or_default().reach(parts, below),
6325		}
6326	}
6327
6328	/// Run `f` on the node `parts` below this one, then prune every node the
6329	/// edit emptied. `below` is subtracted from the subtree counts at every node
6330	/// on the walk. `None` when the node does not exist, leaving the table as is.
6331	fn edit<'a, R>(
6332		&mut self,
6333		mut parts: impl Iterator<Item = &'a str>,
6334		below: Below,
6335		f: impl FnOnce(&mut Self) -> R,
6336	) -> Option<R> {
6337		let result = match parts.next() {
6338			None => f(self),
6339			Some(part) => {
6340				let child = self.children.get_mut(part)?;
6341				let result = child.edit(parts, below, f)?;
6342				if child.is_empty() {
6343					self.children.remove(part);
6344				}
6345				result
6346			}
6347		};
6348		self.cursors_below -= below.cursors;
6349		self.watches_below -= below.watches;
6350		self.snapshots_below -= below.snapshots;
6351		self.interests_below -= below.interests;
6352		Some(result)
6353	}
6354
6355	/// Wake route watchers, and revoke only leases whose selected identity changed.
6356	fn poke(&self, routes: Option<&RouteTable>) {
6357		for (_, watch) in &self.watches {
6358			match watch {
6359				WatchProducer::Changes(watch) => {
6360					if let Ok(mut watched) = watch.write() {
6361						watched.generation += 1;
6362					}
6363				}
6364				WatchProducer::Selection(watch) => {
6365					if let Ok(mut selected) = watch.write() {
6366						let change = match routes {
6367							Some(routes) => selected.change(routes.best_route(
6368								&selected.path,
6369								Horizon::default(),
6370								&HashSet::new(),
6371								|entry| entry.via == selected.via,
6372							)),
6373							None => selected.current.is_some().then_some(Change::End),
6374						};
6375						// Only a change wakes the requests waiting on the selection.
6376						if let Some(change) = change {
6377							selected.apply(change);
6378						}
6379					}
6380				}
6381			}
6382		}
6383	}
6384
6385	/// Wake only the watched subtrees covered by this route.
6386	fn poke_below(&self, routes: &RouteTable) {
6387		if self.watches_below == 0 {
6388			return;
6389		}
6390		self.poke(Some(routes));
6391		for child in self.children.values() {
6392			child.poke_below(routes);
6393		}
6394	}
6395
6396	/// Visit this node and everything below it.
6397	fn walk<'a>(&'a self, visit: &mut impl FnMut(&'a Self)) {
6398		visit(self);
6399		for child in self.children.values() {
6400			child.walk(visit);
6401		}
6402	}
6403
6404	/// Collect the snapshots at this node and below, skipping subtrees with none.
6405	fn collect_snapshots<'a>(&'a self, out: &mut Vec<&'a SnapshotEntry>) {
6406		if self.snapshots_below == 0 {
6407			return;
6408		}
6409		out.extend(&self.snapshots);
6410		for child in self.children.values() {
6411			child.collect_snapshots(out);
6412		}
6413	}
6414
6415	/// Collect the cursors at this node and below, skipping subtrees with none.
6416	fn collect_cursors(&self, out: &mut Vec<ConsumerId>) {
6417		if self.cursors_below == 0 {
6418			return;
6419		}
6420		out.extend(&self.cursors);
6421		for child in self.children.values() {
6422			child.collect_cursors(out);
6423		}
6424	}
6425
6426	/// Collect the broadest interests strictly beneath this node, which sits at
6427	/// `at`: each one no other interest beneath this node covers.
6428	fn collect_interests(&self, at: &Path, out: &mut Vec<Path>) {
6429		for (part, child) in &self.children {
6430			if child.interests_below == 0 {
6431				continue;
6432			}
6433			let path = at.rejoin(&Path::new(part).expect("a segment of a path fits"));
6434			match child.interests > 0 {
6435				true => out.push(path),
6436				false => child.collect_interests(&path, out),
6437			}
6438		}
6439	}
6440}
6441
6442impl RouteTable {
6443	fn best_route(
6444		&self,
6445		path: &Path,
6446		horizon: Horizon,
6447		excluded: &HashSet<u64>,
6448		only: impl Fn(&RouteEntry) -> bool,
6449	) -> Option<&RouteEntry> {
6450		// The most specific claims covering the path are the whole answer, serving or not: one
6451		// that refuses the path still shadows what is broader. A claim shown above its own
6452		// prefix is filed deeper than it is, so the claims of one tier may sit at several
6453		// nodes, and they rank against each other wherever each is filed.
6454		let (above, at) = self.split(path);
6455		// How specific each claim is: its node's depth less how far above it the claim was
6456		// shown, as [`RouteEntry::specificity`] counts without walking the prefix.
6457		// Borrowed, so the clones below copy no node list.
6458		let candidates = (above.iter().copied().chain(at).enumerate())
6459			.flat_map(|(depth, node)| {
6460				(node.entries.iter()).map(move |entry| (depth.saturating_sub(usize::from(entry.lane.above)), entry))
6461			})
6462			.filter(|(_, entry)| entry.live())
6463			.filter(|(_, entry)| entry.authorizes(path))
6464			.filter(|(_, entry)| horizon.admits(entry))
6465			.filter(|(_, entry)| !excluded.contains(&entry.id))
6466			.filter(|(_, entry)| only(entry));
6467		let specificity = candidates.clone().map(|(specific, _)| specific).max()?;
6468		let tier = (candidates.filter(|(specific, _)| *specific == specificity)).map(|(_, entry)| entry);
6469		let epochs = Epochs::of(tier.clone());
6470		tier.filter(|entry| entry.serves(path))
6471			.filter(|entry| !epochs.superseded(entry))
6472			.min_by_key(|entry| route_order(path, entry))
6473	}
6474
6475	/// The nodes above `path` and the node at it, as far as the table has them.
6476	/// The entries of those nodes are exactly the routes covering `path`.
6477	fn split(&self, path: &Path) -> (Vec<&RouteNode>, Option<&RouteNode>) {
6478		let mut above = Vec::new();
6479		let mut node = &self.root;
6480		for part in path.parts() {
6481			above.push(node);
6482			match node.children.get(part) {
6483				Some(child) => node = child,
6484				None => return (above, None),
6485			}
6486		}
6487		(above, Some(node))
6488	}
6489
6490	/// The routes covering `path`: those announced at it and at every prefix of it.
6491	fn covering(&self, path: &Path) -> impl Iterator<Item = &RouteEntry> + Clone {
6492		// Walked lazily rather than through [`Self::split`], which allocates: the
6493		// announce sync asks this per cursor presenting a prefix as its root.
6494		let mut parts = path.parts();
6495		let mut next = Some(&self.root);
6496		std::iter::from_fn(move || {
6497			let node = next?;
6498			next = parts.next().and_then(|part| node.children.get(part));
6499			Some(node)
6500		})
6501		.flat_map(|node| node.entries.iter())
6502	}
6503
6504	/// Whether the live route `id` still covers `path`.
6505	fn covers(&self, path: &Path, id: u64) -> bool {
6506		self.covering(path).any(|entry| entry.id == id && entry.live())
6507	}
6508
6509	/// The routes announced exactly at `prefix`.
6510	fn at(&self, prefix: &Path) -> impl Iterator<Item = &RouteEntry> + Clone {
6511		self.root
6512			.find(prefix.parts())
6513			.into_iter()
6514			.flat_map(|node| node.entries.iter())
6515	}
6516
6517	/// The routes announced exactly at `prefix`, for a change in place.
6518	fn at_mut(&mut self, prefix: &Path) -> impl Iterator<Item = &mut RouteEntry> {
6519		let mut node = Some(&mut self.root);
6520		for part in prefix.parts() {
6521			node = node.and_then(|node| node.children.get_mut(part));
6522		}
6523		node.into_iter().flat_map(|node| node.entries.iter_mut())
6524	}
6525
6526	/// Every route in the table, for the teardown.
6527	fn entries(&self) -> impl Iterator<Item = &RouteEntry> {
6528		let mut nodes = Vec::new();
6529		self.root.walk(&mut |node| nodes.push(node));
6530		nodes.into_iter().flat_map(|node| node.entries.iter())
6531	}
6532
6533	/// Add a route at its prefix, creating the nodes down to it.
6534	fn insert(&mut self, entry: RouteEntry) {
6535		let node = self.root.reach(entry.prefix.parts(), Below::NONE);
6536		node.entries.push(entry);
6537	}
6538
6539	/// The route `id` announced at `prefix`.
6540	fn entry(&self, prefix: &Path, id: u64) -> Option<&RouteEntry> {
6541		let mut node = &self.root;
6542		for part in prefix.parts() {
6543			node = node.children.get(part)?;
6544		}
6545		node.entries.iter().find(|entry| entry.id == id)
6546	}
6547
6548	/// The route `id` announced at `prefix`, for a re-price in place.
6549	fn entry_mut(&mut self, prefix: &Path, id: u64) -> Option<&mut RouteEntry> {
6550		let mut node = &mut self.root;
6551		for part in prefix.parts() {
6552			node = node.children.get_mut(part)?;
6553		}
6554		node.entries.iter_mut().find(|entry| entry.id == id)
6555	}
6556
6557	/// Take the route `id` out of `prefix`, pruning the nodes it leaves empty.
6558	fn remove(&mut self, prefix: &Path, id: u64) -> Option<RouteEntry> {
6559		self.root
6560			.edit(prefix.parts(), Below::NONE, |node| {
6561				let index = node.entries.iter().position(|entry| entry.id == id)?;
6562				Some(node.entries.swap_remove(index))
6563			})
6564			.flatten()
6565	}
6566
6567	/// Hang a cursor at one of its heads, counting it down the walk.
6568	fn add_cursor(&mut self, head: &Path, id: ConsumerId) {
6569		self.root.reach(head.parts(), Below::CURSOR).cursors.push(id);
6570	}
6571
6572	/// Take a cursor off one of its heads, pruning the nodes it leaves empty. Only
6573	/// ever called for a head the cursor was added at, or the counts drift.
6574	fn remove_cursor(&mut self, head: &Path, id: ConsumerId) {
6575		self.root.edit(head.parts(), Below::CURSOR, |node| {
6576			node.cursors.retain(|cursor| *cursor != id)
6577		});
6578	}
6579
6580	/// Register a watch on the routes covering `path`; see [`Watch`].
6581	fn add_watch(&mut self, path: &Path, id: u64) -> kio::Consumer<Watched> {
6582		let producer = kio::Producer::<Watched>::default();
6583		let consumer = producer.consume();
6584		self.root
6585			.reach(path.parts(), Below::WATCH)
6586			.watches
6587			.push((id, WatchProducer::Changes(producer)));
6588		consumer
6589	}
6590
6591	/// Take a watch off its path, pruning the nodes it leaves empty. Only ever
6592	/// called for a path the watch was added at, or the counts drift.
6593	fn remove_watch(&mut self, path: &Path, id: u64) {
6594		self.root.edit(path.parts(), Below::WATCH, |node| {
6595			node.watches.retain(|(watch, _)| *watch != id)
6596		});
6597	}
6598
6599	/// Whether an interest strictly above `path` covers it.
6600	fn interest_above(&self, path: &Path) -> bool {
6601		let mut node = &self.root;
6602		for part in path.parts() {
6603			if node.interests > 0 {
6604				return true;
6605			}
6606			match node.children.get(part) {
6607				Some(child) => node = child,
6608				None => return false,
6609			}
6610		}
6611		false
6612	}
6613
6614	/// The interests at `path` or, failing that, the broadest beneath it: what a
6615	/// session joining now asks about under `path`.
6616	fn interests_from(&self, path: &Path) -> Vec<Path> {
6617		let Some(node) = self.root.find(path.parts()) else {
6618			return Vec::new();
6619		};
6620		if node.interests > 0 {
6621			return vec![path.clone()];
6622		}
6623		let mut out = Vec::new();
6624		node.collect_interests(path, &mut out);
6625		out
6626	}
6627
6628	/// Wake the watches of every path a route at `prefix` covers.
6629	fn poke_below(&self, prefix: &Path) {
6630		if let (_, Some(node)) = self.split(prefix) {
6631			node.poke_below(self);
6632		}
6633	}
6634
6635	/// Wake every watch: the origin is tearing down.
6636	fn poke_all(&self) {
6637		self.root.walk(&mut |node| node.poke(None));
6638	}
6639
6640	/// The cursors a route at `prefix` can present on: a cursor sees a route
6641	/// only when one of its heads is on the walk down to the prefix or somewhere
6642	/// beneath it, so those are the only cursors visited.
6643	fn cursors_touching(&self, prefix: &Path) -> Vec<ConsumerId> {
6644		let (above, at) = self.split(prefix);
6645		let mut cursors: Vec<ConsumerId> = above.iter().flat_map(|node| node.cursors.iter().copied()).collect();
6646		if let Some(node) = at {
6647			node.collect_cursors(&mut cursors);
6648		}
6649		// A cursor with several heads can be reached more than once.
6650		cursors.sort_unstable();
6651		cursors.dedup();
6652		cursors
6653	}
6654}
6655
6656/// The origin's shared state: the route table, the announce cursors observing
6657/// it, and the remotely-served fronts.
6658///
6659/// Carried in a [`kio::Shared`], so producers, consumers, and handlers work
6660/// under one lock. Broadcasts published here are route table entries like the
6661/// routes announced from elsewhere; this holds everything that serves a path.
6662struct OriginState {
6663	// See [`Config::update_hold`]. No `Default`: every origin takes it from its
6664	// config, so no path silently disables the hold.
6665	update_hold: Duration,
6666
6667	// The announced routes, keyed by prefix. The table holds one entry per live
6668	// advertisement, not one per broadcast consumer.
6669	routes: RouteTable,
6670	// RouteInfo ids.
6671	next_route: u64,
6672	next_watch: u64,
6673	next_snapshot: u64,
6674
6675	// The registered announce cursors, each with its own coalescing buffer. Each
6676	// also hangs in the route table at its heads, which is how an announcement
6677	// finds the cursors it can present on.
6678	cursors: HashMap<ConsumerId, TableCursor>,
6679
6680	// The remotely-served fronts; see [`FrontKey`]. Each is a broadcast whose
6681	// watcher task materializes it from the best covering route and switches it
6682	// between routes, so a route change is invisible to subscribers. Weak, so a
6683	// front dies with its watcher and a later request re-creates it.
6684	fronts: WeakCache<FrontKey, RemoteFront>,
6685
6686	// Peers that withdrew a prefix while routes there still passed through them,
6687	// which are stale. See [`Claim::withdrawn`].
6688	withdrawn: HashMap<Path, HashSet<Hop>>,
6689
6690	// Set when the origin's driver dropped: new requests fail with `Closed`
6691	// immediately and handlers observe the end instead of parking forever.
6692	closed: bool,
6693
6694	// The sessions asking their peer about only what readers here want
6695	// discovered; see [`Interests`].
6696	listeners: Vec<Listener>,
6697	next_listener: u64,
6698
6699	// The route layer node this origin's lite-07 sessions share, and the feeder the
6700	// driver owns; see [`Consumer::route_node`]. Weak, since the feeder's cursors hold
6701	// this state.
6702	route_node: Option<(crate::route::Node, std::sync::Weak<std::sync::Mutex<OwnClaims>>)>,
6703}
6704
6705impl OriginState {
6706	fn new(update_hold: Duration) -> Self {
6707		Self {
6708			update_hold,
6709			routes: RouteTable::default(),
6710			next_route: 0,
6711			next_watch: 0,
6712			next_snapshot: 0,
6713			cursors: HashMap::new(),
6714			fronts: WeakCache::default(),
6715			withdrawn: HashMap::new(),
6716			closed: false,
6717			listeners: Vec::new(),
6718			next_listener: 0,
6719			route_node: None,
6720		}
6721	}
6722
6723	/// Whether a peer in `hops` withdrew `prefix`.
6724	fn withdrawn_through(&self, prefix: &Path, hops: &Hops) -> bool {
6725		if self.withdrawn.is_empty() {
6726			return false;
6727		}
6728		self.withdrawn
6729			.get(prefix)
6730			.is_some_and(|peers| hops.iter().any(|hop| peers.contains(hop)))
6731	}
6732
6733	/// Retire every other copy at its prefix of the claim `entry` follows: the same
6734	/// forwarding node, identity and showing ([`Lane::lifecycle`]), at any epoch, since a
6735	/// copy whose session has yet to take a newer epoch would otherwise be left as the
6736	/// fallback. See [`Claim::retire`].
6737	fn retire_copies(&mut self, entry: &RouteEntry) {
6738		let Some(node) = entry.node else {
6739			return;
6740		};
6741		for other in self.routes.at_mut(&entry.prefix) {
6742			if other.node == Some(node)
6743				&& other.identity == entry.identity
6744				&& other.lane.lifecycle == entry.lane.lifecycle
6745			{
6746				other.retired = true;
6747			}
6748		}
6749	}
6750
6751	/// Recompute which entries at `prefix` are stale after its withdrawals changed.
6752	fn restale(&mut self, prefix: &Path) {
6753		let peers = self.withdrawn.get(prefix);
6754		let mut changed = false;
6755		for entry in self.routes.at_mut(prefix) {
6756			let stale = peers.is_some_and(|peers| entry.hops.iter().any(|hop| peers.contains(hop)));
6757			if entry.stale != stale {
6758				entry.stale = stale;
6759				changed = true;
6760				// Back in contention, it ranks as newly arrived.
6761				if entry.live() {
6762					entry.since = self.next_route;
6763					self.next_route += 1;
6764				}
6765			}
6766		}
6767		if changed {
6768			self.sync_route(prefix, Gone::End);
6769		}
6770	}
6771
6772	/// A route at `prefix` was announced or restarted with `hops`. When its sender,
6773	/// the chain's last hop, had withdrawn the prefix, routes through it are live
6774	/// once more.
6775	fn reannounced(&mut self, prefix: &Path, hops: &Hops) {
6776		if let Some(sender) = hops.iter().last()
6777			&& self.withdrawn.get_mut(prefix).is_some_and(|peers| peers.remove(sender))
6778		{
6779			self.restale(prefix);
6780			self.prune_withdrawn(prefix);
6781		}
6782	}
6783
6784	/// Forget the withdrawals at `prefix` that no longer hide a route.
6785	fn prune_withdrawn(&mut self, prefix: &Path) {
6786		if self.withdrawn.is_empty() {
6787			return;
6788		}
6789		let Some(peers) = self.withdrawn.get_mut(prefix) else {
6790			return;
6791		};
6792		if peers.len() <= 1 {
6793			// The common case is already linear and needs no temporary allocation.
6794			peers.retain(|peer| self.routes.at(prefix).any(|entry| entry.hops.contains(peer)));
6795		} else {
6796			let mut unreferenced = peers.clone();
6797			for entry in self.routes.at(prefix) {
6798				if unreferenced.is_empty() {
6799					break;
6800				}
6801				for hop in entry.hops.iter() {
6802					unreferenced.remove(hop);
6803				}
6804			}
6805			peers.retain(|peer| !unreferenced.contains(peer));
6806		}
6807		if peers.is_empty() {
6808			self.withdrawn.remove(prefix);
6809		}
6810	}
6811
6812	/// Re-deliver the best route at every presented prefix `prefix` maps to, on
6813	/// every cursor it can present on. Called after an entry covering `prefix`
6814	/// was added, updated, or removed.
6815	fn sync_route(&mut self, prefix: &Path, gone: Gone) {
6816		// Split borrows: the recompute reads `routes` while mutating a cursor.
6817		let routes = &self.routes;
6818		let mut candidates = None;
6819		for id in routes.cursors_touching(prefix) {
6820			let Some(cursor) = self.cursors.get_mut(&id) else {
6821				continue;
6822			};
6823			if let Some(presented) = cursor.presented(prefix) {
6824				if presented.is_empty() {
6825					// A cursor root can collapse several covering prefixes into one.
6826					Self::sync_cursor(routes, cursor, &presented, gone);
6827				} else {
6828					// Every non-root presentation refers to this exact prefix. Rank
6829					// its routes once, then take each cursor's first eligible visible entry.
6830					let candidates = candidates.get_or_insert_with(|| {
6831						// All of one prefix, so the most specific claim is the least above it.
6832						// Ranked as [`TableCursor::best`] ranks a replayed row.
6833						let mut entries: Vec<_> = routes
6834							.at(prefix)
6835							.map(|entry| {
6836								(
6837									(entry.lane.above, !entry.serves(prefix), route_order(prefix, entry)),
6838									entry,
6839								)
6840							})
6841							.collect();
6842						entries.sort_unstable_by_key(|(order, _)| *order);
6843						entries
6844					});
6845					let visible = candidates
6846						.iter()
6847						.map(|(_, entry)| *entry)
6848						.filter(|entry| cursor.visible(entry));
6849					let epochs = Epochs::of(visible.clone());
6850					let best = visible.clone().find(|entry| !epochs.superseded(entry));
6851					cursor.update(&presented, best, gone);
6852				}
6853			}
6854		}
6855		// The fronts and requesters under the prefix re-select from the table.
6856		routes.poke_below(prefix);
6857	}
6858
6859	/// Start a [`Snapshot`] at the absolute `prefix` for the routes arriving on `link`.
6860	fn snapshot(&mut self, shared: &SendCell<kio::Shared<OriginState>>, prefix: Path, link: Link) -> Snapshot {
6861		// A prefix past the depth limit can carry no route, so nothing waits on it.
6862		if prefix.depth() > Path::MAX_PARTS || self.closed {
6863			return Snapshot::landed();
6864		}
6865		let id = self.next_snapshot;
6866		self.next_snapshot += 1;
6867		self.add_snapshot(
6868			&prefix,
6869			SnapshotEntry {
6870				id,
6871				link,
6872				prefix: prefix.clone(),
6873			},
6874		);
6875		Snapshot {
6876			shared: Some(shared.clone()),
6877			prefix,
6878			id,
6879		}
6880	}
6881
6882	/// Count the absolute `head` as a prefix readers want discovered, telling the
6883	/// listeners when that changes the covering set.
6884	fn add_interest(&mut self, shared: &SendCell<kio::Shared<OriginState>>, head: &Path) {
6885		let node = self.routes.root.reach(head.parts(), Below::INTEREST);
6886		node.interests += 1;
6887		if node.interests > 1 || self.listeners.is_empty() {
6888			return;
6889		}
6890		let mut narrower = Vec::new();
6891		node.collect_interests(head, &mut narrower);
6892		if self.routes.interest_above(head) {
6893			return;
6894		}
6895		// Asked for before the narrower ones it covers are let go, so nothing retracts.
6896		self.emit(shared, head, true);
6897		for prefix in narrower {
6898			self.emit(shared, &prefix, false);
6899		}
6900	}
6901
6902	/// Undo one [`Self::add_interest`] of `head`.
6903	fn remove_interest(&mut self, shared: &SendCell<kio::Shared<OriginState>>, head: &Path) {
6904		let listening = !self.listeners.is_empty();
6905		let narrower = self.routes.root.edit(head.parts(), Below::INTEREST, |node| {
6906			node.interests -= 1;
6907			(node.interests == 0 && listening).then(|| {
6908				let mut narrower = Vec::new();
6909				node.collect_interests(head, &mut narrower);
6910				narrower
6911			})
6912		});
6913		let Some(Some(narrower)) = narrower else {
6914			return;
6915		};
6916		if self.routes.interest_above(head) {
6917			return;
6918		}
6919		for prefix in narrower {
6920			self.emit(shared, &prefix, true);
6921		}
6922		self.emit(shared, head, false);
6923	}
6924
6925	/// Tell every listener the covering set of interests gained or lost the
6926	/// absolute `prefix`.
6927	fn emit(&mut self, shared: &SendCell<kio::Shared<OriginState>>, prefix: &Path, wanted: bool) {
6928		let mut changes = Vec::new();
6929		for listener in &self.listeners {
6930			for relative in listener.asks(prefix) {
6931				// A head too long to root covers no path, so nothing reads it.
6932				let Ok(absolute) = listener.root.join(&relative) else {
6933					continue;
6934				};
6935				changes.push((listener.queue.clone(), absolute, relative, listener.link));
6936			}
6937		}
6938		for (queue, absolute, prefix, link) in changes {
6939			let snapshot = wanted.then(|| self.snapshot(shared, absolute, link));
6940			// A listener still registered has an open queue, except after the teardown,
6941			// whose snapshots are landed: dropping a refused one never takes this lock.
6942			let _ = queue.try_push(InterestChange {
6943				prefix,
6944				wanted,
6945				snapshot,
6946			});
6947		}
6948	}
6949
6950	/// Register a [`Watch`] on the routes covering `path`.
6951	fn watch(&mut self, shared: &SendCell<kio::Shared<OriginState>>, path: &Path) -> Watch {
6952		let id = self.next_watch;
6953		self.next_watch += 1;
6954		let signal = self.routes.add_watch(path, id);
6955		Watch {
6956			shared: shared.clone(),
6957			path: path.clone(),
6958			id,
6959			signal,
6960		}
6961	}
6962
6963	/// Recompute the best visible route presenting at `presented` (relative) for
6964	/// one cursor and deliver the change, if any.
6965	fn sync_cursor(routes: &RouteTable, cursor: &mut TableCursor, presented: &Path, gone: Gone) {
6966		// The entries presenting here are the ones announced at the absolute
6967		// prefix, or, for the cursor's own root, at the root and every prefix
6968		// above it (all of which present as the empty path). Among them, the most
6969		// specific claim wins outright, its tier ranked wherever each claim is filed,
6970		// so the metadata a cursor advertises matches what a request through it resolves.
6971		let best = match presented.is_empty() {
6972			true if cursor.lookup => {
6973				let visible = |entry: &RouteEntry| cursor.visible(entry);
6974				routes.best_route(&cursor.root, cursor.horizon, &HashSet::new(), visible)
6975			}
6976			true => cursor.best(&cursor.root, routes.covering(&cursor.root)),
6977			false => {
6978				let absolute = cursor.root.rejoin(presented);
6979				cursor.best(&absolute, routes.at(&absolute))
6980			}
6981		};
6982
6983		cursor.update(presented, best, gone);
6984	}
6985
6986	/// Register a cursor and replay the current best route per presented prefix.
6987	fn register_cursor(
6988		&mut self,
6989		shared: &SendCell<kio::Shared<OriginState>>,
6990		id: ConsumerId,
6991		mut cursor: TableCursor,
6992	) {
6993		// First, so the snapshots a session takes for these interests hold the cursor
6994		// unsynced from the start, through the scan below.
6995		if cursor.interested {
6996			for head in &cursor.heads {
6997				self.add_interest(shared, head);
6998			}
6999		}
7000
7001		// The routes a cursor can see sit on the walk down to one of its heads or
7002		// somewhere beneath it, so only those subtrees are replayed.
7003		let mut presented: BTreeSet<Path> = BTreeSet::new();
7004		for head in &cursor.heads {
7005			let (above, at) = self.routes.split(head);
7006			let mut nodes = above;
7007			if let Some(node) = at {
7008				node.walk(&mut |node| nodes.push(node));
7009			}
7010			for entry in nodes.into_iter().flat_map(|node| node.entries.iter()) {
7011				if let Some(p) = cursor.presented(&entry.prefix) {
7012					presented.insert(p);
7013				}
7014			}
7015		}
7016		for p in &presented {
7017			Self::sync_cursor(&self.routes, &mut cursor, p, Gone::End);
7018		}
7019		for head in &cursor.heads {
7020			self.routes.add_cursor(head, id);
7021		}
7022
7023		// The snapshots in flight it can see sit where its routes would, each counted once.
7024		let mut snapshots = Vec::new();
7025		for head in &cursor.heads {
7026			let (above, at) = self.routes.split(head);
7027			snapshots.extend(above.into_iter().flat_map(|node| node.snapshots.iter()));
7028			if let Some(node) = at {
7029				node.collect_snapshots(&mut snapshots);
7030			}
7031		}
7032		snapshots.retain(|snapshot| cursor.awaits(snapshot));
7033		snapshots.sort_unstable_by_key(|snapshot| snapshot.id);
7034		snapshots.dedup_by_key(|snapshot| snapshot.id);
7035		if !snapshots.is_empty() {
7036			cursor
7037				.state
7038				.read()
7039				.waiting
7040				.fetch_add(snapshots.len(), Ordering::Relaxed);
7041		}
7042
7043		self.cursors.insert(id, cursor);
7044	}
7045
7046	/// Hold every cursor `snapshot` can present on unsynced until it lands.
7047	fn add_snapshot(&mut self, prefix: &Path, snapshot: SnapshotEntry) {
7048		for id in self.routes.cursors_touching(prefix) {
7049			if let Some(cursor) = self.cursors.get(&id)
7050				&& cursor.awaits(&snapshot)
7051			{
7052				cursor.state.read().waiting.fetch_add(1, Ordering::Relaxed);
7053			}
7054		}
7055		self.routes
7056			.root
7057			.reach(prefix.parts(), Below::SNAPSHOT)
7058			.snapshots
7059			.push(snapshot);
7060	}
7061
7062	/// The snapshot `id` at `prefix` landed: release the cursors it held.
7063	fn remove_snapshot(&mut self, prefix: &Path, id: u64) {
7064		let removed = self.routes.root.edit(prefix.parts(), Below::SNAPSHOT, |node| {
7065			let index = node.snapshots.iter().position(|snapshot| snapshot.id == id)?;
7066			Some(node.snapshots.swap_remove(index))
7067		});
7068		let Some(Some(snapshot)) = removed else {
7069			return;
7070		};
7071		for id in self.routes.cursors_touching(prefix) {
7072			let Some(cursor) = self.cursors.get(&id).filter(|cursor| cursor.awaits(&snapshot)) else {
7073				continue;
7074			};
7075			// Only the last landing changes what a synced waiter sees, so only it takes the
7076			// write guard and wakes. It zeroes the count and owes the queue in one critical
7077			// section, so no poll sees nothing waiting before the owed set is in. The table
7078			// lock keeps the count from moving between the two guards.
7079			{
7080				let state = cursor.state.read();
7081				if state.waiting.load(Ordering::Relaxed) > 1 {
7082					state.waiting.fetch_sub(1, Ordering::Relaxed);
7083					continue;
7084				}
7085			}
7086			match cursor.state.write() {
7087				Ok(mut state) => {
7088					state.waiting.store(0, Ordering::Relaxed);
7089					state.owe();
7090				}
7091				Err(state) => state.waiting.store(0, Ordering::Relaxed),
7092			}
7093		}
7094	}
7095
7096	/// The best served route covering `path` (absolute) for a requester seeing
7097	/// `horizon`, skipping the `excluded` entry ids.
7098	///
7099	/// The most specific claim wins outright, so a narrow advertise-only
7100	/// announcement shadows a broad served one: requests under it resolve
7101	/// unroutable instead of being routed around it. A claim's specificity is its own
7102	/// prefix, wherever it is filed (see [`RouteEntry::specificity`]), and the claims of
7103	/// the winning tier rank together: the best served one by [`route_order`].
7104	///
7105	/// Only announced routes are candidates: an unannounced broadcast serves
7106	/// nobody, and does not shadow anything either. Routes `excluded` for the
7107	/// front's path are skipped. The hash tie-break is keyed on `path`, so
7108	/// equal-cost advertisers of one prefix share its paths. A broadcast
7109	/// published on this origin competes on cost like any other route and wins a
7110	/// tie. Only entries passing `only` are candidates at all, so the rest neither
7111	/// win nor shadow.
7112	fn best_route(
7113		&self,
7114		path: &Path,
7115		horizon: Horizon,
7116		excluded: &HashSet<u64>,
7117		only: impl Fn(&RouteEntry) -> bool,
7118	) -> Option<&RouteEntry> {
7119		self.routes.best_route(path, horizon, excluded, only)
7120	}
7121
7122	/// The prefix route `server` answers through for `path`, when it lends its identity to
7123	/// the job routes answering its requests and its scope authorizes `path`.
7124	fn lender(&self, path: &Path, server: &kio::Shared<ServeState>) -> Option<Lent> {
7125		self.routes
7126			.covering(path)
7127			.find(|entry| {
7128				entry.lends && entry.live() && entry.server.as_ref().is_some_and(|other| other.is_clone(server))
7129			})
7130			.filter(|entry| entry.authorizes(path))
7131			.map(|entry| Lent {
7132				prefix: entry.prefix.clone(),
7133				id: entry.id,
7134				identity: entry.identity.clone(),
7135				epoch: entry.epoch,
7136			})
7137	}
7138
7139	/// A job's route carrying `spent`, the identity it took from the prefix route `id` at
7140	/// `prefix`, stopped serving it: that prefix route moves to a fresh identity.
7141	///
7142	/// One identity is one stream at each path, and the job's keys end with it. Were the
7143	/// prefix route to keep the identity, its next answer for the path, a restarted job,
7144	/// would splice a new key space into everything that holds the old one, and nothing
7145	/// short of remembering every path it ever answered could tell. Under the table's lock,
7146	/// with the job's retraction, so no request resolves the path through the old identity
7147	/// in between. A prefix route already past `spent` has nothing to do.
7148	///
7149	/// A claim filed at several prefixes is one claim, so its route at each moves to the
7150	/// same fresh identity.
7151	fn advance(&mut self, prefix: &Path, id: u64, spent: &Identity) {
7152		let Some(entry) = self.routes.entry(prefix, id) else {
7153			return;
7154		};
7155		let Some(server) = entry.server.clone().filter(|_| entry.identity == *spent) else {
7156			return;
7157		};
7158		let filed = entry.filed.clone();
7159		let identity = Identity::random();
7160		for at in filed.iter() {
7161			let mut moved = false;
7162			for entry in self.routes.at_mut(at) {
7163				let same = entry.lends
7164					&& entry.identity == *spent
7165					&& (entry.server.as_ref()).is_some_and(|other| other.is_clone(&server));
7166				if same {
7167					entry.identity = identity.clone();
7168					entry.epoch = 0;
7169					moved = true;
7170				}
7171			}
7172			if moved {
7173				self.sync_route(at, Gone::End);
7174			}
7175		}
7176	}
7177
7178	/// Whether `identity` still serves `path` as a request would resolve it now: the winning
7179	/// route carries it, or, for a request `pinned` to it, a route of its own remains. The
7180	/// rule [`Consumer::lookup`] resolves by.
7181	fn still_serves(&self, path: &Path, horizon: Horizon, identity: &Identity, pinned: bool) -> bool {
7182		let Some(best) = self.best_route(path, horizon, &HashSet::new(), |_| true) else {
7183			return false;
7184		};
7185		if best.identity == *identity {
7186			return true;
7187		}
7188		pinned
7189			&& self
7190				.best_route(path, horizon, &HashSet::new(), |entry| entry.identity == *identity)
7191				.is_some()
7192	}
7193}
7194
7195/// A prefix route lending its identity, as [`OriginState::lender`] found it.
7196struct Lent {
7197	prefix: Path,
7198	id: u64,
7199	identity: Identity,
7200	epoch: u64,
7201}
7202
7203/// One-shot result of a dynamic broadcast request.
7204///
7205/// Stays `None` until a handler [`serve`](Request::serve)s (yielding the served
7206/// broadcast) or [`reject`](Request::reject)s (yielding an error). The producer is
7207/// dropped right after writing, closing the channel; kio checks the value before the closed
7208/// flag, so an awaiting requester still observes the final result.
7209#[derive(Default)]
7210struct PendingBroadcast {
7211	resolved: Option<Result<broadcast::Consumer, Error>>,
7212}
7213
7214/// A front's verdict, which its requesters wait on: the identity it resolved, or the
7215/// error that ended it unresolved. A request joins the front only while that identity
7216/// still wins at the epoch the front serves, or before then, while the identity it
7217/// selected does. Each requester holds the front's broadcast from the moment it joins, so
7218/// this carries no handle that would keep the front held.
7219struct PendingFront {
7220	resolved: Option<Result<Identity, Error>>,
7221	/// The epoch of the route the front serves from once resolved, and of the one it selected
7222	/// until then. A front still serving or resolving a superseded epoch keeps its readers while
7223	/// it moves to the newer one, but admits nobody: a request selecting the newer epoch must
7224	/// never resolve through the older one, whose answer may already be on its way.
7225	epoch: u64,
7226	/// The identity the front resolves on unless the table moves first: the winner it
7227	/// was minted for, then each one it selects. Written under the table's lock, so a
7228	/// request never joins a front that picked an identity the request saw beaten.
7229	selected: Identity,
7230	/// The selected serving handler refused, rather than the route disappearing.
7231	refused: bool,
7232}
7233
7234impl Claim {
7235	/// Stop keeping the origin's driver running: what a closed session left behind is no
7236	/// owner, and goes with the origin.
7237	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
7238	pub(crate) fn disown(&self) {
7239		let keepalive = self
7240			.state
7241			.keepalive
7242			.lock()
7243			.unwrap_or_else(|err| err.into_inner())
7244			.take();
7245		drop(keepalive);
7246	}
7247
7248	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
7249	pub(super) fn request_validity(&self, path: &Path) -> Option<Selection> {
7250		let shared = &self.state.announcement.shared;
7251		let server = &self.server;
7252		let mut table = shared.lock();
7253		if table.closed {
7254			return None;
7255		}
7256		let entry = table.best_route(path, Horizon::default(), &HashSet::new(), |entry| {
7257			entry.server.as_ref().is_some_and(|entry| entry.is_clone(server))
7258		})?;
7259		let via = entry.via;
7260		let identity = entry.identity.clone();
7261		let active = table
7262			.best_route(path, Horizon::default(), &HashSet::new(), |entry| entry.via == via)
7263			.is_some_and(|entry| entry.identity == identity);
7264		let producer = kio::Producer::new(Selected {
7265			path: path.clone(),
7266			via,
7267			identity,
7268			current: active.then(kio::Producer::default),
7269			answering: active.then(kio::Producer::default),
7270		});
7271		let signal = producer.consume();
7272		let id = table.next_watch;
7273		table.next_watch += 1;
7274		table
7275			.routes
7276			.root
7277			.reach(path.parts(), Below::WATCH)
7278			.watches
7279			.push((id, WatchProducer::Selection(producer)));
7280		Some(Selection {
7281			shared: shared.clone(),
7282			path: path.clone(),
7283			id,
7284			signal,
7285		})
7286	}
7287}
7288
7289impl ServeState {
7290	/// Resolve a pending request: cache an accepted broadcast for repeat
7291	/// requests, remove the queue entry, and wake the requesters.
7292	///
7293	/// Resolved while the queue's lock is held, so this linearizes with the
7294	/// teardown: either the teardown ran first (the `closed` check returns, its
7295	/// rejection stands) or this write lands first and the teardown finds the
7296	/// entry already gone. The queue lock is released before the channel guard
7297	/// drops, so the requester wakes outside it: an inline executor re-entering
7298	/// `request` from the wake must not find the non-reentrant lock
7299	/// still held.
7300	fn resolve(
7301		shared: &kio::Shared<Self>,
7302		path: &Path,
7303		producer: &kio::Producer<PendingBroadcast>,
7304		result: Result<broadcast::Consumer, Error>,
7305	) -> bool {
7306		let mut state = shared.lock();
7307		let Some(resolved) = state.answer(path, producer, result) else {
7308			return false;
7309		};
7310		if let Ok(mut pending) = producer.write() {
7311			pending.resolved.get_or_insert(resolved);
7312			drop(state);
7313		}
7314		true
7315	}
7316
7317	/// Take the request off the queue and cache an accepted broadcast, returning what
7318	/// its requesters resolve with, or `None` once it is no longer ours to answer.
7319	fn answer(
7320		&mut self,
7321		path: &Path,
7322		producer: &kio::Producer<PendingBroadcast>,
7323		result: Result<broadcast::Consumer, Error>,
7324	) -> Option<Result<broadcast::Consumer, Error>> {
7325		self.take(path, producer)?;
7326		let state = self;
7327		let resolved = match result {
7328			Ok(broadcast) => {
7329				// If a live broadcast was already served for this path while we were
7330				// fetching upstream, dedup onto it and drop ours rather than replace
7331				// a good entry with a duplicate subscription. One its session retired
7332				// as this minted is closed, so ours takes the slot after all.
7333				match state
7334					.served
7335					.insert(path.clone(), broadcast.weak())
7336					.map(|weak| weak.consume())
7337				{
7338					Some(existing) if !existing.is_closed() => Ok(existing),
7339					Some(_) => {
7340						state.served.insert(path.clone(), broadcast.weak());
7341						Ok(broadcast)
7342					}
7343					None => Ok(broadcast),
7344				}
7345			}
7346			Err(err) => Err(err),
7347		};
7348		Some(resolved)
7349	}
7350
7351	/// Admit an answer only while its request still belongs to this route identity.
7352	fn take(&mut self, path: &Path, producer: &kio::Producer<PendingBroadcast>) -> Option<()> {
7353		if self.closed {
7354			return None;
7355		}
7356		self.requests.remove_if(path, |p| p.is_clone(producer))?;
7357		Some(())
7358	}
7359
7360	/// Release every request, queued or handed to a handler, and forget the answers served,
7361	/// because the route now names another identity. Returns the released
7362	/// requests for the caller to refuse once it holds no lock, since the refusal wakes
7363	/// their fronts. Those ask again under the new identity; the handler's answer to a
7364	/// released request is dropped.
7365	#[must_use = "the released requests must be refused"]
7366	fn renew(&mut self) -> Vec<kio::Producer<PendingBroadcast>> {
7367		// Counted before any release wakes a front, which reads the count without the lock.
7368		self.renewals.fetch_add(1, Ordering::Release);
7369		self.served = WeakCache::default();
7370		self.requests.drain_all()
7371	}
7372
7373	/// Drop the still-pending entry, if it is still ours.
7374	fn forget(shared: &kio::Shared<Self>, path: &Path, producer: &kio::Producer<PendingBroadcast>) {
7375		shared.lock().requests.remove_if(path, |p| p.is_clone(producer));
7376	}
7377
7378	/// Queue the still-pending entry again for the next handler, its requesters still waiting,
7379	/// or drop it as [`Self::forget`] does when no handler is left to take it.
7380	fn requeue(shared: &kio::Shared<Self>, path: &Path, producer: &kio::Producer<PendingBroadcast>) {
7381		let mut state = shared.lock();
7382		if !state.requests.get(path).is_some_and(|p| p.is_clone(producer)) {
7383			return;
7384		}
7385		if !state.requests.requeue(path.clone()) {
7386			state.requests.remove_if(path, |p| p.is_clone(producer));
7387		}
7388	}
7389}
7390
7391/// A pending request for a broadcast to be served on demand.
7392///
7393/// Yielded by [`Claim::poll_requested`]. The requester is awaiting inside
7394/// [`Consumer::request`]. Answer it one of three ways: [`serve`](Self::serve) a
7395/// broadcast already held, under the prefix route's identity; create the path's own
7396/// exact route with [`route`](Self::route), which continues the identity the prefix route
7397/// lends until it ends; or
7398/// [`reject`](Self::reject) it with an error. Dropping it rejects it.
7399///
7400/// Serve a held broadcast without announcing an exact route:
7401///
7402/// ```
7403/// fn answer(request: moq_net::origin::Request, broadcast: moq_net::broadcast::Consumer) {
7404///     request.serve(broadcast);
7405/// }
7406/// ```
7407pub struct Request {
7408	// Absolute path that was requested.
7409	path: Path,
7410
7411	// Result channel back to the awaiting requester(s). Writing `resolved` and dropping
7412	// this wakes them with the outcome.
7413	producer: kio::Producer<PendingBroadcast>,
7414
7415	// The queue this request came from, so `serve` can cache the served
7416	// broadcast for repeat requests.
7417	home: kio::Shared<ServeState>,
7418
7419	// Applications can create routes in this origin; a session-forwarded request
7420	// can only serve its peer's already-routed broadcast.
7421	publisher: Option<Producer>,
7422
7423	// Dropped back onto its queue rather than refused: its job read an identity the prefix
7424	// route has since moved past, so the handler answers it again.
7425	requeue: bool,
7426}
7427
7428impl Request {
7429	/// The absolute path that was requested.
7430	pub fn path(&self) -> &Path {
7431		&self.path
7432	}
7433
7434	/// Answer with the path's own exact route, owning a new broadcast.
7435	///
7436	/// Unless `options` names an identity, the route takes the one its prefix route lends
7437	/// when it first announces or [`Route::identity`] first reads it, so whatever resolved the path through the prefix route
7438	/// continues on this answer; a prefix route that lends nothing has the route mint its
7439	/// own. Ending the route withdraws only this path, and moves a prefix route that lent
7440	/// its identity to a fresh one, so a job that ends and restarts beneath the same prefix
7441	/// is a new stream for its restarted keys. The prefix route keeps answering later
7442	/// requests. Created visible, the route announces now and answers the requesters
7443	/// waiting on its path. Created [`RouteOptions::hidden`], they wait until
7444	/// [`Route::announce`], so the job can fill its catalog first; dropping the route
7445	/// before then refuses them.
7446	///
7447	/// Fails with [`Error::Unroutable`] on a request a session forwarded, which can only
7448	/// [`serve`](Self::serve) its peer's broadcast, and, announcing nothing, once the
7449	/// request was released or its prefix route retracted. Otherwise it fails as
7450	/// [`Producer::route`] does.
7451	pub fn route(self, options: RouteOptions) -> Result<Route, Error> {
7452		let publisher = self.publisher.clone().ok_or(Error::Unroutable)?;
7453		let path = self.path.clone();
7454		publisher.exact(path, options, Some(self))
7455	}
7456
7457	/// Serve a held broadcast under this prefix route without announcing an exact route.
7458	///
7459	/// The answer belongs to the prefix route's identity at this path: every answer for
7460	/// that path must continue the same key space and bytes. Start a new prefix
7461	/// route to serve different content there. For a job that may restart independently,
7462	/// use [`Self::route`]: its end moves the prefix route to another identity.
7463	pub fn serve(self, broadcast: impl Consume<broadcast::Consumer>) {
7464		let broadcast = broadcast.consume();
7465		let _ = ServeState::resolve(&self.home, &self.path, &self.producer, Ok(broadcast));
7466		// `self.producer` drops here, closing the channel; the value is still observable.
7467	}
7468
7469	/// Reject the request, resolving every awaiting requester with `err`.
7470	pub fn reject(self, err: Error) {
7471		let _ = ServeState::resolve(&self.home, &self.path, &self.producer, Err(err));
7472	}
7473
7474	/// Ready once no requester waits on the answer any more: each left, or the relay
7475	/// moved it to another route. Final: a later requester gets a new request.
7476	#[cfg_attr(feature = "async", kio::wrapper)]
7477	pub fn poll_unwanted(&self, waiter: &kio::Waiter) -> Poll<()> {
7478		// A front adds a requester only through `kio::Producer::join`, which never takes
7479		// the count from zero, so once unwanted it stays so.
7480		self.producer.poll_wanted_changed(waiter, true).map(|_| ())
7481	}
7482}
7483
7484impl Drop for Request {
7485	fn drop(&mut self) {
7486		// Requeued in the same lock as the removal it replaces, so no handler pops it while
7487		// this one still holds it.
7488		if self.requeue {
7489			ServeState::requeue(&self.home, &self.path, &self.producer);
7490			return;
7491		}
7492		// Handed off but neither accepted nor rejected: drop the still-pending entry so its
7493		// producer clone (plus this one) closes the channel, resolving coalesced requesters to
7494		// `Unroutable` rather than hanging.
7495		//
7496		// The identity guard matters: `serve`/`reject` already removed our entry and released
7497		// the lock before we run, so a concurrent request for the same path may have registered
7498		// a *new* one here. Removing unconditionally would clobber it, stranding its requesters.
7499		ServeState::forget(&self.home, &self.path, &self.producer);
7500	}
7501}
7502
7503/// The immediate table lookup serving a peer without initiating application discovery.
7504// private: capability gap
7505pub(crate) struct Lookup {
7506	inner: RequestState,
7507	// The path the requester asked for, relative to its cursor's root. Stamped on the
7508	// resolved broadcast (see [`broadcast::Info::path`]) because a handler is free to
7509	// serve a broadcast created somewhere else entirely, or at no path at all.
7510	path: Path,
7511	// Egress scope applied to the resolved broadcast, so its reads are attributed.
7512	// Empty (no-op) for an untagged consumer.
7513	stats: stats::Scope,
7514	// The identity the requester named, if any: the front may resolve on another one
7515	// when the route changes while the request is in flight.
7516	identity: Option<Identity>,
7517}
7518
7519enum RequestState {
7520	// Unroutable at request time: resolves immediately with this error. Baked in so
7521	// `request` itself stays infallible.
7522	Failed(Error),
7523	// Joined a front: resolves with the front's broadcast once its verdict is in, held
7524	// from the moment of joining so the front cannot retire under the requester.
7525	Pending {
7526		front: kio::Consumer<PendingFront>,
7527		broadcast: broadcast::Consumer,
7528	},
7529}
7530
7531impl Lookup {
7532	fn failed(error: Error) -> Self {
7533		Self::new(RequestState::Failed(error))
7534	}
7535
7536	fn queued(front: kio::Consumer<PendingFront>, broadcast: broadcast::Consumer) -> Self {
7537		Self::new(RequestState::Pending { front, broadcast })
7538	}
7539
7540	fn new(inner: RequestState) -> Self {
7541		Self {
7542			inner,
7543			path: Path::default(),
7544			stats: stats::Scope::default(),
7545			identity: None,
7546		}
7547	}
7548
7549	/// Refuse a resolution on any identity but `identity`.
7550	fn with_identity(mut self, identity: Option<Identity>) -> Self {
7551		self.identity = identity;
7552		self
7553	}
7554
7555	fn with_path(mut self, path: Path) -> Self {
7556		self.path = path;
7557		self
7558	}
7559
7560	/// The egress scope the resolved broadcast's reads are attributed to.
7561	fn with_stats(mut self, scope: stats::Scope) -> Self {
7562		self.stats = scope;
7563		self
7564	}
7565
7566	/// Stamp a resolved broadcast with the path this cursor asked for, its egress scope,
7567	/// and the identity of the route it resolved through.
7568	fn hand_out(&self, broadcast: broadcast::Consumer, identity: Identity) -> broadcast::Consumer {
7569		broadcast
7570			.with_path(self.path.clone())
7571			.with_stats(self.stats.clone())
7572			.with_identity(Some(identity))
7573	}
7574
7575	/// Poll for the requested broadcast without blocking.
7576	pub fn poll_ok(&self, waiter: &kio::Waiter) -> Poll<Result<broadcast::Consumer, Error>> {
7577		match &self.inner {
7578			RequestState::Failed(error) => Poll::Ready(Err(error.clone())),
7579			RequestState::Pending { front, broadcast } => Poll::Ready(
7580				match ready!(front.poll(waiter, |state| match &state.resolved {
7581					Some(result) => Poll::Ready(result.clone()),
7582					None => Poll::Pending,
7583				})) {
7584					// Another identity than the one named: never hand it out.
7585					Ok(Ok(identity)) if self.identity.as_ref().is_some_and(|named| *named != identity) => {
7586						Err(Error::Unroutable)
7587					}
7588					Ok(Ok(identity)) => Ok(self.hand_out(broadcast.clone(), identity)),
7589					Ok(Err(err)) => Err(err),
7590					// The front's driver went away without a verdict: nobody could route it.
7591					Err(_closed) => Err(Error::Unroutable),
7592				},
7593			),
7594		}
7595	}
7596}
7597
7598impl kio::Task for Lookup {
7599	type Output = Result<broadcast::Consumer, Error>;
7600
7601	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Self::Output> {
7602		self.poll_ok(waiter)
7603	}
7604}
7605
7606/// An owned broadcast resolution, driven by polling or awaiting it.
7607pub struct Requesting {
7608	consumer: Consumer,
7609	path: Path,
7610	// Asks sessions to discover the path for as long as this waits on it.
7611	interest: Option<Interest>,
7612	// The covering routes, watched since the generation the last ask saw.
7613	watch: Option<(Watch, u64)>,
7614	// The ask in flight, dropped once it fails `Unroutable` until the routes move.
7615	request: Option<Lookup>,
7616	// The identity every ask is pinned to, if any.
7617	identity: Option<Identity>,
7618	// A finite request owns discovery and can conclude absence once its initial set lands.
7619	discovery: Option<Follow>,
7620	routed: bool,
7621}
7622
7623impl Requesting {
7624	/// Poll for the requested identity, retrying only after its covering routes change.
7625	pub fn poll_ok(&mut self, waiter: &kio::Waiter) -> Poll<Result<broadcast::Consumer, Error>> {
7626		loop {
7627			if let Some(discovery) = &mut self.discovery {
7628				// Sync is an event, not a deadline: sessions hold it from the moment the
7629				// interest is created until the initial announcement set is delivered. Read it
7630				// before draining the routes, so a session delivering its set and syncing
7631				// between the two reads never leaves that set unseen.
7632				let synced = discovery.poll_synced(waiter).is_ready();
7633				loop {
7634					match discovery.poll_next(waiter) {
7635						Poll::Ready(Some(RouteEvent {
7636							kind: RouteKind::End | RouteKind::Offline,
7637							..
7638						})) => self.routed = false,
7639						Poll::Ready(Some(RouteEvent {
7640							kind: RouteKind::Start | RouteKind::Restart | RouteKind::Update,
7641							..
7642						})) => self.routed = true,
7643						Poll::Ready(None) => return Poll::Ready(Err(Error::Closed)),
7644						Poll::Pending => break,
7645					}
7646				}
7647				// The winner says nothing of a pinned identity, which follows its own routes: a pinned
7648				// request concludes only from a lookup the routes have not moved since.
7649				let absent = self.identity.is_none() && !self.routed;
7650				if self.request.is_none()
7651					&& synced && (absent || self.watch.as_ref().is_some_and(|(watch, seen)| watch.seen() == *seen))
7652				{
7653					return Poll::Ready(Err(Error::Unroutable));
7654				}
7655			}
7656
7657			match (&self.watch, &self.request) {
7658				(_, Some(request)) => match ready!(request.poll_ok(waiter)) {
7659					Ok(broadcast) => return Poll::Ready(Ok(broadcast)),
7660					Err(Error::Unroutable) => {
7661						// The front already distinguishes a selected handler's refusal
7662						// from route churn; retain that verdict rather than infer it from
7663						// unrelated changes a prepared answer makes to the table.
7664						let refused = match &request.inner {
7665							RequestState::Pending { front, .. } => front.read().refused,
7666							RequestState::Failed(_) => false,
7667						};
7668						if refused {
7669							return Poll::Ready(Err(Error::Unroutable));
7670						}
7671						self.request = None;
7672					}
7673					Err(err) => return Poll::Ready(Err(err)),
7674				},
7675				(Some((watch, seen)), None) => {
7676					ready!(watch.poll_changed(waiter, *seen));
7677					self.watch = None;
7678				}
7679				(None, None) => {
7680					// `Unroutable` is a verdict of the routes covering the path as they
7681					// stood when the request was made. Re-asking the same routes would
7682					// spin, so watch them before asking and wait for them to move (a
7683					// route arriving or retracting, an identical standby swapping in, a
7684					// local broadcast announcing at the path), then try again. A change
7685					// between the ask and the wait bumps the watch first, so that retry
7686					// is immediate; the teardown pokes every watch, so a closed origin
7687					// is observed on the next pass.
7688					let mut table = self.consumer.shared.lock();
7689					if table.closed {
7690						return Poll::Ready(Err(Error::Closed));
7691					}
7692					let named = match self.consumer.root.join(&self.path) {
7693						Ok(named) => named,
7694						Err(err) => return Poll::Ready(Err(err.into())),
7695					};
7696					let Some(resolved) = self.consumer.scope.resolve(&named) else {
7697						return Poll::Ready(Err(BoundsExceeded.into()));
7698					};
7699					let watch = table.watch(&self.consumer.shared, &resolved);
7700					let seen = watch.seen();
7701					if self.interest.is_none() && self.discovery.is_none() && self.consumer.interested {
7702						let resolved = resolved.clone();
7703						self.interest = Some(Interest::new(&mut table, &self.consumer.shared, resolved));
7704					}
7705					drop(table);
7706					self.watch = Some((watch, seen));
7707					self.request = Some(
7708						self.consumer
7709							.lookup(self.path.clone(), self.identity.as_ref())
7710							.into_inner(),
7711					);
7712				}
7713			}
7714		}
7715	}
7716}
7717
7718impl kio::Task for Requesting {
7719	type Output = Result<broadcast::Consumer, Error>;
7720
7721	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Self::Output> {
7722		self.poll_ok(waiter)
7723	}
7724}
7725
7726/// Waits for an identity to stop serving a path, watching the routes covering it. Unlike
7727/// the broadcast a request resolved, which also closes once its last holder lets it go, this
7728/// ends only when the routes move to another identity or away. Created by [`Consumer::moved`].
7729pub(super) struct Moved {
7730	consumer: Consumer,
7731	path: Path,
7732	identity: Identity,
7733	pinned: bool,
7734	// The covering routes, watched since the generation the last check saw.
7735	watch: Option<(Watch, u64)>,
7736}
7737
7738impl Moved {
7739	/// Ready once `identity` no longer serves the path, or the origin closed.
7740	pub(super) fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> {
7741		loop {
7742			if let Some((watch, seen)) = &self.watch {
7743				ready!(watch.poll_changed(waiter, *seen));
7744			}
7745			let named = match self.consumer.root.join(&self.path) {
7746				Ok(named) if self.consumer.scope.permits(&named) => named,
7747				_ => return Poll::Ready(()),
7748			};
7749			let Some(absolute) = self.consumer.scope.resolve(&named) else {
7750				return Poll::Ready(());
7751			};
7752			let mut state = self.consumer.shared.lock();
7753			if state.closed {
7754				return Poll::Ready(());
7755			}
7756			// Read the generation under the lock that decides, so a change after it bumps
7757			// the watch and the next pass checks again. Filling an empty slot drops no watch,
7758			// whose drop takes this lock.
7759			match &mut self.watch {
7760				Some((watch, seen)) => *seen = watch.seen(),
7761				None => {
7762					let watch = state.watch(&self.consumer.shared, &absolute);
7763					let seen = watch.seen();
7764					self.watch = Some((watch, seen));
7765				}
7766			}
7767			let horizon = self.consumer.horizon.effective(&state.routes, &absolute);
7768			let serves = state.still_serves(&absolute, horizon, &self.identity, self.pinned);
7769			drop(state);
7770			if !serves {
7771				return Poll::Ready(());
7772			}
7773		}
7774	}
7775}
7776
7777/// Derive a read view from a handle.
7778///
7779/// Lets APIs accept either a producer or a consumer (e.g.
7780/// `Client::with_publisher`). The blanket `&T` impl means you can
7781/// pass by value (`foo(x)`) to hand off ownership, or by reference (`foo(&x)`)
7782/// to keep it, without spelling out `.consume()`.
7783pub trait Consume<T> {
7784	/// Derive a read view (a consumer) from this handle.
7785	fn consume(&self) -> T;
7786}
7787
7788impl<T, U: Consume<T>> Consume<T> for &U {
7789	fn consume(&self) -> T {
7790		(**self).consume()
7791	}
7792}
7793
7794impl Consume<Consumer> for Producer {
7795	fn consume(&self) -> Consumer {
7796		// Mirrors the inherent `Producer::consume`; inlined to avoid the
7797		// inherent-vs-trait `consume` ambiguity. Untagged: egress is tagged
7798		// separately from ingress.
7799		Consumer::from_producer(self, stats::Session::default())
7800	}
7801}
7802
7803impl Consume<Consumer> for Consumer {
7804	fn consume(&self) -> Consumer {
7805		self.clone()
7806	}
7807}
7808
7809impl Consume<broadcast::Consumer> for broadcast::Producer {
7810	fn consume(&self) -> broadcast::Consumer {
7811		// The inherent `consume` shadows this trait method, so this delegates.
7812		self.consume()
7813	}
7814}
7815
7816impl Consume<broadcast::Consumer> for broadcast::Consumer {
7817	fn consume(&self) -> broadcast::Consumer {
7818		self.clone()
7819	}
7820}
7821
7822impl Consume<track::Consumer> for track::Producer {
7823	fn consume(&self) -> track::Consumer {
7824		self.consume()
7825	}
7826}
7827
7828impl Consume<track::Consumer> for track::Consumer {
7829	fn consume(&self) -> track::Consumer {
7830		self.clone()
7831	}
7832}
7833
7834/// Cheap read handle over an origin's route table.
7835///
7836/// Clones share the underlying state without allocating any per-cursor
7837/// resources. To receive route announcements, call [`Self::announced`]; to
7838/// resolve a path into a broadcast, call [`Self::request`].
7839#[derive(Clone)]
7840pub struct Consumer {
7841	// Identity of the origin this consumer was derived from.
7842	node: NonZeroU64,
7843	max_hops: NonZeroUsize,
7844	scope: OriginScope,
7845
7846	// A prefix that is automatically stripped from all paths.
7847	root: Path,
7848
7849	// The origin's shared state: the route table, announce cursors, and the
7850	// remotely-served fronts.
7851	shared: SendCell<kio::Shared<OriginState>>,
7852
7853	// Egress stats context. Broadcasts handed out through this consumer (and any
7854	// handle derived from them) are attributed to it (reads counted on the
7855	// publisher/egress side). Empty (no-op) unless a session tagged this handle.
7856	stats: stats::Session,
7857
7858	// Split horizon: routes whose hop chain or announcing session (`via`) is the
7859	// excluded peer are invisible to `announced` and skipped by
7860	// `request`, so a peer is never served (or advertised) its own
7861	// content back. A local view (`Self::local`) hides peer routes the same way,
7862	// and a view taken from an upstream handle hides upstream routes.
7863	horizon: Horizon,
7864
7865	// Which routes beneath a hidden (`.`-prefixed) segment `announced` reports.
7866	hidden: Hidden,
7867
7868	// Whether `announced` also reports routes whose subtree only overlaps the scope.
7869	covering: bool,
7870
7871	// Whether this handle's announcement streams and routed requests count as
7872	// interests, so a session fed into the origin asks its peer about them. Off
7873	// for a session serving its peer (see `Self::serving`).
7874	interested: bool,
7875
7876	// Whether this origin forwards; see [`Config::proxy`].
7877	proxy: bool,
7878
7879	// The cache policy remote fronts inherit, mirroring what
7880	// `route` gives a local front.
7881	pool: cache::Pool,
7882	cache_duration: Option<Duration>,
7883
7884	// Non-owning submission handle to the origin's [`Driver`], for the front
7885	// watcher a routed `request` spawns. Non-owning so a lingering
7886	// read handle never keeps the driver from finishing.
7887	tasks: TasksWeak,
7888
7889	// The driver's clock and timers, threaded into fronts for the track idle
7890	// linger.
7891	timers: Deadlines,
7892}
7893
7894impl Consumer {
7895	fn from_producer(producer: &Producer, stats: stats::Session) -> Self {
7896		Self {
7897			node: producer.node,
7898			max_hops: producer.max_hops,
7899			scope: producer.scope.clone(),
7900			root: producer.root.clone(),
7901			shared: producer.shared.clone(),
7902			stats,
7903			horizon: Horizon {
7904				upstream: producer.link == Link::Upstream,
7905				..Horizon::default()
7906			},
7907			hidden: Hidden::default(),
7908			covering: false,
7909			interested: true,
7910			proxy: producer.proxy,
7911			pool: producer.pool.clone(),
7912			cache_duration: producer.cache_duration,
7913			tasks: producer.tasks.downgrade(),
7914			timers: producer.timers.clone(),
7915		}
7916	}
7917
7918	/// This origin's Node ID, random for each run.
7919	pub fn node(&self) -> NonZeroU64 {
7920		self.node
7921	}
7922
7923	/// A clone that never serves the given peer its own data: routes whose hop
7924	/// chain contains `peer`, or whose announcing session is `peer`, are invisible
7925	/// and never resolved from, matching what the announce loop advertises to them.
7926	/// Sessions apply this once they learn the peer's origin id. Hop 0 identifies
7927	/// nobody, so the announcing session's assigned identity is what keeps an
7928	/// anonymous route from echoing back. Pass [`Hop::UNKNOWN`] for an anonymous
7929	/// peer.
7930	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
7931	pub(crate) fn excluding(mut self, peer: Hop) -> Self {
7932		self.horizon.exclude = Some(peer);
7933		self
7934	}
7935
7936	/// The Node ID a moq-lite-07 session declares when it answers its peer from this
7937	/// handle and takes what the peer publishes into `subscribe`: this origin's, when it
7938	/// forwards, the application linked the session to a cluster peer, and neither handle
7939	/// confines the peer to part of the tree. `None` for every other session, which
7940	/// exchanges claims and no routes.
7941	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
7942	pub(crate) fn node_id(&self, subscribe: &Producer) -> Option<crate::route::NodeId> {
7943		let whole = |root: &Path, scope: &OriginScope| {
7944			root.is_empty() && scope.allowed.matches("") && scope.excluded.is_empty() && scope.mounts.is_empty()
7945		};
7946		let routing = self.proxy
7947			&& subscribe.link() != Link::Local
7948			&& self.shared.is_clone(&subscribe.shared)
7949			&& whole(&self.root, &self.scope)
7950			&& whole(subscribe.root(), &subscribe.scope);
7951		routing.then(|| self.route_node().me())
7952	}
7953
7954	/// The route layer node every lite-07 session on this origin shares, created on
7955	/// first use along with the task that feeds it the routes this node serves
7956	/// itself: everything in the table the route layer did not select. It is caught up
7957	/// with the table on every call, so a stream registered next presents what the
7958	/// table holds now, not what the driver last fed it.
7959	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
7960	pub(crate) fn route_node(&self) -> crate::route::Node {
7961		let existing = self.shared.lock().route_node.clone();
7962		let (node, own) = existing.unwrap_or_else(|| self.create_route_node());
7963		if let Some(own) = own.upgrade() {
7964			// Catching up wakes the node's streams and the feeder's own cursors. Those wakes
7965			// wait for the feeder's lock: a waker may poll a session inline, which calls back here.
7966			let _hold = kio::hold();
7967			lock_own(&own).catch_up();
7968		}
7969		node
7970	}
7971
7972	fn create_route_node(&self) -> (crate::route::Node, std::sync::Weak<std::sync::Mutex<OwnClaims>>) {
7973		// The whole table, counted against no session: only origin-wide state, so the node
7974		// is the same whichever handle creates it. No `..self` here, so a new per-handle
7975		// field cannot leak in.
7976		let own = |upstream| Self {
7977			node: self.node,
7978			max_hops: self.max_hops,
7979			scope: OriginScope::default(),
7980			root: Path::default(),
7981			shared: self.shared.clone(),
7982			stats: stats::Session::default(),
7983			horizon: Horizon {
7984				node: NodeFilter::Own,
7985				upstream,
7986				..Horizon::default()
7987			},
7988			hidden: Hidden {
7989				include: true,
7990				from: None,
7991			},
7992			// Feeding the node is no reason to ask any peer about anything, as when serving.
7993			covering: true,
7994			interested: false,
7995			proxy: false,
7996			pool: self.pool.clone(),
7997			cache_duration: self.cache_duration,
7998			tasks: self.tasks.clone(),
7999			timers: self.timers.clone(),
8000		};
8001		// Built before taking the lock, since opening a cursor takes it.
8002		// Whether the origin forwards is fixed in its config, so every handle agrees here.
8003		let node = crate::route::Node::origin(self.node(), self.proxy, self.timers.clone());
8004		let claims = OwnClaims {
8005			routes: own(false).routes(),
8006			downstream: own(true).routes(),
8007			best: HashMap::new(),
8008			local: HashMap::new(),
8009			gone: BTreeMap::new(),
8010			proxy: self.proxy,
8011			node: node.clone(),
8012		};
8013		let mut shared = self.shared.lock();
8014		// A concurrent first call won the race: use its node, and close these cursors
8015		// only once the lock is released, since closing one takes it.
8016		if let Some(existing) = shared.route_node.clone() {
8017			drop(shared);
8018			return existing;
8019		}
8020		let claims = Arc::new(std::sync::Mutex::new(claims));
8021		let created = (node, Arc::downgrade(&claims));
8022		// A torn-down origin keeps no node: nothing would let go of it again.
8023		if !shared.closed {
8024			shared.route_node = Some(created.clone());
8025		}
8026		drop(shared);
8027		self.tasks.push(FeedOwnClaims {
8028			claims,
8029			origin: self.tasks.clone(),
8030		});
8031		self.tasks.push(RouteTimer {
8032			node: created.0.clone(),
8033			deadline: crate::time::Deadline::new(&self.timers),
8034			origin: self.tasks.clone(),
8035		});
8036		created
8037	}
8038
8039	/// Whether this origin carries its peer's traffic to other origins; see
8040	/// [`Config::proxy`].
8041	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
8042	pub(crate) fn proxy(&self) -> bool {
8043		self.proxy
8044	}
8045
8046	/// Whether the reader of this handle is an upstream peer, which is never sent a
8047	/// route learned from another upstream.
8048	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
8049	pub(crate) fn upstream(&self) -> bool {
8050		self.horizon.upstream
8051	}
8052
8053	/// Whether this handle reaches a claim at the absolute `path` as it names it: a
8054	/// path at or beneath it may be in its scope, as a covering reader sees, and it is
8055	/// not in an excluded subtree. Beneath a mount, `path` names the target's claim
8056	/// there, never one the origin holds at `path` itself (see [`Self::mounted`]).
8057	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
8058	pub(crate) fn reaches(&self, path: &Path) -> bool {
8059		self.scope.allowed.overlaps(path.as_str())
8060			&& !self.scope.excluded.iter().any(|excluded| path.has_prefix(excluded))
8061			&& self.scope.mount(path).is_none_or(|mount| mount.resolve(path).is_some())
8062	}
8063
8064	/// Whether the absolute `path` lies beneath one of this handle's mounts, where the
8065	/// origin's own claims at that path are hidden from it.
8066	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
8067	pub(crate) fn shadows(&self, path: &Path) -> bool {
8068		self.scope.mount(path).is_some()
8069	}
8070
8071	/// The mounts a reader of the absolute `prefix` sees through this handle: each one
8072	/// at or beneath it, or the one it lies beneath, unless excluded.
8073	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
8074	pub(crate) fn mounted(&self, prefix: &Path) -> Vec<Mounted> {
8075		(self.scope.mounts.iter())
8076			.filter(|mount| self.scope.holes(Some(mount)).is_some())
8077			.filter_map(|mount| {
8078				Some(Mounted {
8079					interest: mount.translate_head(prefix)?,
8080					mount: mount.clone(),
8081				})
8082			})
8083			.collect()
8084	}
8085
8086	/// Whether this handle reaches every path at or beneath the absolute `prefix`.
8087	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
8088	pub(crate) fn covers(&self, prefix: &Path) -> bool {
8089		let overlaps = |other: &Path| other.has_prefix(prefix) || prefix.has_prefix(other);
8090		self.scope.allowed.matches(prefix.as_str())
8091			&& !self.scope.excluded.iter().any(overlaps)
8092			&& !self.scope.mounts.iter().any(|mount| overlaps(&mount.at))
8093	}
8094
8095	/// Where `path`, relative to this handle's root, lies on the origin: past its mount,
8096	/// if any. `None` when it does not fit the wire limits there.
8097	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
8098	pub(crate) fn resolve(&self, path: &Path) -> Option<Path> {
8099		self.scope.resolve(&self.root.join(path).ok()?)
8100	}
8101
8102	/// A clone that sees only the routes `node` admits: a request naming an origin
8103	/// node resolves only through that node's routes, and the route layer's own
8104	/// claims are the routes this node serves itself.
8105	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
8106	pub(crate) fn with_node(mut self, node: NodeFilter) -> Self {
8107		self.horizon.node = node;
8108		self
8109	}
8110
8111	/// A clone whose announcements skip the routes this origin cannot forward: a
8112	/// chain already at [`Config::max_hops`] has no room for our hop. Sessions whose
8113	/// wire carries the hop path apply this to the routes they advertise.
8114	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
8115	pub(crate) fn forwardable(mut self) -> Self {
8116		self.horizon.max_hops = Some(self.max_hops);
8117		self
8118	}
8119
8120	/// A view of the routes that entered here: every route a handle marked
8121	/// [`Link::Peer`] or [`Link::Upstream`] announced is hidden from [`Self::announced`]
8122	/// and never resolved by [`Self::request`].
8123	///
8124	/// On a relay, this is what the relay ingests itself, from clients and
8125	/// in-process producers, as opposed to what its cluster peers forward. An embedder
8126	/// that records, republishes, or meters each broadcast once, on the node that
8127	/// ingests it, reads this view.
8128	pub fn local(mut self) -> Self {
8129		self.horizon.local = true;
8130		self
8131	}
8132
8133	/// A clone for a session serving its peer: its reads are the peer's, not a
8134	/// local reader's, so they never make a session ask its own peer about them.
8135	/// It is [`covering`](Self::covering), since the peer routes requests through
8136	/// what we announce.
8137	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
8138	pub(crate) fn serving(mut self) -> Self {
8139		self.interested = false;
8140		self.covering = true;
8141		self
8142	}
8143
8144	/// A clone whose [`announced`](Self::announced) also reports hidden routes:
8145	/// those with a segment starting with `.` below the requested prefix.
8146	/// Hidden routes are left out by default, so a platform can add `.`-named
8147	/// broadcasts without them turning up in apps that list everything.
8148	pub fn with_hidden(mut self, hidden: bool) -> Self {
8149		self.hidden.include = hidden;
8150		self
8151	}
8152
8153	/// A clone whose [`announced`](Self::announced) also reports every route that could
8154	/// serve a path in scope, not just those whose literal name matches it.
8155	///
8156	/// A route is a prefix that serves every path beneath it, so a route at `room` can
8157	/// serve `room/lobby.chat` under a `**/*.chat` scope, and one above the root covers
8158	/// all of it. Code that routes requests or forwards announcements needs those
8159	/// routes; a session serving its peer always uses this view. Listing broadcasts does
8160	/// not. Requests resolve through covering routes either way.
8161	pub fn covering(mut self) -> Self {
8162		self.covering = true;
8163		self
8164	}
8165
8166	/// A clone that never reaches the subtree at `prefix`, relative to this root:
8167	/// [`announced`](Self::announced) leaves out the routes at or beneath it and a
8168	/// request for a path there fails with [`Error::Unauthorized`]. A route
8169	/// announced above `prefix` is still reported. [`allowed`](Self::allowed) is unchanged.
8170	pub fn exclude(&self, prefix: impl TryInto<Path, Error: Into<Error>>) -> Result<Self, Error> {
8171		let prefix = self.root.join(&path::convert(prefix)?)?;
8172		let mut consumer = self.clone();
8173		consumer.scope.excluded = self.scope.excluded.iter().cloned().chain([prefix]).collect();
8174		Ok(consumer)
8175	}
8176
8177	/// Set wire discovery visibility relative to this consumer's requested root.
8178	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
8179	pub(crate) fn discovery(mut self, hidden: bool) -> Self {
8180		self.hidden.include = hidden;
8181		self.hidden.from = Some(self.root.clone());
8182		self
8183	}
8184
8185	/// Whether [`announced`](Self::announced) reports hidden routes too.
8186	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
8187	pub(crate) fn includes_hidden(&self) -> bool {
8188		self.hidden.include
8189	}
8190
8191	/// The egress stats context this handle was tagged with.
8192	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
8193	pub(crate) fn stats(&self) -> &stats::Session {
8194		&self.stats
8195	}
8196
8197	/// Attach an egress stats context: broadcasts handed out through this handle (and
8198	/// any handle derived from it) are attributed to `session` on the publisher
8199	/// (egress) side. Pass [`stats::Session::default`] to opt out.
8200	pub fn with_stats(mut self, session: stats::Session) -> Self {
8201		self.stats = session;
8202		self
8203	}
8204
8205	/// A clone of this consumer with its stats context cleared, so an internal
8206	/// lookup stream (e.g. [`Self::routes`]) doesn't drive the egress
8207	/// announce guards; the caller re-attributes the result itself.
8208	fn untagged(&self) -> Self {
8209		Self {
8210			stats: stats::Session::default(),
8211			..self.clone()
8212		}
8213	}
8214
8215	/// A view with this consumer's identity and root but no scope:
8216	/// [`announced`](Self::announced) yields nothing. Used to answer a peer's
8217	/// announce-interest for a prefix outside our scope by announcing nothing,
8218	/// rather than tearing the stream down.
8219	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
8220	pub(crate) fn empty(&self) -> Self {
8221		Self {
8222			scope: OriginScope::empty(),
8223			..self.clone()
8224		}
8225	}
8226
8227	/// List the paths announced in this consumer's scope, each present or absent.
8228	///
8229	/// A path stays present while any route covers it, whichever identity serves it:
8230	/// hold a [`follow`](Self::follow) to see the broadcast change. Scope, hiding and
8231	/// sync behave as for [`routes`](Self::routes). Drop the returned
8232	/// [`announce::Consumer`](crate::announce::Consumer) to unregister.
8233	pub fn announced(&self) -> AnnounceConsumer {
8234		AnnounceConsumer::new(self.routes())
8235	}
8236
8237	/// Every change to the routes announced in this consumer's scope, for relays and
8238	/// stats: route metadata and identity replacements included.
8239	///
8240	/// Allocates a per-cursor coalescing buffer and replays the currently
8241	/// announced routes as initial updates. Routes stay prefixes and are named
8242	/// relative to this consumer's root; its scope only decides visibility. Only routes
8243	/// the scope covers are reported, unless [`covering`](Self::covering) asks for every
8244	/// route that could serve them. Routes with a segment starting with `.` below a
8245	/// prefix of the scope are hidden unless [`with_hidden`](Self::with_hidden) opted in.
8246	/// The stream also watches its scope: a client session fed by this origin asks
8247	/// its peer about the scope while any stream watches it.
8248	/// Drop the returned [`Routes`] to unregister.
8249	pub fn routes(&self) -> Routes {
8250		self.listing(false)
8251	}
8252
8253	/// [`Self::routes`], for a path lookup when `lookup`; see [`TableCursor::lookup`].
8254	fn listing(&self, lookup: bool) -> Routes {
8255		let state = kio::Producer::<OriginConsumerState>::default();
8256		let cursor =
8257			|root: Path, allowed: Prefixes, hidden: Hidden, mount: Option<&Mount>, under: Path, holes: Vec<Path>| {
8258				TableCursor {
8259					heads: match lookup {
8260						true => vec![root.clone()],
8261						false => heads(&allowed),
8262					},
8263					root,
8264					allowed,
8265					horizon: self.horizon,
8266					hidden,
8267					covering: self.covering,
8268					state: state.clone(),
8269					under,
8270					holes,
8271					mount: mount.cloned(),
8272					interested: self.interested,
8273					current: HashMap::new(),
8274					ranked: self.horizon.node == NodeFilter::Own,
8275					lookup,
8276				}
8277			};
8278
8279		// A root at or beneath a mount reads only the mount: one cursor, re-rooted
8280		// onto the target.
8281		if let Some(mount) = self.scope.mount(&self.root) {
8282			// A root the mount resolves past the depth limit, or an excluded one, has
8283			// nothing to announce.
8284			let (Some(root), Some(holes)) = (mount.resolve(&self.root), self.scope.holes(Some(mount))) else {
8285				return Routes::new(
8286					self.root.clone(),
8287					Vec::new(),
8288					state,
8289					self.stats.clone(),
8290					&self.shared,
8291					self.timers.clone(),
8292				);
8293			};
8294			let cursors = vec![cursor(
8295				root,
8296				mount.translate(&self.scope.allowed),
8297				self.hidden.translate(mount),
8298				Some(mount),
8299				Path::default(),
8300				holes,
8301			)];
8302			return Routes::new(
8303				self.root.clone(),
8304				cursors,
8305				state,
8306				self.stats.clone(),
8307				&self.shared,
8308				self.timers.clone(),
8309			);
8310		}
8311
8312		// Otherwise the consumer's own cursor, minus the mounted and excluded subtrees,
8313		// plus one cursor per mount beneath the root it may discover, presenting under it.
8314		// A lookup reads only what covers its root, which no mount beneath it does.
8315		let heads = heads(&self.scope.allowed);
8316		let mut holes = self.scope.holes(None).unwrap_or_default();
8317		let mut cursors = Vec::new();
8318		for mount in self.scope.mounts.iter().filter(|_| !lookup) {
8319			let Some(under) = mount.at.strip_prefix(&self.root) else {
8320				continue;
8321			};
8322			holes.push(mount.at.clone());
8323			let Some(mount_holes) = self.scope.holes(Some(mount)) else {
8324				continue;
8325			};
8326			let allowed = mount.translate(&self.scope.allowed);
8327			// Hidden at the mount point means hidden throughout: the dot segment is above
8328			// everything the mount holds. A top-up feed's rule moves onto the target.
8329			if allowed.is_empty()
8330				|| !(self.hidden.include
8331					|| !hides(
8332						self.hidden.from.as_ref().map(std::slice::from_ref).unwrap_or(&heads),
8333						&mount.at,
8334					)) {
8335				continue;
8336			}
8337			cursors.push(cursor(
8338				mount.target.clone(),
8339				allowed,
8340				self.hidden.translate(mount),
8341				Some(mount),
8342				under.clone(),
8343				mount_holes,
8344			));
8345		}
8346		cursors.insert(
8347			0,
8348			cursor(
8349				self.root.clone(),
8350				self.scope.allowed.clone(),
8351				self.hidden.clone(),
8352				None,
8353				Path::default(),
8354				holes,
8355			),
8356		);
8357		Routes::new(
8358			self.root.clone(),
8359			cursors,
8360			state,
8361			self.stats.clone(),
8362			&self.shared,
8363			self.timers.clone(),
8364		)
8365	}
8366
8367	/// Returns a cheap duplicate of this read handle.
8368	pub fn consume(&self) -> Self {
8369		self.clone()
8370	}
8371
8372	/// The newest broadcast published on this origin at exactly `path`, if any.
8373	/// Test-only: a request goes through the table like any other.
8374	#[cfg(test)]
8375	pub(crate) fn get_broadcast(&self, path: impl TryInto<Path, Error: Into<Error>>) -> Option<broadcast::Consumer> {
8376		let full = self.root.join(&path::convert::<Error>(path).ok()?).ok()?;
8377		if !self.scope.permits(&full) {
8378			return None;
8379		}
8380		let full = self.scope.resolve(&full)?;
8381		let table = self.shared.lock();
8382		table
8383			.routes
8384			.at(&full)
8385			.filter(|entry| entry.local)
8386			.min_by_key(|entry| (entry.lane.above, route_order(&entry.prefix, entry)))
8387			.and_then(|entry| entry.source.clone())
8388	}
8389
8390	/// Follow the announcements of the routes covering `path`, reduced to the one serving it.
8391	///
8392	/// [`Self::follow`] resolves each identity this reports, and [`Self::request`] concludes
8393	/// absence from its sync. Fails with [`Error::Unauthorized`] when this consumer's scope can
8394	/// never cover the path.
8395	pub(crate) fn path_routes(&self, path: impl TryInto<Path, Error: Into<Error>>) -> Result<Follow, Error> {
8396		let path = path::convert(path)?;
8397
8398		// On a consumer limited to `foo/specific`, no route can ever cover `foo`.
8399		let root = self.root.join(&path)?;
8400		nameable(&root)?;
8401		// The join is bounded in bytes only, and the interest it registers must encode.
8402		if root.depth() > Path::MAX_PARTS {
8403			return Err(BoundsExceeded.into());
8404		}
8405		if !self.scope.permits(&root) {
8406			return Err(Error::Unauthorized);
8407		}
8408
8409		// Rooted at the path, so every claim covering it presents at the root, ranked as one
8410		// answer the way a request ranks them, wherever each claim is filed. The lookup sees
8411		// only those claims (see `TableCursor::lookup`): the rest of the origin never wakes
8412		// it, and a route claiming only paths beneath it (a scoped dynamic at the same
8413		// prefix) never masks the one that serves it, just as a request skips it.
8414		let consumer = Consumer { root, ..self.clone() };
8415
8416		// Untagged: this is a lookup, not egress announce forwarding, so it must not drive
8417		// the announce guards. Hiding narrows discovery, not lookup, so a hidden path
8418		// follows like any other.
8419		let announced = consumer.untagged().with_hidden(true).covering().listing(true);
8420		Ok(Follow::new(announced))
8421	}
8422
8423	/// A resolution that already failed with `err`.
8424	fn failed(&self, err: Error) -> Requesting {
8425		let mut request = self.routing(Path::empty(), None);
8426		request.request = Some(Lookup::failed(err));
8427		request
8428	}
8429
8430	/// Wait for `identity` to stop serving `path`, as a request `pinned` to it or not would
8431	/// resolve it; see [`Moved`].
8432	pub(super) fn moved(&self, path: Path, identity: Identity, pinned: bool) -> Moved {
8433		Moved {
8434			consumer: self.clone(),
8435			path,
8436			identity,
8437			pinned,
8438			watch: None,
8439		}
8440	}
8441
8442	/// Resolve a routed identity, returning a selected handler's refusal directly.
8443	pub(super) fn routing(&self, path: Path, identity: Option<Identity>) -> Requesting {
8444		// The scope keeps narrower permissions intact: if the whole path is not
8445		// reachable, no route can ever cover it, so bail rather than loop forever.
8446		let request = match self.root.join(&path) {
8447			Ok(named) if self.scope.permits(&named) => None,
8448			Ok(_) => Some(Lookup::failed(Error::Unauthorized)),
8449			Err(err) => Some(Lookup::failed(err.into())),
8450		};
8451		Requesting {
8452			consumer: self.clone(),
8453			path,
8454			interest: None,
8455			watch: None,
8456			request,
8457			identity,
8458			discovery: None,
8459			routed: false,
8460		}
8461	}
8462
8463	/// Follow the broadcast at `path` across the identities that serve it.
8464	///
8465	/// The first [`poll_available`](Following::poll_available) resolves the identity serving the path
8466	/// once one is announced, retrying route churn but returning a selected handler's refusal;
8467	/// the call after a refusal waits for the serving route to change. Each later call returns
8468	/// another identity taking over, or `None` once the path goes offline, then whatever serves
8469	/// it next, even the same identity. Drop what was read from the previous broadcast then:
8470	/// its tracks end with an error once its routes go. Another route of the same identity,
8471	/// or another epoch of it, is not a change.
8472	///
8473	/// Pass an owned [`Identity`] to follow only that stream: another one taking over ends
8474	/// it, and the identity is handed out again when it serves the path again. Fails with
8475	/// [`Error::Unauthorized`] when this consumer's scope can never cover the path, and with
8476	/// [`Error::InvalidPath`] when it holds a `*`.
8477	pub fn follow(
8478		&self,
8479		path: impl TryInto<Path, Error: Into<Error>>,
8480		identity: impl Into<Option<Identity>>,
8481	) -> Result<Following, Error> {
8482		let path = path::convert(path)?;
8483		let routes = self.path_routes(&path)?;
8484		Ok(Following::new(self.clone(), path, identity.into(), routes))
8485	}
8486
8487	/// Returns a consumer rooted at `root` and restricted to `prefixes`, each covering
8488	/// its whole subtree.
8489	///
8490	/// `root` is relative to this consumer's root, and `prefixes` are relative to
8491	/// the new root. Returns [`Error::Unauthorized`] when the requested scope has
8492	/// no overlap with this consumer's scope, or [`Error::BoundsExceeded`] when
8493	/// rooting the prefixes would exceed the path limit or the root holds a `*`.
8494	pub fn scope(&self, root: impl TryInto<Path, Error: Into<Error>>, prefixes: &Prefixes) -> Result<Consumer, Error> {
8495		let root = self.root.join(&path::convert(root)?)?;
8496		let rooted = prefixes.rooted(root.as_str()).map_err(|_| BoundsExceeded)?;
8497		let scope = self.scope.narrow(&rooted).ok_or(Error::Unauthorized)?;
8498		Ok(Consumer {
8499			scope,
8500			root,
8501			..self.clone()
8502		})
8503	}
8504
8505	/// Resolve a broadcast by exact path, optionally pinning its [`Identity`].
8506	///
8507	/// Returns a [`kio::Pending`] future, mirroring
8508	/// [`track::Consumer::fetch_group`](track::Consumer::fetch_group). Every
8509	/// path resolves through a front the origin's [`Driver`] runs: the request
8510	/// mints one or joins the one already serving the path, and the front picks
8511	/// one identity's route covering it and materializes it, from the broadcast itself
8512	/// or from the peer that announced the route. The order is the most specific prefix,
8513	/// then, within one identity, only its highest epoch is eligible, cheaper or not.
8514	/// Among identities it is the preferred link ([`Producer::with_priority`]), then
8515	/// the cheapest, then a broadcast published on this origin, then the shortest hop
8516	/// chain, then a hash of the identity and the path, which every relay agrees on and
8517	/// which spreads a pool's paths over its hosts.
8518	///
8519	/// When its serving source dies or a better route of the same identity appears,
8520	/// including a higher epoch, the front switches to it, invisibly to subscribers: the
8521	/// identity promises one continuous key space. Its routes retracting with no
8522	/// replacement ends the broadcast, and the next request re-serves the path;
8523	/// tracks already in flight carry on to their own end. The broadcast also ends
8524	/// once no handle holds it and none of its tracks has been read for a linger,
8525	/// and the next request re-serves the path then too.
8526	///
8527	/// Another identity winning the path leaves the broadcast to its readers until its
8528	/// routes go, while the next request resolves the winner on a fresh broadcast.
8529	/// [`Consumer::routes`] reports that as [`RouteKind::Restart`], and
8530	/// [`Self::follow`] yields the next broadcast. A job's exact route answering a
8531	/// claim's request continues the claim's identity, so it is no restart.
8532	///
8533	/// Pass an owned [`Identity`] to refuse a different stream, both when requesting
8534	/// and when an asynchronous answer resolves. `None` leaves lookup unpinned.
8535	///
8536	/// The request owns discovery for its path and retries when its covering routes change.
8537	/// It reports [`Error::Unroutable`] once discovery has synced without a covering route
8538	/// for the requested identity. A selected handler's explicit refusal is returned as-is.
8539	/// A broadcast resolved through a discovered route keeps
8540	/// its path watched until dropped; no separate announcement watcher is needed.
8541	/// A route claims capability, not inventory: resolving a covered path
8542	/// succeeds optimistically, and a path that names nothing surfaces as
8543	/// [`Error::NotFound`] on its tracks instead.
8544	pub fn request(
8545		&self,
8546		path: impl TryInto<Path, Error: Into<Error>>,
8547		identity: impl Into<Option<Identity>>,
8548	) -> kio::Pending<Requesting> {
8549		let path = match path::convert(path) {
8550			Ok(path) => path,
8551			Err(err) => return kio::Pending::new(self.failed(err)),
8552		};
8553		let mut routing = self.routing(path.clone(), identity.into());
8554		match self.path_routes(&path) {
8555			Ok(discovery) => {
8556				routing.discovery = Some(discovery);
8557				if let Some(resolved) = self.root.join(&path).ok().and_then(|named| self.scope.resolve(&named)) {
8558					let mut table = self.shared.lock();
8559					let watch = table.watch(&self.shared, &resolved);
8560					let seen = watch.seen();
8561					drop(table);
8562					routing.watch = Some((watch, seen));
8563				}
8564				// A requests handler hears an already-routed request at creation time.
8565				routing.request = Some(self.lookup(path, routing.identity.as_ref()).into_inner());
8566			}
8567			Err(err) => routing.request = Some(Lookup::failed(err)),
8568		}
8569		kio::Pending::new(routing)
8570	}
8571
8572	/// The routes as they stand now, without discovery or retry: what a session answers a
8573	/// peer's request with. Refused with [`Error::Unroutable`] unless the winning route serves
8574	/// `identity`: a peer asking for one stream must not be handed another.
8575	pub(crate) fn lookup(&self, path: Path, identity: Option<&Identity>) -> kio::Pending<Lookup> {
8576		// The path as this handle names it, absolute: what its scope authorizes and
8577		// what its egress is counted under, so a read through a mount bills where
8578		// the reader asked.
8579		let named = match self.root.join(&path) {
8580			Ok(named) => named,
8581			Err(err) => return kio::Pending::new(Lookup::failed(err.into())),
8582		};
8583		let scope = self.stats.egress(&named);
8584		// The resolved handle is named by what *this* cursor asked for, not by the absolute
8585		// path: a rooted cursor cannot name anything above its own root, so that is what a
8586		// catalog it reads may reference.
8587		let requested = path;
8588
8589		// Routes only cover paths within this consumer's scope.
8590		if !self.scope.permits(&named) {
8591			return kio::Pending::new(Lookup::failed(Error::Unauthorized));
8592		}
8593
8594		// Key requests by the absolute path on the origin, past any mount, so scoped,
8595		// rooted, and mounted consumers and handlers agree on the same entry and front.
8596		let Some(absolute) = self.scope.resolve(&named) else {
8597			return kio::Pending::new(Lookup::failed(BoundsExceeded.into()));
8598		};
8599
8600		let mut state = self.shared.lock();
8601
8602		// The origin's driver dropped: nothing will ever serve this.
8603		if state.closed {
8604			return kio::Pending::new(Lookup::failed(Error::Closed));
8605		}
8606
8607		let horizon = self.horizon.effective(&state.routes, &absolute);
8608
8609		// Nothing serves the path: no announced broadcast and no served route.
8610		// Checked before joining a front, so a front still draining after its
8611		// route retracted takes no newcomers.
8612		let Some((winner, winning)) = state
8613			.best_route(&absolute, horizon, &HashSet::new(), |_| true)
8614			.map(|best| (best.identity.clone(), best.epoch))
8615		else {
8616			return kio::Pending::new(Lookup::failed(Error::Unroutable));
8617		};
8618		// A request naming another identity than the winner follows that identity's own
8619		// routes: every hop resolves the identity the first one chose.
8620		let pin = identity.filter(|identity| **identity != winner).cloned();
8621		let (best, epoch) = match &pin {
8622			None => (winner, winning),
8623			Some(pin) => match state.best_route(&absolute, horizon, &HashSet::new(), |entry| entry.identity == *pin) {
8624				Some(entry) => (pin.clone(), entry.epoch),
8625				None => return kio::Pending::new(Lookup::failed(Error::Unroutable)),
8626			},
8627		};
8628
8629		// Join the live front for this path and horizon, if any: its watcher
8630		// resolves (or already resolved) the request channel with its verdict, so
8631		// repeat requests share one upstream subscription. A front resolved on
8632		// another identity stays only for the subscriptions already on it, so a new
8633		// request mints a fresh front for the winner rather than join the old one. So
8634		// does a front still resolving one the table has since beaten: it may already
8635		// hold that identity's source, and hand this request an identity it saw lose. So
8636		// does a front serving an older epoch of the winner: it moves its readers onto the
8637		// newer one, but an older epoch never stands in for a newer one that has yet to
8638		// answer. Nor does a front still resolving an older epoch: that epoch's answer may
8639		// already have passed its check and be on its way to resolving it.
8640		let key = (absolute.clone(), horizon, pin.clone());
8641		if let Some(front) = state.fronts.get(&key) {
8642			let current = {
8643				let pending = front.request.read();
8644				pending.epoch == epoch
8645					&& match &pending.resolved {
8646						None => pending.selected == best,
8647						Some(Ok(resolved)) => *resolved == best,
8648						Some(Err(_)) => false,
8649					}
8650			};
8651			// Held from here on, so the front cannot retire under this requester. A
8652			// retiring front closes atomically with this mint: found closed, it is
8653			// ending, and the request mints a fresh one instead.
8654			let held = current
8655				.then(|| front.broadcast.consume())
8656				.filter(|held| !held.is_closed());
8657			if let Some(held) = held {
8658				let pending = Lookup::queued(front.request.consume(), held)
8659					.with_path(requested)
8660					.with_stats(scope)
8661					.with_identity(identity.cloned());
8662				return kio::Pending::new(pending);
8663			}
8664			state.fronts.remove(&key);
8665		}
8666
8667		// A route covers the path: mint the front and hand its watcher the
8668		// request. The watcher materializes the path from the best covering
8669		// route, resolves the channel, and switches the front between routes for
8670		// as long as one serves.
8671		let broadcast = broadcast::Producer::new(broadcast::Info {
8672			pool: self.pool.clone(),
8673			cache_duration: self.cache_duration,
8674			path: absolute.clone(),
8675			identity: None,
8676			// A front reads its routes' copies, so it writes no frames of its own.
8677			frames: Default::default(),
8678			edges: Default::default(),
8679		});
8680		// Each route's source decides which copy a metadata reader gets; the front keeps
8681		// the two apart either way.
8682		broadcast.serve_meta();
8683		let request = kio::Producer::new(PendingFront {
8684			resolved: None,
8685			epoch,
8686			selected: best,
8687			refused: false,
8688		});
8689		let consumer = request.consume();
8690		// The front starts held by this request; see [`Front::new`].
8691		let held = broadcast.consume();
8692		let watch = state.watch(&self.shared, &absolute);
8693		state.fronts.insert(
8694			key,
8695			RemoteFront {
8696				request: request.clone(),
8697				broadcast: held.weak(),
8698			},
8699		);
8700		// Released before the push: a set whose handles are gone drops the task,
8701		// and the `Watch` it carries unregisters under this same lock.
8702		drop(state);
8703		self.tasks.push(FrontServeRun::new(
8704			FrontTask {
8705				shared: self.shared.clone(),
8706				broadcast,
8707				path: absolute,
8708				horizon,
8709				pin,
8710				watch,
8711				request,
8712				timers: self.timers.clone(),
8713			},
8714			self.tasks.clone(),
8715		));
8716		kio::Pending::new(
8717			Lookup::queued(consumer, held)
8718				.with_path(requested)
8719				.with_stats(scope)
8720				.with_identity(identity.cloned()),
8721		)
8722	}
8723
8724	/// Returns the prefix that is automatically stripped from all paths.
8725	pub fn root(&self) -> &Path {
8726		&self.root
8727	}
8728
8729	/// The prefixes this consumer may reach, relative to its root.
8730	pub fn allowed(&self) -> Prefixes {
8731		self.scope.relative(&self.root)
8732	}
8733
8734	/// Converts a relative path to an absolute path.
8735	pub fn absolute(&self, path: impl TryInto<Path, Error: Into<Error>>) -> Result<Path, Error> {
8736		Ok(self.root.join(&path::convert(path)?)?)
8737	}
8738}
8739
8740/// Receives every route change for a scope, for relays and stats.
8741///
8742/// Created by [`Consumer::routes`].
8743/// Drop to unregister.
8744pub struct Routes {
8745	// One registration per table cursor feeding `state`: more than one when the
8746	// consumer reads through a mount.
8747	ids: Vec<ConsumerId>,
8748	shared: SendCell<kio::Shared<OriginState>>,
8749	root: Path,
8750
8751	// Pending updates queued for this cursor. Coalesced so a slow consumer
8752	// can't accumulate redundant announce/retract pairs.
8753	state: kio::Producer<OriginConsumerState>,
8754
8755	// Egress stats context (empty for an untagged stream). Announce events drive the
8756	// per-prefix announce guards below.
8757	stats: stats::Session,
8758
8759	// Live egress announce guards, keyed by absolute prefix. An announce
8760	// opens one (bumping `announces_started` + `announced_bytes`); the matching retraction
8761	// drops it (bumping `announces_ended` + `announced_bytes`).
8762	guards: HashMap<Path, stats::Announce>,
8763
8764	// Holds the waiter a `Stream` poll registered; disjoint from `state` so the
8765	// borrow never collides with the body's.
8766	#[cfg(feature = "async")]
8767	park: kio::Park,
8768
8769	// Held updates (see [`Config::update_hold`]): the hold, the clock it counts
8770	// on, and the timer that wakes the next.
8771	update_hold: Duration,
8772	// Quarantines by prefix, and their retractions in clock order: first waiting
8773	// for a fresh reading (by the stale one), then quarantined (by when each ends).
8774	retracted: HashMap<Path, Quarantine>,
8775	anchoring: VecDeque<(Instant, Path)>,
8776	expiring: VecDeque<(Instant, Path)>,
8777	timers: Deadlines,
8778	hold: crate::time::Deadline,
8779}
8780
8781impl Routes {
8782	#[cfg(test)]
8783	async fn expect_next(&mut self) -> RouteEvent {
8784		#[cfg(feature = "async")]
8785		{
8786			return kio::wait(|waiter| self.poll_next(waiter)).await.expect("no next");
8787		}
8788		#[cfg(not(feature = "async"))]
8789		{
8790			kio::wait(|waiter| self.poll_next(waiter))
8791				.now_or_never()
8792				.expect("next should not block")
8793				.expect("no next")
8794		}
8795	}
8796
8797	#[cfg(test)]
8798	pub(crate) async fn expect_next_active(
8799		&mut self,
8800		expected: impl TryInto<Path, Error: std::fmt::Debug>,
8801	) -> RouteInfo {
8802		let event = self.expect_next().await;
8803		Self::active(event, &expected.try_into().expect("expected path"))
8804	}
8805
8806	#[cfg(test)]
8807	pub(crate) async fn expect_next_restarted(
8808		&mut self,
8809		expected: impl TryInto<Path, Error: std::fmt::Debug>,
8810	) -> RouteInfo {
8811		match self.expect_next().await {
8812			RouteEvent {
8813				kind: RouteKind::Restart,
8814				announce,
8815			} => {
8816				assert_eq!(
8817					announce.prefix,
8818					expected.try_into().expect("expected path"),
8819					"wrong prefix"
8820				);
8821				announce.route
8822			}
8823			other => panic!("should be a restart: got {other:?}"),
8824		}
8825	}
8826
8827	#[cfg(test)]
8828	pub(crate) async fn expect_next_ended(&mut self, expected: impl TryInto<Path, Error: std::fmt::Debug>) {
8829		match self.expect_next().await {
8830			RouteEvent {
8831				kind: RouteKind::End,
8832				announce,
8833			} => assert_eq!(
8834				announce.prefix,
8835				expected.try_into().expect("expected path"),
8836				"wrong prefix"
8837			),
8838			other => panic!("should be a retraction: got {other:?}"),
8839		}
8840	}
8841
8842	#[cfg(test)]
8843	pub(crate) async fn expect_next_offline(&mut self, expected: impl TryInto<Path, Error: std::fmt::Debug>) {
8844		match self.expect_next().await {
8845			RouteEvent {
8846				kind: RouteKind::Offline,
8847				announce,
8848			} => assert_eq!(
8849				announce.prefix,
8850				expected.try_into().expect("expected path"),
8851				"wrong prefix"
8852			),
8853			other => panic!("should go offline: got {other:?}"),
8854		}
8855	}
8856
8857	fn new(
8858		root: Path,
8859		cursors: Vec<TableCursor>,
8860		state: kio::Producer<OriginConsumerState>,
8861		stats: stats::Session,
8862		shared: &SendCell<kio::Shared<OriginState>>,
8863		timers: Deadlines,
8864	) -> Self {
8865		let mut ids = Vec::with_capacity(cursors.len());
8866		let update_hold;
8867		{
8868			let mut table = shared.lock();
8869			update_hold = table.update_hold;
8870			if table.closed {
8871				// A cursor on a dead origin is born ended.
8872				if let Ok(mut state) = state.write() {
8873					state.ended = true;
8874				}
8875			} else {
8876				for cursor in cursors {
8877					let id = ConsumerId::new();
8878					table.register_cursor(shared, id, cursor);
8879					ids.push(id);
8880				}
8881			}
8882			// Under the table lock, so no snapshot lands between the count and this.
8883			if let Ok(mut state) = state.write()
8884				&& state.waiting.load(Ordering::Relaxed) == 0
8885			{
8886				state.owe();
8887			}
8888		}
8889
8890		Self {
8891			ids,
8892			shared: shared.clone(),
8893			root,
8894			state,
8895			stats,
8896			guards: HashMap::new(),
8897			#[cfg(feature = "async")]
8898			park: kio::Park::default(),
8899			update_hold,
8900			retracted: HashMap::new(),
8901			anchoring: VecDeque::new(),
8902			expiring: VecDeque::new(),
8903			hold: crate::time::Deadline::new(&timers),
8904			timers,
8905		}
8906	}
8907
8908	/// Start a retraction's quarantine, a [`lite06_churn`] mitigation. A delivered
8909	/// announcement leaves it to expire: later ones for the prefix are updates, which it
8910	/// never holds.
8911	fn quarantine(&mut self, event: &RouteEvent, now: Instant) {
8912		let RouteEvent {
8913			kind: RouteKind::End | RouteKind::Offline,
8914			announce: update,
8915		} = event
8916		else {
8917			return;
8918		};
8919		if self.update_hold.is_zero() || !lite06_churn::hunts(&update.route.hops, update.route.node) {
8920			return;
8921		}
8922		// An anonymous route names no publisher, so its quarantine holds nothing.
8923		let publisher = lite06_churn::publisher(&update.route.hops);
8924		// The reading may be stale; [`Self::settle`] starts the quarantine on a fresh one.
8925		let quarantine = Quarantine {
8926			held: Held::Anchoring(now),
8927			publisher,
8928			identity: (
8929				update
8930					.route
8931					.identity
8932					.clone()
8933					.expect("a delivered route has an identity"),
8934				update.route.epoch,
8935			),
8936			rank: (update.route.cost, update.route.hops.len()),
8937		};
8938		let replaced = self.retracted.insert(update.prefix.clone(), quarantine);
8939		// Lite-06 churn (see [`lite06_churn`]): a prefix retracted again at the same
8940		// reading is already queued, so churn between clock readings can't grow the queue
8941		// past one entry per prefix.
8942		if !replaced.is_some_and(|q| q.held == Held::Anchoring(now)) {
8943			self.anchoring.push_back((now, update.prefix.clone()));
8944		}
8945	}
8946
8947	/// Start the quarantines of retractions the clock has since moved past, and
8948	/// forget ended ones. Returns when to wake to read the clock again, if any remain.
8949	fn settle(&mut self, now: Instant) -> Option<Instant> {
8950		// Both queues are in clock order, so only their fronts can be due. An entry
8951		// whose prefix was since announced or retracted again no longer matches.
8952		while let Some((seen, prefix)) = self.anchoring.front() {
8953			if *seen >= now {
8954				break;
8955			}
8956			if let Some(quarantine) = self.retracted.get_mut(prefix)
8957				&& quarantine.held == Held::Anchoring(*seen)
8958			{
8959				quarantine.held = Held::Until(now.saturating_add(RETRACT_QUARANTINE));
8960				self.expiring
8961					.push_back((now.saturating_add(RETRACT_QUARANTINE), prefix.clone()));
8962			}
8963			self.anchoring.pop_front();
8964		}
8965		while let Some((until, prefix)) = self.expiring.front() {
8966			if *until > now {
8967				break;
8968			}
8969			if self
8970				.retracted
8971				.get(prefix)
8972				.is_some_and(|q| q.held == Held::Until(*until))
8973			{
8974				self.retracted.remove(prefix);
8975			}
8976			self.expiring.pop_front();
8977		}
8978		let anchoring = self
8979			.anchoring
8980			.front()
8981			.map(|(seen, _)| seen.saturating_add(Duration::from_nanos(1)));
8982		earliest(anchoring, self.expiring.front().map(|(until, _)| *until))
8983	}
8984
8985	/// Drive the egress announce guards for one update.
8986	fn hand_out(&mut self, event: RouteEvent) -> RouteEvent {
8987		match &event {
8988			RouteEvent {
8989				kind: RouteKind::Start | RouteKind::Update | RouteKind::Restart,
8990				announce,
8991			} => {
8992				let scope = self.stats.egress(self.root.rejoin(&announce.prefix));
8993				self.guards
8994					.entry(announce.prefix.clone())
8995					.or_insert_with(|| scope.announce());
8996			}
8997			RouteEvent {
8998				kind: RouteKind::End | RouteKind::Offline,
8999				announce,
9000			} => {
9001				self.guards.remove(&announce.prefix);
9002			}
9003		}
9004		event
9005	}
9006
9007	/// The next route announcement, update, or retraction, its prefix relative to
9008	/// this cursor's root, or `None` once the cursor is closed.
9009	///
9010	/// A retraction is only delivered for a previously announced prefix, and a
9011	/// repeated announcement for the same prefix is a metadata update. With the
9012	/// `async` feature, the consumer is also a `futures::Stream` of the same events.
9013	#[cfg_attr(feature = "async", kio::wrapper)]
9014	pub fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<Option<RouteEvent>> {
9015		loop {
9016			let now = self.timers.now();
9017			let settling = self.settle(now);
9018			let mut wake = None;
9019			// Decided without touching the queue: parking what it holds back is a write,
9020			// which would wake whoever waits on it, this poll included.
9021			let mut state = match self.state.poll(waiter, |state| match state.due(now) {
9022				true => Poll::Ready(()),
9023				false => {
9024					wake = state.wake();
9025					Poll::Pending
9026				}
9027			}) {
9028				Poll::Ready(Ok(state)) => state,
9029				// Closed: discard the Ref so its MutexGuard doesn't escape this call.
9030				Poll::Ready(Err(_)) => return Poll::Ready(None),
9031				Poll::Pending => {
9032					self.hold.set(earliest(wake, settling));
9033					ready!(self.hold.poll(waiter));
9034					continue;
9035				}
9036			};
9037			if state.pending.is_empty() {
9038				// Ended by the origin's teardown, pending updates already drained; close
9039				// the channel so every closure signal agrees.
9040				state.close();
9041				return Poll::Ready(None);
9042			}
9043			// Whatever was due may all be held, parked until a later poll.
9044			let Ok(prefix) = state.scan(&self.retracted, now, self.update_hold) else {
9045				continue;
9046			};
9047			let event = state.take_prefix(prefix);
9048			drop(state);
9049			self.quarantine(&event, now);
9050			return Poll::Ready(Some(self.hand_out(event)));
9051		}
9052	}
9053
9054	/// Returns the next event without blocking.
9055	///
9056	/// Returns None if there is no event available; NOT because the cursor is closed.
9057	/// Use [`Self::is_closed`] to check if the cursor is closed.
9058	pub fn try_next(&mut self) -> Option<RouteEvent> {
9059		let now = self.timers.now();
9060		let settling = self.settle(now);
9061		// Read first, so a call with nothing due writes nothing; see `poll_next`.
9062		let idle = {
9063			let state = self.state.read();
9064			(!state.due(now) || state.pending.is_empty()).then(|| state.wake())
9065		};
9066		let scanned = match idle {
9067			Some(wake) => Err(wake),
9068			None => {
9069				let mut state = self.state.write().ok()?;
9070				state
9071					.scan(&self.retracted, now, self.update_hold)
9072					.map(|prefix| state.take_prefix(prefix))
9073			}
9074		};
9075		let event = match scanned {
9076			Ok(event) => event,
9077			Err(wake) => {
9078				// Arm the hold even though nothing polls it: the armed timer wakes the
9079				// driver, so its clock reaches the deadline for a later call to see.
9080				self.hold.set(earliest(wake, settling));
9081				return None;
9082			}
9083		};
9084		self.quarantine(&event, now);
9085		Some(self.hand_out(event))
9086	}
9087
9088	/// Returns true if the cursor is closed (no more updates will arrive).
9089	pub fn is_closed(&self) -> bool {
9090		let state = self.state.read();
9091		state.is_closed() || state.ended
9092	}
9093
9094	/// Whether this consumer has synced; see [`Self::poll_synced`].
9095	#[cfg(test)]
9096	pub(crate) fn is_synced(&self) -> bool {
9097		let state = self.state.read();
9098		state.is_closed() || state.synced()
9099	}
9100
9101	/// Wait until this consumer has synced with what its sources announced.
9102	///
9103	/// Synced means every session feeding this scope has delivered its peer's
9104	/// announcements as of when it answered, and this consumer has read every event
9105	/// queued before then. A prefix not announced by then is not announced, rather
9106	/// than not heard yet. A session joining the scope later, such as a reconnect,
9107	/// takes this back until it syncs too; routes published on this origin
9108	/// itself never wait. On moq-lite-07 a session syncs only once this origin
9109	/// shows every claim its peer sent.
9110	///
9111	/// Synced is relative to the session's peer, never global: a relay answers with
9112	/// what it holds without waiting on its own upstreams. Versions that cannot mark
9113	/// the boundary (moq-lite-03/04, and moq-transport without MoQ Active Count) catch
9114	/// up once the peer accepts the request, or once it is sent when nothing answers.
9115	///
9116	/// Level-triggered: ready whenever synced, and once the cursor is closed.
9117	pub fn poll_synced(&self, waiter: &kio::Waiter) -> Poll<()> {
9118		self.state
9119			.poll(waiter, |state| match state.synced() {
9120				true => Poll::Ready(()),
9121				false => Poll::Pending,
9122			})
9123			.map(|_| ())
9124	}
9125
9126	// The wire sender uses this only to bound its initial replay.
9127	#[cfg(feature = "async")]
9128	pub(crate) fn pending_len(&self) -> usize {
9129		self.state.read().pending.len()
9130	}
9131
9132	// A wider wire grant must reuse pending slots, rather than bypass the initial queue.
9133	#[cfg(feature = "async")]
9134	pub(crate) fn replay<'a>(&mut self, advertised: impl IntoIterator<Item = &'a Path>, revoked: &HashSet<Path>) {
9135		let advertised: HashSet<_> = advertised.into_iter().collect();
9136		let table = self.shared.lock();
9137		let Ok(mut state) = self.state.write() else {
9138			return;
9139		};
9140		for id in &self.ids {
9141			let Some(cursor) = table.cursors.get(id) else {
9142				continue;
9143			};
9144			for (presented, CursorRoute { meta, .. }) in &cursor.current {
9145				let prefix = cursor.under.rejoin(presented);
9146				if revoked.contains(&prefix) {
9147					state.apply_unannounce(prefix, meta.clone(), Gone::End);
9148					continue;
9149				}
9150				if advertised.contains(&prefix) {
9151					if state.pending.get(&prefix).is_some_and(|pending| {
9152						matches!(
9153							pending.update,
9154							Some(PendingUpdate::Unannounce(..) | PendingUpdate::UnannounceAnnounce { .. })
9155						)
9156					}) {
9157						state.apply_announce(prefix, meta.clone());
9158					}
9159					continue;
9160				}
9161				// The wire never sent this route, so it is a fresh start without a hold.
9162				state.delivered.remove(&prefix);
9163				self.retracted.remove(&prefix);
9164				state.put(prefix, PendingUpdate::Announce(meta.clone()));
9165			}
9166		}
9167	}
9168
9169	/// Returns the root that is automatically stripped from emitted prefixes.
9170	pub fn root(&self) -> &Path {
9171		&self.root
9172	}
9173
9174	/// Converts an emitted prefix back to one rooted at the origin.
9175	pub fn absolute(&self, prefix: impl TryInto<Path, Error: Into<Error>>) -> Result<Path, Error> {
9176		Ok(self.root.join(&path::convert(prefix)?)?)
9177	}
9178}
9179
9180#[cfg(feature = "async")]
9181impl futures::Stream for Routes {
9182	type Item = RouteEvent;
9183
9184	fn poll_next(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Option<Self::Item>> {
9185		let this = self.get_mut();
9186		let waiter = this.park.hold(cx).clone();
9187		this.poll_next(&waiter)
9188	}
9189}
9190
9191impl Drop for Routes {
9192	fn drop(&mut self) {
9193		let mut state = self.shared.lock();
9194		for id in &self.ids {
9195			if let Some(cursor) = state.cursors.remove(id) {
9196				for head in &cursor.heads {
9197					state.routes.remove_cursor(head, *id);
9198					if cursor.interested {
9199						state.remove_interest(&self.shared, head);
9200					}
9201				}
9202			}
9203		}
9204	}
9205}
9206
9207#[cfg(test)]
9208use futures::FutureExt;
9209
9210#[cfg(test)]
9211#[expect(missing_docs, reason = "test-only assertion helpers")]
9212impl Routes {
9213	/// The route of an active event at `expected`.
9214	fn active(event: RouteEvent, expected: &Path) -> RouteInfo {
9215		match event {
9216			RouteEvent {
9217				kind: RouteKind::Start | RouteKind::Update | RouteKind::Restart,
9218				announce,
9219			} => {
9220				assert_eq!(announce.prefix, *expected, "wrong prefix");
9221				announce.route
9222			}
9223			other => panic!("should be an active route: got {other:?}"),
9224		}
9225	}
9226
9227	/// The next update must be an active route at `expected`; returns it.
9228	pub fn assert_next_active(&mut self, expected: impl TryInto<Path, Error: std::fmt::Debug>) -> RouteInfo {
9229		let event = kio::wait(|waiter| self.poll_next(waiter))
9230			.now_or_never()
9231			.expect("next blocked")
9232			.expect("no next");
9233		Self::active(event, &expected.try_into().expect("expected path"))
9234	}
9235
9236	/// The `try_next` counterpart of [`Self::assert_next_active`].
9237	pub fn assert_try_next_active(&mut self, expected: impl TryInto<Path, Error: std::fmt::Debug>) -> RouteInfo {
9238		let event = self.try_next().expect("no next");
9239		Self::active(event, &expected.try_into().expect("expected path"))
9240	}
9241
9242	/// The next update must be a restart at `expected`; returns its route.
9243	pub fn assert_next_restarted(&mut self, expected: impl TryInto<Path, Error: std::fmt::Debug>) -> RouteInfo {
9244		match kio::wait(|waiter| self.poll_next(waiter))
9245			.now_or_never()
9246			.expect("next blocked")
9247			.expect("no next")
9248		{
9249			RouteEvent {
9250				kind: RouteKind::Restart,
9251				announce,
9252			} => {
9253				assert_eq!(
9254					announce.prefix,
9255					expected.try_into().expect("expected path"),
9256					"wrong prefix"
9257				);
9258				announce.route
9259			}
9260			other => panic!("should be a restart: got {other:?}"),
9261		}
9262	}
9263
9264	/// The next update must be a retraction at `expected`.
9265	pub fn assert_next_ended(&mut self, expected: impl TryInto<Path, Error: std::fmt::Debug>) {
9266		self.assert_next_gone(RouteKind::End, expected);
9267	}
9268
9269	fn assert_next_gone(&mut self, kind: RouteKind, expected: impl TryInto<Path, Error: std::fmt::Debug>) {
9270		match kio::wait(|waiter| self.poll_next(waiter))
9271			.now_or_never()
9272			.expect("next blocked")
9273			.expect("no next")
9274		{
9275			RouteEvent { kind: got, announce } if got == kind => assert_eq!(
9276				announce.prefix,
9277				expected.try_into().expect("expected path"),
9278				"wrong prefix"
9279			),
9280			other => panic!("should be {kind:?}: got {other:?}"),
9281		}
9282	}
9283
9284	pub fn assert_next_wait(&mut self) {
9285		if let Some(event) = kio::wait(|waiter| self.poll_next(waiter)).now_or_never() {
9286			panic!("next should block: got {event:?}");
9287		}
9288	}
9289}
9290
9291/// Test-only construction shorthand: build the producer and spawn its driver on
9292/// the test executor, mirroring what `moq_tokio::origin::spawn` does for
9293/// applications.
9294#[cfg(test)]
9295pub(crate) trait ProduceTest {
9296	fn produce(self) -> Producer;
9297}
9298
9299#[cfg(test)]
9300impl ProduceTest for Config {
9301	fn produce(self) -> Producer {
9302		#[cfg(not(feature = "async"))]
9303		let self_ = Self {
9304			update_hold: Duration::ZERO,
9305			..self
9306		};
9307		#[cfg(feature = "async")]
9308		let self_ = self;
9309		let (producer, driver) = Producer::new(self_);
9310		#[cfg(feature = "async")]
9311		if kio::clock::sim::is_running() {
9312			kio::clock::sim::spawn(crate::time::run(driver));
9313			return producer;
9314		}
9315		{
9316			// A sync test: nothing polls the driver, and dropping it would tear
9317			// the origin down, so leak it and rely on the synchronous half.
9318			std::mem::forget(driver);
9319		}
9320		producer
9321	}
9322}
9323
9324#[cfg(test)]
9325impl ProduceTest for Hop {
9326	fn produce(self) -> Producer {
9327		Config::from(self).produce()
9328	}
9329}
9330
9331/// Test-only: an origin's config for a local hop.
9332#[cfg(test)]
9333impl From<Hop> for Config {
9334	fn from(hop: Hop) -> Self {
9335		Self::new(NonZeroU64::new(hop.id).expect("a local hop is non-zero"))
9336	}
9337}
9338
9339/// Test-only: one peer's route selected for `room/a`, which a test withdraws or
9340/// replaces to drive the [`broadcast::RequestValidity`](crate::model::broadcast::RequestValidity)
9341/// it hands out.
9342#[cfg(all(test, feature = "async"))]
9343pub(crate) struct TestSelection {
9344	origin: Producer,
9345	route: Option<Claim>,
9346	replacement: Option<Claim>,
9347}
9348
9349#[cfg(all(test, feature = "async"))]
9350impl TestSelection {
9351	const PEER: u64 = 2;
9352
9353	pub(crate) fn new() -> Self {
9354		let origin = Hop::new(1).unwrap().produce();
9355		let route = origin
9356			.forward("room", RouteInfo::new().with_via(Hop::new(Self::PEER).unwrap()))
9357			.unwrap();
9358		Self {
9359			origin,
9360			route: Some(route),
9361			replacement: None,
9362		}
9363	}
9364
9365	/// What a request for `room/a` through the selected route must still hold.
9366	pub(crate) fn validity(&self) -> crate::model::broadcast::RequestValidity {
9367		crate::model::broadcast::RequestValidity::for_source(self.route.as_ref().unwrap(), &Path::from_static("room/a"))
9368	}
9369
9370	/// The peer withdraws the route.
9371	pub(crate) fn withdraw(&mut self) {
9372		self.route = None;
9373	}
9374
9375	/// Another identity of the peer takes the path.
9376	pub(crate) fn replace(&mut self) {
9377		let route = RouteInfo::new().with_via(Hop::new(Self::PEER).unwrap());
9378		self.replacement = Some(self.origin.forward("room/a", route).unwrap());
9379	}
9380}
9381
9382#[cfg(test)]
9383mod tests {
9384	use super::*;
9385	use crate::frame::Frame;
9386
9387	#[test]
9388	fn max_hops_caps_at_the_wire_bound() {
9389		assert_eq!(Config::default().max_hops.get(), MAX_HOPS);
9390		for (max, effective) in [(1, 1), (6, 6), (32, 32), (33, 32), (usize::MAX, 32)] {
9391			let config = Config {
9392				max_hops: NonZeroUsize::new(max).unwrap(),
9393				..Default::default()
9394			};
9395			let (producer, _driver) = Producer::new(config);
9396			let scoped = producer.scope("room", &Prefixes::all()).unwrap();
9397			assert_eq!(scoped.config().max_hops.get(), effective);
9398			assert_eq!(
9399				scoped.consume().forwardable().horizon.max_hops.map(NonZeroUsize::get),
9400				Some(effective)
9401			);
9402		}
9403	}
9404	#[cfg(feature = "async")]
9405	use crate::test_tracing::count_drop_warnings;
9406	use futures::FutureExt;
9407	use std::sync::atomic::AtomicBool;
9408
9409	fn origin(id: u64) -> Hop {
9410		Hop::new(id).unwrap()
9411	}
9412
9413	/// One publisher identity, shared by every route in a test that resumes across them.
9414	fn identity() -> crate::Identity {
9415		"01900000-0000-7000-8000-000000000001".parse().unwrap()
9416	}
9417
9418	/// A session of `node` whose peer forwards nothing and asked for every claim.
9419	fn route_stream(node: &crate::route::Node) -> crate::route::node::Stream {
9420		use crate::route::relay;
9421		let port = relay::Port {
9422			cost: 1,
9423			priority: 0,
9424			upstream: false,
9425			role: relay::Role::Scoped(Vec::new()),
9426		};
9427		let stream = node.connect(1, port).unwrap();
9428		let ask = relay::Edit {
9429			remove: Vec::new(),
9430			add: vec![Path::empty()],
9431		};
9432		stream.recv(relay::Msg::Ask(ask)).unwrap();
9433		stream.flush();
9434		stream
9435	}
9436
9437	/// The claims `stream` has queued for its peer: each path, and whether it is live.
9438	fn route_changes(stream: &crate::route::node::Stream) -> Vec<(Path, bool)> {
9439		use crate::route::relay;
9440		std::iter::from_fn(|| stream.try_wire())
9441			.filter_map(|msg| match msg {
9442				relay::Msg::Announce { changes } => Some(changes),
9443				_ => None,
9444			})
9445			.flatten()
9446			.map(|((path, _), change)| (path, matches!(change, relay::Change::Live(_))))
9447			.collect()
9448	}
9449
9450	/// The forwarding node of the relay `relay`.
9451	fn node_id(relay: u64) -> crate::route::NodeId {
9452		crate::route::NodeId { relay, marked: false }
9453	}
9454
9455	fn hops(ids: &[u64]) -> Hops {
9456		let mut list = Hops::new();
9457		for &id in ids {
9458			list.push(if id == 0 { Hop::UNKNOWN } else { origin(id) }).unwrap();
9459		}
9460		list
9461	}
9462
9463	/// The scope granting these prefixes: each spelled as its subtree pattern.
9464	fn scopes(prefixes: &[&str]) -> Prefixes {
9465		prefixes
9466			.iter()
9467			.map(|prefix| crate::Prefix::try_from(*prefix).unwrap())
9468			.collect()
9469	}
9470
9471	/// A track whose outcome is already an error still serves its finished history through
9472	/// a front: learning the info and the outcome in one driver poll must not refuse it.
9473	#[test]
9474	fn an_errored_copy_serves_history_before_its_outcome() {
9475		let now = Instant::ZERO;
9476		let waiter = kio::Waiter::noop();
9477		let (producer, mut driver) = Producer::new(Config::from(origin(1)));
9478		let server = producer
9479			.forward("room", RouteInfo::new().with_hops(hops(&[10])))
9480			.unwrap();
9481		let broadcast = broadcast::Info::new().produce();
9482		let track = broadcast.reserve_track("video").unwrap();
9483
9484		let mut requesting = producer.consume().request("room", None);
9485		driver.poll(now, &waiter).unwrap();
9486		let Poll::Ready(Some(request)) = server.poll_requested(&waiter) else {
9487			panic!("the route receives the request");
9488		};
9489		request.serve(&broadcast);
9490		driver.poll(now, &waiter).unwrap();
9491		let Poll::Ready(Ok(remote)) = requesting.poll_ok(&waiter) else {
9492			panic!("the broadcast resolves");
9493		};
9494		let subscribing = remote.track("video").unwrap().subscribe(None);
9495		driver.poll(now, &waiter).unwrap();
9496		assert!(subscribing.poll_ok(&waiter).is_pending());
9497
9498		// The query is already in flight when metadata and the abort arrive together.
9499		let track = track.accept(track::Info::timed());
9500		let mut group = track.append_next().unwrap();
9501		group
9502			.write_frame(Frame::new(group.key_time(), b"history".as_ref()))
9503			.unwrap();
9504		group.finish().unwrap();
9505		track.abort(Error::App(7)).unwrap();
9506		driver.poll(now, &waiter).unwrap();
9507		let Poll::Ready(Ok(mut subscriber)) = subscribing.poll_ok(&waiter) else {
9508			panic!("the errored copy's info resolves");
9509		};
9510		let Poll::Ready(Ok(Some(mut group))) = subscriber.poll_recv_group(&waiter) else {
9511			panic!("the finished history is still readable");
9512		};
9513		let Poll::Ready(Ok(Some(frame))) = group.poll_read_frame(&waiter) else {
9514			panic!("the history's frame is still readable");
9515		};
9516		assert_eq!(frame.payload.as_ref(), b"history");
9517		assert!(matches!(
9518			subscriber.poll_recv_group(&waiter),
9519			Poll::Ready(Err(Error::App(7)))
9520		));
9521	}
9522
9523	/// Ending a logical track must finish its metadata producer as well as its routes,
9524	/// without losing the source's final group or warning about an unfinished writer.
9525	#[kio::test]
9526	#[cfg(feature = "async")]
9527	async fn a_finished_logical_track_does_not_warn() {
9528		let warns = count_drop_warnings("track::Producer dropped without finish", || {
9529			let broadcast = Arc::new(broadcast::Info::default());
9530			let source = track::Producer::new(broadcast.clone(), "catalog.json", crate::track::Info::timed());
9531			let mut group = source.create_empty(7u64.into()).unwrap();
9532			group
9533				.write_frame(Frame::new(group.key_time(), b"snapshot".as_ref()))
9534				.unwrap();
9535			group.finish().unwrap();
9536			let source = source.finish().unwrap();
9537
9538			let routes = crate::model::resume::Producer::new();
9539			routes.serve(source.consume());
9540			let request = track::Request::new(broadcast, "catalog.json");
9541			let consumer = request.consume();
9542			let weak = request.weak();
9543			let accepted = request.routes(routes.consume()).accept(None);
9544			let mut io = TrackIo {
9545				ready: crate::util::QueueWake::new("catalog.json".into(), kio::Queue::new()),
9546				park: Default::default(),
9547				logical: Logical::Accepted(accepted),
9548
9549				weak,
9550				routes,
9551				query: None,
9552				staged: None,
9553				copy: None,
9554				held: None,
9555				wanted: true,
9556			};
9557			let mut subscriber = consumer.subscribe(None).now_or_never().unwrap().unwrap();
9558			io.end(Ok(()), None);
9559
9560			let mut group = subscriber.recv_group().now_or_never().unwrap().unwrap().unwrap();
9561			assert_eq!(group.start, 7);
9562			let frame = group.read_frame().now_or_never().unwrap().unwrap().unwrap();
9563			assert_eq!(frame.payload.as_ref(), b"snapshot");
9564			assert!(subscriber.recv_group().now_or_never().unwrap().unwrap().is_none());
9565		});
9566		assert_eq!(warns, 0, "a clean logical end must not drop an unfinished producer");
9567	}
9568
9569	/// A torn-down origin ends the logical tracks its fronts were serving, rather than warn about
9570	/// producers dropped unfinished.
9571	#[kio::test]
9572	#[cfg(feature = "async")]
9573	async fn teardown_ends_the_logical_tracks() {
9574		let (producer, mut driver) = Producer::new(Config::from(origin(1)));
9575		let consumer = producer.consume();
9576		let source = producer.route("room", RouteOptions::default()).unwrap();
9577		let _source_track = source.broadcast().create_track("video", None).unwrap();
9578		let waiter = kio::Waiter::noop();
9579
9580		// The driver runs the front that answers each of these.
9581		let mut request = Box::pin(consumer.request("room", None));
9582		let front = loop {
9583			driver.poll(kio::clock::now(), &waiter).unwrap();
9584			if let Some(front) = request.as_mut().now_or_never() {
9585				break front.unwrap();
9586			}
9587			kio::clock::sim::yield_now().await;
9588		};
9589		let track = front.track("video").unwrap();
9590		let mut subscribing = Box::pin(track.subscribe(None));
9591		let subscriber = loop {
9592			driver.poll(kio::clock::now(), &waiter).unwrap();
9593			if let Some(subscriber) = subscribing.as_mut().now_or_never() {
9594				break subscriber.unwrap();
9595			}
9596			kio::clock::sim::yield_now().await;
9597		};
9598
9599		let warns = count_drop_warnings("track::Producer dropped without finish", || drop(driver));
9600		assert_eq!(warns, 0, "a torn-down front must not drop an unfinished track");
9601		drop(subscriber);
9602	}
9603
9604	#[kio::test]
9605	async fn default_config_mints_a_real_hop() {
9606		let config = Config::default();
9607		let (producer, _driver) = Producer::new(config.clone());
9608		assert!(
9609			producer.node().get() < 1 << 53,
9610			"older JS clients decode it as a number"
9611		);
9612		assert_eq!(producer.consume().node(), producer.node());
9613		// One config, or the config an origin reports, builds a new node each time: a
9614		// Relay ID names one run.
9615		let (again, _driver) = Producer::new(config);
9616		let (rebuilt, _driver) = Producer::new(producer.config());
9617		assert_ne!(again.node(), producer.node());
9618		assert_ne!(rebuilt.node(), producer.node());
9619	}
9620
9621	#[kio::test]
9622	async fn random_hops_fit_legacy_lite_clients() {
9623		for _ in 0..32 {
9624			assert!(Hop::random().id() < 1u64 << 53);
9625		}
9626	}
9627
9628	/// Yield to the driver until `check` passes, bounded so a bug fails instead
9629	/// of hanging.
9630	#[cfg(feature = "async")]
9631	async fn settle(mut check: impl FnMut() -> bool) {
9632		for _ in 0..100 {
9633			if check() {
9634				return;
9635			}
9636			kio::clock::sim::yield_now().await;
9637		}
9638		panic!("condition never settled");
9639	}
9640
9641	/// Yield to the driver until the server's front watcher delivers a request.
9642	#[cfg(feature = "async")]
9643	async fn queued(server: &Claim) -> Request {
9644		let mut request = None;
9645		settle(|| match server.poll_requested(&kio::Waiter::noop()) {
9646			Poll::Ready(Some(popped)) => {
9647				request = Some(popped);
9648				true
9649			}
9650			_ => false,
9651		})
9652		.await;
9653		request.unwrap()
9654	}
9655
9656	/// Yield to the driver until the subscription has its next group or its end.
9657	#[cfg(feature = "async")]
9658	async fn next_group(subscription: &mut crate::track::Subscriber) -> Result<Option<crate::group::Consumer>, Error> {
9659		let mut next = None;
9660		settle(|| match subscription.poll_recv_group(&kio::Waiter::noop()) {
9661			Poll::Ready(result) => {
9662				next = Some(result);
9663				true
9664			}
9665			Poll::Pending => false,
9666		})
9667		.await;
9668		next.unwrap()
9669	}
9670
9671	#[kio::test]
9672	async fn announce_and_retract() {
9673		let producer = origin(1).produce();
9674		let consumer = producer.consume();
9675		let mut announced = consumer.routes();
9676		announced.assert_next_wait();
9677
9678		let announcement = producer.announce("room/alice", RouteInfo::new()).unwrap();
9679		let route = announced.expect_next_active("room/alice").await;
9680		assert!(route.hops.is_empty());
9681		assert_eq!(route.cost, Cost::default());
9682		announced.assert_next_wait();
9683
9684		drop(announcement);
9685		announced.expect_next_ended("room/alice").await;
9686		announced.assert_next_wait();
9687	}
9688
9689	/// A consumer is synced once a snapshot lands and it has read what came before.
9690	#[test]
9691	fn synced_after_the_snapshot_and_its_events() {
9692		let producer = origin(1).produce();
9693		let snapshot = producer.snapshot("room");
9694		let mut announced = producer.consume().routes();
9695		assert!(!announced.is_synced(), "a snapshot in flight holds it");
9696
9697		let _alice = producer.announce("room/alice", RouteInfo::new()).unwrap();
9698		drop(snapshot);
9699		assert!(!announced.is_synced(), "never before an earlier event is read");
9700
9701		announced.assert_next_active("room/alice");
9702		assert!(announced.is_synced());
9703
9704		// A later announcement is news, not part of what it synced with.
9705		let _bob = producer.announce("room/bob", RouteInfo::new()).unwrap();
9706		assert!(announced.is_synced());
9707	}
9708
9709	/// Without any session feeding it, a consumer syncs on its own replay.
9710	#[test]
9711	fn a_local_origin_catches_up_on_its_replay() {
9712		let producer = origin(1).produce();
9713		let mut empty = producer.consume().routes();
9714		assert!(empty.is_synced(), "nothing to wait on");
9715		empty.assert_next_wait();
9716
9717		let _alice = producer.announce("room/alice", RouteInfo::new()).unwrap();
9718		let mut announced = producer.consume().routes();
9719		assert!(!announced.is_synced(), "the replay is owed");
9720		announced.assert_next_active("room/alice");
9721		assert!(announced.is_synced());
9722	}
9723
9724	#[test]
9725	fn initial_routes_precede_live_prefixes() {
9726		let producer = origin(1).produce();
9727		let _initial = producer.announce("z/initial", RouteInfo::new()).unwrap();
9728		let mut announced = producer.consume().routes();
9729		let _live = producer.announce("a/live", RouteInfo::new()).unwrap();
9730		announced.assert_next_active("z/initial");
9731		assert!(announced.is_synced());
9732	}
9733
9734	#[test]
9735	fn stalled_initial_replay_collapses_churn_without_a_backlog() {
9736		let producer = origin(1).produce();
9737		let initial = producer.announce("z/initial", RouteInfo::new()).unwrap();
9738		let mut announced = producer.consume().routes();
9739		for i in 0..1_000 {
9740			let transient = producer.announce(format!("a/{i}"), RouteInfo::new()).unwrap();
9741			initial.update(RouteInfo::new().with_cost(i)).unwrap();
9742			drop(transient);
9743			assert_eq!(announced.state.read().pending.len(), 1);
9744		}
9745		announced.assert_next_active("z/initial");
9746		assert!(announced.is_synced());
9747		announced.assert_next_wait();
9748	}
9749
9750	/// A start and end that cancel before being read are owed nothing.
9751	#[test]
9752	fn a_cancelled_start_still_catches_up() {
9753		let producer = origin(1).produce();
9754		let snapshot = producer.snapshot("");
9755		let mut announced = producer.consume().routes();
9756
9757		let alice = producer.announce("room/alice", RouteInfo::new()).unwrap();
9758		drop(snapshot);
9759		assert!(!announced.is_synced());
9760		drop(alice);
9761		assert!(announced.is_synced(), "the pair cancelled");
9762		announced.assert_next_wait();
9763	}
9764
9765	/// A re-price of a route already read is not owed: the set of prefixes is unchanged.
9766	#[test]
9767	fn an_update_is_not_owed() {
9768		let producer = origin(1).produce();
9769		let mut announced = producer.consume().routes();
9770		let alice = producer.announce("room/alice", RouteInfo::new()).unwrap();
9771		announced.assert_next_active("room/alice");
9772
9773		let snapshot = producer.snapshot("");
9774		alice.update(RouteInfo::new().with_cost(5)).unwrap();
9775		drop(snapshot);
9776		assert!(announced.is_synced());
9777	}
9778
9779	/// A snapshot taken after syncing (a reconnect) holds it again until it lands.
9780	#[test]
9781	fn a_new_snapshot_takes_sync_back() {
9782		let producer = origin(1).produce();
9783		let announced = producer.consume().routes();
9784		assert!(announced.is_synced());
9785
9786		let snapshot = producer.snapshot("room/alice");
9787		assert!(!announced.is_synced(), "a snapshot beneath the scope holds it");
9788		let second = producer.snapshot("");
9789		drop(snapshot);
9790		assert!(!announced.is_synced(), "every current snapshot must land");
9791		drop(second);
9792		assert!(announced.is_synced());
9793	}
9794
9795	/// Only snapshots that could present on a consumer hold it.
9796	#[test]
9797	fn only_overlapping_snapshots_hold() {
9798		let producer = origin(1).produce();
9799		let room = producer.consume().scope("room", &Prefixes::all()).unwrap();
9800
9801		let other = producer.snapshot("other");
9802		assert!(room.routes().is_synced(), "a disjoint prefix");
9803
9804		let above = producer.snapshot("");
9805		let announced = room.routes();
9806		assert!(!announced.is_synced(), "a snapshot above the root covers it");
9807		drop(above);
9808		assert!(announced.is_synced());
9809
9810		drop(other);
9811
9812		// A local view never waits on a peer's routes.
9813		let _peer = producer.clone().with_link(Link::Peer).snapshot("room");
9814		assert!(producer.consume().local().routes().is_synced());
9815		assert!(!producer.consume().routes().is_synced());
9816	}
9817
9818	/// A source shadowed by a mount can present nothing on the handle, so it never holds it.
9819	#[test]
9820	fn a_shadowed_snapshot_never_holds() {
9821		let producer = origin(1).produce();
9822		let project = mounted(&producer, "p1", &[""]).with_hidden(true);
9823		let announced = project.routes();
9824		assert!(announced.is_synced());
9825
9826		let shadowed = producer.snapshot("p1/.svc");
9827		assert!(announced.is_synced(), "a snapshot in flight under the hole");
9828		assert!(project.routes().is_synced(), "a reader registering past one");
9829		drop(shadowed);
9830
9831		let _target = producer.snapshot(".svc/p1");
9832		assert!(!announced.is_synced(), "the mount's target does hold it");
9833	}
9834
9835	/// A source under a hidden segment holds only the readers that opt into hidden routes.
9836	#[test]
9837	fn a_hidden_snapshot_holds_only_hidden_readers() {
9838		let producer = origin(1).produce();
9839		let announced = producer.consume().routes();
9840		let _stats = producer.snapshot(".stats");
9841		assert!(announced.is_synced(), "a snapshot in flight under a hidden segment");
9842		assert!(producer.consume().routes().is_synced(), "a reader registering past one");
9843		assert!(!producer.consume().with_hidden(true).routes().is_synced());
9844	}
9845
9846	/// A waiter parked on syncing is woken when it does.
9847	#[test]
9848	fn catching_up_wakes_the_waiter() {
9849		struct Woken(AtomicBool);
9850		impl Wake for Woken {
9851			fn wake(self: Arc<Self>) {
9852				self.0.store(true, Ordering::SeqCst);
9853			}
9854		}
9855
9856		let producer = origin(1).produce();
9857		let snapshot = producer.snapshot("");
9858		let announced = producer.consume().routes();
9859		let woken = Arc::new(Woken(AtomicBool::new(false)));
9860		let waiter = kio::Waiter::new(std::task::Waker::from(woken.clone()));
9861		assert!(announced.poll_synced(&waiter).is_pending());
9862		drop(snapshot);
9863		assert!(woken.0.load(Ordering::SeqCst), "not woken");
9864		assert!(announced.poll_synced(&waiter).is_ready());
9865	}
9866
9867	/// A session joining or landing short of the last one wakes no parked cursor, so a
9868	/// relay's announce feeds stay idle while peers connect.
9869	#[test]
9870	fn holding_back_wakes_nobody() {
9871		struct Woken(AtomicBool);
9872		impl Wake for Woken {
9873			fn wake(self: Arc<Self>) {
9874				self.0.store(true, Ordering::SeqCst);
9875			}
9876		}
9877
9878		let producer = origin(1).produce();
9879		let mut announced = producer.consume().routes();
9880		let woken = Arc::new(Woken(AtomicBool::new(false)));
9881		let waiter = kio::Waiter::new(std::task::Waker::from(woken.clone()));
9882		assert!(announced.poll_next(&waiter).is_pending());
9883		assert!(announced.poll_synced(&waiter).is_ready());
9884
9885		let first = producer.snapshot("");
9886		let second = producer.snapshot("room");
9887		drop(first);
9888		assert!(!woken.0.load(Ordering::SeqCst), "woken while still held back");
9889		drop(second);
9890		assert!(woken.0.load(Ordering::SeqCst), "the last landing wakes");
9891	}
9892
9893	/// A `.`-prefixed segment below the requested prefix hides a route from
9894	/// discovery unless the reader opts in; one inside the prefix does not.
9895	#[kio::test]
9896	async fn hidden_routes_need_an_opt_in() {
9897		let producer = origin(1).produce();
9898		let consumer = producer.consume();
9899		let _visible = producer.announce("room/alice", RouteInfo::new()).unwrap();
9900		let _stats = producer.announce(".stats/node", RouteInfo::new()).unwrap();
9901		let _nested = producer.announce("room/.internal", RouteInfo::new()).unwrap();
9902		// Only a leading dot hides: a suffix is part of the name.
9903		let _suffix = producer.announce("room/catalog.pro", RouteInfo::new()).unwrap();
9904
9905		let mut announced = consumer.routes();
9906		announced.expect_next_active("room/alice").await;
9907		announced.expect_next_active("room/catalog.pro").await;
9908		announced.assert_next_wait();
9909
9910		let mut announced = consumer.clone().with_hidden(true).routes();
9911		announced.expect_next_active(".stats/node").await;
9912		announced.expect_next_active("room/.internal").await;
9913		announced.expect_next_active("room/alice").await;
9914		announced.expect_next_active("room/catalog.pro").await;
9915		announced.assert_next_wait();
9916
9917		// Naming the dot segment lists what is under it, by root or by pattern.
9918		let mut announced = consumer.scope(".stats", &Prefixes::all()).unwrap().routes();
9919		announced.expect_next_active("node").await;
9920		announced.assert_next_wait();
9921		let mut announced = consumer.scope("", &scopes(&["room/.internal"])).unwrap().routes();
9922		announced.expect_next_active("room/.internal").await;
9923		announced.assert_next_wait();
9924	}
9925
9926	/// Hiding narrows discovery only: an exact request resolves without an opt-in.
9927	#[kio::test]
9928	#[cfg(feature = "async")]
9929	async fn hidden_broadcast_resolves_by_path() {
9930		let producer = origin(1).produce();
9931		let consumer = producer.consume();
9932		let broadcast = producer.route(".stats/node", RouteOptions::hidden()).unwrap();
9933		broadcast.announce().unwrap();
9934
9935		consumer.routes().assert_next_wait();
9936		let resolved = consumer.request(".stats/node", None).await.expect("resolves");
9937		assert_eq!(resolved.info().path.as_str(), ".stats/node");
9938	}
9939
9940	/// An excluded subtree is neither discovered nor resolved, even under a route
9941	/// covering it, while its hidden siblings and the covering route still show.
9942	#[kio::test]
9943	#[cfg(feature = "async")]
9944	async fn exclude_hides_and_refuses_the_subtree() {
9945		let producer = origin(1).produce();
9946		let _claim = producer.announce("p1", RouteInfo::new()).unwrap();
9947		let _cam = producer.route("p1/cam", RouteOptions::default()).unwrap();
9948		let _private = producer.route("p1/.private/cam", RouteOptions::default()).unwrap();
9949		let _overlay = producer.route("p1/.pro/cam", RouteOptions::default()).unwrap();
9950		let consumer = producer
9951			.consume()
9952			.scope("p1", &Prefixes::all())
9953			.unwrap()
9954			.with_hidden(true)
9955			.exclude(".pro")
9956			.unwrap();
9957
9958		let mut announced = consumer.routes();
9959		announced.expect_next_active("").await;
9960		announced.expect_next_active(".private/cam").await;
9961		announced.expect_next_active("cam").await;
9962		announced.assert_next_wait();
9963
9964		consumer.request("cam", None).await.expect("resolves");
9965		for path in [".pro", ".pro/cam", ".pro/cam/.pro/transcode.hang"] {
9966			let refused = consumer.request(path, None).now_or_never().expect("refused at once");
9967			assert!(matches!(refused, Err(Error::Unauthorized)), "{path}");
9968			assert!(
9969				matches!(consumer.follow(path, None), Err(Error::Unauthorized)),
9970				"{path}"
9971			);
9972		}
9973		// Only whole segments: a sibling sharing the prefix text is untouched.
9974		let _sibling = producer.route("p1/.prod", RouteOptions::default()).unwrap();
9975		announced.expect_next_active(".prod").await;
9976	}
9977
9978	/// An exclusion inside a mount carves the target, and one over the mount point
9979	/// drops the mount.
9980	#[kio::test]
9981	async fn exclude_reaches_into_a_mount() {
9982		let producer = origin(1).produce();
9983		let _foo = producer.route(".svc/p1/foo", RouteOptions::default()).unwrap();
9984		let _bar = producer.route(".svc/p1/bar", RouteOptions::default()).unwrap();
9985		let _cam = producer.route("p1/cam", RouteOptions::default()).unwrap();
9986		let project = mounted(&producer, "p1", &[""]).with_hidden(true);
9987
9988		let mut announced = project.exclude(".svc/foo").unwrap().routes();
9989		announced.expect_next_active("cam").await;
9990		announced.expect_next_active(".svc/bar").await;
9991		announced.assert_next_wait();
9992
9993		let mut announced = project.exclude(".svc").unwrap().routes();
9994		announced.expect_next_active("cam").await;
9995		announced.assert_next_wait();
9996
9997		// Rooted inside the mount, the exclusion moves onto the target.
9998		let mut inside = project
9999			.scope(".svc", &Prefixes::all())
10000			.unwrap()
10001			.exclude("foo")
10002			.unwrap()
10003			.routes();
10004		inside.expect_next_active("bar").await;
10005		inside.assert_next_wait();
10006	}
10007
10008	/// A project-rooted handle reading `.svc` from the fleet-wide `.svc/<pid>`.
10009	fn mounted(producer: &Producer, pid: &str, prefixes: &[&str]) -> Consumer {
10010		producer
10011			.mount(format!("{pid}/.svc"), format!(".svc/{pid}"))
10012			.unwrap()
10013			.scope(pid, &scopes(prefixes))
10014			.unwrap()
10015			.consume()
10016	}
10017
10018	/// A request through a mount is a request for the target path: it joins the
10019	/// one front there, so the fleet-wide claim is asked once for both readers.
10020	#[kio::test]
10021	#[cfg(feature = "async")]
10022	async fn mount_resolves_on_the_target_front() {
10023		let producer = origin(1).produce();
10024		let server = producer.forward(".svc", RouteInfo::new()).unwrap();
10025		let project = mounted(&producer, "p1", &[""]);
10026
10027		let through = project.request(".svc/foo", None);
10028		let direct = producer.consume().request(".svc/p1/foo", None);
10029
10030		let request = queued(&server).await;
10031		assert_eq!(request.path().as_str(), ".svc/p1/foo");
10032		assert!(server.poll_requested(&kio::Waiter::noop()).is_pending());
10033		let source = broadcast::Info::new().produce();
10034		request.serve(&source);
10035
10036		let through = through.await.expect("resolves");
10037		let direct = direct.await.expect("resolves");
10038		assert!(through.is_clone(&direct));
10039		// Named by what the reader asked for.
10040		assert_eq!(through.info().path.as_str(), ".svc/foo");
10041	}
10042
10043	/// Routes under the target, and the claim covering it, present under the
10044	/// mount; what the origin holds at the mounted path itself does not.
10045	#[kio::test]
10046	#[cfg(feature = "async")]
10047	async fn mount_presents_target_routes_under_the_mount() {
10048		let producer = origin(1).produce();
10049		let _claim = producer.announce(".svc", RouteInfo::new()).unwrap();
10050		let foo = producer.route(".svc/p1/foo", RouteOptions::default()).unwrap();
10051		let _other = producer.route(".svc/p2/bar", RouteOptions::default()).unwrap();
10052		let _cam = producer.route("p1/cam", RouteOptions::default()).unwrap();
10053		let _shadowed = producer.route("p1/.svc/forged", RouteOptions::default()).unwrap();
10054		let project = mounted(&producer, "p1", &[""]);
10055
10056		// A dot segment hides the mount like any other.
10057		let mut announced = project.routes();
10058		announced.expect_next_active("cam").await;
10059		announced.assert_next_wait();
10060
10061		let mut announced = project.clone().with_hidden(true).covering().routes();
10062		announced.expect_next_active("cam").await;
10063		announced.expect_next_active(".svc").await;
10064		announced.expect_next_active(".svc/foo").await;
10065		announced.assert_next_wait();
10066
10067		// Rooted inside the mount, the claim covers the root itself.
10068		let mut inside = project.scope(".svc", &Prefixes::all()).unwrap().covering().routes();
10069		inside.expect_next_active("").await;
10070		inside.expect_next_active("foo").await;
10071		inside.assert_next_wait();
10072
10073		drop(foo);
10074		announced.expect_next_ended(".svc/foo").await;
10075		inside.expect_next_ended("foo").await;
10076		announced.assert_next_wait();
10077
10078		// The shadowed path never resolves: the mount answers for it.
10079		let err = project.request(".svc/forged", None).await.err().unwrap();
10080		assert!(matches!(err, Error::NotFound | Error::Unroutable), "{err:?}");
10081	}
10082
10083	/// The handle's own patterns authorize a path through the mount, named as the
10084	/// handle names it.
10085	#[kio::test]
10086	#[cfg(feature = "async")]
10087	async fn mount_authorizes_the_named_path() {
10088		let producer = origin(1).produce();
10089		let _foo = producer.route(".svc/p1/foo", RouteOptions::default()).unwrap();
10090		let _bar = producer.route(".svc/p1/bar", RouteOptions::default()).unwrap();
10091
10092		let granted = mounted(&producer, "p1", &["foo", ".svc/foo"]);
10093		granted.request(".svc/foo", None).await.expect("granted");
10094		let refused = granted
10095			.request(".svc/bar", None)
10096			.now_or_never()
10097			.expect("refused at once");
10098		assert!(matches!(refused, Err(Error::Unauthorized)));
10099		let mut announced = granted.clone().with_hidden(true).routes();
10100		announced.expect_next_active(".svc/foo").await;
10101		announced.assert_next_wait();
10102
10103		let narrower = mounted(&producer, "p1", &["foo"]);
10104		let refused = narrower
10105			.request(".svc/foo", None)
10106			.now_or_never()
10107			.expect("refused at once");
10108		assert!(matches!(refused, Err(Error::Unauthorized)));
10109		narrower.clone().with_hidden(true).routes().assert_next_wait();
10110
10111		// Another project's mount reaches its own target, never this one's.
10112		let other = mounted(&producer, "p2", &[""]);
10113		other.clone().with_hidden(true).routes().assert_next_wait();
10114		let err = other.request(".svc/foo", None).await.err().unwrap();
10115		assert!(matches!(err, Error::Unroutable));
10116	}
10117
10118	/// A target at the maximum depth still presents its exact path: nothing a scope
10119	/// covers beneath it fits there.
10120	#[kio::test]
10121	#[cfg(feature = "async")]
10122	async fn mount_keeps_a_max_depth_target() {
10123		let producer = origin(1).produce();
10124		let deep = vec!["d"; Path::MAX_PARTS].join("/");
10125		let _leaf = producer.route(deep.as_str(), RouteOptions::default()).unwrap();
10126		let project = producer
10127			.mount("p1/.svc", deep.as_str())
10128			.unwrap()
10129			.scope("p1", &Prefixes::all())
10130			.unwrap()
10131			.consume()
10132			.with_hidden(true);
10133
10134		let mut announced = project.routes();
10135		announced.expect_next_active(".svc").await;
10136		announced.assert_next_wait();
10137
10138		// Beneath the mount the target has no room: refused, never handed to a route.
10139		let err = project.request(".svc/x", None).await.err().unwrap();
10140		assert!(matches!(err, Error::BoundsExceeded(_)), "{err:?}");
10141		let inside = project.scope(".svc/x", &Prefixes::all()).unwrap();
10142		inside.routes().assert_next_wait();
10143	}
10144
10145	/// A mount point deeper than its target never presents a route whose name
10146	/// through the mount is past the depth limit, and a mount point past it is refused.
10147	#[kio::test]
10148	async fn mount_bounds_the_named_path() {
10149		let producer = origin(1).produce();
10150		let _near = producer.route("t/x", RouteOptions::default()).unwrap();
10151		let deep = format!("t/{}", vec!["d"; Path::MAX_PARTS - 1].join("/"));
10152		let _deep = producer.route(deep.as_str(), RouteOptions::default()).unwrap();
10153		let project = producer
10154			.mount("p1/a/b", "t")
10155			.unwrap()
10156			.scope("p1", &Prefixes::all())
10157			.unwrap()
10158			.consume();
10159
10160		let mut announced = project.routes();
10161		announced.expect_next_active("a/b/x").await;
10162		announced.assert_next_wait();
10163
10164		let over = vec!["d"; Path::MAX_PARTS + 1].join("/");
10165		assert!(matches!(
10166			producer.mount(over.as_str(), "t"),
10167			Err(Error::BoundsExceeded(_))
10168		));
10169	}
10170
10171	/// Nothing is published at or beneath a mount.
10172	#[kio::test]
10173	async fn mount_is_read_only() {
10174		let producer = origin(1).produce();
10175		let project = producer
10176			.mount("p1/.svc", ".svc/p1")
10177			.unwrap()
10178			.scope("p1", &Prefixes::all())
10179			.unwrap();
10180		assert!(matches!(
10181			project.route(".svc/foo", RouteOptions::hidden()),
10182			Err(Error::Unauthorized)
10183		));
10184		assert!(matches!(
10185			project.forward(".svc", RouteInfo::new()),
10186			Err(Error::Unauthorized)
10187		));
10188		assert!(matches!(
10189			project.forward(".svc/foo", RouteInfo::new()),
10190			Err(Error::Unauthorized)
10191		));
10192		let _cam = project.route("cam", RouteOptions::default()).unwrap();
10193	}
10194
10195	/// A mount reaches only what the handle already reaches, and mounts never nest.
10196	#[kio::test]
10197	async fn mount_never_widens_a_scope() {
10198		let (producer, _driver) = Producer::new(Config::from(origin(1)));
10199		let project = producer.scope("", &scopes(&["p1"])).unwrap();
10200		assert!(matches!(project.mount("p1/.svc", ".svc/p1"), Err(Error::Unauthorized)));
10201
10202		let mounted = producer.mount("p1/.svc", ".svc/p1").unwrap();
10203		assert!(matches!(mounted.mount("p1/.svc/x", ".other"), Err(Error::Duplicate)));
10204		assert!(matches!(mounted.mount("p1", ".other"), Err(Error::Duplicate)));
10205		// A target through a mount would read the subtree the mount shadows.
10206		assert!(matches!(mounted.mount("p2", "p1/.svc/x"), Err(Error::Duplicate)));
10207		assert!(matches!(mounted.mount("p2", "p1"), Err(Error::Duplicate)));
10208		// A mount point on a target would chain through it, in either order.
10209		assert!(matches!(mounted.mount(".svc/p1/x", ".other"), Err(Error::Duplicate)));
10210		assert!(matches!(mounted.mount(".svc", ".other"), Err(Error::Duplicate)));
10211		mounted.mount("p1/.other", ".other/p1").unwrap();
10212		// Mount points may share a target.
10213		mounted.mount("p2/.svc", ".svc/p1").unwrap();
10214		// A mount point overlapping its own target is refused like any other overlap.
10215		for (at, target) in [("a", "a/b"), ("a/b", "a"), ("a", "a")] {
10216			assert!(
10217				matches!(producer.mount(at, target), Err(Error::Duplicate)),
10218				"{at} -> {target}"
10219			);
10220		}
10221	}
10222
10223	/// A mount never reads a subtree the handle was excluded from: not the target
10224	/// itself, nor one above or beneath it.
10225	#[kio::test]
10226	#[cfg(feature = "async")]
10227	async fn mount_never_reaches_an_excluded_subtree() {
10228		let producer = origin(1).produce();
10229		let _secret = producer.route(".stats/node", RouteOptions::default()).unwrap();
10230		let excluded = producer.exclude(".stats").unwrap();
10231		for target in [".stats", ".stats/node", ""] {
10232			assert!(
10233				matches!(excluded.mount("view", target), Err(Error::Unauthorized)),
10234				"{target}"
10235			);
10236		}
10237		let partly = producer.exclude(".stats/node").unwrap();
10238		assert!(matches!(partly.mount("view", ".stats"), Err(Error::Unauthorized)));
10239
10240		// A target beside the excluded subtree mounts, and the exclusion still holds.
10241		let mounted = excluded.mount("view", "public").unwrap();
10242		let err = mounted.consume().request(".stats/node", None).await.err().unwrap();
10243		assert!(matches!(err, Error::Unauthorized), "{err:?}");
10244	}
10245
10246	/// Egress through a mount counts under the path the reader named, so it
10247	/// attributes to the reader's root rather than the fleet-wide target.
10248	#[kio::test]
10249	#[cfg(feature = "async")]
10250	async fn mount_egress_counts_under_the_named_path() {
10251		let registry = stats::Registry::new(stats::Config::new());
10252		let producer = origin(1).produce();
10253		let _foo = producer.route(".svc/p1/foo", RouteOptions::default()).unwrap();
10254		let project = mounted(&producer, "p1", &[""])
10255			.with_stats(
10256				registry
10257					.tier(stats::Tier::default())
10258					.session(crate::stats::SessionInfo::new(crate::Path::from_static("p1"))),
10259			)
10260			.with_hidden(true);
10261
10262		let mut announced = project.routes();
10263		announced.expect_next_active(".svc/foo").await;
10264		project.request(".svc/foo", None).await.expect("resolves");
10265
10266		let mut report = stats::Report::default();
10267		registry.report(&mut report, crate::time::Instant::now());
10268		let paths: Vec<_> = report
10269			.traffic
10270			.iter()
10271			.map(|entry| entry.path.as_str().to_string())
10272			.collect();
10273		assert_eq!(paths, ["p1/.svc/foo"]);
10274	}
10275
10276	/// Reads through an unmetered track handle count toward no session, while the metered
10277	/// handle on the same broadcast still counts the same group.
10278	#[kio::test]
10279	#[cfg(feature = "async")]
10280	async fn an_unmetered_track_counts_nothing() {
10281		let registry = stats::Registry::new(stats::Config::new());
10282		let producer = origin(1).produce();
10283		let route = producer.route("room/alice", RouteOptions::default()).unwrap();
10284		let track = route
10285			.broadcast()
10286			.create_track("video", crate::track::Info::timed())
10287			.unwrap();
10288		let consumer = producer.consume().with_stats(
10289			registry
10290				.tier(stats::Tier::default())
10291				.session(crate::stats::SessionInfo::new(crate::Path::from_static("viewer"))),
10292		);
10293		let broadcast = consumer.request("room/alice", None).await.expect("resolves");
10294		let bytes = || -> u64 {
10295			registry
10296				.snapshot()
10297				.traffic()
10298				.into_iter()
10299				.map(|(_, _, traffic)| traffic.bytes)
10300				.sum()
10301		};
10302
10303		let mut unmetered = broadcast
10304			.track("video")
10305			.unwrap()
10306			.unmetered()
10307			.subscribe(None)
10308			.await
10309			.unwrap();
10310		let mut metered = broadcast.track("video").unwrap().subscribe(None).await.unwrap();
10311		let mut group = track.append_next().unwrap();
10312		group
10313			.write_frame(Frame::new(group.key_time(), b"frame".as_ref()))
10314			.unwrap();
10315		group.finish().unwrap();
10316
10317		let mut read = unmetered.recv_group().await.unwrap().expect("a group");
10318		assert_eq!(
10319			read.read_frame().await.unwrap().expect("a frame").payload.as_ref(),
10320			b"frame"
10321		);
10322		assert_eq!(bytes(), 0, "an unmetered read counts nothing");
10323
10324		let mut read = metered.recv_group().await.unwrap().expect("a group");
10325		assert_eq!(
10326			read.read_frame().await.unwrap().expect("a frame").payload.as_ref(),
10327			b"frame"
10328		);
10329		assert_eq!(bytes(), 5, "the metered handle still counts");
10330	}
10331
10332	/// A billed subscriber counts nothing it reads, whether read whole or in chunks, and
10333	/// counts each frame its reader delivers.
10334	#[kio::test]
10335	#[cfg(feature = "async")]
10336	async fn a_billed_track_counts_only_what_its_reader_delivers() {
10337		let registry = stats::Registry::new(stats::Config::new());
10338		let producer = origin(1).produce();
10339		let route = producer.route("room/alice", RouteOptions::default()).unwrap();
10340		let track = route
10341			.broadcast()
10342			.create_track("video", crate::track::Info::timed())
10343			.unwrap();
10344		let consumer = producer.consume().with_stats(
10345			registry
10346				.tier(stats::Tier::default())
10347				.session(crate::stats::SessionInfo::new(crate::Path::from_static("viewer"))),
10348		);
10349		let broadcast = consumer.request("room/alice", None).await.expect("resolves");
10350		let counted = || -> (u64, u64) {
10351			registry
10352				.snapshot()
10353				.traffic()
10354				.into_iter()
10355				.fold((0, 0), |(frames, bytes), (_, _, traffic)| {
10356					(frames + traffic.frames, bytes + traffic.bytes)
10357				})
10358		};
10359
10360		let mut subscriber = broadcast.track("video").unwrap().subscribe(None).await.unwrap();
10361		let bill = subscriber.bill();
10362		let mut group = track.append_empty(crate::Timestamp::from_millis(0).unwrap()).unwrap();
10363		group
10364			.write_frame(Frame::new(crate::Timestamp::ZERO, b"dropped".as_ref()))
10365			.unwrap();
10366		group
10367			.write_frame(Frame::new(crate::Timestamp::ZERO, b"sent".as_ref()))
10368			.unwrap();
10369		group.finish().unwrap();
10370
10371		let mut read = subscriber.recv_group().await.unwrap().expect("a group");
10372		let mut chunked = read.clone();
10373		assert_eq!(
10374			read.read_frame().await.unwrap().expect("a frame").payload.as_ref(),
10375			b"dropped"
10376		);
10377		let sent = read.read_frame().await.unwrap().expect("a frame").payload;
10378		chunked
10379			.next_frame()
10380			.await
10381			.unwrap()
10382			.expect("a frame")
10383			.read_all()
10384			.await
10385			.unwrap();
10386		assert_eq!(counted(), (0, 0), "a read counts nothing");
10387
10388		bill.deliver(sent.len() as u64);
10389		assert_eq!(counted(), (1, 4), "a delivered frame counts");
10390	}
10391
10392	/// A group a fill answers is ingress like a group the publisher writes live: a relay
10393	/// writes what a FETCH brings back through its track's requests.
10394	#[kio::test]
10395	#[cfg(feature = "async")]
10396	async fn a_fetched_group_counts_as_ingress() {
10397		let registry = stats::Registry::new(stats::Config::new());
10398		let producer = origin(1).produce().with_stats(
10399			registry
10400				.tier(stats::Tier::default())
10401				.session(crate::stats::SessionInfo::new(crate::Path::from_static("room"))),
10402		);
10403		let route = producer.route("room/alice", RouteOptions::default()).unwrap();
10404		let track = route
10405			.broadcast()
10406			.create_track("video", crate::track::Info::timed())
10407			.unwrap();
10408		let requests = track.requests();
10409		let ingress = || -> u64 {
10410			registry
10411				.snapshot()
10412				.traffic()
10413				.into_iter()
10414				.filter(|(_, role, _)| *role == stats::Role::Subscriber)
10415				.map(|(_, _, traffic)| traffic.bytes)
10416				.sum()
10417		};
10418
10419		let mut live = track.create_empty(crate::group::Info { start: 1 }).unwrap();
10420		live.write_frame(Frame::new(crate::Timestamp::from_millis(1).unwrap(), b"live".as_ref()))
10421			.unwrap();
10422		live.finish().unwrap();
10423		assert_eq!(ingress(), 4);
10424
10425		let fetch = track.consume().fetch_group(0, None);
10426		let fill = requests.requested_fill_group().await.unwrap();
10427		let mut fetched = fill
10428			.accept(crate::track::Info::timed())
10429			.unwrap()
10430			.expect("a fresh group");
10431		fetched
10432			.write_frame(Frame::new(crate::Timestamp::ZERO, b"fetched".as_ref()))
10433			.unwrap();
10434		fetched.finish().unwrap();
10435		fetch.await.unwrap();
10436		assert_eq!(ingress(), 4 + 7, "the fetched group counts as well");
10437
10438		// A reader outliving the publisher keeps the track's groups, not its session.
10439		let reader = track.consume();
10440		drop((track, requests, route, producer));
10441		let active: u64 = registry
10442			.snapshot()
10443			.sessions()
10444			.into_iter()
10445			.map(|(_, presence)| presence.active())
10446			.sum();
10447		assert_eq!(active, 0, "the publisher's session ended");
10448		drop(reader);
10449	}
10450
10451	/// Abandoning a track at its declared end ends the publisher's session too, whether a
10452	/// reader still wants the track or only holds it: the reader keeps the groups, not the session.
10453	#[kio::test]
10454	#[cfg(feature = "async")]
10455	async fn an_abandoned_track_releases_its_session() {
10456		for wanted in [true, false] {
10457			let registry = stats::Registry::new(stats::Config::new());
10458			let producer = origin(1).produce().with_stats(
10459				registry
10460					.tier(stats::Tier::default())
10461					.session(crate::stats::SessionInfo::new(crate::Path::from_static("room"))),
10462			);
10463			let route = producer.route("room/alice", RouteOptions::default()).unwrap();
10464			let mut track = route
10465				.broadcast()
10466				.create_track("video", crate::track::Info::timed())
10467				.unwrap();
10468			let subscriber = track.subscribe(None);
10469			let consumer = track.consume();
10470			track
10471				.create_empty(crate::group::Info { start: 0 })
10472				.unwrap()
10473				.finish()
10474				.unwrap();
10475			track.finish_at(crate::track::Position::group(3)).unwrap();
10476			let subscriber = wanted.then_some(subscriber);
10477
10478			track.abandon();
10479			drop((route, producer));
10480			let active: u64 = registry
10481				.snapshot()
10482				.sessions()
10483				.into_iter()
10484				.map(|(_, presence)| presence.active())
10485				.sum();
10486			assert_eq!(active, 0, "the publisher's session ended (wanted: {wanted})");
10487			drop((subscriber, consumer));
10488		}
10489	}
10490
10491	/// A route that turns up later is filtered the same way as the replay.
10492	#[kio::test]
10493	async fn hidden_route_announced_later_stays_hidden() {
10494		let producer = origin(1).produce();
10495		let consumer = producer.consume();
10496		let mut announced = consumer.routes();
10497		let mut opted = consumer.clone().with_hidden(true).routes();
10498
10499		let hidden = producer.announce(".stats/node", RouteInfo::new()).unwrap();
10500		announced.assert_next_wait();
10501		opted.expect_next_active(".stats/node").await;
10502
10503		drop(hidden);
10504		announced.assert_next_wait();
10505		opted.expect_next_ended(".stats/node").await;
10506	}
10507
10508	#[kio::test]
10509	async fn a_replayed_route_retracted_before_delivery_cancels() {
10510		let producer = origin(1).produce();
10511		let alice = producer.announce("alice", RouteInfo::new()).unwrap();
10512		let mut announced = producer.consume().routes();
10513		drop(alice);
10514		announced.assert_next_wait();
10515	}
10516
10517	#[kio::test]
10518	#[cfg(feature = "async")]
10519	async fn a_hidden_route_announces_its_own_path() {
10520		let producer = origin(1).produce();
10521		let consumer = producer.consume();
10522		let mut announced = consumer.routes();
10523		let mut peer = consumer.clone().excluding(Hop::UNKNOWN).routes();
10524
10525		// Created but not announced: invisible to local and peer cursors alike, even
10526		// once priced.
10527		let broadcast = producer.route("room/alice", RouteOptions::hidden()).unwrap();
10528		broadcast.set_cost(3).unwrap();
10529		announced.assert_next_wait();
10530		peer.assert_next_wait();
10531
10532		broadcast.announce().unwrap();
10533		assert_eq!(announced.expect_next_active("room/alice").await.cost, Cost::new(3));
10534		assert_eq!(peer.expect_next_active("room/alice").await.cost, Cost::new(3));
10535
10536		// Re-pricing a visible route updates it in place.
10537		broadcast.set_cost(1).unwrap();
10538		assert_eq!(announced.expect_next_active("room/alice").await.cost, Cost::new(1));
10539		assert_eq!(peer.expect_next_active("room/alice").await.cost, Cost::new(1));
10540
10541		// Off the air: the route retracts for everyone and the path is unroutable.
10542		broadcast.withdraw();
10543		announced.expect_next_ended("room/alice").await;
10544		peer.expect_next_ended("room/alice").await;
10545		broadcast.withdraw();
10546		announced.assert_next_wait();
10547		let err = consumer.request("room/alice", None).await.err().unwrap();
10548		assert!(matches!(err, Error::Unroutable));
10549
10550		// Back on the air, then the end of the broadcast retracts for good.
10551		broadcast.announce().unwrap();
10552		announced.expect_next_active("room/alice").await;
10553		peer.expect_next_active("room/alice").await;
10554		broadcast.broadcast().close();
10555		announced.expect_next_ended("room/alice").await;
10556		peer.expect_next_ended("room/alice").await;
10557		assert!(matches!(broadcast.announce(), Err(Error::Closed)));
10558		announced.assert_next_wait();
10559	}
10560
10561	#[kio::test]
10562	async fn a_route_retracts_with_its_last_clone() {
10563		let producer = origin(1).produce();
10564		let consumer = producer.consume();
10565		let mut announced = consumer.routes();
10566
10567		let route = producer.route("room/alice", RouteOptions::hidden()).unwrap();
10568		let clone = route.clone();
10569		let source = route.broadcast().clone();
10570		route.announce().unwrap();
10571		announced.expect_next_active("room/alice").await;
10572
10573		// A clone keeps the route alive; a broadcast producer does not.
10574		drop(route);
10575		announced.assert_next_wait();
10576		drop(clone);
10577		announced.expect_next_ended("room/alice").await;
10578		assert!(!source.consume().is_closed());
10579	}
10580
10581	#[kio::test]
10582	async fn publish_creates_and_announces_together() {
10583		let producer = origin(1).produce();
10584		let mut announced = producer.consume().routes();
10585		let _broadcast = producer.route("room/alice", RouteOptions::default()).unwrap();
10586		announced.expect_next_active("room/alice").await;
10587	}
10588
10589	#[kio::test]
10590	async fn announce_replays_to_late_cursor() {
10591		let producer = origin(1).produce();
10592		let _a = producer.announce("room/alice", RouteInfo::new()).unwrap();
10593		let _b = producer.announce("room/bob", RouteInfo::new()).unwrap();
10594
10595		let mut announced = producer.consume().routes();
10596		// Replay follows the table traversal order.
10597		announced.expect_next_active("room/alice").await;
10598		announced.expect_next_active("room/bob").await;
10599		announced.assert_next_wait();
10600	}
10601
10602	/// A claim broader than its producer's grant is filed at each granted prefix beneath it,
10603	/// as many segments above it as it is broader, so it is shown only where it may serve.
10604	#[kio::test]
10605	async fn a_claim_is_filed_at_the_grant_prefixes_beneath_it() {
10606		let producer = origin(1).produce();
10607		let scoped = producer.scope("", &scopes(&["a/b", "a/c/d", "z"])).unwrap();
10608
10609		let _a = scoped.announce("a", RouteInfo::new()).unwrap();
10610		let mut announced = producer.consume().routes();
10611		let mut seen = Vec::new();
10612		for _ in 0..2 {
10613			let event = announced.expect_next().await;
10614			let RouteKind::Start = event.kind else {
10615				panic!("should start: {event:?}");
10616			};
10617			seen.push((event.announce.prefix.to_string(), event.announce.route.lane.above));
10618		}
10619		seen.sort();
10620		assert_eq!(seen, [("a/b".to_string(), 1), ("a/c/d".to_string(), 2)]);
10621		announced.assert_next_wait();
10622
10623		// A request outside the grant finds nothing to resolve through.
10624		let outside = Path::new("a/q").unwrap();
10625		assert!(producer.shared.lock().routes.covering(&outside).next().is_none());
10626
10627		// Within a granted prefix, the claim is filed where it was announced.
10628		let _b = scoped.announce("z/y", RouteInfo::new()).unwrap();
10629		let route = announced.expect_next_active("z/y").await;
10630		assert_eq!(route.lane.above, 0);
10631
10632		// Disjoint prefixes cannot be claimed at all.
10633		assert!(matches!(
10634			scoped.announce("other", RouteInfo::new()),
10635			Err(Error::Unauthorized)
10636		));
10637	}
10638
10639	#[kio::test]
10640	async fn cursor_keeps_an_overlapping_prefix_above_its_scope() {
10641		let producer = origin(1).produce();
10642		let _a = producer.announce("", RouteInfo::new()).unwrap();
10643
10644		let consumer = producer.consume().scope("", &scopes(&["room"])).unwrap();
10645		let mut announced = consumer.clone().covering().routes();
10646		announced.expect_next_active("").await;
10647		consumer.routes().assert_next_wait();
10648	}
10649
10650	#[kio::test]
10651	async fn cursor_root_strips_prefix() {
10652		let producer = origin(1).produce();
10653		let _a = producer.announce("room/alice", RouteInfo::new()).unwrap();
10654
10655		let consumer = producer.consume().scope("room", &Prefixes::all()).unwrap();
10656		let mut announced = consumer.routes();
10657		announced.expect_next_active("alice").await;
10658	}
10659
10660	#[kio::test]
10661	async fn best_route_wins_and_fails_over() {
10662		let producer = origin(1).produce();
10663		let mut announced = producer.consume().routes();
10664
10665		let expensive = producer
10666			.announce("room", RouteInfo::new().with_hops(hops(&[10])).with_cost(5))
10667			.unwrap();
10668		let route = announced.expect_next_active("room").await;
10669		assert_eq!(route.cost, Cost::new(5));
10670
10671		// A cheaper route for the same prefix takes over in place.
10672		let cheap = producer
10673			.announce("room", RouteInfo::new().with_hops(hops(&[20])).with_cost(1))
10674			.unwrap();
10675		let route = announced.expect_next_active("room").await;
10676		assert_eq!(route.cost, Cost::new(1));
10677
10678		// Losing the winner falls back to the survivor, still in place.
10679		drop(cheap);
10680		let route = announced.expect_next_active("room").await;
10681		assert_eq!(route.cost, Cost::new(5));
10682
10683		// Losing the last retracts.
10684		drop(expensive);
10685		announced.expect_next_ended("room").await;
10686	}
10687
10688	/// Pinned so `spreadHash` in `js/net` picks the same pool member for a path.
10689	#[kio::test]
10690	async fn spread_hash_matches_js() {
10691		assert_eq!(identity_key("pool/job-0", &"a".parse().unwrap()), 0x3df8f75a44f8eefb);
10692		assert_eq!(identity_key("pool/job-0", &"b".parse().unwrap()), 0x3df8f85a44f8f0ae);
10693	}
10694
10695	/// Pinned so `js/net` breaks a tie between lite-07 claims as this does: by the
10696	/// rendezvous hash of each origin node under a claim, and at a claim's own path by the
10697	/// newest claim, which a re-price leaves in place.
10698	#[kio::test]
10699	async fn lite07_ties_match_js() {
10700		let identity = |name: &str| -> Identity { name.parse().unwrap() };
10701		assert_eq!(rendezvous("pool/job", &identity("a")), 0x3e128da0fff39252);
10702		assert_eq!(rendezvous("pool/job", &identity("b")), 0x3e128ca0fff3909f);
10703
10704		let producer = origin(1).produce();
10705		let claim = |node: u64, name: &str, cost: u64| {
10706			RouteInfo::new()
10707				.with_identity(name.parse().unwrap(), 0)
10708				.with_cost(cost)
10709				.with_node(Some(node_id(node)))
10710		};
10711		let older = producer.forward("pool", claim(0x7a, "a", 5)).unwrap();
10712		let _newer = producer.forward("pool", claim(0x8b, "b", 1)).unwrap();
10713		older.update(older.route().unwrap().with_cost(1)).unwrap();
10714
10715		let best = |path: &str| {
10716			let table = producer.shared.read();
10717			table
10718				.best_route(&Path::new(path).unwrap(), Horizon::default(), &HashSet::new(), |_| true)
10719				.and_then(|entry| entry.node)
10720		};
10721		assert_eq!(
10722			best("pool"),
10723			Some(node_id(0x8b)),
10724			"the newer claim keeps a tie a re-price made"
10725		);
10726		assert_eq!(
10727			best("pool/job"),
10728			Some(node_id(0x8b)),
10729			"the lower identity hash wins under the claims"
10730		);
10731
10732		// A lite-06 route keys on its identity and chain under the older basis, a lite-07
10733		// claim on its identity under the standard one, each on its own: here the claim's
10734		// is lower.
10735		assert_eq!(identity_key("pool/job", &identity("b")), 0xd16a3821c67a2d25);
10736		let producer = origin(1).produce();
10737		let _claim = producer.forward("pool", claim(0x7a, "a", 1)).unwrap();
10738		let legacy = RouteInfo::new()
10739			.with_identity("b".parse().unwrap(), 0)
10740			.with_hops(hops(&[11]))
10741			.with_cost(1);
10742		let _legacy = producer.forward("pool", legacy).unwrap();
10743		let table = producer.shared.read();
10744		let winner = table
10745			.best_route(
10746				&Path::new("pool/job").unwrap(),
10747				Horizon::default(),
10748				&HashSet::new(),
10749				|_| true,
10750			)
10751			.and_then(|entry| entry.node);
10752		assert_eq!(winner, Some(node_id(0x7a)), "each route keyed on its own");
10753	}
10754
10755	/// Equal-cost advertisers of one prefix share its paths: a set of requested
10756	/// paths spreads across the pool, and one path always resolves to the same
10757	/// advertiser, whatever order the routes arrived in. The split is a rendezvous
10758	/// hash, so losing an advertiser moves only the paths it won.
10759	#[kio::test]
10760	async fn equal_cost_pool_spreads_paths() {
10761		const WORKERS: [u64; 4] = [10, 11, 12, 13];
10762		const PATHS: usize = 64;
10763
10764		// The first hop of the route each path resolves to on a node whose pool
10765		// arrived in `order`.
10766		fn winners(order: impl Iterator<Item = u64>) -> Vec<Hop> {
10767			let producer = origin(1).produce();
10768			let _pool: Vec<Claim> = order
10769				.map(|id| {
10770					producer
10771						.forward(
10772							"pool",
10773							RouteInfo::new()
10774								.with_identity(format!("worker-{id}").parse().unwrap(), 0)
10775								.with_hops(hops(&[id]))
10776								.with_cost(3),
10777						)
10778						.unwrap()
10779				})
10780				.collect();
10781			let table = producer.shared.read();
10782			(0..PATHS)
10783				.map(|i| {
10784					let path = Path::new(&format!("pool/job-{i}")).unwrap();
10785					let entry = table
10786						.best_route(&path, Horizon::default(), &HashSet::new(), |_| true)
10787						.expect("the pool serves every path");
10788					entry.hops.iter().next().copied().unwrap()
10789				})
10790				.collect()
10791		}
10792
10793		let forward = winners(WORKERS.into_iter());
10794		let reverse = winners(WORKERS.into_iter().rev());
10795		assert_eq!(forward, reverse, "a path must resolve the same way on every node");
10796
10797		// Not an assertion about any two paths, which a correct hash may put on
10798		// one worker: only that the set does not pile onto a few.
10799		for worker in WORKERS {
10800			let share = forward.iter().filter(|hop| **hop == origin(worker)).count();
10801			assert!(share >= PATHS / 16, "worker {worker} took {share} of {PATHS} paths");
10802		}
10803
10804		// A mod-N style hash would reshuffle most paths here.
10805		let lost = origin(WORKERS[1]);
10806		let survivors = winners(WORKERS.into_iter().filter(|id| origin(*id) != lost));
10807		for (i, (before, after)) in forward.iter().zip(&survivors).enumerate() {
10808			if *before != lost {
10809				assert_eq!(after, before, "pool/job-{i} moved off a surviving worker");
10810			}
10811		}
10812	}
10813
10814	/// An identical route from a fresh announcement (a reconnect) wins at once. One that
10815	/// mints its own identity is another stream, so consumers restart; one with the same
10816	/// identity is the same stream, and nothing is delivered. Retracting the stale twin is
10817	/// quiet either way.
10818	#[kio::test]
10819	async fn identical_reannounce_restarts_under_another_identity() {
10820		for named in [None, Some(identity())] {
10821			let producer = origin(1).produce();
10822			let mut announced = producer.consume().routes();
10823			let mut route = RouteInfo::new().with_hops(hops(&[10]));
10824			route.identity = named.clone();
10825
10826			let old = producer.announce("room", route.clone()).unwrap();
10827			let first = announced.expect_next_active("room").await;
10828			assert_eq!(first.hops.as_slice(), hops(&[10]).as_slice());
10829
10830			let _new = producer.announce("room", route).unwrap();
10831			match named {
10832				None => assert_eq!(announced.expect_next_restarted("room").await.hops, hops(&[10])),
10833				Some(_) => announced.assert_next_wait(),
10834			}
10835
10836			drop(old);
10837			announced.assert_next_wait();
10838		}
10839	}
10840
10841	/// A re-price of the winning route is an update in place, never a restart.
10842	#[kio::test]
10843	#[cfg(feature = "async")]
10844	async fn a_reprice_is_an_update() {
10845		let producer = origin(1).produce();
10846		let mut announced = producer.consume().routes();
10847		let route = producer.forward("room", RouteInfo::new().with_cost(3)).unwrap();
10848		announced.expect_next_active("room").await;
10849
10850		route.update(RouteInfo::new().with_cost(5)).unwrap();
10851		match announced.next().await.expect("no next") {
10852			RouteEvent {
10853				kind: RouteKind::Update,
10854				announce: update,
10855			} => assert_eq!(update.route.cost, Cost::new(5)),
10856			other => panic!("should be an update: got {other:?}"),
10857		}
10858	}
10859
10860	/// Swapping a route's auth is an update in place carrying the new auth, so the session
10861	/// advertising it can renew its request.
10862	#[kio::test]
10863	#[cfg(feature = "async")]
10864	async fn an_auth_swap_is_an_update() {
10865		let handle = crate::auth::Link::ietf();
10866		let first = handle.present(bytes::Bytes::from_static(b"first"), false).unwrap();
10867		let second = handle.present(bytes::Bytes::from_static(b"second"), false).unwrap();
10868		let producer = origin(1).produce();
10869		let mut announced = producer.consume().routes();
10870		let route = producer
10871			.forward("room", RouteInfo::new().with_auth(first.clone()))
10872			.unwrap();
10873		assert_eq!(announced.expect_next_active("room").await.auth, Some(first));
10874
10875		route.update(RouteInfo::new().with_auth(second.clone())).unwrap();
10876		match announced.next().await.expect("no next") {
10877			RouteEvent {
10878				kind: RouteKind::Update,
10879				announce: update,
10880			} => assert_eq!(update.route.auth, Some(second)),
10881			other => panic!("should be an update: got {other:?}"),
10882		}
10883	}
10884
10885	/// A change to a closed route fails and keeps nothing, so the route holds no
10886	/// credential it was refused.
10887	#[kio::test]
10888	#[cfg(feature = "async")]
10889	async fn a_closed_route_keeps_no_refused_change() {
10890		let handle = crate::auth::Link::ietf();
10891		let token = handle.present(bytes::Bytes::from_static(b"token"), false).unwrap();
10892		let producer = origin(1).produce();
10893		let mut announced = producer.consume().routes();
10894		let route = producer.route("room", RouteOptions::hidden()).unwrap();
10895		route.announce().unwrap();
10896		announced.expect_next_active("room").await;
10897		route.broadcast().close();
10898		announced.expect_next_ended("room").await;
10899
10900		assert!(matches!(route.set_auth(Some(token.clone())), Err(Error::Closed)));
10901		assert!(matches!(route.set_cost(7), Err(Error::Closed)));
10902		let control = route.state.control.lock();
10903		assert!(control.options.auth.is_none());
10904		assert_eq!(control.options.cost, Cost::default());
10905	}
10906
10907	/// A replacement under another identity from a cluster peer at equal cost and chain
10908	/// length, whose hash loses, competes with the lingering old route: nothing restarts and
10909	/// requests stay on the old route until it is withdrawn, then consumers restart and a
10910	/// re-request lands on the replacement. Every node ranks peer routes alike.
10911	#[kio::test]
10912	#[cfg(feature = "async")]
10913	async fn an_equal_cost_peer_replacement_waits_for_the_old_route() {
10914		// Pinned in `spread_hash_matches_js`: identity `a` hashes below `b` for this path.
10915		// Restarts are delivered at once: the hold is not what this checks.
10916		let producer = Config {
10917			update_hold: Duration::ZERO,
10918			..Config::from(origin(1))
10919		}
10920		.produce();
10921		let consumer = producer.consume();
10922		let mut announced = consumer.routes();
10923		let peer = producer.clone().with_link(Link::Peer);
10924		let old = peer
10925			.forward(
10926				"pool/job-0",
10927				RouteInfo::new()
10928					.with_identity("a".parse().unwrap(), 0)
10929					.with_hops(hops(&[11])),
10930			)
10931			.unwrap();
10932		announced.expect_next_active("pool/job-0").await;
10933
10934		let new = peer
10935			.forward(
10936				"pool/job-0",
10937				RouteInfo::new()
10938					.with_identity("b".parse().unwrap(), 0)
10939					.with_hops(hops(&[10])),
10940			)
10941			.unwrap();
10942		announced.assert_next_wait();
10943
10944		let pending = consumer.request("pool/job-0", None);
10945		let request = queued(&old).await;
10946		let first = broadcast::Info::new().produce();
10947		request.serve(&first);
10948		let resolved = pending.await.expect("the old route resolves");
10949		assert!(new.poll_requested(&kio::Waiter::noop()).is_pending());
10950
10951		drop(old);
10952		assert_eq!(announced.expect_next_restarted("pool/job-0").await.hops, hops(&[10]));
10953
10954		let pending = consumer.request("pool/job-0", None);
10955		let request = queued(&new).await;
10956		let second = broadcast::Info::new().produce();
10957		request.serve(&second);
10958		let replaced = pending.await.expect("the replacement resolves");
10959		assert!(!replaced.is_clone(&resolved));
10960	}
10961
10962	/// A peer route that arrives after an equally ranked one in use never displaces it,
10963	/// whichever hashes lower: neither between the identities two sessions minted for one
10964	/// broadcast (moq-lite-06 carries none), nor between two chains of one named identity.
10965	/// It takes over only when the route in use leaves or ranks worse, and keeps the tie
10966	/// when that one recovers.
10967	#[kio::test]
10968	#[cfg(feature = "async")]
10969	async fn an_equal_route_keeps_the_one_in_use() {
10970		for minted in [true, false] {
10971			let named = identity();
10972			for job in 0..16 {
10973				let path = format!("pool/job-{job}");
10974				let producer = Config {
10975					update_hold: Duration::ZERO,
10976					..Config::from(origin(1))
10977				}
10978				.produce();
10979				let consumer = producer.consume();
10980				let mut announced = consumer.routes();
10981				let peer = producer.clone().with_link(Link::Peer);
10982				let identities = match minted {
10983					true => [Identity::minted(), Identity::minted()],
10984					false => [named.clone(), named.clone()],
10985				};
10986				let route = |hop: u64| {
10987					let identity = identities[usize::from(hop == 11)].clone();
10988					RouteInfo::new().with_identity(identity, 0).with_hops(hops(&[hop]))
10989				};
10990				let resolved = || {
10991					let table = producer.shared.read();
10992					let path = Path::new(&path).unwrap();
10993					let entry = table.best_route(&path, Horizon::default(), &HashSet::new(), |_| true);
10994					entry.map(|entry| entry.hops.clone())
10995				};
10996
10997				let first = peer.forward(path.as_str(), route(10)).unwrap();
10998				assert_eq!(announced.expect_next_active(path.as_str()).await.hops, hops(&[10]));
10999				let second = peer.forward(path.as_str(), route(11)).unwrap();
11000				announced.assert_next_wait();
11001				assert_eq!(resolved(), Some(hops(&[10])), "{path}: the later route took requests");
11002
11003				// The one in use ranks worse: the other takes over, and keeps the tie once
11004				// the first recovers.
11005				first.update(route(10).with_cost(2)).unwrap();
11006				let moved = announced.expect_next().await;
11007				assert_eq!(moved.announce.route.hops, hops(&[11]), "{path}: {moved:?}");
11008				first.update(route(10)).unwrap();
11009				announced.assert_next_wait();
11010				assert_eq!(
11011					resolved(),
11012					Some(hops(&[11])),
11013					"{path}: the recovered route took requests"
11014				);
11015
11016				drop(second);
11017				assert_eq!(announced.expect_next().await.announce.route.hops, hops(&[10]));
11018				drop(first);
11019			}
11020		}
11021	}
11022
11023	/// Claims of one prefix filed at different depths tie as one tier: the one announced
11024	/// first keeps a path beneath both, whichever filing it has, and one announced again
11025	/// ranks as newly arrived, as `js/net`'s `compareTie` has it.
11026	#[kio::test]
11027	#[cfg(feature = "async")]
11028	async fn an_equal_claim_filed_elsewhere_keeps_the_one_in_use() {
11029		let named = identity();
11030		let route = |hop: u64, above: u8| {
11031			RouteInfo::new()
11032				.with_identity(named.clone(), 0)
11033				.with_hops(hops(&[hop]))
11034				.with_lane(Lane {
11035					above,
11036					..Lane::default()
11037				})
11038		};
11039		// Hop 10 is filed at `src/a` a level above its own prefix, hop 11 at `src`.
11040		let filing = |hop: u64| match hop {
11041			10 => ("src/a", route(10, 1)),
11042			_ => ("src", route(11, 0)),
11043		};
11044		for (first, second) in [(10, 11), (11, 10)] {
11045			let producer = Config {
11046				update_hold: Duration::ZERO,
11047				..Config::from(origin(1))
11048			}
11049			.produce();
11050			let peer = producer.clone().with_link(Link::Peer);
11051			let resolved = || {
11052				let table = producer.shared.read();
11053				let path = Path::new("src/a/b").unwrap();
11054				let entry = table.best_route(&path, Horizon::default(), &HashSet::new(), |_| true);
11055				entry.map(|entry| entry.hops.clone())
11056			};
11057			let forward = |hop| {
11058				let (prefix, route) = filing(hop);
11059				peer.forward(prefix, route).unwrap()
11060			};
11061			let held = forward(first);
11062			let _later = forward(second);
11063			assert_eq!(resolved(), Some(hops(&[first])), "the later claim took requests");
11064			drop(held);
11065			assert_eq!(resolved(), Some(hops(&[second])));
11066			let _again = forward(first);
11067			assert_eq!(
11068				resolved(),
11069				Some(hops(&[second])),
11070				"the claim announced again took requests"
11071			);
11072		}
11073	}
11074
11075	/// A publisher that restarts while its old session lingers announces its own path under
11076	/// a new first hop. The restart takes over at once whichever chain hashes lower, so new
11077	/// requests never wait on the old session.
11078	#[kio::test]
11079	#[cfg(feature = "async")]
11080	async fn an_equal_cost_local_replacement_takes_over_at_once() {
11081		for (old_hop, new_hop) in [(11, 10), (10, 11)] {
11082			let producer = Config {
11083				update_hold: Duration::ZERO,
11084				..Config::from(origin(1))
11085			}
11086			.produce();
11087			let consumer = producer.consume();
11088			let mut announced = consumer.routes();
11089			let _old = producer
11090				.forward("pool/job-0", RouteInfo::new().with_hops(hops(&[old_hop])))
11091				.unwrap();
11092			announced.expect_next_active("pool/job-0").await;
11093
11094			let new = producer
11095				.forward("pool/job-0", RouteInfo::new().with_hops(hops(&[new_hop])))
11096				.unwrap();
11097			assert_eq!(
11098				announced.expect_next_restarted("pool/job-0").await.hops,
11099				hops(&[new_hop])
11100			);
11101
11102			let pending = consumer.request("pool/job-0", None);
11103			queued(&new).await.serve(broadcast::Info::new().produce());
11104			pending.await.expect("the replacement resolves");
11105		}
11106	}
11107
11108	/// An origin delivering restarts at once, and a way to claim `prefix` with a
11109	/// producer scoped to `scope`, from `hop` at `cost`.
11110	#[cfg(feature = "async")]
11111	fn scoped_pool() -> (Producer, impl Fn(&str, &str, u64, u64) -> Claim) {
11112		let producer = Config {
11113			update_hold: Duration::ZERO,
11114			..Config::from(origin(1))
11115		}
11116		.produce();
11117		let claims = producer.clone();
11118		let claim = move |prefix: &str, scope: &str, hop: u64, cost: u64| {
11119			claims
11120				.scope("", &scopes(&[scope]))
11121				.unwrap()
11122				.forward(prefix, RouteInfo::new().with_hops(hops(&[hop])).with_cost(cost))
11123				.unwrap()
11124		};
11125		(producer, claim)
11126	}
11127
11128	/// Request `path` from `consumer` and have `server` answer it: the answer, and
11129	/// the requester's broadcast.
11130	#[cfg(feature = "async")]
11131	async fn hold(consumer: &Consumer, path: &str, server: &Claim) -> (broadcast::Producer, broadcast::Consumer) {
11132		let pending = consumer.request(path, None);
11133		let answer = broadcast::Info::new().produce();
11134		queued(server).await.serve(&answer);
11135		(answer, pending.await.expect("the request resolves"))
11136	}
11137
11138	/// Let the fronts react, then expect nothing more on `announced`.
11139	#[cfg(feature = "async")]
11140	async fn quiet(announced: &mut Routes) {
11141		for _ in 0..20 {
11142			kio::clock::sim::yield_now().await;
11143		}
11144		announced.assert_next_wait();
11145	}
11146
11147	/// A route from before the request repricing to win both the prefix and the held
11148	/// path restarts the prefix once: the cursor's own switch covers the move.
11149	#[kio::test]
11150	#[cfg(feature = "async")]
11151	async fn a_repriced_route_taking_a_held_path_restarts_once() {
11152		let (producer, claim) = scoped_pool();
11153		let consumer = producer.consume();
11154		let a = claim("room", "room", 10, 5);
11155		let b = claim("room", "room", 11, 9);
11156		let mut announced = consumer.routes();
11157		assert_eq!(announced.expect_next_active("room").await.cost, Cost::new(5));
11158		let _sticky = hold(&consumer, "room/job", &a).await;
11159
11160		b.update(RouteInfo::new().with_hops(hops(&[11])).with_cost(3)).unwrap();
11161		assert_eq!(announced.expect_next_restarted("room").await.cost, Cost::new(3));
11162		quiet(&mut announced).await;
11163	}
11164
11165	#[kio::test]
11166	async fn exclude_hides_routes_through_the_peer() {
11167		let producer = origin(1).produce();
11168		let _a = producer
11169			.announce("room", RouteInfo::new().with_hops(hops(&[7])))
11170			.unwrap();
11171
11172		let mut hidden = producer.consume().excluding(origin(7)).routes();
11173		hidden.assert_next_wait();
11174
11175		let mut visible = producer.consume().excluding(origin(8)).routes();
11176		visible.expect_next_active("room").await;
11177	}
11178
11179	#[kio::test]
11180	async fn exclude_matches_via_when_the_chain_is_anonymous() {
11181		let producer = origin(1).produce();
11182		let assigned = origin(777);
11183		let _echoed = producer
11184			.announce("echoed", RouteInfo::new().with_hops(hops(&[0])).with_via(assigned))
11185			.unwrap();
11186		let _local = producer
11187			.announce("local", RouteInfo::new().with_hops(hops(&[10])))
11188			.unwrap();
11189
11190		let mut hidden = producer.consume().excluding(assigned).routes();
11191		hidden.expect_next_active("local").await;
11192		hidden.assert_next_wait();
11193	}
11194
11195	#[kio::test]
11196	async fn anonymous_route_loses_to_identified_at_any_cost() {
11197		let producer = origin(1).produce();
11198		let mut announced = producer.consume().routes();
11199
11200		let _anonymous = producer
11201			.announce("room", RouteInfo::new().with_hops(hops(&[0])).with_cost(1))
11202			.unwrap();
11203		let route = announced.expect_next_active("room").await;
11204		assert!(route.is_anonymous());
11205		assert_eq!(route.cost, Cost::new(1));
11206
11207		let _identified = producer
11208			.announce("room", RouteInfo::new().with_hops(hops(&[10])).with_cost(5))
11209			.unwrap();
11210		let route = announced.expect_next_active("room").await;
11211		assert!(!route.is_anonymous());
11212		assert_eq!(route.cost, Cost::new(5));
11213	}
11214
11215	#[kio::test]
11216	async fn a_lite07_claims_carried_chain_does_not_rank_it() {
11217		let producer = origin(1).produce();
11218		let mut announced = producer.consume().routes();
11219
11220		let _native = producer
11221			.announce(
11222				"room",
11223				RouteInfo::new()
11224					.with_hops(hops(&[10]))
11225					.with_cost(5)
11226					.with_node(Some(node_id(10))),
11227			)
11228			.unwrap();
11229		announced.expect_next_active("room").await;
11230
11231		let _carried = producer
11232			.announce(
11233				"room",
11234				RouteInfo::new()
11235					.with_hops(hops(&[0, 7, 20]))
11236					.with_cost(1)
11237					.with_node(Some(node_id(20))),
11238			)
11239			.unwrap();
11240		let route = announced.expect_next_active("room").await;
11241		assert_eq!(route.cost, Cost::new(1));
11242	}
11243
11244	#[kio::test]
11245	async fn anonymous_routes_order_by_cost() {
11246		let producer = origin(1).produce();
11247		let mut announced = producer.consume().routes();
11248
11249		let expensive = producer
11250			.announce("room", RouteInfo::new().with_hops(hops(&[0])).with_cost(5))
11251			.unwrap();
11252		let route = announced.expect_next_active("room").await;
11253		assert_eq!(route.cost, Cost::new(5));
11254
11255		let _cheap = producer
11256			.announce("room", RouteInfo::new().with_hops(hops(&[0, 7])).with_cost(1))
11257			.unwrap();
11258		let route = announced.expect_next_active("room").await;
11259		assert!(route.is_anonymous());
11260		assert_eq!(route.cost, Cost::new(1));
11261
11262		drop(expensive);
11263		announced.assert_next_wait();
11264	}
11265
11266	#[kio::test]
11267	async fn anonymous_chain_from_identified_peer_still_ranks_last() {
11268		let producer = origin(1).produce();
11269		let mut announced = producer.consume().routes();
11270
11271		let _anonymous = producer
11272			.announce(
11273				"room",
11274				RouteInfo::new()
11275					.with_hops(hops(&[0, 7]))
11276					.with_cost(1)
11277					.with_via(origin(7)),
11278			)
11279			.unwrap();
11280		announced.expect_next_active("room").await;
11281
11282		let _identified = producer
11283			.announce("room", RouteInfo::new().with_hops(hops(&[10, 20])).with_cost(5))
11284			.unwrap();
11285		let route = announced.expect_next_active("room").await;
11286		assert!(!route.is_anonymous());
11287		assert_eq!(route.cost, Cost::new(5));
11288	}
11289
11290	#[kio::test]
11291	#[cfg(feature = "async")]
11292	async fn request_prefers_identified_over_cheaper_anonymous() {
11293		let producer = origin(1).produce();
11294		let consumer = producer.consume();
11295
11296		let anonymous = producer
11297			.forward("room", RouteInfo::new().with_hops(hops(&[0])).with_cost(1))
11298			.unwrap();
11299		let identified = producer
11300			.forward("room", RouteInfo::new().with_hops(hops(&[10])).with_cost(5))
11301			.unwrap();
11302
11303		let _pending = consumer.request("room/alice", None);
11304		let request = queued(&identified).await;
11305		assert_eq!(request.path().as_str(), "room/alice");
11306		assert!(
11307			anonymous.poll_requested(&kio::Waiter::noop()).is_pending(),
11308			"the cheaper anonymous route must not serve"
11309		);
11310	}
11311
11312	#[kio::test]
11313	#[cfg(feature = "async")]
11314	async fn request_avoids_a_demoted_link_even_when_cheaper() {
11315		let producer = origin(1).produce();
11316		let consumer = producer.consume();
11317
11318		let demoted = producer
11319			.clone()
11320			.with_priority(Priority::new(-1))
11321			.forward("room", RouteInfo::new().with_hops(hops(&[10])).with_cost(1))
11322			.unwrap();
11323		let unranked = producer
11324			.forward("room", RouteInfo::new().with_hops(hops(&[11])).with_cost(5))
11325			.unwrap();
11326
11327		let _pending = consumer.request("room/alice", None);
11328		let request = queued(&unranked).await;
11329		assert_eq!(request.path().as_str(), "room/alice");
11330		assert!(
11331			demoted.poll_requested(&kio::Waiter::noop()).is_pending(),
11332			"the cheaper demoted link must not serve"
11333		);
11334	}
11335
11336	/// A lite-07 route ranks by the lowest priority of any link on its path, so one that
11337	/// crossed a demoted link further on loses to a dearer one that crossed none.
11338	#[kio::test]
11339	#[cfg(feature = "async")]
11340	async fn request_avoids_a_path_through_a_demoted_link_even_when_cheaper() {
11341		let producer = origin(1).produce();
11342		let consumer = producer.consume();
11343		let route = |node, priority, cost| {
11344			let lane = Lane {
11345				priority: Some(priority),
11346				..Lane::default()
11347			};
11348			RouteInfo::new()
11349				.with_hops(hops(&[node]))
11350				.with_node(Some(node_id(node)))
11351				.with_lane(lane)
11352				.with_cost(cost)
11353		};
11354
11355		let demoted = producer.forward("room", route(10, -10, 1)).unwrap();
11356		let unranked = producer.forward("room", route(11, 0, 5)).unwrap();
11357
11358		let _pending = consumer.request("room/alice", None);
11359		let request = queued(&unranked).await;
11360		assert_eq!(request.path().as_str(), "room/alice");
11361		assert!(
11362			demoted.poll_requested(&kio::Waiter::noop()).is_pending(),
11363			"the cheaper path through a demoted link must not serve"
11364		);
11365	}
11366
11367	/// The most specific claim wins whichever prefix shows it: a claim for `src` shown at
11368	/// `src/a/b` is deeper in the table than one for `src/a` shown at its own prefix, yet
11369	/// broader, so it must not take the request the more specific claim's publisher serves.
11370	#[kio::test]
11371	#[cfg(feature = "async")]
11372	async fn request_prefers_the_more_specific_claim_whichever_prefix_shows_it() {
11373		let producer = origin(1).produce();
11374		let consumer = producer.consume();
11375		let route = |node, above, cost| {
11376			RouteInfo::new()
11377				.with_hops(hops(&[node]))
11378				.with_node(Some(node_id(node)))
11379				.with_lane(Lane {
11380					above,
11381					..Lane::default()
11382				})
11383				.with_cost(cost)
11384		};
11385
11386		let broad = producer.forward("src/a/b", route(10, 2, 1)).unwrap();
11387		let exact = producer.forward("src/a", route(11, 0, 5)).unwrap();
11388
11389		let _pending = consumer.request("src/a/b/c", None);
11390		let request = queued(&exact).await;
11391		assert_eq!(request.path().as_str(), "src/a/b/c");
11392		assert!(
11393			broad.poll_requested(&kio::Waiter::noop()).is_pending(),
11394			"the broader claim must not serve what a more specific one covers"
11395		);
11396	}
11397
11398	/// A broadcast published here shadows what is beneath it, and so does it against a broader
11399	/// claim shown at the same prefix: the broadcast refuses the request, and the request goes
11400	/// no further than that refusal.
11401	#[kio::test]
11402	#[cfg(feature = "async")]
11403	async fn a_broadcast_here_shadows_a_broader_claim_shown_at_its_prefix() {
11404		let producer = origin(1).produce();
11405		let _broad = producer
11406			.forward(
11407				"src/a",
11408				RouteInfo::new()
11409					.with_hops(hops(&[10]))
11410					.with_node(Some(node_id(10)))
11411					.with_lane(Lane {
11412						above: 1,
11413						..Lane::default()
11414					}),
11415			)
11416			.unwrap();
11417		let exact = producer.route("src/a", RouteOptions::default()).unwrap();
11418		exact.announce().unwrap();
11419
11420		let table = producer.shared.read();
11421		let best =
11422			|path: &str| table.best_route(&Path::new(path).unwrap(), Horizon::default(), &HashSet::new(), |_| true);
11423		assert!(
11424			best("src/a/b").is_none(),
11425			"the broadcast at the prefix refuses what is beneath it"
11426		);
11427		assert!(best("src/a").is_some_and(|entry| entry.source.is_some()));
11428	}
11429
11430	/// A broader claim shown at a prefix never supersedes the claim of that prefix: an identity's
11431	/// higher epoch on a claim above the prefix is another claim's, so the announce stream
11432	/// advertises what a request resolves to, the broadcast here.
11433	#[kio::test]
11434	#[cfg(feature = "async")]
11435	async fn a_broader_claim_at_a_higher_epoch_does_not_supersede_the_exact_one() {
11436		// Updates are delivered at once: the hold is not what this checks.
11437		let producer = Config {
11438			update_hold: Duration::ZERO,
11439			..Config::from(origin(1))
11440		}
11441		.produce();
11442		let mut announced = producer.consume().routes();
11443		let identity = crate::Identity::random();
11444		let _exact = producer
11445			.route("src/a", RouteOptions::default().with_identity(identity.clone(), 0))
11446			.unwrap();
11447		let first = announced.expect_next_active("src/a").await;
11448		assert_eq!(first.epoch, 0);
11449
11450		let _broad = producer
11451			.forward(
11452				"src/a",
11453				RouteInfo::new()
11454					.with_identity(identity.clone(), 1)
11455					.with_hops(hops(&[10]))
11456					.with_node(Some(node_id(10)))
11457					.with_lane(Lane {
11458						above: 1,
11459						..Lane::default()
11460					}),
11461			)
11462			.unwrap();
11463
11464		let table = producer.shared.read();
11465		let best = table
11466			.best_route(
11467				&Path::new("src/a").unwrap(),
11468				Horizon::default(),
11469				&HashSet::new(),
11470				|_| true,
11471			)
11472			.expect("the exact claim serves its own prefix");
11473		assert_eq!((best.epoch, best.lane.above), (0, 0));
11474		drop(table);
11475		assert!(
11476			announced.try_next().is_none(),
11477			"the broader claim at a higher epoch must not replace the exact one in the announcement"
11478		);
11479	}
11480
11481	/// Claims of one prefix rank against each other wherever each is filed: a claim for `src`
11482	/// filed at `src/a` (shown there, a level above) never takes `src/a/b` from a claim made
11483	/// at `src` without being ranked against it. Its identity's higher epoch at `src`
11484	/// supersedes it, and so does a live claim of another identity outrank it while it drains,
11485	/// for a request and for an announce stream rooted beneath both.
11486	#[kio::test]
11487	#[cfg(feature = "async")]
11488	async fn a_claim_filed_deeper_ranks_against_the_claim_of_its_prefix() {
11489		let route = |identity: &crate::Identity, epoch, node, above, draining| {
11490			RouteInfo::new()
11491				.with_identity(identity.clone(), epoch)
11492				.with_hops(hops(&[node]))
11493				.with_node(Some(node_id(node)))
11494				.with_lane(Lane {
11495					above,
11496					..Lane::default()
11497				})
11498				.with_draining(draining)
11499		};
11500		let (old, other) = (crate::Identity::random(), crate::Identity::random());
11501		for (deep, direct) in [(old.clone(), old.clone()), (old.clone(), other.clone())] {
11502			// Updates are delivered at once: the hold is not what this checks.
11503			let producer = Config {
11504				update_hold: Duration::ZERO,
11505				..Config::from(origin(1))
11506			}
11507			.produce();
11508			let consumer = producer.consume();
11509			let mut announced = consumer.scope("src/a", &Prefixes::all()).unwrap().covering().routes();
11510			let filed = producer.forward("src/a", route(&deep, 1, 10, 1, true)).unwrap();
11511			let made = producer.forward("src", route(&direct, 2, 11, 0, false)).unwrap();
11512
11513			let _pending = consumer.request("src/a/b", None);
11514			let request = queued(&made).await;
11515			assert_eq!(request.path().as_str(), "src/a/b");
11516			assert!(
11517				filed.poll_requested(&kio::Waiter::noop()).is_pending(),
11518				"the claim filed deeper must not serve while it ranks below"
11519			);
11520			let mut last = None;
11521			while let Some(route) = announced.try_next() {
11522				last = Some(route);
11523			}
11524			let last = last.expect("the stream presents a claim at its root");
11525			assert_eq!(
11526				(last.announce.route.identity(), last.announce.route.epoch),
11527				(&direct, 2)
11528			);
11529		}
11530	}
11531
11532	/// A follower of a path ranks a claim filed deeper against the claim of its prefix as a
11533	/// request does, so a better claim of the tier filed shallower takes over.
11534	#[kio::test]
11535	#[cfg(feature = "async")]
11536	async fn a_follower_takes_the_claim_a_request_resolves() {
11537		let route = |identity: &crate::Identity, node, above, draining| {
11538			RouteInfo::new()
11539				.with_identity(identity.clone(), 0)
11540				.with_hops(hops(&[node]))
11541				.with_node(Some(node_id(node)))
11542				.with_lane(Lane {
11543					above,
11544					..Lane::default()
11545				})
11546				.with_draining(draining)
11547		};
11548		let producer = Config {
11549			update_hold: Duration::ZERO,
11550			..Config::from(origin(1))
11551		}
11552		.produce();
11553		let consumer = producer.consume();
11554		let mut follow = consumer.path_routes("src/a/b").unwrap();
11555		let (deep, direct) = (crate::Identity::random(), crate::Identity::random());
11556
11557		let _filed = producer.forward("src/a", route(&deep, 10, 1, true)).unwrap();
11558		let event = follow.next().await.expect("the origin is open");
11559		assert!(
11560			matches!(&event, RouteEvent { kind: RouteKind::Start, announce } if announce.route.identity() == &deep),
11561			"{event:?}"
11562		);
11563
11564		let made = producer.forward("src", route(&direct, 11, 0, false)).unwrap();
11565		let event = kio::clock::timeout(Duration::from_secs(1), follow.next())
11566			.await
11567			.expect("the follower hears the takeover")
11568			.expect("the origin is open");
11569		assert!(
11570			matches!(&event, RouteEvent { kind: RouteKind::Restart, announce } if announce.route.identity() == &direct),
11571			"{event:?}"
11572		);
11573		let _pending = consumer.request("src/a/b", None);
11574		assert_eq!(queued(&made).await.path().as_str(), "src/a/b");
11575	}
11576
11577	/// The identity a follower of `follow`'s path settles on, once it goes quiet.
11578	#[cfg(feature = "async")]
11579	async fn settled_on(follow: &mut Follow) -> Option<crate::Identity> {
11580		let mut serving = None;
11581		while let Ok(event) = kio::clock::timeout(Duration::from_secs(1), follow.next()).await {
11582			let event = event.expect("the origin is open");
11583			serving = match event.kind {
11584				RouteKind::End | RouteKind::Offline => None,
11585				_ => event.announce.route.identity.clone(),
11586			};
11587		}
11588		serving
11589	}
11590
11591	#[cfg(feature = "async")]
11592	fn claim_route(identity: &crate::Identity, node: u64, above: u8, cost: u64) -> RouteInfo {
11593		RouteInfo::new()
11594			.with_identity(identity.clone(), 0)
11595			.with_hops(hops(&[node]))
11596			.with_node(Some(node_id(node)))
11597			.with_lane(Lane {
11598				above,
11599				..Lane::default()
11600			})
11601			.with_cost(cost)
11602	}
11603
11604	/// A claim whose producer may not serve the path never wins a follower of it, however cheap,
11605	/// as it never wins a request.
11606	#[kio::test]
11607	#[cfg(feature = "async")]
11608	async fn a_follower_skips_a_claim_excluded_from_the_path() {
11609		let producer = Config {
11610			update_hold: Duration::ZERO,
11611			..Config::from(origin(1))
11612		}
11613		.produce();
11614		let consumer = producer.consume();
11615		let mut follow = consumer.path_routes("src/a/b").unwrap();
11616		let (cheap, allowed) = (crate::Identity::random(), crate::Identity::random());
11617		let excluded = producer.exclude("src/a/b").unwrap();
11618		let _cheap = excluded.forward("src", claim_route(&cheap, 10, 0, 1)).unwrap();
11619		let filed = producer.forward("src/a", claim_route(&allowed, 11, 1, 5)).unwrap();
11620		assert_eq!(settled_on(&mut follow).await, Some(allowed));
11621		let _pending = consumer.request("src/a/b", None);
11622		assert_eq!(queued(&filed).await.path().as_str(), "src/a/b");
11623	}
11624
11625	/// A broadcast published at a prefix serves only its own path, so a follower of a path beneath
11626	/// it settles on the claim of the same tier that serves, as a request does.
11627	#[kio::test]
11628	#[cfg(feature = "async")]
11629	async fn a_follower_skips_a_broadcast_that_cannot_serve_the_path() {
11630		let producer = Config {
11631			update_hold: Duration::ZERO,
11632			..Config::from(origin(1))
11633		}
11634		.produce();
11635		let consumer = producer.consume();
11636		let mut follow = consumer.path_routes("src/a/b").unwrap();
11637		let (published, claimed) = (crate::Identity::random(), crate::Identity::random());
11638		let _broadcast = producer
11639			.route("src", RouteOptions::default().with_identity(published, 0))
11640			.unwrap();
11641		let filed = producer.forward("src/a", claim_route(&claimed, 10, 1, 0)).unwrap();
11642		assert_eq!(settled_on(&mut follow).await, Some(claimed));
11643		let _pending = consumer.request("src/a/b", None);
11644		assert_eq!(queued(&filed).await.path().as_str(), "src/a/b");
11645	}
11646
11647	/// A request pinned to an identity follows that identity's own routes, so a better claim of
11648	/// another identity arriving with it, while discovery syncs, never ends the request.
11649	#[kio::test]
11650	#[cfg(feature = "async")]
11651	async fn a_pinned_request_resolves_its_identity_under_a_better_claim() {
11652		let producer = Config {
11653			update_hold: Duration::ZERO,
11654			..Config::from(origin(1))
11655		}
11656		.produce();
11657		let consumer = producer.consume();
11658		let snapshot = producer.snapshot("src");
11659		let (pinned, other) = (crate::Identity::random(), crate::Identity::random());
11660		let pending = consumer.request("src/a/b", pinned.clone());
11661		let filed = producer.forward("src/a", claim_route(&pinned, 10, 1, 5)).unwrap();
11662		let _made = producer.forward("src", claim_route(&other, 11, 0, 1)).unwrap();
11663		drop(snapshot);
11664		let answer = async {
11665			let request = kio::clock::timeout(Duration::from_secs(1), queued(&filed))
11666				.await
11667				.expect("the pinned identity was never asked");
11668			assert_eq!(request.path().as_str(), "src/a/b");
11669			let source = broadcast::Info::new().produce();
11670			request.serve(&source);
11671			source
11672		};
11673		let (result, _source) = futures::join!(kio::clock::timeout(Duration::from_secs(1), pending), answer);
11674		let resolved = result.expect("the pinned request never resolved").expect("resolves");
11675		assert_eq!(resolved.info().identity, Some(pinned));
11676	}
11677
11678	/// An escaped `/` belongs to its segment, so a claim filed beneath a scope's escaped prefix
11679	/// sits one segment below its own prefix, not two, and keeps that prefix's tier.
11680	#[test]
11681	fn a_filing_counts_an_escaped_slash_as_part_of_its_segment() {
11682		let mut scope = Prefixes::new();
11683		scope.insert(r"src/a\/b".parse().unwrap());
11684		let requested = Path::new("src").unwrap();
11685		assert_eq!(
11686			filed(&scope, &requested, |_| true),
11687			[(Path::new(r"src/a\/b").unwrap(), 1)]
11688		);
11689	}
11690
11691	/// Claims of one tier filed at different depths that tie through every rank hash on the path
11692	/// a covering stream presents them at, as a request for that path does, so the stream
11693	/// advertises what the request resolves to, for every pair of identities.
11694	#[test]
11695	fn a_covering_root_advertises_what_a_request_for_it_resolves() {
11696		let route = |name: &str, node, above| {
11697			RouteInfo::new()
11698				.with_identity(name.parse().unwrap(), 0)
11699				.with_hops(hops(&[node]))
11700				.with_node(Some(node_id(node)))
11701				.with_lane(Lane {
11702					above,
11703					..Lane::default()
11704				})
11705		};
11706		// A route entered here at the path skips the hash, so the claim filed at the root wins
11707		// whichever identity it carries; any other pair is settled by the hash on the root.
11708		for (link, i) in [Link::Peer, Link::Local]
11709			.into_iter()
11710			.flat_map(|link| (0..32).map(move |i| (link, i)))
11711		{
11712			let producer = Config {
11713				update_hold: Duration::ZERO,
11714				..Config::from(origin(1))
11715			}
11716			.produce();
11717			let mut announced = (producer.consume().scope("src/a", &Prefixes::all()).unwrap())
11718				.covering()
11719				.routes();
11720			let handle = producer.clone().with_link(link);
11721			let _made = handle.forward("src", route(&format!("made{i}"), 10, 0)).unwrap();
11722			let _filed = handle.forward("src/a", route(&format!("filed{i}"), 11, 1)).unwrap();
11723
11724			let table = producer.shared.read();
11725			let resolved = table
11726				.best_route(
11727					&Path::new("src/a").unwrap(),
11728					Horizon::default(),
11729					&HashSet::new(),
11730					|_| true,
11731				)
11732				.map(|entry| entry.identity.clone());
11733			drop(table);
11734			let mut advertised = None;
11735			while let Some(event) = announced.try_next() {
11736				advertised = Some(event.announce.route.identity().clone());
11737			}
11738			assert_eq!(advertised, resolved, "{link:?} pair {i}");
11739			if link == Link::Local {
11740				assert_eq!(resolved, Some(format!("filed{i}").parse().unwrap()), "pair {i}");
11741			}
11742		}
11743	}
11744
11745	/// A covering stream's root advertises the claim a request for the root takes, passing over a
11746	/// cheaper one that cannot serve it. A broadcast published above the root serves only its own
11747	/// path, so it ranks behind a tier-mate that serves. A claim whose producer excludes the root
11748	/// is no candidate at all: it neither outranks a tier-mate, shadows a broader claim, nor
11749	/// supersedes an older epoch of its identity.
11750	#[test]
11751	fn a_covering_root_passes_over_a_claim_that_cannot_serve_it() {
11752		#[derive(Debug, Clone, Copy)]
11753		enum Case {
11754			Broadcast,
11755			Excluded,
11756			ExcludedShadow,
11757			ExcludedEpoch,
11758		}
11759		let route = |identity: &crate::Identity, epoch, node, above, cost: u64| {
11760			RouteInfo::new()
11761				.with_identity(identity.clone(), epoch)
11762				.with_hops(hops(&[node]))
11763				.with_node(Some(node_id(node)))
11764				.with_lane(Lane {
11765					above,
11766					..Lane::default()
11767				})
11768				.with_cost(cost)
11769		};
11770		for case in [
11771			Case::Broadcast,
11772			Case::Excluded,
11773			Case::ExcludedShadow,
11774			Case::ExcludedEpoch,
11775		] {
11776			let producer = Config {
11777				update_hold: Duration::ZERO,
11778				..Config::from(origin(1))
11779			}
11780			.produce();
11781			let mut announced = (producer.consume().scope("src/a", &Prefixes::all()).unwrap())
11782				.covering()
11783				.routes();
11784			let (cheap, serving) = (crate::Identity::random(), crate::Identity::random());
11785			let excluded = producer.exclude("src/a").unwrap();
11786			let mut held = Vec::new();
11787			let mut broadcast = None;
11788			match case {
11789				Case::Broadcast => {
11790					let options = RouteOptions::default().with_identity(cheap.clone(), 0);
11791					broadcast = Some(producer.route("src", options).unwrap());
11792					held.push(producer.forward("src/a", route(&serving, 0, 11, 1, 5)).unwrap());
11793				}
11794				Case::Excluded => {
11795					held.push(excluded.forward("src", route(&cheap, 0, 10, 0, 0)).unwrap());
11796					held.push(producer.forward("src/a", route(&serving, 0, 11, 1, 5)).unwrap());
11797				}
11798				Case::ExcludedShadow => {
11799					held.push(excluded.forward("src", route(&cheap, 0, 10, 0, 0)).unwrap());
11800					held.push(producer.forward("", route(&serving, 0, 11, 0, 5)).unwrap());
11801				}
11802				Case::ExcludedEpoch => {
11803					held.push(excluded.forward("src", route(&serving, 2, 10, 0, 0)).unwrap());
11804					held.push(producer.forward("src/a", route(&serving, 1, 11, 1, 5)).unwrap());
11805				}
11806			}
11807
11808			let table = producer.shared.read();
11809			let resolved = table
11810				.best_route(
11811					&Path::new("src/a").unwrap(),
11812					Horizon::default(),
11813					&HashSet::new(),
11814					|_| true,
11815				)
11816				.map(|entry| (entry.identity.clone(), entry.cost));
11817			drop(table);
11818			assert_eq!(resolved, Some((serving.clone(), Cost::from(5u64))), "{case:?}");
11819			let mut advertised = None;
11820			while let Some(event) = announced.try_next() {
11821				advertised = Some((event.announce.route.identity().clone(), event.announce.route.cost()));
11822			}
11823			assert_eq!(advertised, resolved, "{case:?}");
11824			drop((held, broadcast));
11825		}
11826	}
11827
11828	/// A stream's row beneath its root ranks a route that serves its prefix ahead of a cheaper
11829	/// one that serves nothing, whether the row was synced as the routes arrived or replayed
11830	/// for a stream that started after them.
11831	#[test]
11832	fn a_row_ranks_a_serving_route_alike_synced_or_replayed() {
11833		let producer = Config {
11834			update_hold: Duration::ZERO,
11835			..Config::from(origin(1))
11836		}
11837		.produce();
11838		let mut synced = producer.consume().routes();
11839		let (advertised, serving) = (crate::Identity::random(), crate::Identity::random());
11840		let route = |identity: &crate::Identity, node, cost: u64| {
11841			RouteInfo::new()
11842				.with_identity(identity.clone(), 0)
11843				.with_hops(hops(&[node]))
11844				.with_cost(cost)
11845		};
11846		let _advertised = producer.announce("src", route(&advertised, 10, 1)).unwrap();
11847		let _serving = producer.forward("src", route(&serving, 11, 5)).unwrap();
11848		let mut replayed = producer.consume().routes();
11849		let last = |announced: &mut Routes| {
11850			let mut last = None;
11851			while let Some(event) = announced.try_next() {
11852				last = Some(event.announce.route.identity().clone());
11853			}
11854			last
11855		};
11856		assert_eq!(last(&mut synced), Some(serving.clone()));
11857		assert_eq!(last(&mut replayed), Some(serving));
11858	}
11859
11860	/// A draining route still reaches its origin, so it outranks one held unavailable,
11861	/// however cheap: the held route may serve nothing.
11862	#[kio::test]
11863	#[cfg(feature = "async")]
11864	async fn a_draining_route_outranks_an_unavailable_one() {
11865		let producer = origin(1).produce();
11866		let consumer = producer.consume();
11867		let held = RouteInfo::new()
11868			.with_hops(hops(&[10]))
11869			.with_node(Some(node_id(10)))
11870			.with_lane(Lane {
11871				priority: Some(0),
11872				..Lane::default()
11873			})
11874			.with_available(false)
11875			.with_cost(1);
11876		let held = producer.forward("room", held).unwrap();
11877		let draining = producer
11878			.clone()
11879			.with_link(Link::Peer)
11880			.forward(
11881				"room",
11882				RouteInfo::new().with_hops(hops(&[11])).with_cost(5).with_draining(true),
11883			)
11884			.unwrap();
11885
11886		let _pending = consumer.request("room/alice", None);
11887		let request = queued(&draining).await;
11888		assert_eq!(request.path().as_str(), "room/alice");
11889		assert!(
11890			held.poll_requested(&kio::Waiter::noop()).is_pending(),
11891			"the unavailable route must not serve while a draining one reaches the origin"
11892		);
11893	}
11894
11895	/// A route learned over an older version reaches the route node with its link priority
11896	/// and its drain, so the claim this node announces for it ranks as the route does here.
11897	/// A drain that changes nothing a reader sees still reaches the node, at once: the update
11898	/// hold damps path hunting, which a drain is not, and a peer closing within the hold would
11899	/// otherwise end the route before the node ever learned it drains.
11900	#[test]
11901	fn the_route_node_learns_a_bridged_routes_priority_and_drain() {
11902		use crate::route::relay;
11903		let config = Config::from(origin(1));
11904		assert!(!config.update_hold().is_zero());
11905		let producer = config.produce();
11906		let route = RouteInfo::new().with_hops(hops(&[10])).with_cost(3);
11907		let bridged = (producer.clone().with_link(Link::Peer))
11908			.with_priority(Priority::new(-5))
11909			.forward("room/alice", route)
11910			.unwrap();
11911		let stream = route_stream(&producer.route_node());
11912		let told = |stream: &crate::route::node::Stream| {
11913			std::iter::from_fn(|| stream.try_wire())
11914				.filter_map(|msg| match msg {
11915					relay::Msg::Announce { changes } => Some(changes),
11916					_ => None,
11917				})
11918				.flatten()
11919				.filter_map(|(_, change)| match change {
11920					relay::Change::Live(claim) => Some((claim.priority, claim.draining)),
11921					_ => None,
11922				})
11923				.last()
11924		};
11925		assert_eq!(told(&stream), Some((-5, false)));
11926
11927		bridged.update(bridged.route().unwrap().with_draining(true)).unwrap();
11928		// Nothing polls this test's driver: `route_node` catches the feeder up.
11929		producer.route_node();
11930		stream.flush();
11931		assert_eq!(told(&stream), Some((-5, true)));
11932	}
11933
11934	/// A restarted publisher's dead identity, held unavailable, never wins back the path from
11935	/// its live replacement while the replacement's closest way moves to another session:
11936	/// the old way is demoted before the session taking over serves the new one.
11937	#[kio::test]
11938	#[cfg(feature = "async")]
11939	async fn a_dead_identity_never_outranks_a_live_one_between_its_ways() {
11940		let producer = origin(1).produce();
11941		let consumer = producer.consume();
11942		let mut announced = consumer.routes();
11943		let route = |identity: &crate::Identity, node, primary, available, cost| {
11944			RouteInfo::new()
11945				.with_identity(identity.clone(), 0)
11946				.with_hops(hops(&[node]))
11947				.with_node(Some(node_id(node)))
11948				.with_lane(Lane {
11949					primary,
11950					priority: Some(0),
11951					..Lane::default()
11952				})
11953				.with_available(available)
11954				.with_cost(cost)
11955		};
11956		let (dead, live) = (crate::Identity::random(), crate::Identity::random());
11957
11958		// The dead identity is cheaper, and still the closest way to its own claim.
11959		let _dead = producer
11960			.forward("room/alice", route(&dead, 10, true, false, 1))
11961			.unwrap();
11962		let way = producer.forward("room/alice", route(&live, 11, true, true, 5)).unwrap();
11963		assert_eq!(announced.expect_next_active("room/alice").await.identity(), &live);
11964
11965		way.update(route(&live, 11, false, true, 5)).unwrap();
11966		assert!(
11967			announced.try_next().is_none(),
11968			"the live identity's demoted way keeps the path"
11969		);
11970		let _pending = consumer.request("room/alice", None);
11971		let request = queued(&way).await;
11972		assert_eq!(request.path().as_str(), "room/alice");
11973	}
11974
11975	/// A draining route ranks below every other eligible one, even on a preferred link
11976	/// against a demoted one, whatever the costs say.
11977	#[kio::test]
11978	#[cfg(feature = "async")]
11979	async fn request_avoids_a_draining_route_even_on_a_preferred_link() {
11980		let producer = origin(1).produce();
11981		let consumer = producer.consume();
11982
11983		let draining = producer
11984			.clone()
11985			.with_priority(Priority::new(1))
11986			.forward(
11987				"room",
11988				RouteInfo::new().with_hops(hops(&[10])).with_cost(1).with_draining(true),
11989			)
11990			.unwrap();
11991		let demoted = producer
11992			.clone()
11993			.with_priority(Priority::new(-1))
11994			.forward("room", RouteInfo::new().with_hops(hops(&[11])).with_cost(5))
11995			.unwrap();
11996		let _bob = consumer.request("room/bob", None);
11997		let request = queued(&demoted).await;
11998		assert_eq!(request.path().as_str(), "room/bob");
11999		assert!(
12000			draining.poll_requested(&kio::Waiter::noop()).is_pending(),
12001			"the draining route must not serve"
12002		);
12003	}
12004
12005	/// Draining is local selection state: the winner draining changes nothing a reader
12006	/// sees, and the route keeps its real cost.
12007	#[kio::test]
12008	async fn draining_is_invisible_to_readers() {
12009		let producer = origin(1).produce();
12010		let mut announced = producer.consume().routes();
12011
12012		let dynamic = producer
12013			.forward("room", RouteInfo::new().with_hops(hops(&[10])).with_cost(3))
12014			.unwrap();
12015		announced.expect_next_active("room").await;
12016		dynamic.update(dynamic.route().unwrap().with_draining(true)).unwrap();
12017		// Past the hold a best-route change would wait out.
12018		// An update is held back from the poll that first sees it, so poll on both sides of the hold.
12019		announced.assert_next_wait();
12020		kio::clock::sleep(Config::default().update_hold * 2).await;
12021		announced.assert_next_wait();
12022		let route = dynamic.route().unwrap();
12023		assert_eq!((route.cost, route.draining), (Cost::new(3), true));
12024	}
12025
12026	#[kio::test]
12027	async fn update_reprices_in_place() {
12028		let producer = origin(1).produce();
12029		let mut announced = producer.consume().routes();
12030
12031		let announcement = producer.announce("room", RouteInfo::new()).unwrap();
12032		announced.expect_next_active("room").await;
12033
12034		announcement.update(RouteInfo::new().with_cost(9)).unwrap();
12035		let route = announced.expect_next_active("room").await;
12036		assert_eq!(route.cost, Cost::new(9));
12037	}
12038
12039	/// Re-pricing from the current route keeps the identity, so it stays one broadcast.
12040	#[kio::test]
12041	async fn reprice_from_the_current_route_keeps_the_identity() {
12042		let producer = origin(1).produce();
12043		let mut announced = producer.consume().routes();
12044
12045		let dynamic = producer
12046			.forward("room", RouteInfo::new().with_identity(identity(), 0).with_cost(5))
12047			.unwrap();
12048		announced.expect_next_active("room").await;
12049		dynamic.update(dynamic.route().unwrap().with_cost(1)).unwrap();
12050		let route = announced.expect_next_active("room").await;
12051		assert_eq!((route.identity, route.cost), (Some(identity()), Cost::new(1)));
12052		assert_eq!(dynamic.route().unwrap().cost, Cost::new(1));
12053
12054		let options = RouteOptions::hidden().with_identity(identity(), 0).with_cost(5);
12055		let broadcast = producer.route("lobby", options).unwrap();
12056		assert!(broadcast.route().is_none(), "not announced yet");
12057		broadcast.announce().unwrap();
12058		announced.expect_next_active("lobby").await;
12059		broadcast.set_cost(1).unwrap();
12060		let route = announced.expect_next_active("lobby").await;
12061		assert_eq!((route.identity, route.cost), (Some(identity()), Cost::new(1)));
12062		broadcast.withdraw();
12063		assert!(broadcast.route().is_none(), "withdrawn");
12064	}
12065
12066	#[kio::test]
12067	async fn retract_after_undelivered_reprice_still_delivered() {
12068		let producer = origin(1).produce();
12069		let mut announced = producer.consume().routes();
12070
12071		let announcement = producer.announce("room", RouteInfo::new()).unwrap();
12072		announced.expect_next_active("room").await;
12073
12074		// Reprice, then retract before the consumer observes the reprice: the
12075		// pending metadata update must not cancel the retraction the delivered
12076		// announce still owes.
12077		announcement.update(RouteInfo::new().with_cost(9)).unwrap();
12078		drop(announcement);
12079		announced.expect_next_ended("room").await;
12080		announced.assert_next_wait();
12081	}
12082
12083	#[kio::test]
12084	async fn scoped_cursor_advertises_most_specific_covering_route() {
12085		let producer = origin(1).produce();
12086		// Broad and cheap; narrow and expensive. Both present relative to a cursor
12087		// rooted below them, and the narrow one is what a request there resolves.
12088		let _broad = producer.announce("room", RouteInfo::new().with_cost(1)).unwrap();
12089		let _narrow = producer.announce("room/alice", RouteInfo::new().with_cost(9)).unwrap();
12090
12091		let consumer = producer.consume().scope("room/alice", &Prefixes::all()).unwrap();
12092		let mut announced = consumer.routes();
12093		let route = announced.expect_next_active("").await;
12094		assert_eq!(route.cost, Cost::new(9));
12095		announced.assert_next_wait();
12096	}
12097
12098	/// A broader route of another identity taking over a presented prefix from a lost one
12099	/// is a restart: another identity serves the prefix, so it never goes offline.
12100	#[kio::test]
12101	async fn a_broader_route_taking_over_a_lost_one_restarts() {
12102		let producer = origin(1).produce();
12103		let _broad = producer.announce("room", RouteInfo::new()).unwrap();
12104		let exact = producer.forward("room/alice", RouteInfo::new()).unwrap();
12105		let mut announced = producer
12106			.consume()
12107			.scope("room/alice", &Prefixes::all())
12108			.unwrap()
12109			.covering()
12110			.routes();
12111		announced.expect_next_active("").await;
12112
12113		drop(exact);
12114		announced.expect_next_restarted("").await;
12115		announced.assert_next_wait();
12116	}
12117
12118	#[kio::test]
12119	#[cfg(feature = "async")]
12120	async fn restart_coalesced_keeps_the_lost_identity_offline() {
12121		let producer = origin(1).produce();
12122		let lost = producer.forward("room/alice", RouteInfo::new()).unwrap();
12123		let mut announced = producer.consume().routes();
12124		announced.expect_next_active("room/alice").await;
12125
12126		// Another identity comes and is withdrawn before the next poll: the one
12127		// retraction delivered is the lost identity's.
12128		drop(lost);
12129		let other = producer.announce("room/alice", RouteInfo::new()).unwrap();
12130		drop(other);
12131		announced.expect_next_offline("room/alice").await;
12132	}
12133
12134	/// A broader route taking over from a lost one, then withdrawn before the next poll,
12135	/// retracts the identity the consumer holds as lost, not ended.
12136	#[kio::test]
12137	#[cfg(feature = "async")]
12138	async fn a_broader_takeover_withdrawn_before_the_poll_keeps_the_lost_route_offline() {
12139		let producer = origin(1).produce();
12140		let broad = producer.announce("room", RouteInfo::new()).unwrap();
12141		let exact = producer.forward("room/alice", RouteInfo::new()).unwrap();
12142		let mut announced = producer
12143			.consume()
12144			.scope("room/alice", &Prefixes::all())
12145			.unwrap()
12146			.covering()
12147			.routes();
12148		let held = announced.expect_next_active("").await.identity().clone();
12149
12150		drop(exact);
12151		drop(broad);
12152		match announced.expect_next().await {
12153			RouteEvent {
12154				kind: RouteKind::Offline,
12155				announce,
12156			} => assert_eq!(announce.route.identity(), &held),
12157			other => panic!("should go offline: got {other:?}"),
12158		}
12159	}
12160
12161	/// An identity already present taking over from a lost one, then withdrawn before the
12162	/// next poll, retracts the identity the consumer holds as lost, not ended.
12163	#[kio::test]
12164	#[cfg(feature = "async")]
12165	async fn a_present_takeover_withdrawn_before_the_poll_keeps_the_lost_identity_offline() {
12166		let producer = origin(1).produce();
12167		let lost = producer
12168			.forward("room/alice", RouteInfo::new().with_hops(hops(&[10])).with_cost(1))
12169			.unwrap();
12170		let mut announced = producer.consume().routes();
12171		let held = announced.expect_next_active("room/alice").await.identity().clone();
12172		let present = producer
12173			.announce("room/alice", RouteInfo::new().with_cost(100))
12174			.unwrap();
12175		announced.assert_next_wait();
12176
12177		drop(lost);
12178		drop(present);
12179		match announced.expect_next().await {
12180			RouteEvent {
12181				kind: RouteKind::Offline,
12182				announce,
12183			} => assert_eq!(announce.route.identity(), &held),
12184			other => panic!("should go offline: got {other:?}"),
12185		}
12186	}
12187
12188	/// A cheaper route outranking the held one, then both lost before the next poll, retracts
12189	/// the held identity as lost: neither publisher withdrew.
12190	#[kio::test]
12191	#[cfg(feature = "async")]
12192	async fn an_outranked_route_lost_with_its_replacement_goes_offline() {
12193		let producer = origin(1).produce();
12194		let mut announced = producer.consume().routes();
12195		let first: crate::Identity = "01900000-0000-7000-8000-000000000002".parse().unwrap();
12196		let held = producer
12197			.forward(
12198				"room/alice",
12199				RouteInfo::new()
12200					.with_identity(first, 0)
12201					.with_hops(hops(&[10]))
12202					.with_cost(3),
12203			)
12204			.unwrap();
12205		let listed = announced.expect_next_active("room/alice").await.identity().clone();
12206
12207		let cheaper = producer
12208			.forward(
12209				"room/alice",
12210				RouteInfo::new()
12211					.with_identity(identity(), 0)
12212					.with_hops(hops(&[11]))
12213					.with_cost(1),
12214			)
12215			.unwrap();
12216		drop(held);
12217		drop(cheaper);
12218		match announced.expect_next().await {
12219			RouteEvent {
12220				kind: RouteKind::Offline,
12221				announce,
12222			} => assert_eq!(announce.route.identity(), &listed),
12223			other => panic!("should go offline: got {other:?}"),
12224		}
12225	}
12226
12227	/// A restart onto another identity and back before the next poll leaves the identity
12228	/// the consumer holds: an update, never a restart to the same identity.
12229	#[kio::test]
12230	#[cfg(feature = "async")]
12231	async fn restart_away_and_back_is_an_update() {
12232		let producer = origin(1).produce();
12233		let mut announced = producer.consume().routes();
12234		let held: crate::Identity = "01900000-0000-7000-8000-000000000002".parse().unwrap();
12235		let _held = producer
12236			.forward(
12237				"room/alice",
12238				RouteInfo::new()
12239					.with_identity(held.clone(), 0)
12240					.with_hops(hops(&[10]))
12241					.with_cost(3),
12242			)
12243			.unwrap();
12244		announced.expect_next_active("room/alice").await;
12245
12246		let other = producer
12247			.forward(
12248				"room/alice",
12249				RouteInfo::new()
12250					.with_identity(identity(), 0)
12251					.with_hops(hops(&[11]))
12252					.with_cost(1),
12253			)
12254			.unwrap();
12255		drop(other);
12256		match announced.expect_next().await {
12257			RouteEvent {
12258				kind: RouteKind::Update,
12259				announce,
12260			} => assert_eq!(announce.route.identity(), &held),
12261			other => panic!("should be an update: got {other:?}"),
12262		}
12263	}
12264
12265	#[kio::test]
12266	#[cfg(feature = "async")]
12267	async fn follow_resolves_once_announced() {
12268		let producer = origin(1).produce();
12269		let consumer = producer.consume();
12270
12271		// Asking before anything is announced parks instead of failing Unroutable.
12272		let mut following = consumer.follow("room/alice", None).unwrap();
12273		let mut resolving = Box::pin(following.available());
12274		assert!((&mut resolving).now_or_never().is_none());
12275
12276		// Creating is not announcing: still parked.
12277		let broadcast = producer.route("room/alice", RouteOptions::hidden()).unwrap();
12278		for _ in 0..20 {
12279			kio::clock::sim::yield_now().await;
12280		}
12281		assert!((&mut resolving).now_or_never().is_none());
12282
12283		broadcast.announce().unwrap();
12284		let resolved = resolving.await.expect("resolves once announced").unwrap();
12285		assert_eq!(resolved.info().path.as_str(), "room/alice");
12286		drop(broadcast);
12287	}
12288
12289	/// A local broadcast competes on its announced cost: a cheaper route at the
12290	/// same path wins, for cursors and requests alike.
12291	#[kio::test]
12292	#[cfg(feature = "async")]
12293	async fn cheaper_remote_route_beats_a_local_broadcast() {
12294		let producer = origin(1).produce();
12295		let consumer = producer.consume();
12296		let mut announced = consumer.routes();
12297
12298		let _local = producer
12299			.route(
12300				"room/alice",
12301				RouteOptions::default().with_identity(identity(), 0).with_cost(5),
12302			)
12303			.unwrap();
12304		assert_eq!(announced.expect_next_active("room/alice").await.cost, Cost::new(5));
12305
12306		let server = producer
12307			.forward(
12308				"room/alice",
12309				RouteInfo::new()
12310					.with_identity(identity(), 0)
12311					.with_hops(hops(&[10]))
12312					.with_cost(1),
12313			)
12314			.unwrap();
12315		let route = announced.expect_next_active("room/alice").await;
12316		assert_eq!(route.cost, Cost::new(1));
12317		assert_eq!(route.hops, hops(&[10]));
12318
12319		// The request goes upstream rather than to the local broadcast.
12320		let pending = consumer.request("room/alice", None);
12321		let request = queued(&server).await;
12322		let upstream = broadcast::Info::new().produce();
12323		request.serve(&upstream);
12324		pending.await.expect("resolves through the cheaper route");
12325	}
12326
12327	/// A resolved broadcast names the identity of the route it came through: a stable
12328	/// one, or the one its publication minted.
12329	#[kio::test]
12330	#[cfg(feature = "async")]
12331	async fn a_resolved_broadcast_carries_its_route_identity() {
12332		let producer = origin(1).produce();
12333		let consumer = producer.consume();
12334
12335		let _stable = producer
12336			.route("room/alice", RouteOptions::default().with_identity(identity(), 0))
12337			.unwrap();
12338		let minted = producer.route("room/bob", RouteOptions::default()).unwrap();
12339
12340		let alice = consumer.request("room/alice", None).await.unwrap();
12341		assert_eq!(alice.info().identity, Some(identity()));
12342		let bob = consumer.request("room/bob", None).await.unwrap();
12343		let identity = minted.route().unwrap().identity;
12344		assert!(identity.is_some());
12345		assert_eq!(bob.info().identity, identity);
12346	}
12347
12348	/// A cheaper route that appears after a front was minted takes the front over: it
12349	/// carries the same identity, so a newcomer joins the front.
12350	#[kio::test]
12351	#[cfg(feature = "async")]
12352	async fn cheaper_route_after_a_front_takes_it_over() {
12353		let producer = origin(1).produce();
12354		let consumer = producer.consume();
12355
12356		let _local = producer
12357			.route(
12358				"room/alice",
12359				RouteOptions::default().with_identity(identity(), 0).with_cost(5),
12360			)
12361			.unwrap();
12362		let first = consumer.request("room/alice", None).await.expect("resolves locally");
12363
12364		let server = producer
12365			.forward(
12366				"room/alice",
12367				RouteInfo::new()
12368					.with_identity(identity(), 0)
12369					.with_hops(hops(&[10]))
12370					.with_cost(1),
12371			)
12372			.unwrap();
12373		let request = queued(&server).await;
12374		let upstream = broadcast::Info::new().produce();
12375		request.serve(&upstream);
12376
12377		let second = consumer.request("room/alice", None).await.expect("resolves");
12378		assert!(first.is_clone(&second), "the newcomer joins the front");
12379	}
12380
12381	/// The next event, a datagram track's name prefixed `d:`.
12382	#[cfg(feature = "async")]
12383	async fn listed(tracks: &mut broadcast::Tracks) -> String {
12384		let named = |kind: broadcast::Kind, name: Arc<str>| match kind {
12385			broadcast::Kind::Track => name.to_string(),
12386			broadcast::Kind::Datagrams => format!("d:{name}"),
12387		};
12388		match tracks.next().await {
12389			Ok(Some(broadcast::TracksEvent::Added { name, info })) => format!("+{}", named(info.kind(), name)),
12390			Ok(Some(broadcast::TracksEvent::Removed { kind, name })) => format!("-{}", named(kind, name)),
12391			Ok(Some(broadcast::TracksEvent::Finished { kind, name })) => format!("~{}", named(kind, name)),
12392			Ok(Some(broadcast::TracksEvent::Synced)) => "synced".into(),
12393			Ok(None) => "end".into(),
12394			Err(err) => format!("error: {err}"),
12395		}
12396	}
12397
12398	/// A front lists what its serving source lists, as it changes.
12399	#[kio::test]
12400	#[cfg(feature = "async")]
12401	async fn a_front_lists_its_source() {
12402		let producer = origin(1).produce();
12403		let consumer = producer.consume();
12404		let source = producer.route("room/alice", RouteOptions::default()).unwrap();
12405		let video = source.broadcast().create_track("video", None).unwrap();
12406
12407		let front = consumer.request("room/alice", None).await.unwrap();
12408		let mut tracks = front.tracks().unwrap();
12409		assert_eq!(listed(&mut tracks).await, "+video");
12410		assert_eq!(listed(&mut tracks).await, "synced");
12411
12412		let _audio = source.broadcast().create_track("audio", None).unwrap();
12413		assert_eq!(listed(&mut tracks).await, "+audio");
12414		let datagrams = source
12415			.broadcast()
12416			.create_datagrams("video", Default::default())
12417			.unwrap();
12418		assert_eq!(listed(&mut tracks).await, "+d:video");
12419		drop(video);
12420		assert_eq!(listed(&mut tracks).await, "-video");
12421		datagrams.finish();
12422		assert_eq!(listed(&mut tracks).await, "~d:video");
12423
12424		drop(source);
12425		assert_eq!(listed(&mut tracks).await, "end");
12426	}
12427
12428	/// A source closing right after its tracks finished, held or not, ends the front's
12429	/// listing after those finishes, never ahead of them.
12430	#[kio::test]
12431	#[cfg(feature = "async")]
12432	async fn a_front_forwards_the_finishes_before_its_source_closed() {
12433		let producer = origin(1).produce();
12434		let consumer = producer.consume();
12435		let source = producer.route("room/alice", RouteOptions::default()).unwrap();
12436		let dropped = source.broadcast().create_track("dropped", None).unwrap();
12437		let held = source.broadcast().create_track("held", None).unwrap();
12438		let _live = source.broadcast().create_track("live", None).unwrap();
12439
12440		let front = consumer.request("room/alice", None).await.unwrap();
12441		let mut tracks = front.tracks().unwrap();
12442		for event in ["+dropped", "+held", "+live", "synced"] {
12443			assert_eq!(listed(&mut tracks).await, event);
12444		}
12445
12446		let dropped = dropped.finish().unwrap();
12447		drop(dropped);
12448		let _held = held.finish().unwrap();
12449		source.broadcast().close();
12450		for event in ["~dropped", "~held", "end"] {
12451			assert_eq!(listed(&mut tracks).await, event);
12452		}
12453	}
12454
12455	/// A source's handler ending its listing while the source stays, as a session does on
12456	/// its peer's FIN before any retraction, ends the front's listing too.
12457	#[kio::test]
12458	#[cfg(feature = "async")]
12459	async fn a_front_ends_its_listing_with_its_sources() {
12460		let producer = origin(1).produce();
12461		let consumer = producer.consume();
12462		let source = producer.route("room/alice", RouteOptions::default()).unwrap();
12463		let lister = source.broadcast().requests().lister().unwrap();
12464		lister.add("video", crate::track::Info::default()).unwrap();
12465		lister.synced();
12466
12467		let front = consumer.request("room/alice", None).await.unwrap();
12468		let mut tracks = front.tracks().unwrap();
12469		assert_eq!(listed(&mut tracks).await, "+video");
12470		assert_eq!(listed(&mut tracks).await, "synced");
12471
12472		lister.end();
12473		assert_eq!(listed(&mut tracks).await, "end");
12474		assert!(!front.is_closed(), "the listing's end is not the broadcast's");
12475	}
12476
12477	/// A same-identity route taking the front over lists the same tracks: readers see
12478	/// only what differs, once the new source's listing synced.
12479	#[kio::test]
12480	#[cfg(feature = "async")]
12481	async fn a_front_reconciles_a_takeover() {
12482		let producer = origin(1).produce();
12483		let consumer = producer.consume();
12484		let local = producer
12485			.route(
12486				"room/alice",
12487				RouteOptions::default().with_identity(identity(), 0).with_cost(5),
12488			)
12489			.unwrap();
12490		let _a = local.broadcast().create_track("a", None).unwrap();
12491		let _b = local.broadcast().create_track("b", None).unwrap();
12492
12493		let front = consumer.request("room/alice", None).await.unwrap();
12494		let mut tracks = front.tracks().unwrap();
12495		assert_eq!(listed(&mut tracks).await, "+a");
12496		assert_eq!(listed(&mut tracks).await, "+b");
12497		assert_eq!(listed(&mut tracks).await, "synced");
12498
12499		let server = producer
12500			.forward(
12501				"room/alice",
12502				RouteInfo::new()
12503					.with_identity(identity(), 0)
12504					.with_hops(hops(&[10]))
12505					.with_cost(1),
12506			)
12507			.unwrap();
12508		let upstream = broadcast::Info::new().produce();
12509		let _b = upstream.create_track("b", None).unwrap();
12510		let _c = upstream.create_track("c", None).unwrap();
12511		queued(&server).await.serve(&upstream);
12512
12513		assert_eq!(listed(&mut tracks).await, "+c");
12514		assert_eq!(listed(&mut tracks).await, "-a");
12515	}
12516
12517	/// A path served on request through a covering prefix is not a broadcast anyone
12518	/// announced, so it has nothing to list.
12519	#[kio::test]
12520	#[cfg(feature = "async")]
12521	async fn a_front_through_a_covering_prefix_lists_nothing() {
12522		let producer = origin(1).produce();
12523		let consumer = producer.consume();
12524		let server = producer.forward("room", RouteInfo::new()).unwrap();
12525		let pending = consumer.request("room/alice", None);
12526		let upstream = broadcast::Info::new().produce();
12527		let _video = upstream.create_track("video", None).unwrap();
12528		queued(&server).await.serve(&upstream);
12529		let front = pending.await.unwrap();
12530
12531		let mut tracks = front.tracks().unwrap();
12532		assert_eq!(listed(&mut tracks).await, format!("error: {}", Error::NotFound));
12533	}
12534
12535	/// At equal cost the local broadcast wins even over a route with no hops of its
12536	/// own, such as a later claim on this origin: locality is the tie-break after
12537	/// cost, not the newest entry.
12538	#[kio::test]
12539	#[cfg(feature = "async")]
12540	async fn local_broadcast_wins_a_tie_with_a_hopless_route() {
12541		let producer = origin(1).produce();
12542		let consumer = producer.consume();
12543
12544		let _local = producer.route("room/alice", RouteOptions::default()).unwrap();
12545		let server = producer.forward("room/alice", RouteInfo::new()).unwrap();
12546
12547		// Were the claim to win, the request would park on its handler forever.
12548		let resolved = kio::clock::timeout(Duration::from_secs(1), consumer.request("room/alice", None))
12549			.await
12550			.expect("the newer hopless route won the tie")
12551			.expect("resolves");
12552		assert_eq!(resolved.info().path.as_str(), "room/alice");
12553		assert!(server.poll_requested(&kio::Waiter::noop()).is_pending());
12554	}
12555
12556	/// Ingress announce stats count advertised intervals, not the broadcast's
12557	/// lifetime: nothing while hidden, one per announce, none for a re-price.
12558	#[kio::test]
12559	async fn announce_stats_follow_the_advertisement() {
12560		let registry = stats::Registry::new(stats::Config::new());
12561		let producer = origin(1).produce().with_stats(
12562			registry
12563				.tier(stats::Tier::default())
12564				.session(crate::stats::SessionInfo::new(crate::Path::from_static("root"))),
12565		);
12566		let announces = || {
12567			registry
12568				.snapshot()
12569				.traffic()
12570				.into_iter()
12571				.find(|(_, role, _)| *role == stats::Role::Subscriber)
12572				.map(|(_, _, traffic)| (traffic.announces_started, traffic.announces_ended))
12573				.unwrap_or_default()
12574		};
12575
12576		let broadcast = producer.route("room/alice", RouteOptions::hidden()).unwrap();
12577		assert_eq!(announces(), (0, 0), "a hidden broadcast is not announced");
12578		broadcast.announce().unwrap();
12579		broadcast.set_cost(3).unwrap();
12580		assert_eq!(announces(), (1, 0), "a re-price is not another announce");
12581		broadcast.withdraw();
12582		assert_eq!(announces(), (1, 1));
12583		broadcast.announce().unwrap();
12584		drop(broadcast);
12585		assert_eq!(announces(), (2, 2));
12586	}
12587
12588	/// A route node already fed by its driver still answers a new stream with the table as
12589	/// it stands, including a claim announced since the driver last ran, whichever handle
12590	/// created it: one scoped away from the claim, upstream, and hiding hidden
12591	/// routes sees the whole table all the same.
12592	#[test]
12593	fn the_route_node_answers_with_the_table_as_it_stands() {
12594		let producer = origin(1).produce();
12595		(producer.clone().with_link(Link::Upstream).consume())
12596			.scope("elsewhere", &Prefixes::all())
12597			.unwrap()
12598			.with_hidden(false)
12599			.route_node();
12600		// Nothing polls this test's driver.
12601		let _shown = producer.announce("room/alice", RouteInfo::new()).unwrap();
12602		let stream = route_stream(&producer.route_node());
12603		assert!(
12604			route_changes(&stream)
12605				.iter()
12606				.any(|(path, live)| path.as_str() == "room/alice" && *live),
12607			"the new stream is told the announced claim"
12608		);
12609	}
12610
12611	/// A route that takes a path over from another reaches the route node before the one
12612	/// it replaces ends, so a peer reading the two apart sees the path restart, not end.
12613	#[test]
12614	fn a_takeover_tells_the_route_node_the_successor_first() {
12615		use crate::route::relay;
12616		let producer = origin(1).produce();
12617		let old = producer.route("room/alice", RouteOptions::hidden()).unwrap();
12618		old.announce().unwrap();
12619		let stream = route_stream(&producer.route_node());
12620		while stream.try_wire().is_some() {}
12621		let gone = old.identity();
12622		let new = producer.route("room/alice", RouteOptions::hidden()).unwrap();
12623		new.announce().unwrap();
12624		// Nothing polls this test's driver: each `route_node` catches the feeder up.
12625		producer.route_node();
12626		drop(old);
12627		producer.route_node();
12628		let changes: Vec<(Identity, bool)> = std::iter::from_fn(|| stream.try_wire())
12629			.filter_map(|msg| match msg {
12630				relay::Msg::Announce { changes } => Some(changes),
12631				_ => None,
12632			})
12633			.flatten()
12634			.map(|((_, identity), change)| (identity, matches!(change, relay::Change::Live(_))))
12635			.collect();
12636		assert_eq!(changes, [(new.identity(), true), (gone, false)]);
12637	}
12638
12639	/// Feeding the route node counts nothing against the session whose handle created it.
12640	#[test]
12641	fn the_route_node_counts_nothing_against_its_creator() {
12642		let registry = stats::Registry::new(stats::Config::new());
12643		let session = registry
12644			.tier(stats::Tier::default())
12645			.session(crate::stats::SessionInfo::new(crate::Path::from_static("root")));
12646		let producer = origin(1).produce();
12647		let _shown = producer.announce("room/alice", RouteInfo::new()).unwrap();
12648		producer.consume().with_stats(session).route_node();
12649		assert!(
12650			registry.snapshot().traffic().is_empty(),
12651			"nothing was sent to the session"
12652		);
12653	}
12654
12655	/// A stream the route node wakes may have its session polled inline, calling back
12656	/// into the node, so no wake goes out under the feeder's lock or the node's: neither
12657	/// when `route_node` catches the feeder up nor when the driver feeds it.
12658	#[test]
12659	fn the_route_node_wakes_its_streams_unlocked() {
12660		struct Reenter {
12661			consumer: Consumer,
12662			reentered: AtomicUsize,
12663			locked: AtomicBool,
12664		}
12665		impl Wake for Reenter {
12666			fn wake(self: Arc<Self>) {
12667				self.wake_by_ref();
12668			}
12669			fn wake_by_ref(self: &Arc<Self>) {
12670				let feeder = self.consumer.shared.lock().route_node.clone().unwrap().1;
12671				// Re-entering a lock this thread holds would deadlock the test instead of failing it.
12672				if feeder.upgrade().unwrap().try_lock().is_err() {
12673					self.locked.store(true, Ordering::SeqCst);
12674					return;
12675				}
12676				self.consumer.route_node().me();
12677				self.reentered.fetch_add(1, Ordering::SeqCst);
12678			}
12679		}
12680
12681		let (producer, mut driver) = Producer::new(Config::from(origin(1)));
12682		let stream = route_stream(&producer.route_node());
12683		let reenter = Arc::new(Reenter {
12684			consumer: producer.consume(),
12685			reentered: AtomicUsize::new(0),
12686			locked: AtomicBool::new(false),
12687		});
12688		let waiter = kio::Waiter::new(Waker::from(reenter.clone()));
12689		let park = || {
12690			while stream.try_wire().is_some() {}
12691			assert!(stream.poll_wire(&waiter).is_pending());
12692		};
12693
12694		park();
12695		let _alice = producer.announce("room/alice", RouteInfo::new()).unwrap();
12696		producer.route_node();
12697		assert!(
12698			!reenter.locked.load(Ordering::SeqCst),
12699			"catching up woke under the feeder's lock"
12700		);
12701		assert_eq!(
12702			reenter.reentered.load(Ordering::SeqCst),
12703			1,
12704			"catching up woke no stream"
12705		);
12706
12707		driver.poll(Instant::ZERO, &kio::Waiter::noop()).unwrap();
12708		park();
12709		let _bob = producer.announce("room/bob", RouteInfo::new()).unwrap();
12710		driver.poll(Instant::ZERO, &kio::Waiter::noop()).unwrap();
12711		assert!(
12712			!reenter.locked.load(Ordering::SeqCst),
12713			"the driver woke under the feeder's lock"
12714		);
12715		assert_eq!(reenter.reentered.load(Ordering::SeqCst), 2, "the driver woke no stream");
12716	}
12717
12718	/// At equal cost the local broadcast wins.
12719	#[kio::test]
12720	#[cfg(feature = "async")]
12721	async fn local_broadcast_wins_a_cost_tie() {
12722		let producer = origin(1).produce();
12723		let consumer = producer.consume();
12724		let mut announced = consumer.routes();
12725
12726		let server = producer
12727			.forward(
12728				"room/alice",
12729				RouteInfo::new()
12730					.with_identity(identity(), 0)
12731					.with_hops(hops(&[10]))
12732					.with_cost(2),
12733			)
12734			.unwrap();
12735		announced.expect_next_active("room/alice").await;
12736		let _local = producer
12737			.route(
12738				"room/alice",
12739				RouteOptions::default().with_identity(identity(), 0).with_cost(2),
12740			)
12741			.unwrap();
12742		assert!(announced.expect_next_active("room/alice").await.hops.is_empty());
12743
12744		let resolved = consumer.request("room/alice", None).await.expect("resolves");
12745		assert_eq!(resolved.info().path.as_str(), "room/alice");
12746		for _ in 0..20 {
12747			kio::clock::sim::yield_now().await;
12748		}
12749		assert!(server.poll_requested(&kio::Waiter::noop()).is_pending());
12750	}
12751
12752	/// Unannouncing ends the front the origin served from the broadcast and
12753	/// refuses new requests at once, even before the front acts on it.
12754	#[kio::test]
12755	#[cfg(feature = "async")]
12756	async fn unannounce_ends_the_front() {
12757		let producer = origin(1).produce();
12758		let consumer = producer.consume();
12759
12760		let broadcast = producer.route("room/alice", RouteOptions::default()).unwrap();
12761		let resolved = consumer.request("room/alice", None).await.expect("resolves");
12762
12763		broadcast.withdraw();
12764		let err = consumer.request("room/alice", None).await.err().unwrap();
12765		assert!(matches!(err, Error::Unroutable), "joined a retracted front: {err}");
12766		settle(|| resolved.is_closed()).await;
12767		assert!(
12768			!broadcast.broadcast().consume().is_closed(),
12769			"the broadcast itself lives on"
12770		);
12771
12772		// Announcing again serves a fresh front.
12773		broadcast.announce().unwrap();
12774		let again = consumer.request("room/alice", None).await.expect("resolves again");
12775		assert!(!again.is_clone(&resolved));
12776	}
12777
12778	/// Ending a publication leaves a subscriber waiting on its track info in flight:
12779	/// the source can still answer and finish the copy it already handed out.
12780	#[kio::test]
12781	#[cfg(feature = "async")]
12782	async fn ending_a_publication_keeps_a_track_awaiting_its_info() {
12783		for close in [false, true] {
12784			for replacement in [false, true] {
12785				let producer = origin(1).produce();
12786				let consumer = producer.consume();
12787
12788				let broadcast = producer
12789					.route(
12790						"room/alice",
12791						RouteOptions::default().with_identity(crate::Identity::random(), 0),
12792					)
12793					.unwrap();
12794				let mut dynamic = broadcast.broadcast().requests();
12795				let resolved = consumer.request("room/alice", None).await.expect("resolves");
12796				let track = resolved.track("video").unwrap();
12797				let mut subscribing = track.subscribe(crate::track::Subscription::default().prioritized(3));
12798				assert!((&mut subscribing).now_or_never().is_none());
12799				let request = kio::clock::timeout(Duration::from_secs(1), dynamic.requested_track())
12800					.await
12801					.expect("the front asked the source")
12802					.expect("request");
12803				let _replacement = replacement.then(|| {
12804					producer
12805						.forward(
12806							"room/alice",
12807							RouteInfo::new()
12808								.with_identity(crate::Identity::random(), 0)
12809								.with_hops(hops(&[10])),
12810						)
12811						.unwrap()
12812				});
12813
12814				if close {
12815					broadcast.broadcast().close();
12816				} else {
12817					broadcast.withdraw();
12818				}
12819				settle(|| resolved.is_closed()).await;
12820				subscribing
12821					.update(crate::track::Subscription::default().prioritized(7))
12822					.unwrap();
12823				settle(|| {
12824					request
12825						.subscription()
12826						.is_some_and(|subscription| subscription.policy().priority == 7)
12827				})
12828				.await;
12829
12830				let source = request.accept(crate::track::Info::timed());
12831				let mut group = source.append_next().unwrap();
12832				group
12833					.write_frame(Frame::new(group.key_time(), b"late".as_ref()))
12834					.unwrap();
12835				group.finish().unwrap();
12836				let source = source.finish().unwrap();
12837
12838				let mut subscription = subscribing.await.expect("subscribe survives the retraction");
12839				assert_eq!(subscription.info(), source.info(), "the source's actual track info");
12840				let mut group = subscription.recv_group().await.unwrap().expect("the source's group");
12841				assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"late");
12842				assert!(matches!(subscription.recv_group().await, Ok(None)), "ends cleanly");
12843			}
12844		}
12845	}
12846
12847	/// A front resolved through a served route, as a relay's upstream session serves
12848	/// one: the upstream broadcast's track requests arrive on the returned handle.
12849	#[cfg(feature = "async")]
12850	async fn served_front() -> (Claim, broadcast::Producer, broadcast::Requests, broadcast::Consumer) {
12851		let producer = origin(1).produce();
12852		let consumer = producer.consume();
12853		let server = producer
12854			.forward("room/alice", RouteInfo::new().with_hops(hops(&[10])))
12855			.unwrap();
12856		let pending = consumer.request("room/alice", None);
12857		let upstream = broadcast::Info::new().produce();
12858		let dynamic = upstream.requests();
12859		queued(&server).await.serve(&upstream);
12860		let resolved = pending.await.expect("resolves");
12861		(server, upstream, dynamic, resolved)
12862	}
12863
12864	/// A finished track stays readable from the front while it is read and for the
12865	/// linger after, then leaves the broadcast so it stops pinning its cache: the next
12866	/// reader asks the source afresh.
12867	#[kio::test]
12868	#[cfg(feature = "async")]
12869	async fn finished_track_is_forgotten_after_the_linger() {
12870		let (_server, _upstream, mut dynamic, resolved) = served_front().await;
12871
12872		let track = resolved.track("catalog").unwrap();
12873		let subscribing = kio::clock::sim::spawn(async move { track.subscribe(None).await });
12874		let request = kio::clock::timeout(Duration::from_secs(1), dynamic.requested_track())
12875			.await
12876			.expect("the front asked the source")
12877			.expect("request");
12878		let source = request.request_start(None).accept(crate::track::Info::timed());
12879		let mut group = source.create_empty(0u64.into()).unwrap();
12880		group
12881			.write_frame(Frame::new(group.key_time(), b"snapshot".as_ref()))
12882			.unwrap();
12883		group.finish().unwrap();
12884		let source = source.finish().unwrap();
12885		let mut subscription = subscribing.await.unwrap().expect("subscribe");
12886		assert_eq!(
12887			next_group(&mut subscription).await.unwrap().expect("the catalog").start,
12888			0
12889		);
12890		assert!(next_group(&mut subscription).await.unwrap().is_none());
12891		drop(subscription);
12892		drop(source);
12893
12894		// Within the linger, a returning reader gets the finished track from the front.
12895		let mut subscription = resolved.track("catalog").unwrap().subscribe(None).await.unwrap();
12896		assert_eq!(
12897			next_group(&mut subscription).await.unwrap().expect("the catalog").start,
12898			0
12899		);
12900		assert!(next_group(&mut subscription).await.unwrap().is_none());
12901		drop(subscription);
12902		assert!(
12903			kio::clock::timeout(Duration::from_secs(1), dynamic.requested_track())
12904				.await
12905				.is_err(),
12906			"a finished track within the linger asked the source again"
12907		);
12908
12909		// Paused time runs the front's earlier deadline before this sleep returns.
12910		kio::clock::sleep(track::IDLE_LINGER).await;
12911
12912		let track = resolved.track("catalog").unwrap();
12913		let _subscribing = kio::clock::sim::spawn(async move { track.subscribe(None).await });
12914		kio::clock::timeout(Duration::from_secs(1), dynamic.requested_track())
12915			.await
12916			.expect("the finished track outlived the linger")
12917			.expect("request");
12918	}
12919
12920	/// Every viewer session excludes a hop of its own that no route chain names, so
12921	/// they all share the plain front instead of each minting one that outlives them
12922	/// for as long as the route stands (#4799). Its tracks still go with the linger.
12923	#[kio::test]
12924	#[cfg(feature = "async")]
12925	async fn viewer_sessions_share_the_plain_front() {
12926		let producer = origin(1).produce();
12927		// A prefix route, which resolves any path beneath it optimistically.
12928		let server = producer
12929			.forward("room", RouteInfo::new().with_hops(hops(&[10])))
12930			.unwrap();
12931		let upstream = broadcast::Info::new().produce();
12932		let source = upstream.create_track("video", crate::track::Info::timed()).unwrap();
12933		let mut group = source.append_next().unwrap();
12934		group
12935			.write_frame(Frame::new(group.key_time(), b"live".as_ref()))
12936			.unwrap();
12937
12938		let counts = || {
12939			let table = producer.shared.lock();
12940			let watches = table
12941				.routes
12942				.root
12943				.find(Path::from_static("room/alice").parts())
12944				.map_or(0, |node| node.watches.len());
12945			(table.fronts.len(), watches)
12946		};
12947
12948		let mut first = None;
12949		let mut front = None;
12950		let mut budget = kio::coop::Budget::new(32);
12951		for viewer in 0..1000 {
12952			kio::wait(|waiter| budget.poll_yield(waiter)).await;
12953			let session = producer.consume().excluding(Hop::random());
12954			let pending = session.request("room/alice", None);
12955			if viewer == 0 {
12956				queued(&server).await.serve(&upstream);
12957			}
12958			let resolved = pending.await.expect("resolves");
12959			let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
12960			next_group(&mut subscription).await.unwrap().expect("the live group");
12961			drop(subscription);
12962			first.get_or_insert_with(counts);
12963			front = Some(resolved);
12964		}
12965		assert_eq!(first, Some((1, 1)), "one front and one watch for the first viewer");
12966		assert_eq!(counts(), (1, 1), "viewers minted fronts of their own");
12967
12968		// The front outlives its viewers while the route stands, but not their track.
12969		let front = front.unwrap();
12970		assert_eq!(front.open_tracks(), 1, "the unread track lingers");
12971		kio::clock::sleep(track::IDLE_LINGER).await;
12972		settle(|| front.open_tracks() == 0).await;
12973	}
12974
12975	/// A requester excluding a peer that a covering route passes through gets a front
12976	/// of its own. Decided per request: a peer whose hop joins a chain after it joined
12977	/// the plain front gets the filtered one on its next request.
12978	#[kio::test]
12979	#[cfg(feature = "async")]
12980	async fn a_hop_in_a_chain_gets_its_own_front() {
12981		let producer = origin(1).produce();
12982		let _incumbent = producer
12983			.forward("room", RouteInfo::new().with_hops(hops(&[10])))
12984			.unwrap();
12985		let fronts = || producer.shared.lock().fronts.len();
12986
12987		let peer = producer.consume().excluding(origin(7));
12988		let _local = producer.consume().request("room/alice", None);
12989		let _peer = peer.request("room/alice", None);
12990		assert_eq!(fronts(), 1, "a hop no chain names excludes nothing");
12991
12992		// The same publisher, now also reached through the peer.
12993		let _echo = producer
12994			.forward("room", RouteInfo::new().with_hops(hops(&[10, 7])))
12995			.unwrap();
12996		let _filtered = peer.request("room/alice", None);
12997		assert_eq!(fronts(), 2, "the peer still shares the plain front");
12998		let _viewer = producer.consume().excluding(origin(8)).request("room/alice", None);
12999		assert_eq!(fronts(), 2, "a viewer left the plain front");
13000	}
13001
13002	/// A front ends once nothing reads it for the linger and nothing holds its
13003	/// broadcast, rather than for as long as its route stands, and lets go of its source.
13004	#[kio::test]
13005	#[cfg(feature = "async")]
13006	async fn an_unread_front_ends_after_the_linger() {
13007		let producer = origin(1).produce();
13008		let consumer = producer.consume();
13009		let server = producer
13010			.forward("room", RouteInfo::new().with_hops(hops(&[10])))
13011			.unwrap();
13012		let upstream = broadcast::Info::new().produce();
13013		let source = upstream.create_track("video", crate::track::Info::timed()).unwrap();
13014		let mut group = source.append_next().unwrap();
13015		group
13016			.write_frame(Frame::new(group.key_time(), b"live".as_ref()))
13017			.unwrap();
13018		let fronts = || producer.shared.lock().fronts.len();
13019
13020		let pending = consumer.request("room/alice", None);
13021		queued(&server).await.serve(&upstream);
13022		let resolved = pending.await.expect("resolves");
13023		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
13024		next_group(&mut subscription).await.unwrap().expect("the live group");
13025		let front = resolved.weak();
13026		drop(subscription);
13027		drop(resolved);
13028
13029		// Within the linger the unread track keeps its front for a returning reader.
13030		kio::clock::sleep(track::IDLE_LINGER / 2).await;
13031		assert_eq!(fronts(), 1);
13032		assert!(upstream.is_held(), "the front let go of its source early");
13033
13034		kio::clock::sleep(track::IDLE_LINGER).await;
13035		settle(|| fronts() == 0).await;
13036		assert!(front.is_closed());
13037		assert!(!upstream.is_held(), "an ended front still holds its source");
13038	}
13039
13040	/// A request racing a front's retirement never joins it as it ends: one that holds
13041	/// the front before its driver looks keeps it, and one after mints a fresh front.
13042	#[kio::test]
13043	#[cfg(feature = "async")]
13044	async fn a_request_racing_a_front_retiring_never_joins_it_ending() {
13045		let producer = origin(1).produce();
13046		let consumer = producer.consume();
13047		let _broadcast = producer.route("room/alice", RouteOptions::default()).unwrap();
13048		let fronts = || producer.shared.lock().fronts.len();
13049
13050		let first = consumer.request("room/alice", None).await.expect("resolves");
13051		let front = first.weak();
13052		drop(first);
13053		let again = consumer.request("room/alice", None).await.expect("joins in time");
13054		assert!(again.is_clone(&front.consume()), "a request in time keeps the front");
13055
13056		drop(again);
13057		settle(|| front.is_closed()).await;
13058		assert_eq!(fronts(), 0, "a retired front left the table");
13059		let fresh = consumer.request("room/alice", None).await.expect("a fresh front");
13060		assert!(!fresh.is_closed());
13061		assert_eq!(fronts(), 1);
13062	}
13063
13064	/// A track that ends while read is unread from then on, even with its reader still
13065	/// holding it: the front sees it go unread once and lets it linger, rather than
13066	/// keeping it read forever or spinning on it while it lingers ended and unread.
13067	#[kio::test]
13068	#[cfg(feature = "async")]
13069	async fn a_track_ending_while_read_lets_its_front_retire() {
13070		let producer = origin(1).produce();
13071		let consumer = producer.consume();
13072		let server = producer
13073			.forward("room", RouteInfo::new().with_hops(hops(&[10])))
13074			.unwrap();
13075		let upstream = broadcast::Info::new().produce();
13076		let source = upstream.create_track("video", None).unwrap();
13077		let fronts = || producer.shared.lock().fronts.len();
13078
13079		let pending = consumer.request("room/alice", None);
13080		queued(&server).await.serve(&upstream);
13081		let resolved = pending.await.expect("resolves");
13082		let reader = resolved.track("video").unwrap().subscribe(None);
13083		settle(|| source.demand().is_wanted()).await;
13084
13085		// The source refuses the track before delivering, which ends it for the reader.
13086		source.abort(Error::NotFound).unwrap();
13087		drop(resolved);
13088
13089		kio::clock::sleep(track::IDLE_LINGER).await;
13090		settle(|| fronts() == 0).await;
13091		drop(reader);
13092	}
13093
13094	/// A front whose broadcast closes under it ends, rather than polling a holder edge
13095	/// that a closed broadcast answers at once. Nothing but the front closes it today, so
13096	/// the test does; a regression spins inside one poll and hangs the test.
13097	#[kio::test]
13098	#[cfg(feature = "async")]
13099	async fn a_front_whose_broadcast_closes_ends() {
13100		let producer = origin(1).produce();
13101		let consumer = producer.consume();
13102		let _published = producer.route("room/alice", RouteOptions::default()).unwrap();
13103		let path = consumer.absolute("room/alice").unwrap();
13104		let broadcast = broadcast::Info::new().produce();
13105		// Held, so the front waits on its holder rather than retiring on its own.
13106		let holder = broadcast.consume();
13107		let watch = consumer.shared.lock().watch(&consumer.shared, &path);
13108		let task = FrontTask {
13109			shared: consumer.shared.clone(),
13110			broadcast: broadcast.clone(),
13111			path,
13112			horizon: Horizon::default(),
13113			pin: None,
13114			watch,
13115			// Nothing joins this front, and its first selection overwrites the identity.
13116			request: kio::Producer::new(PendingFront {
13117				resolved: None,
13118				epoch: 0,
13119				selected: identity(),
13120				refused: false,
13121			}),
13122			timers: consumer.timers.clone(),
13123		};
13124		let mut front = kio::Pending::new(FrontServe::new(task));
13125		assert!((&mut front).now_or_never().is_none(), "the front ended early");
13126
13127		broadcast.close();
13128		let in_flight = kio::clock::timeout(Duration::from_secs(1), front)
13129			.await
13130			.expect("the front outlived its broadcast");
13131		assert!(in_flight.is_empty());
13132		drop(holder);
13133	}
13134
13135	/// The filtered front a peer session gets for a chain through it goes once the peer
13136	/// stops reading it, leaving the plain front its viewers share.
13137	#[kio::test]
13138	#[cfg(feature = "async")]
13139	async fn a_peers_filtered_front_ends_once_unread() {
13140		let producer = origin(1).produce();
13141		let server = producer
13142			.forward("room", RouteInfo::new().with_hops(hops(&[10])))
13143			.unwrap();
13144		// The same publisher, also reached through the peer, at a price the plain front skips.
13145		let _echo = producer
13146			.forward("room", RouteInfo::new().with_hops(hops(&[10, 7])).with_cost(100))
13147			.unwrap();
13148		let upstream = broadcast::Info::new().produce();
13149		let source = upstream.create_track("video", crate::track::Info::timed()).unwrap();
13150		let mut group = source.append_next().unwrap();
13151		group
13152			.write_frame(Frame::new(group.key_time(), b"live".as_ref()))
13153			.unwrap();
13154		let fronts = || producer.shared.lock().fronts.len();
13155
13156		let pending = producer.consume().request("room/alice", None);
13157		queued(&server).await.serve(&upstream);
13158		let _viewer = pending.await.expect("the plain front resolves");
13159
13160		let peer = producer.consume().excluding(origin(7));
13161		let peered = peer.request("room/alice", None).await.expect("resolves");
13162		assert_eq!(fronts(), 2, "the peer has a front of its own");
13163		let mut subscription = peered.track("video").unwrap().subscribe(None).await.unwrap();
13164		next_group(&mut subscription).await.unwrap().expect("the live group");
13165
13166		// The peer session closes.
13167		drop(subscription);
13168		drop(peered);
13169		drop(peer);
13170		kio::clock::sleep(track::IDLE_LINGER).await;
13171		settle(|| fronts() == 1).await;
13172	}
13173
13174	/// The hairpin the per-request choice accepts ends on its own. A peer still on the
13175	/// plain front when the only route left runs through it gets that route, but its own
13176	/// view withdraws the path, so it stops serving the path back to us.
13177	#[kio::test]
13178	#[cfg(feature = "async")]
13179	async fn a_hairpin_through_the_plain_front_is_withdrawn() {
13180		let producer = origin(1).produce();
13181		let peer = producer.consume().excluding(origin(7));
13182		let mut view = peer.routes();
13183		let incumbent = producer
13184			.forward(
13185				"room",
13186				RouteInfo::new().with_identity(identity(), 0).with_hops(hops(&[10])),
13187			)
13188			.unwrap();
13189		view.expect_next_active("room").await;
13190
13191		let pending = peer.request("room/alice", None);
13192		let source = broadcast::Info::new().produce();
13193		queued(&incumbent).await.serve(&source);
13194		let resolved = pending.await.expect("resolves through the incumbent");
13195
13196		// The same publisher, now also reached through the peer, outlives the incumbent.
13197		let echo = producer
13198			.forward(
13199				"room",
13200				RouteInfo::new().with_identity(identity(), 0).with_hops(hops(&[10, 7])),
13201			)
13202			.unwrap();
13203		drop(incumbent);
13204		drop(source);
13205
13206		let replacement = broadcast::Info::new().produce();
13207		queued(&echo).await.serve(&replacement);
13208		resolved.assert_not_closed();
13209		view.expect_next_offline("room").await;
13210	}
13211
13212	/// A route that ends abruptly releases its open groups, and the next route may
13213	/// deliver only the frames past the break. The reader mid-group carries on from
13214	/// there, and a reader arriving afterwards fetches the whole group from that route:
13215	/// whether the old route dies before the new one takes over (a reconnect) or after
13216	/// (a cheaper route preempting it). A reader joining mid-outage gets it too, and the
13217	/// reader already mid-group is not handed it a second time.
13218	#[kio::test]
13219	#[cfg(feature = "async")]
13220	async fn a_takeover_serves_the_open_group_head_to_later_readers() {
13221		for dies_first in [true, false] {
13222			takeover_keeps_the_open_group_head(dies_first).await;
13223		}
13224	}
13225
13226	#[cfg(feature = "async")]
13227	async fn takeover_keeps_the_open_group_head(dies_first: bool) {
13228		let producer = origin(1).produce();
13229		let first_server = producer
13230			.forward(
13231				"room/alice",
13232				RouteInfo::new()
13233					.with_identity(identity(), 0)
13234					.with_hops(hops(&[10]))
13235					.with_cost(5),
13236			)
13237			.unwrap();
13238		let pending = producer.consume().request("room/alice", None);
13239		let upstream = broadcast::Info::new().produce();
13240		let mut dynamic = upstream.requests();
13241		queued(&first_server).await.serve(&upstream);
13242		let resolved = pending.await.unwrap();
13243
13244		#[cfg(feature = "async")]
13245		async fn read(group: &mut crate::group::Consumer) -> Vec<u8> {
13246			let frame = kio::clock::timeout(Duration::from_secs(1), group.read_frame())
13247				.await
13248				.expect("frame")
13249				.unwrap()
13250				.expect("group ended");
13251			frame.payload.to_vec()
13252		}
13253
13254		// A reader is mid-way through the open group when the route changes.
13255		let track = resolved.track("log").unwrap();
13256		let subscribing = kio::clock::sim::spawn(async move { track.subscribe(None).await });
13257		let source = dynamic
13258			.requested_track()
13259			.await
13260			.unwrap()
13261			.accept(crate::track::Info::timed());
13262		let mut group = source.create_empty(0u64.into()).unwrap();
13263		group.write_frame(Frame::new(group.key_time(), b"a".as_ref())).unwrap();
13264		group.write_frame(Frame::new(group.key_time(), b"b".as_ref())).unwrap();
13265		let mut subscription = subscribing.await.unwrap().unwrap();
13266		let mut reading = subscription.recv_group().await.unwrap().unwrap();
13267		assert_eq!(read(&mut reading).await, b"a");
13268		assert_eq!(read(&mut reading).await, b"b");
13269
13270		// Either the first route's session ends and reconnects, announcing the same route
13271		// afresh while the old one is still held, or a cheaper route preempts the live one.
13272		let mut first = Some((group, source, upstream, dynamic));
13273		let mut joining = None;
13274		if dies_first {
13275			drop(first.take());
13276			// The reader sees its route die and stalls. Polled in place: yielding would let
13277			// the front give up on a path with no route left before the replacement lands.
13278			assert!(futures::FutureExt::now_or_never(subscription.recv_group()).is_none());
13279			let track = resolved.track("log").unwrap();
13280			joining = Some(kio::clock::sim::spawn(async move {
13281				let mut joined = track.subscribe(None).await.unwrap();
13282				let group = joined.recv_group().await.unwrap().expect("track ended");
13283				(joined, group)
13284			}));
13285		}
13286		let cost = if dies_first { 5 } else { 0 };
13287		let replacement_server = producer
13288			.forward(
13289				"room/alice",
13290				RouteInfo::new()
13291					.with_identity(identity(), 0)
13292					.with_hops(hops(&[10]))
13293					.with_cost(cost),
13294			)
13295			.unwrap();
13296		let replacement = broadcast::Info::new().produce();
13297		let mut replacement_dynamic = replacement.requests();
13298		queued(&replacement_server).await.serve(&replacement);
13299		let request = kio::clock::timeout(Duration::from_secs(1), replacement_dynamic.requested_track())
13300			.await
13301			.expect("the front asked the replacement")
13302			.unwrap();
13303		// The replacement serves the whole group to a fetch, frames still to come included.
13304		let fetches = request.requests();
13305		let fetched = Arc::new(std::sync::Mutex::new(Vec::<crate::group::Producer>::new()));
13306		let serving = fetched.clone();
13307		let _fetching = kio::clock::sim::spawn(async move {
13308			while let Ok(request) = fetches.requested_fill_group().await {
13309				let mut group = request
13310					.accept(crate::track::Info::timed())
13311					.unwrap()
13312					.expect("a fresh group");
13313				for frame in [b"a", b"b", b"c"] {
13314					group.write_frame(Frame::new(group.key_time(), frame.as_ref())).unwrap();
13315				}
13316				serving.lock().unwrap().push(group);
13317			}
13318		});
13319		let mut next = request.request_start(None).accept(crate::track::Info::timed());
13320		next.start_at(0).unwrap();
13321		let mut next_group = next.create_empty(0u64.into()).unwrap();
13322		next_group.start_at(2).unwrap();
13323		next_group
13324			.write_frame(Frame::new(next_group.key_time(), b"c".as_ref()))
13325			.unwrap();
13326		assert_eq!(read(&mut reading).await, b"c", "dies_first={dies_first}");
13327
13328		// A preempted route still owns its open group: its writer and other readers carry
13329		// on, and its copy of the frame the replacement already wrote is a duplicate.
13330		if let Some((group, ..)) = &mut first {
13331			let mut independent = group.consume();
13332			group.write_frame(Frame::new(group.key_time(), b"c".as_ref())).unwrap();
13333			for expect in [b"a", b"b", b"c"] {
13334				assert_eq!(read(&mut independent).await, expect);
13335			}
13336		}
13337		drop(first);
13338
13339		let track = resolved.track("log").unwrap();
13340		let mut later = kio::clock::timeout(Duration::from_secs(1), track.subscribe(None))
13341			.await
13342			.expect("subscribe")
13343			.unwrap();
13344		let mut late = kio::clock::timeout(Duration::from_secs(1), later.recv_group())
13345			.await
13346			.unwrap_or_else(|_| panic!("dies_first={dies_first}: the later reader never got the group"))
13347			.unwrap()
13348			.expect("track ended");
13349		assert_eq!(late.start, 0);
13350		for expect in [b"a", b"b", b"c"] {
13351			assert_eq!(read(&mut late).await, expect, "dies_first={dies_first}");
13352		}
13353		let mut joined = None;
13354		if let Some(joining) = joining {
13355			let (subscription, mut group) = kio::clock::timeout(Duration::from_secs(1), joining)
13356				.await
13357				.expect("the reader joining mid-outage never got the group")
13358				.unwrap();
13359			assert_eq!(group.start, 0);
13360			for expect in [b"a", b"b", b"c"] {
13361				assert_eq!(read(&mut group).await, expect);
13362			}
13363			joined = Some((subscription, group));
13364		}
13365
13366		// The reader that was mid-group already has it.
13367		assert!(
13368			kio::clock::timeout(Duration::from_secs(1), subscription.recv_group())
13369				.await
13370				.is_err(),
13371			"dies_first={dies_first}: the group was handed out twice"
13372		);
13373
13374		// The continuation still flows to both.
13375		next_group
13376			.write_frame(Frame::new(next_group.key_time(), b"d".as_ref()))
13377			.unwrap();
13378		for group in fetched.lock().unwrap().iter_mut() {
13379			group.write_frame(Frame::new(group.key_time(), b"d".as_ref())).unwrap();
13380		}
13381		assert_eq!(read(&mut reading).await, b"d");
13382		assert_eq!(read(&mut late).await, b"d");
13383		if let Some((_, group)) = &mut joined {
13384			assert_eq!(read(group).await, b"d");
13385		}
13386		next_group.finish().unwrap();
13387		drop((
13388			joined,
13389			reading,
13390			late,
13391			subscription,
13392			later,
13393			next,
13394			replacement,
13395			replacement_server,
13396			first_server,
13397		));
13398	}
13399
13400	/// The same holds for a reader returning to a parked track: its warm cache
13401	/// does not stand in for the copy it is waiting on.
13402	#[kio::test]
13403	#[cfg(feature = "async")]
13404	async fn unannounce_keeps_a_returning_reader_awaiting_its_info() {
13405		let producer = origin(1).produce();
13406		let consumer = producer.consume();
13407
13408		let broadcast = producer.route("room/alice", RouteOptions::default()).unwrap();
13409		let mut dynamic = broadcast.broadcast().requests();
13410		let resolved = consumer.request("room/alice", None).await.expect("resolves");
13411		let track = resolved.track("video").unwrap();
13412		let subscribing = kio::clock::sim::spawn(async move { track.subscribe(None).await });
13413		let request = kio::clock::timeout(Duration::from_secs(1), dynamic.requested_track())
13414			.await
13415			.expect("the front asked the source")
13416			.expect("request");
13417		let source = request.accept(crate::track::Info::timed());
13418		let mut group = source.append_next().unwrap();
13419		group
13420			.write_frame(Frame::new(group.key_time(), b"cached".as_ref()))
13421			.unwrap();
13422		group.finish().unwrap();
13423		let mut subscription = subscribing.await.unwrap().expect("subscribe");
13424		subscription.recv_group().await.unwrap().expect("the cached group");
13425		drop(subscription);
13426
13427		// Parked: the source copy goes, the delivered group stays warm. The source
13428		// then tears its idle track down, so a returning reader asks it afresh.
13429		kio::clock::timeout(Duration::from_secs(1), source.demand().until(|wanted| !wanted))
13430			.await
13431			.expect("parked")
13432			.expect("source open");
13433		drop(source);
13434		let track = resolved.track("video").unwrap();
13435		let subscribing = kio::clock::sim::spawn(async move { track.subscribe(None).await });
13436		let request = kio::clock::timeout(Duration::from_secs(1), dynamic.requested_track())
13437			.await
13438			.expect("the front asked the source again")
13439			.expect("request");
13440
13441		broadcast.withdraw();
13442		settle(|| resolved.is_closed()).await;
13443
13444		// A fresh source copy numbers groups past what the cache already delivered.
13445		let source = request.accept(crate::track::Info::timed());
13446		let mut group = source.create_empty(1u64.into()).unwrap();
13447		group
13448			.write_frame(Frame::new(group.key_time(), b"late".as_ref()))
13449			.unwrap();
13450		group.finish().unwrap();
13451		let _source = source.finish().unwrap();
13452
13453		let mut subscription = subscribing.await.unwrap().expect("subscribe survives the retraction");
13454		let mut payloads = Vec::new();
13455		while let Some(mut group) = subscription.recv_group().await.expect("ends cleanly") {
13456			payloads.push(group.read_frame().await.unwrap().unwrap().payload);
13457		}
13458		assert_eq!(payloads.last().map(|p| &p[..]), Some(&b"late"[..]));
13459	}
13460
13461	/// Once a front observes a gap, a request after the route returns cannot join it while
13462	/// its terminal actions are still being applied on another thread.
13463	#[test]
13464	fn a_request_after_a_gap_skips_the_front_already_ending() {
13465		let (producer, mut driver) = Producer::new(Config::default());
13466		let consumer = producer.consume();
13467		let publication = producer.route("room/alice", RouteOptions::default()).unwrap();
13468		let path = consumer.absolute("room/alice").unwrap();
13469		let key = (path.clone(), Horizon::default(), None);
13470		let broadcast = broadcast::Info::new().produce();
13471		let held = broadcast.consume();
13472		let (request, watch) = {
13473			let mut state = consumer.shared.lock();
13474			let selected = state
13475				.best_route(&path, Horizon::default(), &HashSet::new(), |_| true)
13476				.unwrap()
13477				.identity
13478				.clone();
13479			let request = kio::Producer::new(PendingFront {
13480				resolved: None,
13481				epoch: 0,
13482				selected,
13483				refused: false,
13484			});
13485			state.fronts.insert(
13486				key,
13487				RemoteFront {
13488					request: request.clone(),
13489					broadcast: held.weak(),
13490				},
13491			);
13492			let watch = state.watch(&consumer.shared, &path);
13493			(request, watch)
13494		};
13495		let mut front = FrontServe::new(FrontTask {
13496			shared: consumer.shared.clone(),
13497			broadcast,
13498			path,
13499			horizon: Horizon::default(),
13500			pin: None,
13501			watch,
13502			request,
13503			timers: consumer.timers.clone(),
13504		});
13505		let waiter = kio::Waiter::noop();
13506		assert!(kio::Task::poll(&mut front, &waiter).is_pending());
13507		let Poll::Ready(Ok(first)) = consumer
13508			.lookup(Path::new("room/alice").unwrap(), None)
13509			.into_inner()
13510			.poll_ok(&waiter)
13511		else {
13512			panic!("the first front did not resolve")
13513		};
13514
13515		publication.withdraw();
13516		let ending = front.select();
13517		assert!(matches!(ending, Event::Selected { best: None, .. }));
13518		publication.announce().unwrap();
13519		let next = consumer.lookup(Path::new("room/alice").unwrap(), None).into_inner();
13520		assert!(next.poll_ok(&waiter).is_pending(), "joined the front already ending");
13521
13522		front.events.push_back(ending);
13523		assert!(kio::Task::poll(&mut front, &waiter).is_ready());
13524		driver.poll(Instant::ZERO, &waiter).unwrap();
13525		let Poll::Ready(Ok(fresh)) = next.poll_ok(&waiter) else {
13526			panic!("the fresh front did not resolve")
13527		};
13528		assert!(!fresh.is_clone(&first));
13529		assert!(!fresh.is_closed());
13530		assert!(fresh.track("video").is_ok());
13531	}
13532
13533	/// A re-announce that lands before the front acts on the retraction reuses
13534	/// the same route entry, so the front carries on.
13535	#[kio::test]
13536	#[cfg(feature = "async")]
13537	async fn reannounce_before_the_front_acts_keeps_it() {
13538		let producer = origin(1).produce();
13539		let consumer = producer.consume();
13540
13541		let broadcast = producer.route("room/alice", RouteOptions::default()).unwrap();
13542		let resolved = consumer.request("room/alice", None).await.expect("resolves");
13543
13544		broadcast.withdraw();
13545		broadcast.announce().unwrap();
13546		for _ in 0..20 {
13547			kio::clock::sim::yield_now().await;
13548		}
13549		assert!(!resolved.is_closed(), "the front ended across a reannouncement");
13550		let again = consumer.request("room/alice", None).await.expect("resolves");
13551		assert!(again.is_clone(&resolved));
13552	}
13553
13554	#[kio::test]
13555	#[cfg(feature = "async")]
13556	async fn local_broadcast_resolves_once_announced() {
13557		let producer = origin(1).produce();
13558		let consumer = producer.consume();
13559
13560		// Created but not announced: nobody can reach it, locally included.
13561		let broadcast = producer.route("room/alice", RouteOptions::hidden()).unwrap();
13562		let err = consumer
13563			.request("room/alice", None)
13564			.now_or_never()
13565			.expect("unroutable is synchronous")
13566			.err()
13567			.unwrap();
13568		assert!(matches!(err, Error::Unroutable));
13569
13570		broadcast.announce().unwrap();
13571		let resolved = consumer.request("room/alice", None).await.expect("resolves");
13572		assert_eq!(resolved.info().path.as_str(), "room/alice");
13573		drop(broadcast);
13574
13575		// Nothing covers an unknown path and no handler exists.
13576		let err = consumer
13577			.request("room/bob", None)
13578			.now_or_never()
13579			.expect("unroutable is synchronous")
13580			.err()
13581			.unwrap();
13582		assert!(matches!(err, Error::Unroutable));
13583	}
13584
13585	#[kio::test]
13586	async fn route_accepts_a_path_at_the_wire_limits() {
13587		let producer = origin(1).produce();
13588		let path = vec!["a"; Path::MAX_PARTS].join("/");
13589		let _broadcast = producer
13590			.route(path.as_str(), RouteOptions::hidden())
13591			.expect("max depth is allowed");
13592		let deeper = vec!["a"; Path::MAX_PARTS + 1].join("/");
13593		assert!(matches!(
13594			producer.route(deeper.as_str(), RouteOptions::hidden()),
13595			Err(Error::BoundsExceeded(_))
13596		));
13597
13598		// The byte limit counts the root the producer joins on.
13599		let rooted = producer.scope("r", &Prefixes::all()).unwrap();
13600		let longest = "b".repeat(Path::MAX_BYTES - 2);
13601		let _long = rooted
13602			.route(longest.as_str(), RouteOptions::hidden())
13603			.expect("max length is allowed");
13604		let longer = "c".repeat(Path::MAX_BYTES - 1);
13605		assert!(matches!(
13606			rooted.route(longer.as_str(), RouteOptions::hidden()),
13607			Err(Error::BoundsExceeded(_))
13608		));
13609	}
13610
13611	#[kio::test]
13612	#[cfg(feature = "async")]
13613	async fn duplicate_routes_aggregate_until_the_last_leaves() {
13614		let producer = origin(1).produce();
13615		let first = producer.forward("live", RouteInfo::new().with_cost(3)).unwrap();
13616		let second = producer.forward("live", RouteInfo::new().with_cost(1)).unwrap();
13617
13618		let mut announced = producer.consume().routes();
13619		let Some(Some(RouteEvent {
13620			kind: RouteKind::Start,
13621			announce: update,
13622		})) = announced.next().now_or_never()
13623		else {
13624			panic!("expected the announcement");
13625		};
13626		assert_eq!(update.prefix.as_str(), "live");
13627		assert_eq!(update.route.cost, Cost::new(1));
13628		announced.assert_next_wait();
13629
13630		// Under another identity the survivor is another source.
13631		drop(second);
13632		assert_eq!(announced.expect_next_restarted("live").await.cost, Cost::new(3));
13633
13634		drop(first);
13635		announced.expect_next_offline("live").await;
13636		announced.assert_next_wait();
13637	}
13638
13639	#[kio::test]
13640	async fn dynamic_may_cover_a_scope_but_disjoint_prefixes_are_refused() {
13641		let producer = origin(1).produce();
13642		let scoped = producer.scope("", &scopes(&["room"])).unwrap();
13643		let _broad = scoped
13644			.forward("", RouteInfo::new())
13645			.expect("an overlapping prefix is accepted");
13646
13647		let _ok = scoped
13648			.forward("room/alice", RouteInfo::new())
13649			.expect("a contained prefix is accepted");
13650		assert!(matches!(
13651			scoped.forward("other", RouteInfo::new()),
13652			Err(Error::Unauthorized)
13653		));
13654	}
13655
13656	#[kio::test]
13657	#[cfg(feature = "async")]
13658	async fn forward_keeps_its_producer_scope() {
13659		let producer = origin(1).produce();
13660		let scoped = producer.scope("", &scopes(&["room/chat"])).unwrap();
13661		let dynamic = scoped.forward("", RouteInfo::new()).unwrap();
13662
13663		let mut matching = producer
13664			.consume()
13665			.scope("", &scopes(&["room/chat"]))
13666			.unwrap()
13667			.covering()
13668			.routes();
13669		// Filed at its grant, beneath the prefix it claims.
13670		assert_eq!(matching.expect_next_active("room/chat").await.lane.above, 2);
13671		let mut outside = producer
13672			.consume()
13673			.scope("", &scopes(&["room/video"]))
13674			.unwrap()
13675			.covering()
13676			.routes();
13677		outside.assert_next_wait();
13678
13679		let refused = producer
13680			.consume()
13681			.request("room/video", None)
13682			.now_or_never()
13683			.expect("an out-of-scope request must be refused synchronously");
13684		assert!(matches!(refused, Err(Error::Unroutable)));
13685		assert!(dynamic.requested().now_or_never().is_none());
13686
13687		let _pending = producer.consume().request("room/chat", None);
13688		let request = queued(&dynamic).await;
13689		assert_eq!(request.path().as_str(), "room/chat");
13690	}
13691
13692	#[kio::test]
13693	async fn scoped_cursor_selects_among_the_routes_it_can_see() {
13694		let producer = origin(1).produce();
13695		let scoped = |prefix: &str| producer.scope("", &scopes(&[prefix])).unwrap();
13696		let _chat = scoped("room/chat").forward("", RouteInfo::new().with_cost(1)).unwrap();
13697		let _video = scoped("room/video").forward("", RouteInfo::new().with_cost(5)).unwrap();
13698
13699		let mut video = producer
13700			.consume()
13701			.scope("", &scopes(&["room/video"]))
13702			.unwrap()
13703			.covering()
13704			.routes();
13705		// Each claim is filed at its grant, so the cursor sees the one filed within its scope.
13706		assert_eq!(video.expect_next_active("room/video").await.cost, Cost::new(5));
13707	}
13708
13709	#[kio::test]
13710	#[cfg(feature = "async")]
13711	async fn route_changes_preserve_each_cursors_visible_winner() {
13712		let producer = origin(1).produce();
13713		let consumer = producer.consume();
13714		let mut all = consumer.clone().routes();
13715		let mut excluded = consumer.clone().excluding(origin(7)).routes();
13716		let mut video = consumer
13717			.clone()
13718			.scope("", &scopes(&["room/live/video"]))
13719			.unwrap()
13720			.covering()
13721			.routes();
13722		let mut rooted = consumer.scope("room/live", &Prefixes::all()).unwrap().routes();
13723
13724		// Each claim of `room/live` is filed at its own grant, so each cursor sees only those
13725		// within its scope and horizon.
13726		let chat = producer
13727			.scope("", &scopes(&["room/live/chat"]))
13728			.unwrap()
13729			.forward("room/live", RouteInfo::new().with_hops(hops(&[7])).with_cost(1))
13730			.unwrap();
13731		assert_eq!(all.expect_next_active("room/live/chat").await.cost, Cost::new(1));
13732		assert_eq!(rooted.expect_next_active("chat").await.cost, Cost::new(1));
13733		excluded.assert_next_wait();
13734		video.assert_next_wait();
13735
13736		let video_route = producer
13737			.scope("", &scopes(&["room/live/video"]))
13738			.unwrap()
13739			.forward("room/live", RouteInfo::new().with_hops(hops(&[8])).with_cost(5))
13740			.unwrap();
13741		assert_eq!(all.expect_next_active("room/live/video").await.cost, Cost::new(5));
13742		assert_eq!(rooted.expect_next_active("video").await.cost, Cost::new(5));
13743		assert_eq!(excluded.expect_next_active("room/live/video").await.cost, Cost::new(5));
13744		assert_eq!(video.expect_next_active("room/live/video").await.cost, Cost::new(5));
13745
13746		chat.update(RouteInfo::new().with_hops(hops(&[7])).with_cost(9))
13747			.unwrap();
13748		assert_eq!(all.expect_next_active("room/live/chat").await.cost, Cost::new(9));
13749		assert_eq!(rooted.expect_next_active("chat").await.cost, Cost::new(9));
13750		excluded.assert_next_wait();
13751		video.assert_next_wait();
13752
13753		drop(video_route);
13754		all.expect_next_offline("room/live/video").await;
13755		rooted.expect_next_offline("video").await;
13756		excluded.expect_next_offline("room/live/video").await;
13757		video.expect_next_offline("room/live/video").await;
13758	}
13759
13760	#[kio::test]
13761	#[cfg(feature = "async")]
13762	async fn root_cursor_keeps_the_more_specific_covering_route() {
13763		let producer = origin(1).produce();
13764		let broad = producer.forward("room", RouteInfo::new().with_cost(1)).unwrap();
13765		let narrow = producer.forward("room/live", RouteInfo::new().with_cost(9)).unwrap();
13766		let mut announced = producer
13767			.consume()
13768			.scope("room/live/video", &Prefixes::all())
13769			.unwrap()
13770			.covering()
13771			.routes();
13772		assert_eq!(announced.expect_next_active("").await.cost, Cost::new(9));
13773
13774		broad.update(RouteInfo::new().with_cost(0)).unwrap();
13775		announced.assert_next_wait();
13776		narrow.update(RouteInfo::new().with_cost(8)).unwrap();
13777		assert_eq!(announced.expect_next_active("").await.cost, Cost::new(8));
13778		drop(narrow);
13779		assert_eq!(announced.expect_next_active("").await.cost, Cost::new(0));
13780	}
13781
13782	#[kio::test]
13783	#[cfg(feature = "async")]
13784	async fn dynamic_accepts_a_max_depth_prefix() {
13785		let producer = origin(1).produce();
13786		let path = (0..Path::MAX_PARTS)
13787			.map(|i| format!("s{i}"))
13788			.collect::<Vec<_>>()
13789			.join("/");
13790		let mut announced = producer.consume().routes();
13791
13792		let dynamic = producer.forward(&path, RouteInfo::new()).expect("max depth is allowed");
13793		announced.expect_next_active(&path).await;
13794
13795		let _pending = producer.consume().request(&path, None);
13796		let request = queued(&dynamic).await;
13797		assert_eq!(request.path().as_str(), path);
13798	}
13799
13800	#[kio::test]
13801	async fn dynamic_exclusion_skips_routes_through_the_subscriber() {
13802		let producer = origin(1).produce();
13803		let _server = producer
13804			.forward("live", RouteInfo::new().with_hops(hops(&[7])))
13805			.unwrap();
13806
13807		let mut excluded = producer.consume().excluding(origin(7)).routes();
13808		excluded.assert_next_wait();
13809
13810		let mut clean = producer.consume().excluding(origin(8)).routes();
13811		clean.expect_next_active("live").await;
13812	}
13813
13814	/// The consumer is a `Stream` of the same updates as `next`.
13815	#[kio::test]
13816	#[cfg(feature = "async")]
13817	async fn announce_consumer_is_a_stream() {
13818		use futures::StreamExt;
13819		let producer = origin(1).produce();
13820		let server = producer.forward("live", RouteInfo::new()).unwrap();
13821		let mut announced = producer.consume().routes();
13822		let mut next = || StreamExt::next(&mut announced).now_or_never();
13823		let Some(Some(RouteEvent {
13824			kind: RouteKind::Start,
13825			announce: update,
13826		})) = next()
13827		else {
13828			panic!("expected the replayed route");
13829		};
13830		assert_eq!(update.prefix.as_str(), "live");
13831		assert!(next().is_none());
13832		drop(server);
13833		assert!(matches!(
13834			next(),
13835			Some(Some(RouteEvent {
13836				kind: RouteKind::Offline,
13837				..
13838			}))
13839		));
13840	}
13841
13842	#[kio::test]
13843	async fn dynamic_retracts() {
13844		let producer = origin(1).produce();
13845		let server = producer.forward("live", RouteInfo::new()).unwrap();
13846		let mut announced = producer.consume().routes();
13847		announced.expect_next_active("live").await;
13848
13849		drop(server);
13850		announced.expect_next_offline("live").await;
13851	}
13852
13853	#[kio::test]
13854	async fn local_broadcast_is_invisible_until_announced() {
13855		let producer = origin(1).produce();
13856		let mut local = producer.consume().routes();
13857		let mut peer = producer.consume().excluding(Hop::UNKNOWN).routes();
13858		let broadcast = producer.route("room/alice", RouteOptions::hidden()).unwrap();
13859		local.assert_next_wait();
13860		peer.assert_next_wait();
13861
13862		broadcast.announce().unwrap();
13863		local.expect_next_active("room/alice").await;
13864		peer.expect_next_active("room/alice").await;
13865
13866		drop(broadcast);
13867		local.expect_next_ended("room/alice").await;
13868		peer.expect_next_ended("room/alice").await;
13869	}
13870
13871	#[kio::test]
13872	#[cfg(feature = "async")]
13873	async fn served_route_materializes_on_demand() {
13874		let producer = origin(1).produce();
13875		let consumer = producer.consume();
13876
13877		let server = producer.claim("room", RouteOptions::default()).unwrap();
13878
13879		let pending = consumer.request("room/alice", None);
13880		let request = queued(&server).await;
13881		assert_eq!(request.path().as_str(), "room/alice");
13882
13883		let source = broadcast::Info::new().produce();
13884		request.serve(&source);
13885
13886		let resolved = pending.await.expect("resolves");
13887		// The handle is named by what the requester asked for.
13888		assert_eq!(resolved.info().path.as_str(), "room/alice");
13889
13890		// A repeat request shares the served broadcast instead of re-asking.
13891		let again = consumer.request("room/alice", None).await.expect("resolves");
13892		assert!(again.is_clone(&resolved));
13893	}
13894
13895	/// An excluded producer can neither publish into the excluded subtree nor serve
13896	/// a request there through a covering prefix route.
13897	#[kio::test]
13898	#[cfg(feature = "async")]
13899	async fn excluded_subtree_is_never_published_or_served() {
13900		let producer = origin(1).produce();
13901		let consumer = producer.consume();
13902		let excluded = producer.exclude(".stats").unwrap();
13903		assert!(excluded.route(".stats/node", RouteOptions::default()).is_err());
13904		assert!(excluded.claim(".stats", RouteOptions::default()).is_err());
13905
13906		let server = excluded.claim("", RouteOptions::default()).unwrap();
13907		let Err(err) = consumer.request(".stats/evil", None).await else {
13908			panic!("excluded path served")
13909		};
13910		assert!(matches!(err, Error::Unroutable), "got {err:?}");
13911
13912		let pending = consumer.request("room/alice", None);
13913		let request = queued(&server).await;
13914		assert_eq!(request.path().as_str(), "room/alice");
13915		request.serve(broadcast::Info::new().produce());
13916		pending.await.expect("resolves outside the excluded subtree");
13917	}
13918
13919	#[kio::test]
13920	#[cfg(feature = "async")]
13921	async fn served_requests_coalesce() {
13922		let producer = origin(1).produce();
13923		let consumer = producer.consume();
13924		let server = producer.forward("room", RouteInfo::new()).unwrap();
13925
13926		let first = consumer.request("room/alice", None);
13927		let second = consumer.request("room/alice", None);
13928
13929		let request = queued(&server).await;
13930		// Only one request reaches the server.
13931		assert!(server.poll_requested(&kio::Waiter::noop()).is_pending());
13932
13933		let source = broadcast::Info::new().produce();
13934		request.serve(&source);
13935
13936		let first = first.await.expect("resolves");
13937		let second = second.await.expect("resolves");
13938		assert!(first.is_clone(&second));
13939	}
13940
13941	#[kio::test]
13942	#[cfg(feature = "async")]
13943	async fn retract_rejects_pending_requests() {
13944		let producer = origin(1).produce();
13945		let consumer = producer.consume();
13946		let server = producer.forward("room", RouteInfo::new()).unwrap();
13947
13948		let pending = consumer.request("room/alice", None);
13949		drop(server);
13950
13951		let err = pending.await.err().unwrap();
13952		assert!(matches!(err, Error::Unroutable));
13953
13954		// With the route gone, later requests are unroutable immediately.
13955		let err = consumer
13956			.request("room/alice", None)
13957			.now_or_never()
13958			.expect("unroutable")
13959			.err()
13960			.unwrap();
13961		assert!(matches!(err, Error::Unroutable));
13962	}
13963
13964	#[kio::test]
13965	#[cfg(feature = "async")]
13966	async fn follow_survives_serving_route_retraction() {
13967		let producer = origin(1).produce();
13968		let consumer = producer.consume();
13969
13970		// Three identical routes, oldest first: the newest identical route wins
13971		// requests, and swapping between them emits no announce update.
13972		let standby_server = producer.forward("room", RouteInfo::new()).unwrap();
13973		let second_server = producer.forward("room", RouteInfo::new()).unwrap();
13974		let incumbent_server = producer.forward("room", RouteInfo::new()).unwrap();
13975
13976		let mut following = consumer.follow("room/alice", None).unwrap();
13977		let mut resolving = Box::pin(following.available());
13978		assert!((&mut resolving).now_or_never().is_none());
13979
13980		// Each incumbent dies with the front's request in flight on it: the
13981		// front's watcher observes the retraction and retries through the next
13982		// standby instead of parking on an announce update that never comes. Two
13983		// retractions in a row, so the announce stream's initial coverage replay
13984		// cannot paper over the missing retry.
13985		drop(incumbent_server);
13986		assert!((&mut resolving).now_or_never().is_none());
13987		drop(second_server);
13988		assert!((&mut resolving).now_or_never().is_none());
13989
13990		let request = queued(&standby_server).await;
13991		let source = broadcast::Info::new().produce();
13992		request.serve(&source);
13993
13994		let resolved = resolving.await.expect("resolves via the standby").unwrap();
13995		assert_eq!(resolved.info().path.as_str(), "room/alice");
13996	}
13997
13998	#[kio::test]
13999	async fn split_horizon_skips_routes_through_the_requester() {
14000		let producer = origin(1).produce();
14001		let _server = producer
14002			.forward("room", RouteInfo::new().with_hops(hops(&[7])))
14003			.unwrap();
14004
14005		// The requester's own bytes must not be served back to it.
14006		let excluded = producer.consume().excluding(origin(7));
14007		let err = excluded
14008			.request("room/alice", None)
14009			.now_or_never()
14010			.expect("unroutable")
14011			.err()
14012			.unwrap();
14013		assert!(matches!(err, Error::Unroutable));
14014
14015		// A clean requester resolves through the route (the request queues).
14016		let clean = producer.consume().excluding(origin(8));
14017		let pending = clean.request("room/alice", None);
14018		assert!(pending.now_or_never().is_none());
14019	}
14020
14021	#[kio::test]
14022	async fn routes_report_where_they_entered() {
14023		let producer = origin(1).produce();
14024		let peer = producer.clone().with_link(Link::Peer);
14025		let mut announced = producer.consume().routes();
14026
14027		let _ingest = producer
14028			.forward("client", RouteInfo::new().with_hops(hops(&[5])).with_via(origin(5)))
14029			.unwrap();
14030		let _gateway = producer.route("gateway", RouteOptions::default()).unwrap();
14031		let _forwarded = peer
14032			.forward(
14033				"forwarded",
14034				RouteInfo::new().with_hops(hops(&[5, 7])).with_via(origin(7)),
14035			)
14036			.unwrap();
14037
14038		assert_eq!(announced.expect_next_active("client").await.source(), Source::Local);
14039		assert_eq!(announced.expect_next_active("gateway").await.source(), Source::Local);
14040		assert_eq!(
14041			announced.expect_next_active("forwarded").await.source(),
14042			Source::Peer(7)
14043		);
14044
14045		// The mark survives narrowing the handle.
14046		let scoped = peer.scope("room", &Prefixes::all()).unwrap();
14047		let _nested = scoped.forward("x", RouteInfo::new().with_via(origin(8))).unwrap();
14048		assert_eq!(announced.expect_next_active("room/x").await.source(), Source::Peer(8));
14049	}
14050
14051	/// A caller that only polls with `try_next` still gets a held update once its
14052	/// hold passes. Nothing else wakes the idle driver, so the hold's own timer
14053	/// must, or the origin's clock never reaches the deadline.
14054	#[kio::test]
14055	#[cfg(feature = "async")]
14056	async fn try_next_delivers_a_held_update() {
14057		// Let paused time pass and every task woken by it run.
14058		#[cfg(feature = "async")]
14059		async fn step(by: Duration) {
14060			kio::clock::sim::advance(by).await;
14061			for _ in 0..10 {
14062				kio::clock::sim::yield_now().await;
14063			}
14064		}
14065
14066		let producer = origin(1).produce();
14067		let peer = producer.clone().with_link(Link::Peer);
14068		let mut announced = producer.consume().routes();
14069		step(Duration::from_millis(1)).await;
14070
14071		// One identity, so the winner moving between routes is an update, not a restart.
14072		let route = |chain: &[u64], via| {
14073			RouteInfo::new()
14074				.with_identity(identity(), 0)
14075				.with_hops(hops(chain))
14076				.with_via(origin(via))
14077		};
14078		let near = peer.forward("room", route(&[9, 2], 2)).unwrap();
14079		announced.assert_try_next_active("room");
14080
14081		let _far = peer.forward("room", route(&[9, 3, 4], 4)).unwrap();
14082		drop(near);
14083		assert!(announced.try_next().is_none(), "the update is held");
14084		step(Duration::from_millis(1)).await;
14085		assert!(announced.try_next().is_none(), "the update is still held");
14086		step(DEFAULT_UPDATE_HOLD).await;
14087		match announced.try_next().expect("the hold passed") {
14088			RouteEvent {
14089				kind: RouteKind::Update,
14090				announce: update,
14091			} => assert_eq!(update.route.hops, hops(&[9, 3, 4])),
14092			other => panic!("should be an update: got {other:?}"),
14093		}
14094	}
14095
14096	/// Two peers carry the same `k` broadcasts of one publisher, and both go away a
14097	/// broadcast at a time, the cursor polled after each change. The first peer's
14098	/// withdrawals queue `k` held updates; the second's, in the opposite order, make
14099	/// each ready behind the held rest. A poll touches only what is due, so the wave
14100	/// costs each cursor O(k log k) steps, not O(k²).
14101	#[test]
14102	fn a_withdrawal_wave_costs_k_log_k_steps() {
14103		for k in [64usize, 256, 1024] {
14104			let (producer, mut driver) = Producer::new(Config::from(origin(1)));
14105			driver
14106				.poll(
14107					Instant::ZERO.saturating_add(Duration::from_secs(1)),
14108					&kio::Waiter::noop(),
14109				)
14110				.unwrap();
14111			let peer = producer.clone().with_link(Link::Peer);
14112			// One identity, so the winner moving between routes is an update, not a restart.
14113			let route = |chain: &[u64], via| {
14114				RouteInfo::new()
14115					.with_identity(identity(), 0)
14116					.with_hops(hops(chain))
14117					.with_via(origin(via))
14118			};
14119			let mut near = Vec::new();
14120			let mut far = Vec::new();
14121			for i in 0..k {
14122				near.push(peer.forward(format!("room/{i}"), route(&[9, 2], 2)).unwrap());
14123				far.push(peer.forward(format!("room/{i}"), route(&[9, 3, 4], 4)).unwrap());
14124			}
14125			let mut announced = producer.consume().routes();
14126			for _ in 0..k {
14127				assert!(matches!(
14128					announced.try_next(),
14129					Some(RouteEvent {
14130						kind: RouteKind::Start,
14131						..
14132					})
14133				));
14134			}
14135			let before = announced.state.read().steps;
14136
14137			for route in near {
14138				drop(route);
14139				assert!(announced.try_next().is_none(), "the update is held");
14140			}
14141			for (i, route) in far.into_iter().enumerate().rev() {
14142				drop(route);
14143				match announced.try_next() {
14144					Some(RouteEvent {
14145						kind: RouteKind::Offline,
14146						announce: end,
14147					}) => assert_eq!(end.prefix, Path::new(&format!("room/{i}")).unwrap()),
14148					other => panic!("should go offline: got {other:?}"),
14149				}
14150			}
14151
14152			let steps = announced.state.read().steps - before;
14153			let bound = 4 * k * (k.ilog2() as usize + 1);
14154			assert!(steps <= bound, "{k} broadcasts took {steps} steps, over {bound}");
14155		}
14156	}
14157
14158	/// A new route and a removal are delivered at once. A change of the best route
14159	/// within one identity waits out the update hold, and a newer change during the
14160	/// wait replaces it. So does a switch between hop-chain routes to one publisher that
14161	/// each session minted its own identity for, since the wire carries none: it is
14162	/// delivered as a restart, once. One onto another publisher goes at once.
14163	#[kio::test]
14164	#[cfg(feature = "async")]
14165	async fn a_changed_route_waits_out_the_hold() {
14166		for minted in [false, true] {
14167			let producer = origin(1).produce();
14168			let peer = producer.clone().with_link(Link::Peer);
14169			let mut announced = producer.consume().routes();
14170			// Holds count on the driver's clock, which starts at its first poll.
14171			kio::clock::sleep(Duration::from_millis(1)).await;
14172
14173			let named = identity();
14174			let route = |chain: &[u64], via| {
14175				let identity = match minted {
14176					true => Identity::minted(),
14177					false => named.clone(),
14178				};
14179				RouteInfo::new()
14180					.with_identity(identity, 0)
14181					.with_hops(hops(chain))
14182					.with_via(origin(via))
14183			};
14184			let near = peer.forward("room", route(&[9, 2], 2)).unwrap();
14185			announced.expect_next_active("room").await;
14186
14187			// The best route changes twice; the consumer sees only the last, once.
14188			let far = peer.forward("room", route(&[9, 3, 4], 4)).unwrap();
14189			let farther = peer.forward("room", route(&[9, 5, 6, 7], 7)).unwrap();
14190			let start = kio::clock::now();
14191			drop(near);
14192			drop(far);
14193			let kind = match minted {
14194				true => RouteKind::Restart,
14195				false => RouteKind::Update,
14196			};
14197			let event = announced.next().await.unwrap();
14198			assert_eq!(event.kind, kind, "minted {minted}: {event:?}");
14199			assert_eq!(event.announce.route.hops, hops(&[9, 5, 6, 7]));
14200			assert_eq!(kio::clock::now() - start, DEFAULT_UPDATE_HOLD, "minted {minted}");
14201			announced.assert_next_wait();
14202
14203			// The last route goes: retracted at once.
14204			drop(farther);
14205			announced.expect_next_offline("room").await;
14206		}
14207
14208		// Another publisher's broadcast at the path restarts it at once.
14209		let producer = origin(1).produce();
14210		let peer = producer.clone().with_link(Link::Peer);
14211		let mut announced = producer.consume().routes();
14212		kio::clock::sleep(Duration::from_millis(1)).await;
14213		let route = |chain: &[u64], via| {
14214			RouteInfo::new()
14215				.with_identity(Identity::minted(), 0)
14216				.with_hops(hops(chain))
14217				.with_via(origin(via))
14218		};
14219		let old = peer.forward("room", route(&[9, 2], 2)).unwrap();
14220		announced.expect_next_active("room").await;
14221		let _new = peer.forward("room", route(&[8, 3, 4], 4)).unwrap();
14222		let start = kio::clock::now();
14223		drop(old);
14224		let event = announced.next().await.unwrap();
14225		assert_eq!(event.kind, RouteKind::Restart, "{event:?}");
14226		assert_eq!(event.announce.route.hops, hops(&[8, 3, 4]));
14227		assert_eq!(kio::clock::now(), start);
14228	}
14229
14230	/// After a retraction, a worse path to the same publisher waits out the
14231	/// quarantine, under its identity or, for a hop chain, any identity a session
14232	/// minted. An anonymous route names no publisher, so one after it is not held.
14233	#[kio::test]
14234	#[cfg(feature = "async")]
14235	async fn a_retraction_quarantines_a_named_publisher() {
14236		for minted in [false, true] {
14237			let producer = origin(1).produce();
14238			let peer = producer.clone().with_link(Link::Peer);
14239			let mut announced = producer.consume().routes();
14240			kio::clock::sleep(Duration::from_millis(1)).await;
14241
14242			// Every path is to one publisher, so to one identity, unless each session
14243			// minted its own.
14244			let named = identity();
14245			let route = |chain: &[u64], via| {
14246				let identity = match minted {
14247					true => Identity::minted(),
14248					false => named.clone(),
14249				};
14250				RouteInfo::new()
14251					.with_identity(identity, 0)
14252					.with_hops(hops(chain))
14253					.with_via(origin(via))
14254			};
14255
14256			let near = peer.forward("named", route(&[9, 2], 2)).unwrap();
14257			announced.expect_next_active("named").await;
14258			drop(near);
14259			announced.expect_next_offline("named").await;
14260			let start = kio::clock::now();
14261			let _stale = peer.forward("named", route(&[9, 3, 4], 4)).unwrap();
14262			match announced.next().await.unwrap() {
14263				RouteEvent {
14264					kind: RouteKind::Start,
14265					announce,
14266				} => assert_eq!(announce.route.hops, hops(&[9, 3, 4])),
14267				other => panic!("should be a start: got {other:?}"),
14268			}
14269			assert!(kio::clock::now() - start >= RETRACT_QUARANTINE, "minted {minted}");
14270			if minted {
14271				continue;
14272			}
14273
14274			let near = peer.forward("anonymous", route(&[0, 2], 2)).unwrap();
14275			announced.expect_next_active("anonymous").await;
14276			drop(near);
14277			announced.expect_next_offline("anonymous").await;
14278			let _other = peer.forward("anonymous", route(&[0, 3, 4], 4)).unwrap();
14279			announced.expect_next_active("anonymous").await;
14280
14281			// Retract and announce cycles at one clock reading queue the prefix once,
14282			// whether or not the route names its publisher.
14283			let queued = announced.anchoring.len();
14284			for chain in [[9, 2], [0, 2], [9, 2], [0, 2]] {
14285				let churn = peer.forward("churn", route(&chain, 2)).unwrap();
14286				announced.expect_next_active("churn").await;
14287				drop(churn);
14288				announced.expect_next_offline("churn").await;
14289			}
14290			assert_eq!(announced.anchoring.len(), queued + 1);
14291
14292			// A quarantine is forgotten once it ends: the cursor wakes to anchor it,
14293			// then again to drop it.
14294			let gone = peer.forward("gone", route(&[9, 2], 2)).unwrap();
14295			announced.expect_next_active("gone").await;
14296			drop(gone);
14297			announced.expect_next_offline("gone").await;
14298			assert!(!announced.retracted.is_empty());
14299			for _ in 0..2 {
14300				announced.assert_next_wait();
14301				kio::clock::sleep(RETRACT_QUARANTINE).await;
14302			}
14303			announced.assert_next_wait();
14304			assert!(announced.retracted.is_empty(), "the ended quarantine is still held");
14305		}
14306	}
14307
14308	/// A peer withdrawing a prefix hides the routes there through it, so the next
14309	/// best is never a path derived from the one withdrawn. Announcing again
14310	/// revives them, and nothing is remembered once no route passes through it.
14311	#[kio::test]
14312	async fn withdrawn_peer_hides_routes_through_it() {
14313		let producer = origin(1).produce();
14314		let peer = producer.clone().with_link(Link::Peer);
14315		let mut announced = producer.consume().routes();
14316
14317		// Publisher 9 ingests at relay 2; relay 3 relays 2's route.
14318		let direct = || RouteInfo::new().with_hops(hops(&[9, 2])).with_via(origin(2));
14319		let first = peer.forward("room", direct()).unwrap();
14320		let relayed = peer
14321			.forward("room", RouteInfo::new().with_hops(hops(&[9, 2, 3])).with_via(origin(3)))
14322			.unwrap();
14323		announced.expect_next_active("room").await;
14324		announced.assert_next_wait();
14325
14326		// Relay 2 withdraws: the relayed copy goes with it rather than taking over.
14327		first.withdrawn();
14328		announced.expect_next_ended("room").await;
14329		announced.assert_next_wait();
14330
14331		// Relay 2 announces again, and the relayed copy is live with it.
14332		let second = peer.forward("room", direct()).unwrap();
14333		announced.expect_next_active("room").await;
14334		assert!(producer.shared.lock().withdrawn.is_empty());
14335
14336		// Nothing passes through relay 2 once both routes are gone.
14337		second.withdrawn();
14338		drop(relayed);
14339		announced.expect_next_ended("room").await;
14340		assert!(producer.shared.lock().withdrawn.is_empty());
14341	}
14342
14343	/// The route layer letting go of one copy of a lite-07 claim takes every copy of the
14344	/// same node, identity and showing with it, a copy still at an older epoch too: a
14345	/// cursor sees the claim end or go offline, never a move onto another copy first.
14346	/// Another node's claim of the identity stays.
14347	#[kio::test]
14348	async fn retiring_a_claim_retires_every_copy() {
14349		for ended in [true, false] {
14350			let producer = origin(1).produce();
14351			let peer = producer.clone().with_link(Link::Peer);
14352			let mut announced = producer.consume().routes();
14353			let copy = |node: u64, cost: u64| {
14354				RouteInfo::new()
14355					.with_identity(identity(), 0)
14356					.with_hops(hops(&[node]))
14357					.with_cost(cost)
14358					.with_node(Some(node_id(node)))
14359			};
14360			let near = peer.forward("room", copy(7, 1)).unwrap();
14361			let _far = peer.forward("room", copy(7, 2)).unwrap();
14362			announced.expect_next_active("room").await;
14363			announced.assert_next_wait();
14364			near.retire(ended);
14365			match ended {
14366				true => announced.expect_next_ended("room").await,
14367				false => announced.expect_next_offline("room").await,
14368			}
14369			announced.assert_next_wait();
14370
14371			// A session that has yet to take the newer epoch still holds the older one.
14372			let newer = |node: u64, cost: u64| copy(node, cost).with_identity(identity(), 1);
14373			let near = peer.forward("room", newer(7, 1)).unwrap();
14374			let _stale = peer.forward("room", copy(7, 2)).unwrap();
14375			announced.expect_next_active("room").await;
14376			announced.assert_next_wait();
14377			near.retire(ended);
14378			match ended {
14379				true => announced.expect_next_ended("room").await,
14380				false => announced.expect_next_offline("room").await,
14381			}
14382			announced.assert_next_wait();
14383
14384			let near = peer.forward("room", copy(7, 1)).unwrap();
14385			let _other = peer.forward("room", copy(8, 3)).unwrap();
14386			announced.expect_next_active("room").await;
14387			announced.assert_next_wait();
14388			near.retire(ended);
14389			let other = announced.expect_next_active("room").await;
14390			assert_eq!(other.node, Some(node_id(8)), "ended: {ended}");
14391		}
14392	}
14393
14394	/// A copy whose session releases it only after the route layer showed the claim again
14395	/// through another session retires its own showing, not the new one, even when the new
14396	/// one's chain passes through the old one's last hop.
14397	#[kio::test]
14398	async fn a_late_retirement_spares_a_later_showing() {
14399		for ended in [true, false] {
14400			let producer = origin(1).produce();
14401			let peer = producer.clone().with_link(Link::Peer);
14402			let mut announced = producer.consume().routes();
14403			let copy = |chain: &[u64], cost: u64, lifecycle: u64| {
14404				RouteInfo::new()
14405					.with_identity(identity(), 0)
14406					.with_hops(hops(chain))
14407					.with_cost(cost)
14408					.with_node(Some(node_id(7)))
14409					.with_lane(Lane {
14410						lifecycle,
14411						..Lane::default()
14412					})
14413			};
14414			let old = peer.forward("room", copy(&[7], 1, 1)).unwrap();
14415			announced.expect_next_active("room").await;
14416			announced.assert_next_wait();
14417			let _new = peer.forward("room", copy(&[7, 9], 2, 2)).unwrap();
14418			old.retire(ended);
14419			let new = announced.expect_next_active("room").await;
14420			assert_eq!(new.cost, Cost::from(2), "ended: {ended}");
14421			announced.assert_next_wait();
14422		}
14423	}
14424
14425	/// Overlapping sessions carrying one identity are independent claims, regardless of
14426	/// announcement order, and falling back from one to the other is the same stream.
14427	#[kio::test]
14428	async fn old_session_withdrawal_keeps_newer_route() {
14429		for old_first in [false, true] {
14430			let producer = origin(1).produce();
14431			let peer = producer.clone().with_link(Link::Peer);
14432			let mut announced = producer.consume().routes();
14433			let route = RouteInfo::new().with_identity(identity(), 0).with_hops(hops(&[9, 2]));
14434			let first = peer.forward("room", route.clone()).unwrap();
14435			let second = peer.forward("room", route.clone()).unwrap();
14436			announced.expect_next_active("room").await;
14437			announced.assert_next_wait();
14438			let remaining = if old_first {
14439				first.withdrawn();
14440				second
14441			} else {
14442				second.withdrawn();
14443				first
14444			};
14445			announced.assert_next_wait();
14446			assert!(producer.shared.lock().withdrawn.is_empty());
14447			remaining.withdrawn();
14448			announced.expect_next_ended("room").await;
14449			assert!(producer.shared.lock().withdrawn.is_empty());
14450		}
14451	}
14452
14453	#[kio::test]
14454	async fn withdrawn_route_no_longer_covers_requests() {
14455		let producer = origin(1).produce();
14456		let peer = producer.clone().with_link(Link::Peer);
14457		let direct = peer.forward("room", RouteInfo::new().with_hops(hops(&[9, 2]))).unwrap();
14458		let _relayed = peer
14459			.forward("room", RouteInfo::new().with_hops(hops(&[9, 2, 3])))
14460			.unwrap();
14461		let path = Path::from_static("room/video");
14462		let id = producer
14463			.shared
14464			.read()
14465			.routes
14466			.covering(&path)
14467			.find(|entry| entry.hops.iter().last() == Some(&origin(3)))
14468			.unwrap()
14469			.id;
14470		assert!(producer.shared.read().routes.covers(&path, id));
14471		direct.withdrawn();
14472		assert!(!producer.shared.read().routes.covers(&path, id));
14473	}
14474
14475	/// A change of source alone is delivered: the same chain and cost arriving
14476	/// from a peer instead of a client is a different fact for the consumer. Under one
14477	/// identity it is an update.
14478	#[kio::test]
14479	#[cfg(feature = "async")]
14480	async fn source_change_is_an_update() {
14481		let producer = origin(1).produce();
14482		let peer = producer.clone().with_link(Link::Peer);
14483		let mut announced = producer.consume().routes();
14484
14485		let route = RouteInfo::new()
14486			.with_identity(identity(), 0)
14487			.with_hops(hops(&[7]))
14488			.with_via(origin(7));
14489		let _forwarded = peer.forward("room", route.clone()).unwrap();
14490		assert_eq!(announced.expect_next_active("room").await.source(), Source::Peer(7));
14491
14492		// The newest identical route wins, so the local twin takes over.
14493		let local = producer.forward("room", route).unwrap();
14494		match announced.next().await.expect("no next") {
14495			RouteEvent {
14496				kind: RouteKind::Update,
14497				announce,
14498			} => assert_eq!(announce.route.source(), Source::Local),
14499			other => panic!("should be an update: got {other:?}"),
14500		}
14501
14502		drop(local);
14503		assert_eq!(announced.expect_next_active("room").await.source(), Source::Peer(7));
14504	}
14505
14506	#[kio::test]
14507	async fn local_view_hides_peer_routes() {
14508		let producer = origin(1).produce();
14509		let peer = producer.clone().with_link(Link::Peer);
14510		let mut local = producer.consume().local().routes();
14511
14512		let _forwarded = peer
14513			.forward("remote", RouteInfo::new().with_hops(hops(&[7])).with_via(origin(7)))
14514			.unwrap();
14515		local.assert_next_wait();
14516
14517		// A path both ingested here and forwarded by a peer shows the local route,
14518		// and retracts from the local view when the local route goes, even though
14519		// the peer's still covers it.
14520		let _shadow = peer
14521			.forward("both", RouteInfo::new().with_hops(hops(&[7])).with_via(origin(7)))
14522			.unwrap();
14523		let ingest = producer
14524			.forward(
14525				"both",
14526				RouteInfo::new().with_hops(hops(&[5])).with_via(origin(5)).with_cost(9),
14527			)
14528			.unwrap();
14529		assert_eq!(local.expect_next_active("both").await.source(), Source::Local);
14530		drop(ingest);
14531		local.expect_next_offline("both").await;
14532
14533		// Resolution agrees with the cursor: a peer-only path is unroutable here,
14534		// while the full view queues the request on the peer's route.
14535		let err = producer
14536			.consume()
14537			.local()
14538			.request("remote/alice", None)
14539			.now_or_never()
14540			.expect("unroutable")
14541			.err()
14542			.unwrap();
14543		assert!(matches!(err, Error::Unroutable));
14544		assert!(
14545			producer
14546				.consume()
14547				.request("remote/alice", None)
14548				.now_or_never()
14549				.is_none()
14550		);
14551	}
14552
14553	/// An upstream link is offered what entered here and what other peers
14554	/// forwarded, but never a route learned on another upstream link, and the
14555	/// best route it sees skips a better upstream one.
14556	#[kio::test]
14557	async fn upstream_view_hides_upstream_routes() {
14558		let producer = origin(1).produce();
14559		let peer = producer.clone().with_link(Link::Peer);
14560		let core = producer.clone().with_link(Link::Upstream);
14561		let mut toward_core = core.consume().routes();
14562		let mut everyone = producer.consume().routes();
14563
14564		let _core = core
14565			.forward("core", RouteInfo::new().with_hops(hops(&[7])).with_via(origin(7)))
14566			.unwrap();
14567		assert_eq!(everyone.expect_next_active("core").await.source(), Source::Peer(7));
14568		toward_core.assert_next_wait();
14569
14570		let _mesh = peer
14571			.forward("mesh", RouteInfo::new().with_hops(hops(&[8])).with_via(origin(8)))
14572			.unwrap();
14573		assert_eq!(toward_core.expect_next_active("mesh").await.source(), Source::Peer(8));
14574
14575		// A path both an upstream and a mesh peer reach: the upstream route is
14576		// cheaper, yet the upstream view selects the mesh peer's.
14577		let _cheap = core
14578			.forward("both", RouteInfo::new().with_hops(hops(&[7])).with_via(origin(7)))
14579			.unwrap();
14580		let mesh = peer
14581			.forward(
14582				"both",
14583				RouteInfo::new().with_hops(hops(&[8])).with_via(origin(8)).with_cost(9),
14584			)
14585			.unwrap();
14586		assert_eq!(toward_core.expect_next_active("both").await.source(), Source::Peer(8));
14587		drop(mesh);
14588		toward_core.expect_next_offline("both").await;
14589
14590		// Resolution agrees with the cursor: an upstream-only path is unroutable
14591		// toward an upstream, while the full view queues it on the core's route.
14592		let err = core
14593			.consume()
14594			.request("core/alice", None)
14595			.now_or_never()
14596			.expect("unroutable")
14597			.err()
14598			.unwrap();
14599		assert!(matches!(err, Error::Unroutable));
14600		assert!(producer.consume().request("core/alice", None).now_or_never().is_none());
14601	}
14602
14603	/// A handler that rejects a path with `Unroutable` while its route stands
14604	/// gives the requester that answer; the front must not re-ask the same route
14605	/// forever, which would spin the origin driver.
14606	#[kio::test]
14607	#[cfg(feature = "async")]
14608	async fn handler_rejection_is_final() {
14609		let producer = origin(1).produce();
14610		let consumer = producer.consume();
14611		let server = producer.forward("room", RouteInfo::new()).unwrap();
14612
14613		let pending = consumer.request("room/alice", None);
14614		let request = queued(&server).await;
14615		request.reject(Error::Unroutable);
14616		let err = kio::clock::timeout(Duration::from_secs(5), pending)
14617			.await
14618			.expect("the front must give up, not spin")
14619			.err()
14620			.unwrap();
14621		assert!(matches!(err, Error::Unroutable));
14622
14623		// The route still stands and serves the next path.
14624		let pending = consumer.request("room/bob", None);
14625		let request = queued(&server).await;
14626		assert_eq!(request.path().as_str(), "room/bob");
14627		let served = broadcast::Info::new().produce();
14628		request.serve(&served);
14629		pending.await.expect("resolves");
14630	}
14631
14632	#[kio::test]
14633	#[cfg(feature = "async")]
14634	async fn claim_answer_is_hidden_until_published_under_the_claims_identity() {
14635		let producer = origin(1).produce();
14636		let consumer = producer.consume();
14637		let claim = producer.claim("room", RouteOptions::default()).unwrap();
14638		let mut pending = Box::pin(consumer.request("room/alice", None));
14639		assert!((&mut pending).now_or_never().is_none());
14640
14641		let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap();
14642		let _track = prepared
14643			.broadcast()
14644			.create_track("video", crate::track::Info::timed())
14645			.unwrap();
14646		assert!((&mut pending).now_or_never().is_none());
14647
14648		prepared.announce().unwrap();
14649		let resolved = pending.await.unwrap();
14650		assert_eq!(resolved.info().identity, prepared.route().unwrap().identity);
14651		assert_eq!(
14652			resolved.info().identity,
14653			claim.route().unwrap().identity,
14654			"the job continues the claim's stream at its path"
14655		);
14656		assert!(resolved.track("video").is_ok());
14657	}
14658
14659	/// A hidden job's route is listed by no cursor until it announces, under its identity.
14660	#[kio::test]
14661	#[cfg(feature = "async")]
14662	async fn a_hidden_job_route_is_listed_only_once_announced() {
14663		let producer = origin(1).produce();
14664		let mut announced = producer.consume().routes();
14665		let claim = producer.claim("room", RouteOptions::default()).unwrap();
14666		announced.assert_next_active("room");
14667		let pending = producer.consume().request("room/alice", None);
14668		let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap();
14669		assert!(prepared.route().is_none());
14670		announced.assert_next_wait();
14671
14672		prepared.announce().unwrap();
14673		let identity = prepared.route().and_then(|route| route.identity);
14674		assert_eq!(identity, claim.route().unwrap().identity, "the claim's identity");
14675		match announced.expect_next().await {
14676			RouteEvent {
14677				kind: RouteKind::Start,
14678				announce,
14679			} => {
14680				assert_eq!(announce.prefix.as_str(), "room/alice");
14681				assert_eq!(announce.route.identity, identity);
14682			}
14683			other => panic!("should start beneath the claim: got {other:?}"),
14684		}
14685		assert_eq!(pending.await.unwrap().info().identity, identity);
14686	}
14687
14688	/// Route clones share announcement control, while a fill handle on its broadcast
14689	/// keeps the broadcast alive but not the route.
14690	#[kio::test]
14691	#[cfg(feature = "async")]
14692	async fn route_clones_share_control_and_fill_handles_do_not_retain_it() {
14693		let producer = origin(1).produce();
14694		let consumer = producer.consume();
14695		let mut events = consumer.routes();
14696		let publication = producer
14697			.route("room/alice", RouteOptions::hidden().with_identity(identity(), 0))
14698			.unwrap();
14699		let fill = publication.broadcast().clone();
14700		let control = publication.clone();
14701		publication.announce().unwrap();
14702		assert_eq!(events.expect_next_active("room/alice").await.identity, Some(identity()));
14703		control.withdraw();
14704		events.expect_next_ended("room/alice").await;
14705		assert!(publication.route().is_none());
14706		publication.announce().unwrap();
14707		assert_eq!(events.expect_next_active("room/alice").await.identity, Some(identity()));
14708		drop(control);
14709		events.assert_next_wait();
14710		let held = consumer.request("room/alice", None).await.unwrap();
14711		drop(publication);
14712		events.expect_next_ended("room/alice").await;
14713		assert!(matches!(
14714			consumer.request("room/alice", None).await,
14715			Err(Error::Unroutable)
14716		));
14717		assert!(!held.is_closed(), "the fill handle keeps the broadcast alive");
14718		drop(fill);
14719	}
14720
14721	/// A withdrawn stale publication cannot remove a replacement identity's route.
14722	#[kio::test]
14723	#[cfg(feature = "async")]
14724	async fn stale_publication_control_cannot_withdraw_a_replacement() {
14725		let producer = origin(1).produce();
14726		let consumer = producer.consume();
14727		let old = producer
14728			.route("room/alice", RouteOptions::default().with_identity(identity(), 0))
14729			.unwrap();
14730		let replacement_identity: crate::Identity = "01900000-0000-7000-8000-000000000002".parse().unwrap();
14731		let replacement = producer
14732			.route(
14733				"room/alice",
14734				RouteOptions::default().with_identity(replacement_identity.clone(), 0),
14735			)
14736			.unwrap();
14737		old.withdraw();
14738		old.broadcast().close();
14739		assert_eq!(
14740			replacement.route().unwrap().identity,
14741			Some(replacement_identity.clone())
14742		);
14743		let resolved = consumer
14744			.request("room/alice", replacement_identity.clone())
14745			.await
14746			.unwrap();
14747		assert_eq!(resolved.info().identity.as_ref(), Some(&replacement_identity));
14748	}
14749
14750	/// A refused answer keeps its announcer withheld, so a clone cannot announce it later.
14751	#[kio::test]
14752	#[cfg(feature = "async")]
14753	async fn a_refused_prepared_answer_cannot_announce_later() {
14754		let producer = origin(1).produce();
14755		let claim = producer.claim("room", RouteOptions::default()).unwrap();
14756		let _pending = producer.consume().request("room/alice", None);
14757		let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap();
14758		let clone = prepared.clone();
14759
14760		drop(claim);
14761		assert!(matches!(prepared.announce(), Err(Error::Unroutable)));
14762		assert!(matches!(clone.announce(), Err(Error::Closed)));
14763	}
14764
14765	#[kio::test]
14766	#[cfg(feature = "async")]
14767	async fn dropping_a_prepared_claim_answer_refuses_the_request() {
14768		let producer = origin(1).produce();
14769		let consumer = producer.consume();
14770		let claim = producer.claim("room", RouteOptions::default()).unwrap();
14771		let pending = consumer.request("room/alice", None);
14772		let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap();
14773		drop(prepared);
14774		assert!(matches!(pending.await, Err(Error::Unroutable)));
14775	}
14776
14777	/// Whether a held request reports nobody waits on it, without waiting.
14778	#[cfg(feature = "async")]
14779	fn unwanted(request: &Request) -> bool {
14780		request.poll_unwanted(&kio::Waiter::noop()).is_ready()
14781	}
14782
14783	/// A held request is unwanted once its only requester leaves, and stays so: a new
14784	/// requester gets a new request rather than reviving the skipped one.
14785	#[kio::test]
14786	#[cfg(feature = "async")]
14787	async fn a_request_is_unwanted_once_its_requester_leaves() {
14788		let producer = origin(1).produce();
14789		let consumer = producer.consume();
14790		let claim = producer.claim("room", RouteOptions::default()).unwrap();
14791		let pending = consumer.request("room/alice", None);
14792		let request = queued(&claim).await;
14793		assert!(!unwanted(&request));
14794
14795		drop(pending);
14796		settle(|| unwanted(&request)).await;
14797
14798		let pending = consumer.request("room/alice", None);
14799		let fresh = queued(&claim).await;
14800		assert!(unwanted(&request), "a new requester never revives it");
14801		assert!(!unwanted(&fresh));
14802		drop(request);
14803		fresh.serve(broadcast::Info::new().produce());
14804		pending.await.expect("the fresh request answers");
14805	}
14806
14807	/// Coalesced requesters share one request: it is unwanted only once the last leaves.
14808	#[kio::test]
14809	#[cfg(feature = "async")]
14810	async fn a_coalesced_request_is_unwanted_once_the_last_requester_leaves() {
14811		let producer = origin(1).produce();
14812		let consumer = producer.consume();
14813		let claim = producer.claim("room", RouteOptions::default()).unwrap();
14814		let first = consumer.request("room/alice", None);
14815		let second = consumer.request("room/alice", None);
14816		let request = queued(&claim).await;
14817
14818		drop(first);
14819		for _ in 0..10 {
14820			kio::clock::sim::yield_now().await;
14821		}
14822		assert!(!unwanted(&request), "the second requester still waits");
14823		assert!(
14824			claim.poll_requested(&kio::Waiter::noop()).is_pending(),
14825			"one request for both"
14826		);
14827
14828		drop(second);
14829		settle(|| unwanted(&request)).await;
14830	}
14831
14832	/// A front moving to a cheaper route leaves the request it held unwanted, while its
14833	/// requester resolves through the new route.
14834	#[kio::test]
14835	#[cfg(feature = "async")]
14836	async fn a_request_is_unwanted_once_its_front_moves_to_another_route() {
14837		let producer = origin(1).produce();
14838		let consumer = producer.consume();
14839		let pool = producer.claim("room", RouteOptions::default().with_cost(5)).unwrap();
14840		let pending = consumer.request("room/alice", None);
14841		let request = queued(&pool).await;
14842
14843		let node = producer.claim("room", RouteOptions::default().with_cost(1)).unwrap();
14844		let moved = queued(&node).await;
14845		settle(|| unwanted(&request)).await;
14846		assert!(!unwanted(&moved));
14847
14848		let served = broadcast::Info::new().produce();
14849		moved.serve(&served);
14850		pending.await.expect("resolves through the cheaper route");
14851	}
14852
14853	/// A front moving to a route that serves at once, such as a local broadcast, also
14854	/// leaves the request it held unwanted.
14855	#[kio::test]
14856	#[cfg(feature = "async")]
14857	async fn a_request_is_unwanted_once_a_direct_route_takes_over() {
14858		let producer = origin(1).produce();
14859		let consumer = producer.consume();
14860		let pool = producer.claim("room", RouteOptions::default().with_cost(5)).unwrap();
14861		let pending = consumer.request("room/alice", None);
14862		let request = queued(&pool).await;
14863
14864		let _direct = producer
14865			.route("room/alice", RouteOptions::default().with_cost(1))
14866			.unwrap();
14867		settle(|| unwanted(&request)).await;
14868		pending.await.expect("resolves through the direct route");
14869	}
14870
14871	/// A front that gives up a switch without asking anew, because its serving route is
14872	/// the best again, leaves the switch's request unwanted.
14873	#[kio::test]
14874	#[cfg(feature = "async")]
14875	async fn a_request_is_unwanted_once_its_front_gives_up_the_switch() {
14876		let producer = origin(1).produce();
14877		let consumer = producer.consume();
14878		let options = |cost: u64| RouteOptions::default().with_identity(identity(), 0).with_cost(cost);
14879		let serving = producer.claim("room", options(5)).unwrap();
14880		let pending = consumer.request("room/alice", None);
14881		let source = broadcast::Info::new().produce();
14882		queued(&serving).await.serve(&source);
14883		let _resolved = pending.await.expect("resolves through the serving claim");
14884
14885		let cheaper = producer.claim("room", options(1)).unwrap();
14886		let switch = queued(&cheaper).await;
14887		assert!(!unwanted(&switch));
14888
14889		cheaper.set_cost(10).unwrap();
14890		settle(|| unwanted(&switch)).await;
14891	}
14892
14893	/// An answer prepared for a claim that went away is refused, never announced.
14894	#[kio::test]
14895	#[cfg(feature = "async")]
14896	async fn a_prepared_answer_for_an_abandoned_claim_is_never_announced() {
14897		let producer = origin(1).produce();
14898		let mut announced = producer.consume().routes();
14899		let claim = producer.claim("room", RouteOptions::default()).unwrap();
14900		announced.assert_next_active("room");
14901		let _pending = producer.consume().request("room/alice", None);
14902		let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap();
14903
14904		drop(claim);
14905		announced.assert_next_ended("room");
14906		assert!(matches!(prepared.announce(), Err(Error::Unroutable)));
14907		announced.assert_next_wait();
14908	}
14909
14910	/// Withdrawing a prefix route releases its pending requests, so a hidden job route
14911	/// prepared for one is refused rather than announced, and the requester is refused.
14912	#[kio::test]
14913	#[cfg(feature = "async")]
14914	async fn a_job_route_for_a_withdrawn_prefix_is_never_announced() {
14915		let producer = origin(1).produce();
14916		let mut announced = producer.consume().routes();
14917		let claim = producer.claim("room", RouteOptions::default()).unwrap();
14918		announced.assert_next_active("room");
14919		let pending = producer.consume().request("room/alice", None);
14920		let job = queued(&claim).await.route(RouteOptions::hidden()).unwrap();
14921
14922		claim.withdraw();
14923		announced.assert_next_ended("room");
14924		assert!(matches!(job.announce(), Err(Error::Unroutable)));
14925		assert!(!job.is_announced());
14926		assert!(matches!(pending.await, Err(Error::Unroutable)));
14927		announced.assert_next_wait();
14928
14929		// The prefix route itself comes back and answers new requests.
14930		claim.announce().unwrap();
14931		announced.assert_next_active("room");
14932		let _again = producer.consume().request("room/bob", None);
14933		assert_eq!(queued(&claim).await.path().as_str(), "room/bob");
14934	}
14935
14936	/// An answer prepared before the claim changed identity is refused, never announced.
14937	#[kio::test]
14938	#[cfg(feature = "async")]
14939	async fn a_prepared_answer_for_a_released_request_is_never_announced() {
14940		let producer = origin(1).produce();
14941		let mut announced = producer.consume().routes();
14942		let claim = producer.claim("room", RouteOptions::default()).unwrap();
14943		announced.assert_next_active("room");
14944		let _pending = producer.consume().request("room/alice", None);
14945		let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap();
14946
14947		claim
14948			.update(RouteInfo::new().with_identity(crate::Identity::random(), 0))
14949			.unwrap();
14950		announced.assert_next_restarted("room");
14951		assert!(matches!(prepared.announce(), Err(Error::Unroutable)));
14952		announced.assert_next_wait();
14953	}
14954
14955	/// A published job must stop answering through its claim when its exact route leaves,
14956	/// even while its fill handle and readers keep the broadcast alive.
14957	#[kio::test]
14958	#[cfg(feature = "async")]
14959	async fn a_withdrawn_publication_is_not_a_cached_claim_answer() {
14960		let producer = origin(1).produce();
14961		let claim = producer.claim("room", RouteOptions::default()).unwrap();
14962		let path = Path::from_static("room/alice");
14963		let pending = producer.consume().request(path.clone(), None);
14964		let publication = queued(&claim).await.route(RouteOptions::default()).unwrap();
14965		let held = pending.await.unwrap();
14966		publication.withdraw();
14967		assert!(
14968			claim.server().lock().served.get(&path).is_none(),
14969			"withdrawn job still cached"
14970		);
14971		let next = producer.consume().request(path, None);
14972		let request = queued(&claim).await;
14973		request.reject(Error::App(42));
14974		assert!(next.await.is_err());
14975		drop(held);
14976	}
14977
14978	/// A job withdrawn while it carries the claim's identity ends that stream at its path, so
14979	/// the claim moves to a fresh identity with it: the next job, at that path or another,
14980	/// starts a new stream rather than splicing into the old one.
14981	#[kio::test]
14982	#[cfg(feature = "async")]
14983	async fn a_withdrawn_job_moves_the_claim_to_a_fresh_identity() {
14984		let producer = origin(1).produce();
14985		let consumer = producer.consume();
14986		let mut announced = consumer.routes();
14987		let claim = producer.claim("room", RouteOptions::default()).unwrap();
14988		announced.assert_next_active("room");
14989		let first = claim.identity();
14990
14991		let answer = async |path: &str| {
14992			let pending = consumer.request(path, None);
14993			let published = queued(&claim).await.route(RouteOptions::default()).unwrap();
14994			pending.await.unwrap();
14995			published
14996		};
14997
14998		let alice = answer("room/alice").await;
14999		assert_eq!(alice.identity(), first, "the job takes the claim's identity");
15000		announced.assert_next_active("room/alice");
15001
15002		let bob = answer("room/bob").await;
15003		assert_eq!(bob.identity(), first, "jobs at sibling paths share it");
15004		announced.assert_next_active("room/bob");
15005
15006		alice.withdraw();
15007		let second = claim.identity();
15008		assert_ne!(second, first, "the claim moved on");
15009		match announced.expect_next().await {
15010			RouteEvent {
15011				kind: RouteKind::End,
15012				announce,
15013			} => assert_eq!(announce.prefix.as_str(), "room/alice"),
15014			other => panic!("should end the job: got {other:?}"),
15015		}
15016		match announced.expect_next().await {
15017			RouteEvent {
15018				kind: RouteKind::Restart,
15019				announce,
15020			} => {
15021				assert_eq!(announce.prefix.as_str(), "room");
15022				assert_eq!(announce.route.identity, Some(second.clone()));
15023			}
15024			other => panic!("should restart the claim: got {other:?}"),
15025		}
15026		// The sibling keeps the stream it holds.
15027		assert_eq!(bob.identity(), first);
15028
15029		let carol = answer("room/carol").await;
15030		assert_eq!(carol.identity(), second, "a later job takes the claim's new identity");
15031		// Bob ending now spends nothing the claim still lends.
15032		drop(bob);
15033		assert_eq!(claim.identity(), second);
15034		drop(carol);
15035		assert_ne!(claim.identity(), second);
15036	}
15037
15038	/// A claim filed at several grant prefixes is one claim: a job withdrawn under any of them
15039	/// moves every filing to the same fresh identity, which the claim reports and each later
15040	/// job takes.
15041	#[kio::test]
15042	#[cfg(feature = "async")]
15043	async fn a_withdrawn_job_moves_every_filing_of_the_claim() {
15044		let producer = origin(1).produce();
15045		let consumer = producer.consume();
15046		let scoped = producer.scope("", &scopes(&["room/a", "room/b"])).unwrap();
15047		let claim = scoped.claim("room", RouteOptions::default()).unwrap();
15048		let first = claim.identity();
15049
15050		let answer = async |path: &str| {
15051			let pending = consumer.request(path, None);
15052			let published = queued(&claim).await.route(RouteOptions::default()).unwrap();
15053			pending.await.unwrap();
15054			published
15055		};
15056
15057		let a = answer("room/a/x").await;
15058		let b = answer("room/b/x").await;
15059		assert_eq!(a.identity(), first, "each filing lends the claim's identity");
15060		assert_eq!(b.identity(), first, "each filing lends the claim's identity");
15061		b.withdraw();
15062		let second = claim.identity();
15063		assert_ne!(second, first, "the claim moved on");
15064		// Held, since a job that ends moves the claim on again.
15065		let mut held = vec![a];
15066		for path in ["room/a/y", "room/b/y"] {
15067			let job = answer(path).await;
15068			assert_eq!(
15069				job.identity(),
15070				second,
15071				"{path}: every filing moved to the claim's new identity"
15072			);
15073			held.push(job);
15074		}
15075	}
15076
15077	/// A job's route takes the identity its claim lends when it announces, not when it was
15078	/// created: a hidden job that never read its identity outlives a sibling's end and joins
15079	/// the claim's next stream.
15080	#[kio::test]
15081	#[cfg(feature = "async")]
15082	async fn a_hidden_job_takes_the_claims_identity_when_it_announces() {
15083		let producer = origin(1).produce();
15084		let consumer = producer.consume();
15085		let claim = producer.claim("room", RouteOptions::default()).unwrap();
15086
15087		let alice = consumer.request("room/alice", None);
15088		let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap();
15089		let bob = consumer.request("room/bob", None);
15090		let sibling = queued(&claim).await.route(RouteOptions::default()).unwrap();
15091		bob.await.unwrap();
15092		let first = claim.identity();
15093		assert_eq!(sibling.identity(), first);
15094
15095		drop(sibling);
15096		let second = claim.identity();
15097		assert_ne!(second, first);
15098
15099		prepared.announce().unwrap();
15100		assert_eq!(prepared.identity(), second);
15101		assert_eq!(alice.await.unwrap().info().identity, Some(second));
15102	}
15103
15104	/// A hidden job that read its identity, as a signer does, announces under it or not at
15105	/// all: once a sibling's end moves the claim past it, the announce is refused and its
15106	/// request goes back to the worker, which prepares the job under the new identity. Every
15107	/// requester waits on, including one that joined after the claim moved.
15108	#[kio::test]
15109	#[cfg(feature = "async")]
15110	async fn a_job_that_read_its_identity_is_refused_once_the_claim_moves() {
15111		let producer = origin(1).produce();
15112		let consumer = producer.consume();
15113		let claim = producer.claim("room", RouteOptions::default()).unwrap();
15114
15115		let alice = consumer.request("room/alice", None);
15116		let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap();
15117		let bob = consumer.request("room/bob", None);
15118		let sibling = queued(&claim).await.route(RouteOptions::default()).unwrap();
15119		bob.await.unwrap();
15120		let first = prepared.identity();
15121		assert_eq!(first, claim.identity());
15122
15123		drop(sibling);
15124		let second = claim.identity();
15125		assert_ne!(second, first);
15126		assert_eq!(prepared.identity(), first, "a read identity moved");
15127		let late = consumer.request("room/alice", None);
15128		assert!(matches!(prepared.announce(), Err(Error::Unroutable)));
15129
15130		let again = queued(&claim).await.route(RouteOptions::hidden()).unwrap();
15131		assert_eq!(again.identity(), second);
15132		again.announce().unwrap();
15133		assert_eq!(alice.await.unwrap().info().identity, Some(second.clone()));
15134		assert_eq!(late.await.unwrap().info().identity, Some(second));
15135	}
15136
15137	/// A request pinned to the claim's identity resolves through its job's route even when a
15138	/// sibling job ending moved the claim on before the request looked again.
15139	#[kio::test]
15140	#[cfg(feature = "async")]
15141	async fn a_pinned_request_reaches_its_job_after_a_sibling_moves_the_claim() {
15142		let producer = origin(1).produce();
15143		let consumer = producer.consume();
15144		let claim = producer.claim("room", RouteOptions::default()).unwrap();
15145		let lent = claim.identity();
15146
15147		let reader = consumer.request("room/alice", None);
15148		let alice = queued(&claim).await.route(RouteOptions::default()).unwrap();
15149		let held = reader.await.unwrap();
15150
15151		let pinned = consumer.request("room/bob", lent.clone());
15152		let bob = queued(&claim).await.route(RouteOptions::default()).unwrap();
15153		drop(alice);
15154		assert_ne!(claim.identity(), lent);
15155		assert_eq!(bob.identity(), lent);
15156		let resolved = pinned.await.expect("the job still serves the pinned identity");
15157		assert_eq!(resolved.info().identity, Some(lent));
15158		drop(held);
15159	}
15160
15161	/// Once a job ends, a request pinned to its identity is refused without asking the
15162	/// claim, which serves another stream now, while an unpinned one starts the next job.
15163	#[kio::test]
15164	#[cfg(feature = "async")]
15165	async fn a_request_pinned_to_an_ended_job_is_refused() {
15166		let producer = origin(1).produce();
15167		let consumer = producer.consume();
15168		let claim = producer.claim("room", RouteOptions::default()).unwrap();
15169
15170		let pending = consumer.request("room/alice", None);
15171		let job = queued(&claim).await.route(RouteOptions::default()).unwrap();
15172		let held = pending.await.unwrap();
15173		let ended = job.identity();
15174		job.broadcast().close();
15175		drop(job);
15176
15177		let pinned = consumer.request("room/alice", ended.clone()).await;
15178		assert!(matches!(pinned, Err(Error::Unroutable)));
15179		assert!(
15180			claim.poll_requested(&kio::Waiter::noop()).is_pending(),
15181			"the claim was asked"
15182		);
15183
15184		let pending = consumer.request("room/alice", None);
15185		let restarted = queued(&claim).await.route(RouteOptions::default()).unwrap();
15186		assert_ne!(restarted.identity(), ended);
15187		let fresh = pending.await.unwrap();
15188		assert!(!fresh.is_clone(&held), "joined the ended job");
15189	}
15190
15191	/// A claim and its job end independently: a job outliving its claim keeps its stream,
15192	/// and a claim outliving its job moves on.
15193	#[kio::test]
15194	#[cfg(feature = "async")]
15195	async fn a_claim_and_its_job_end_independently() {
15196		let producer = origin(1).produce();
15197		let consumer = producer.consume();
15198		let claim = producer.claim("room", RouteOptions::default()).unwrap();
15199		let pending = consumer.request("room/alice", None);
15200		let job = queued(&claim).await.route(RouteOptions::default()).unwrap();
15201		let held = pending.await.unwrap();
15202		let lent = claim.identity();
15203
15204		drop(claim);
15205		assert_eq!(job.identity(), lent);
15206		let again = consumer.request("room/alice", lent.clone()).await.unwrap();
15207		assert!(again.is_clone(&held), "the job's stream ended with its claim");
15208		drop(job);
15209		assert!(consumer.request("room/alice", lent).await.is_err());
15210	}
15211
15212	/// A claim naming a stable identity lends nothing: its answers mint their own, and their
15213	/// end leaves the claim's identity as it is. A job naming its identity keeps it too.
15214	#[kio::test]
15215	#[cfg(feature = "async")]
15216	async fn named_identities_are_neither_lent_nor_moved() {
15217		let producer = origin(1).produce();
15218		let consumer = producer.consume();
15219		let stable = identity();
15220		let claim = producer
15221			.claim("room", RouteOptions::default().with_identity(stable.clone(), 0))
15222			.unwrap();
15223
15224		let pending = consumer.request("room/alice", None);
15225		let minted = queued(&claim).await.route(RouteOptions::default()).unwrap();
15226		pending.await.unwrap();
15227		assert_ne!(minted.identity(), stable, "a stable claim lent its identity");
15228		drop(minted);
15229		assert_eq!(claim.identity(), stable);
15230
15231		let lending = producer.claim("lent", RouteOptions::default()).unwrap();
15232		let lent = lending.identity();
15233		let named = identity();
15234		let pending = consumer.request("lent/bob", None);
15235		let job = queued(&lending)
15236			.await
15237			.route(RouteOptions::default().with_identity(named.clone(), 0))
15238			.unwrap();
15239		pending.await.unwrap();
15240		assert_eq!(job.identity(), named);
15241		drop(job);
15242		assert_eq!(lending.identity(), lent, "a named job's end moved the claim");
15243	}
15244
15245	/// A request pinned to an identity resolves only through the answer published under
15246	/// it, never by asking the claim, which serves another identity.
15247	#[kio::test]
15248	#[cfg(feature = "async")]
15249	async fn a_pinned_request_resolves_only_through_the_published_identity() {
15250		let producer = origin(1).produce();
15251		let consumer = producer.consume();
15252		let claim = producer.claim("room", RouteOptions::default()).unwrap();
15253		let unknown = consumer.request("room/alice", crate::Identity::random());
15254		assert!(matches!(unknown.await, Err(Error::Unroutable)));
15255
15256		let pending = consumer.request("room/alice", None);
15257		let published = queued(&claim).await.route(RouteOptions::default()).unwrap();
15258		let identity = published.route().unwrap().identity.unwrap();
15259		pending.await.expect("resolves");
15260
15261		let pinned = consumer.request("room/alice", identity.clone()).await;
15262		assert_eq!(pinned.expect("resolves").info().identity.as_ref(), Some(&identity));
15263		let stale = consumer.request("room/alice", crate::Identity::random());
15264		assert!(matches!(stale.await, Err(Error::Unroutable)));
15265	}
15266
15267	/// A refusal from the longest prefix is the answer: neither a costlier advertiser of
15268	/// that prefix nor a catch-all is asked instead.
15269	#[kio::test]
15270	#[cfg(feature = "async")]
15271	async fn refusal_never_falls_through() {
15272		let producer = origin(1).produce();
15273		let consumer = producer.consume();
15274		let catch_all = producer.forward("", RouteInfo::new()).unwrap();
15275		let winner = producer.forward("room", RouteInfo::new()).unwrap();
15276		let sibling = producer.forward("room", RouteInfo::new().with_cost(2)).unwrap();
15277
15278		let mut pending = Box::pin(consumer.request("room/alice", None));
15279		assert!((&mut pending).now_or_never().is_none());
15280		queued(&winner).await.reject(Error::NotFound);
15281		let mut result = None;
15282		settle(|| {
15283			result = (&mut pending).now_or_never();
15284			result.is_some()
15285		})
15286		.await;
15287		let err = result.unwrap().err().unwrap();
15288		assert!(matches!(err, Error::NotFound), "unexpected end: {err}");
15289
15290		for other in [&sibling, &catch_all] {
15291			assert!(other.poll_requested(&kio::Waiter::noop()).is_pending());
15292		}
15293	}
15294
15295	/// A refusal from a route a local broadcast superseded while it was pending is moot:
15296	/// the request resolves to the local broadcast instead of ending.
15297	#[kio::test]
15298	#[cfg(feature = "async")]
15299	async fn superseded_refusal_does_not_end_the_request() {
15300		let producer = origin(1).produce();
15301		let consumer = producer.consume();
15302		let stale = producer.forward("room", RouteInfo::new()).unwrap();
15303
15304		let mut pending = Box::pin(consumer.request("room/alice", None));
15305		assert!((&mut pending).now_or_never().is_none());
15306		let request = queued(&stale).await;
15307
15308		// The local broadcast wins before the front sees the rejection.
15309		let local = producer.route("room/alice", RouteOptions::hidden()).unwrap();
15310		local.announce().unwrap();
15311		request.reject(Error::NotFound);
15312
15313		let mut result = None;
15314		settle(|| {
15315			result = (&mut pending).now_or_never();
15316			result.is_some()
15317		})
15318		.await;
15319		assert!(result.unwrap().is_ok(), "the superseded refusal ended the request");
15320	}
15321
15322	/// The same holds for a more specific remote route: the beaten route's refusal is
15323	/// moot, and the new winner is asked instead.
15324	#[kio::test]
15325	#[cfg(feature = "async")]
15326	async fn refusal_from_a_beaten_route_asks_the_new_winner() {
15327		let producer = origin(1).produce();
15328		let consumer = producer.consume();
15329		let stale = producer.forward("room", RouteInfo::new()).unwrap();
15330
15331		let mut pending = Box::pin(consumer.request("room/alice", None));
15332		assert!((&mut pending).now_or_never().is_none());
15333		let request = queued(&stale).await;
15334
15335		let winner = producer.forward("room/alice", RouteInfo::new()).unwrap();
15336		request.reject(Error::NotFound);
15337		let source = broadcast::Info::new().produce();
15338		queued(&winner).await.serve(&source);
15339
15340		let mut result = None;
15341		settle(|| {
15342			result = (&mut pending).now_or_never();
15343			result.is_some()
15344		})
15345		.await;
15346		assert!(result.unwrap().is_ok(), "the beaten route's refusal ended the request");
15347	}
15348
15349	/// Teardown rejects the parked request with the origin's own terminal cause.
15350	#[kio::test]
15351	#[cfg(feature = "async")]
15352	async fn follow_reports_teardown_as_closed() {
15353		let (producer, driver) = Producer::new(Config::from(origin(1)));
15354		let consumer = producer.consume();
15355		let _server = producer.forward("room", RouteInfo::new()).unwrap();
15356
15357		// Park on the covering route, past the loop's closed check.
15358		let mut following = consumer.follow("room/alice", None).unwrap();
15359		let mut resolving = Box::pin(following.available());
15360		assert!((&mut resolving).now_or_never().is_none());
15361
15362		drop(driver);
15363
15364		let err = kio::clock::timeout(Duration::from_secs(5), resolving)
15365			.await
15366			.expect("teardown resolves the wait")
15367			.err()
15368			.unwrap();
15369		assert!(matches!(err, Error::Closed), "unexpected end: {err}");
15370	}
15371
15372	/// A datagram track a published broadcast creates reaches a reader through the origin:
15373	/// the front looks it up on the source it serves from.
15374	#[kio::test]
15375	#[cfg(feature = "async")]
15376	async fn a_front_serves_its_sources_datagram_tracks() {
15377		let producer = origin(1).produce();
15378		let publication = producer.route("room", RouteOptions::default()).unwrap();
15379		let mut datagrams = publication
15380			.broadcast()
15381			.create_datagrams("audio", crate::datagram::Info::default())
15382			.unwrap();
15383
15384		let front = producer.consume().request("room", None).await.unwrap();
15385		let mut reader = front.datagrams("audio").unwrap();
15386		datagrams.append(crate::Timestamp::unscaled(0), "x").unwrap();
15387		let datagram = reader.recv().now_or_never().unwrap().unwrap().unwrap();
15388		assert_eq!(datagram.sequence, 0);
15389		assert!(matches!(front.datagrams("video"), Err(Error::NotFound)));
15390	}
15391
15392	/// A track first subscribed after the front is already serving another still
15393	/// replays what its source holds, like the first track did.
15394	#[kio::test]
15395	#[cfg(feature = "async")]
15396	async fn late_track_on_a_served_front_replays() {
15397		let producer = origin(1).produce();
15398		let consumer = producer.consume();
15399		let server = producer.forward("room", RouteInfo::new()).unwrap();
15400
15401		let source = broadcast::Info::new().produce();
15402		for name in ["a", "b"] {
15403			let track = source.create_track(name, crate::track::Info::timed()).unwrap();
15404			let mut group = track.append_next().unwrap();
15405			group
15406				.write_frame(Frame::new(group.key_time(), name.as_bytes()))
15407				.unwrap();
15408			group.finish().unwrap();
15409			// The producer stays alive: the track is open, like a live SI track.
15410			std::mem::forget(track);
15411		}
15412
15413		let pending = consumer.request("room/alice", None);
15414		queued(&server).await.serve(&source);
15415		let resolved = pending.await.expect("resolves");
15416
15417		let budget = track::Subscription::default().with_max(Duration::from_secs(3600));
15418		for name in ["a", "b"] {
15419			let mut subscription = resolved
15420				.track(name)
15421				.unwrap()
15422				.subscribe(budget.clone())
15423				.await
15424				.expect("subscribe");
15425			let mut group = kio::clock::timeout(Duration::from_secs(5), subscription.recv_group())
15426				.await
15427				.expect("the late track must replay, not park")
15428				.expect("recv group")
15429				.expect("track ended early");
15430			let frame = group.read_frame().await.expect("read frame").expect("frame");
15431			assert_eq!(&frame.payload[..], name.as_bytes());
15432		}
15433	}
15434
15435	#[kio::test]
15436	#[cfg(feature = "async")]
15437	async fn most_specific_prefix_shadows() {
15438		let producer = origin(1).produce();
15439		let consumer = producer.consume();
15440
15441		let broad_server = producer.forward("", RouteInfo::new()).unwrap();
15442		// A narrow advertise-only claim: requests under it must NOT route to the
15443		// broad server; they fall through to the (absent) fallback handler.
15444		let _narrow = producer.announce(".dash", RouteInfo::new()).unwrap();
15445
15446		let err = consumer
15447			.request(".dash/pid", None)
15448			.now_or_never()
15449			.expect("unroutable")
15450			.err()
15451			.unwrap();
15452		assert!(matches!(err, Error::Unroutable));
15453
15454		// Everything else still routes to the broad server.
15455		let _pending = consumer.request("room/alice", None);
15456		let request = queued(&broad_server).await;
15457		assert_eq!(request.path().as_str(), "room/alice");
15458	}
15459
15460	#[kio::test]
15461	#[cfg(feature = "async")]
15462	async fn root_dynamic_serves_any_path() {
15463		let producer = origin(1).produce();
15464		let consumer = producer.consume();
15465		let mut announced = consumer.routes();
15466		let dynamic = producer.forward("", RouteInfo::new()).unwrap();
15467		// The root claim is advertised like any other prefix.
15468		announced.expect_next_active("").await;
15469
15470		let pending = consumer.request("anything/at/all", None);
15471		let request = queued(&dynamic).await;
15472		assert_eq!(request.path().as_str(), "anything/at/all");
15473
15474		let source = broadcast::Info::new().produce();
15475		request.serve(&source);
15476		let resolved = pending.await.expect("resolves");
15477		assert_eq!(resolved.info().path.as_str(), "anything/at/all");
15478
15479		// Nothing serves an uncovered path once the handler is gone.
15480		drop(dynamic);
15481		announced.expect_next_offline("").await;
15482		let err = consumer
15483			.request("something/else", None)
15484			.now_or_never()
15485			.expect("unroutable")
15486			.err()
15487			.unwrap();
15488		assert!(matches!(err, Error::Unroutable));
15489	}
15490
15491	/// A path outside the consumer's scope never reaches a live dynamic handler.
15492	///
15493	/// `scope` is authoritative, so an out-of-scope path is unauthorized before
15494	/// routing can send a request to the handler. A `Request` carries only a path,
15495	/// so the handler cannot tell who asked.
15496	#[kio::test]
15497	#[cfg(feature = "async")]
15498	async fn out_of_scope_request_never_reaches_the_dynamic_handler() {
15499		let producer = origin(1).produce();
15500		let dynamic = producer.forward("", RouteInfo::new()).unwrap();
15501		let scoped = producer.consume().scope("", &scopes(&["tenant-a"])).unwrap();
15502
15503		// `tenant-a-other` shares a character prefix but not a segment, so this
15504		// also pins that the check is segment-aware rather than textual.
15505		for path in ["tenant-b/live", "tenant-a-other/live"] {
15506			let refused = scoped
15507				.request(path, None)
15508				.now_or_never()
15509				.expect("an out-of-scope request must be refused synchronously, not queued");
15510			assert!(matches!(refused, Err(Error::Unauthorized)));
15511			assert!(
15512				dynamic.requested().now_or_never().is_none(),
15513				"the dynamic handler was asked to create a broadcast the requester may not read"
15514			);
15515		}
15516	}
15517
15518	/// The route a follower's first event starts on.
15519	#[cfg(feature = "async")]
15520	fn started(event: Option<RouteEvent>) -> RouteInfo {
15521		match event.expect("routed") {
15522			RouteEvent {
15523				kind: RouteKind::Start,
15524				announce,
15525			} => announce.route,
15526			other => panic!("should start: got {other:?}"),
15527		}
15528	}
15529
15530	#[kio::test]
15531	#[cfg(feature = "async")]
15532	async fn routes_wait_for_coverage() {
15533		let producer = origin(1).produce();
15534		let consumer = producer.consume();
15535
15536		let mut routes = consumer.path_routes("room/alice").unwrap();
15537		let mut fut = routes.next().boxed();
15538		assert!((&mut fut).now_or_never().is_none());
15539
15540		// A covering prefix resolves the wait.
15541		let _a = producer.forward("room", RouteInfo::new().with_cost(3)).unwrap();
15542		let route = started(fut.now_or_never().expect("covered"));
15543		assert_eq!(route.cost, Cost::new(3));
15544
15545		// Already covered: resolves immediately.
15546		let mut routes = consumer.path_routes("room/alice/cam").unwrap();
15547		started(routes.next().now_or_never().expect("covered"));
15548	}
15549
15550	#[kio::test]
15551	#[cfg(feature = "async")]
15552	async fn routes_ignore_deeper_routes() {
15553		let producer = origin(1).produce();
15554		let consumer = producer.consume();
15555
15556		// A deeper route does not cover the shorter path.
15557		let _deep = producer.forward("room/alice/cam", RouteInfo::new()).unwrap();
15558		let mut routes = consumer.path_routes("room/alice").unwrap();
15559		let mut fut = routes.next().boxed();
15560		assert!((&mut fut).now_or_never().is_none());
15561
15562		let _exact = producer.forward("room/alice", RouteInfo::new()).unwrap();
15563		started(fut.now_or_never().expect("covered"));
15564	}
15565
15566	#[kio::test]
15567	#[cfg(feature = "async")]
15568	async fn routes_accept_a_max_depth_path() {
15569		let producer = origin(1).produce();
15570		let consumer = producer.consume();
15571		let path = (0..Path::MAX_PARTS)
15572			.map(|i| format!("s{i}"))
15573			.collect::<Vec<_>>()
15574			.join("/");
15575		assert_eq!(Path::new(&path).unwrap().parts().count(), Path::MAX_PARTS);
15576
15577		assert!(consumer.allowed().matches(&path));
15578
15579		let mut routes = consumer.path_routes(&path).unwrap();
15580		let mut fut = routes.next().boxed();
15581		assert!((&mut fut).now_or_never().is_none());
15582
15583		// A covering root still resolves: the lookup must not require `path/**`.
15584		let _a = producer.forward("", RouteInfo::new()).unwrap();
15585		started(fut.now_or_never().expect("covered"));
15586	}
15587
15588	#[kio::test]
15589	#[cfg(feature = "async")]
15590	async fn teardown_ends_everything() {
15591		let (producer, driver) = Producer::new(Config::from(origin(1)));
15592		let consumer = producer.consume();
15593		let _announcement = producer.announce("room", RouteInfo::new()).unwrap();
15594		let mut announced = consumer.routes();
15595		announced.expect_next_active("room").await;
15596
15597		let _server = producer.forward("served", RouteInfo::new()).unwrap();
15598		let pending = consumer.request("served/path", None);
15599
15600		drop(driver);
15601
15602		// The cursor observes the end (after draining pending updates).
15603		announced.expect_next_active("served").await;
15604		assert!(announced.next().now_or_never().expect("ended").is_none());
15605
15606		// Pending requests reject; new work refuses.
15607		assert!(matches!(pending.now_or_never().expect("rejected"), Err(Error::Closed)));
15608		assert!(matches!(producer.announce("x", RouteInfo::new()), Err(Error::Closed)));
15609		assert!(matches!(
15610			producer.route("x", RouteOptions::hidden()),
15611			Err(Error::Closed)
15612		));
15613		let err = consumer
15614			.request("y", None)
15615			.now_or_never()
15616			.expect("closed")
15617			.err()
15618			.unwrap();
15619		assert!(matches!(err, Error::Closed));
15620
15621		// A cursor born after the teardown is born ended.
15622		let mut late = consumer.routes();
15623		assert!(late.next().now_or_never().expect("ended").is_none());
15624	}
15625
15626	/// A teardown with a snapshot in flight still owes what the cursor has not read.
15627	#[test]
15628	#[cfg(feature = "async")]
15629	fn teardown_owes_what_a_snapshot_held() {
15630		let (producer, driver) = Producer::new(Config::from(origin(1)));
15631		let snapshot = producer.snapshot("room");
15632		let mut announced = producer.consume().routes();
15633		let _alice = producer.announce("room/alice", RouteInfo::new()).unwrap();
15634
15635		drop(driver);
15636		assert!(!announced.is_synced(), "the queue is still owed");
15637		announced.assert_next_active("room/alice");
15638		assert!(announced.is_synced());
15639		drop(snapshot);
15640	}
15641
15642	#[test]
15643	fn internal_route_requests_are_closed_on_teardown() {
15644		let (producer, mut driver) = Producer::new(Config::from(origin(1)));
15645		let server = producer.forward("room", RouteInfo::new()).unwrap();
15646		let _pending = producer.consume().request("room/alice", None);
15647		driver.poll(Instant::now(), &kio::Waiter::noop()).unwrap();
15648		let Poll::Ready(Some(request)) = server.poll_requested(&kio::Waiter::noop()) else {
15649			panic!("front requested its route");
15650		};
15651		drop(driver);
15652		assert!(matches!(request.producer.read().resolved, Some(Err(Error::Closed))));
15653	}
15654
15655	/// An inline native executor can re-enter both tables from the rejection's wake.
15656	#[test]
15657	fn refusing_route_requests_wakes_after_unlocking() {
15658		struct Reenter {
15659			table: SendCell<kio::Shared<OriginState>>,
15660			server: kio::Shared<ServeState>,
15661			woken: AtomicBool,
15662		}
15663		impl Wake for Reenter {
15664			fn wake(self: Arc<Self>) {
15665				let _table = self.table.lock();
15666				let _server = self.server.read();
15667				self.woken.store(true, Ordering::SeqCst);
15668			}
15669		}
15670
15671		for teardown in [false, true] {
15672			let (producer, mut driver) = Producer::new(Config::from(origin(1)));
15673			let server = producer.forward("room", RouteInfo::new()).unwrap();
15674			let _pending = producer.consume().request("room/alice", None);
15675			driver.poll(Instant::ZERO, &kio::Waiter::noop()).unwrap();
15676			let channel = server
15677				.server()
15678				.read()
15679				.requests
15680				.get(&Path::from_static("room/alice"))
15681				.unwrap()
15682				.consume();
15683			// Park on both the request's channel and the server's queue.
15684			let reenter = || {
15685				Arc::new(Reenter {
15686					table: producer.shared.clone(),
15687					server: server.server().clone(),
15688					woken: AtomicBool::new(false),
15689				})
15690			};
15691			let (request, queue) = (reenter(), reenter());
15692			let waiter = kio::Waiter::new(std::task::Waker::from(request.clone()));
15693			assert!(channel.poll(&waiter, |_| Poll::<()>::Pending).is_pending());
15694			let waiter = kio::Waiter::new(std::task::Waker::from(queue.clone()));
15695			assert!(server.server().poll(&waiter, |_| Poll::Pending).is_pending());
15696			if teardown {
15697				drop(driver);
15698			} else {
15699				drop(server);
15700			}
15701			assert!(request.woken.load(Ordering::SeqCst));
15702			assert!(queue.woken.load(Ordering::SeqCst));
15703		}
15704	}
15705
15706	/// One live subscription reading a track through a remote front, plus the
15707	/// bookkeeping to kill and replace its serving route.
15708	#[cfg(feature = "async")]
15709	struct ResumeRig {
15710		producer: Producer,
15711		resolved: broadcast::Consumer,
15712		subscription: track::Subscriber,
15713		/// Keeps the incumbent's track producing; dropping it would abort the
15714		/// track out from under the front mid-test.
15715		incumbent_track: track::Producer,
15716	}
15717
15718	#[cfg(feature = "async")]
15719	impl ResumeRig {
15720		/// Announce a served route with `first` as its first hop, materialize
15721		/// "room/alice" through it with a one-group "before" track, and subscribe.
15722		#[cfg(feature = "async")]
15723		async fn new(first: &[u64]) -> (Self, Claim, broadcast::Producer) {
15724			let producer = origin(1).produce();
15725			let consumer = producer.consume();
15726
15727			let server = producer
15728				.forward(
15729					"room",
15730					RouteInfo::new().with_identity(identity(), 0).with_hops(hops(first)),
15731				)
15732				.unwrap();
15733
15734			let pending = consumer.request("room/alice", None);
15735			let request = queued(&server).await;
15736			let source = broadcast::Info::new().produce();
15737			let track = source.create_track("video", crate::track::Info::timed()).unwrap();
15738			let mut group = track.append_next().unwrap();
15739			group
15740				.write_frame(Frame::new(group.key_time(), b"before".as_ref()))
15741				.unwrap();
15742			group.finish().unwrap();
15743			request.serve(&source);
15744
15745			let resolved = pending.await.expect("resolves");
15746			let mut subscription = resolved
15747				.track("video")
15748				.unwrap()
15749				.subscribe(None)
15750				.await
15751				.expect("subscribe");
15752			let mut group = subscription
15753				.recv_group()
15754				.await
15755				.expect("recv group")
15756				.expect("track ended early");
15757			let frame = group.read_frame().await.expect("read frame").expect("frame");
15758			assert_eq!(&frame.payload[..], b"before");
15759
15760			(
15761				Self {
15762					producer,
15763					resolved,
15764					subscription,
15765					incumbent_track: track,
15766				},
15767				server,
15768				source,
15769			)
15770		}
15771
15772		/// Stand up a second served route with `first` as its first hop and hand
15773		/// back its handle, ready to answer the front's re-request.
15774		fn standby(&self, first: &[u64]) -> Claim {
15775			self.producer
15776				.forward(
15777					"room",
15778					RouteInfo::new().with_identity(identity(), 0).with_hops(hops(first)),
15779				)
15780				.unwrap()
15781		}
15782	}
15783
15784	/// Accept the front's re-request on `server` with a source carrying the same
15785	/// content stream (the delivered group plus its successor) and prove the
15786	/// rig's subscription resumes onto it: the successor group is delivered on
15787	/// the same subscription, at the group boundary.
15788	#[cfg(feature = "async")]
15789	async fn assert_resumes(rig: &mut ResumeRig, server: &Claim) {
15790		let request = queued(server).await;
15791		let replacement = broadcast::Info::new().produce();
15792		let track = replacement.create_track("video", crate::track::Info::timed()).unwrap();
15793		// The same content: group 0 was already delivered through the old route,
15794		// so the track resumes at group 1.
15795		let mut group = track.append_next().unwrap();
15796		group
15797			.write_frame(Frame::new(group.key_time(), b"before".as_ref()))
15798			.unwrap();
15799		group.finish().unwrap();
15800		request.serve(&replacement);
15801
15802		let mut group = track.append_next().unwrap();
15803		group
15804			.write_frame(Frame::new(group.key_time(), b"resumed".as_ref()))
15805			.unwrap();
15806		group.finish().unwrap();
15807
15808		let mut group = rig
15809			.subscription
15810			.recv_group()
15811			.await
15812			.expect("subscription survives the failover")
15813			.expect("track ended early");
15814		let frame = group.read_frame().await.expect("read frame").expect("frame");
15815		assert_eq!(&frame.payload[..], b"resumed");
15816	}
15817
15818	/// Only an identity's highest epoch is eligible: a costlier route at a higher epoch
15819	/// takes the front over from the cheaper older one still standing, and the reader
15820	/// continues across the epoch change without a seam, since the identity's keys
15821	/// continue. A new request joins the same broadcast.
15822	#[kio::test]
15823	#[cfg(feature = "async")]
15824	async fn a_higher_epoch_supersedes_a_cheaper_route_and_the_reader_continues() {
15825		let (mut rig, _incumbent, _source) = ResumeRig::new(&[10]).await;
15826		let newer = rig
15827			.producer
15828			.forward(
15829				"room",
15830				RouteInfo::new()
15831					.with_identity(identity(), 1)
15832					.with_hops(hops(&[11]))
15833					.with_cost(9),
15834			)
15835			.unwrap();
15836		assert_resumes(&mut rig, &newer).await;
15837		let joined = rig.producer.consume().request("room/alice", None).await.unwrap();
15838		assert!(
15839			joined.is_clone(&rig.resolved),
15840			"a newcomer joins the continued broadcast"
15841		);
15842	}
15843
15844	/// A claim of `src`'s identity at `epoch`, through relay `node`, shown `above` levels
15845	/// beneath its prefix.
15846	#[cfg(feature = "async")]
15847	fn epoch_claim(epoch: u64, node: u64, above: u8) -> RouteInfo {
15848		RouteInfo::new()
15849			.with_identity(identity(), epoch)
15850			.with_hops(hops(&[node]))
15851			.with_node(Some(node_id(node)))
15852			.with_lane(Lane {
15853				above,
15854				..Lane::default()
15855			})
15856	}
15857
15858	/// A front held through an older epoch keeps serving its readers while it waits on the
15859	/// newer one, but a fresh request never resolves through it: with the newer epoch
15860	/// winning and turned unavailable before it answers, the request waits on that epoch
15861	/// and fails with its refusal.
15862	#[kio::test]
15863	#[cfg(feature = "async")]
15864	async fn a_superseded_epoch_never_answers_a_fresh_request() {
15865		let producer = Config {
15866			update_hold: Duration::ZERO,
15867			..Config::from(origin(1))
15868		}
15869		.produce();
15870		let consumer = producer.consume();
15871		// A claim of `src` filed at `src/a`, shown a level beneath its prefix.
15872		let filed = producer.forward("src/a", epoch_claim(1, 10, 1)).unwrap();
15873		let pending = consumer.request("src/a/b", None);
15874		let source = broadcast::Info::new().produce();
15875		let track = source.create_track("video", crate::track::Info::timed()).unwrap();
15876		queued(&filed).await.serve(&source);
15877		let held = pending.await.expect("resolves through epoch 1");
15878		let mut subscription = held.track("video").unwrap().subscribe(None).await.unwrap();
15879		deliver(&track, &mut subscription, b"before").await;
15880
15881		let newer = producer.forward("src", epoch_claim(2, 11, 0)).unwrap();
15882		let switch = queued(&newer).await;
15883		newer.update(newer.route().unwrap().with_available(false)).unwrap();
15884
15885		let mut fresh = Box::pin(consumer.request("src/a/b", None));
15886		deliver(&track, &mut subscription, b"held").await;
15887		assert!(
15888			(&mut fresh).now_or_never().is_none(),
15889			"a fresh request must not resolve through the superseded epoch"
15890		);
15891
15892		// No route reaches the newer epoch, so its session refuses whatever it is asked.
15893		switch.reject(Error::Unroutable);
15894		let mut result = None;
15895		settle(|| {
15896			while let Poll::Ready(Some(request)) = newer.poll_requested(&kio::Waiter::noop()) {
15897				request.reject(Error::Unroutable);
15898			}
15899			result = (&mut fresh).now_or_never();
15900			result.is_some()
15901		})
15902		.await;
15903		assert!(matches!(result.unwrap(), Err(Error::Unroutable)));
15904	}
15905
15906	/// An older epoch's answer to a request in flight when the newer epoch won never
15907	/// resolves it: the front asks the newer epoch, whose refusal is the request's answer.
15908	#[kio::test]
15909	#[cfg(feature = "async")]
15910	async fn an_older_epochs_answer_never_resolves_a_request_the_newer_one_won() {
15911		let producer = Config {
15912			update_hold: Duration::ZERO,
15913			..Config::from(origin(1))
15914		}
15915		.produce();
15916		let consumer = producer.consume();
15917		let filed = producer.forward("src/a", epoch_claim(1, 10, 1)).unwrap();
15918		let mut fresh = Box::pin(consumer.request("src/a/b", None));
15919		let asked = queued(&filed).await;
15920
15921		// The newer epoch wins before the front hears the older one's answer.
15922		let newer = producer.forward("src", epoch_claim(2, 11, 0)).unwrap();
15923		asked.serve(broadcast::Info::new().produce());
15924		let switch = queued(&newer).await;
15925		assert!(
15926			(&mut fresh).now_or_never().is_none(),
15927			"the older epoch's answer must not resolve the request"
15928		);
15929
15930		switch.reject(Error::Unroutable);
15931		let mut result = None;
15932		settle(|| {
15933			result = (&mut fresh).now_or_never();
15934			result.is_some()
15935		})
15936		.await;
15937		assert!(matches!(result.unwrap(), Err(Error::Unroutable)));
15938	}
15939
15940	/// A front still resolving the older epoch admits no request that selects the newer one,
15941	/// since the older epoch's answer may already have passed its staleness check before the
15942	/// newer epoch won, and resolve the front on its way out.
15943	#[kio::test]
15944	#[cfg(feature = "async")]
15945	async fn a_front_resolving_an_older_epoch_admits_no_request_for_the_newer_one() {
15946		let producer = Config {
15947			update_hold: Duration::ZERO,
15948			..Config::from(origin(1))
15949		}
15950		.produce();
15951		let consumer = producer.consume();
15952		let filed = producer.forward("src/a", epoch_claim(1, 10, 1)).unwrap();
15953		let first = consumer.lookup(Path::new("src/a/b").unwrap(), None);
15954		let _asked = queued(&filed).await;
15955		let key = (consumer.absolute("src/a/b").unwrap(), Horizon::default(), None);
15956		let request = producer.shared.lock().fronts.get(&key).unwrap().request.clone();
15957
15958		// The newer epoch wins before the front selects again.
15959		let _newer = producer.forward("src", epoch_claim(2, 11, 0)).unwrap();
15960		let fresh = consumer.lookup(Path::new("src/a/b").unwrap(), None).into_inner();
15961		// The older epoch's answer lands, as the front publishes one that passed its check.
15962		if let Ok(mut pending) = request.write() {
15963			pending.resolved = Some(Ok(identity()));
15964			pending.epoch = 1;
15965		}
15966		let waiter = kio::Waiter::noop();
15967		assert!(
15968			first.into_inner().poll_ok(&waiter).is_ready(),
15969			"the older epoch's requester resolves"
15970		);
15971		assert!(
15972			fresh.poll_ok(&waiter).is_pending(),
15973			"a request selecting the newer epoch must not resolve through the older one"
15974		);
15975	}
15976
15977	/// An older epoch's answer whose route left the table before the front heard it never
15978	/// resolves the request either: the newer epoch that replaced it is asked instead.
15979	#[kio::test]
15980	#[cfg(feature = "async")]
15981	async fn an_older_epochs_answer_never_resolves_once_its_route_left() {
15982		let producer = Config {
15983			update_hold: Duration::ZERO,
15984			..Config::from(origin(1))
15985		}
15986		.produce();
15987		let consumer = producer.consume();
15988		let filed = producer.forward("src/a", epoch_claim(1, 10, 1)).unwrap();
15989		let mut fresh = Box::pin(consumer.request("src/a/b", None));
15990		let asked = queued(&filed).await;
15991
15992		// The newer epoch replaces the older one's route before the front hears its answer.
15993		let newer = producer.forward("src", epoch_claim(2, 11, 0)).unwrap();
15994		asked.serve(broadcast::Info::new().produce());
15995		drop(filed);
15996		let switch = queued(&newer).await;
15997		assert!(
15998			(&mut fresh).now_or_never().is_none(),
15999			"the older epoch's answer must not resolve the request"
16000		);
16001
16002		switch.reject(Error::Unroutable);
16003		let mut result = None;
16004		settle(|| {
16005			result = (&mut fresh).now_or_never();
16006			result.is_some()
16007		})
16008		.await;
16009		assert!(matches!(result.unwrap(), Err(Error::Unroutable)));
16010	}
16011
16012	/// Nor when the newer epoch, superseding it, leaves another identity winning: the
16013	/// request resolves on that identity, never on the older epoch's departed answer.
16014	#[kio::test]
16015	#[cfg(feature = "async")]
16016	async fn an_older_epochs_departed_answer_never_resolves_once_another_identity_wins() {
16017		let producer = Config {
16018			update_hold: Duration::ZERO,
16019			..Config::from(origin(1))
16020		}
16021		.produce();
16022		let consumer = producer.consume();
16023		let filed = producer.forward("src", epoch_claim(1, 10, 0).with_cost(1)).unwrap();
16024		let other = RouteInfo::new()
16025			.with_identity(crate::Identity::random(), 0)
16026			.with_hops(hops(&[12]))
16027			.with_node(Some(node_id(12)))
16028			.with_cost(5);
16029		let other = producer.forward("src", other).unwrap();
16030		let mut fresh = Box::pin(consumer.request("src/b", None));
16031		let asked = queued(&filed).await;
16032
16033		// The newer epoch supersedes the older one, which leaves, so the other identity wins.
16034		let newer = producer.forward("src", epoch_claim(2, 11, 0).with_cost(9)).unwrap();
16035		asked.serve(broadcast::Info::new().produce());
16036		drop(filed);
16037		let switch = queued(&other).await;
16038		assert!(
16039			(&mut fresh).now_or_never().is_none(),
16040			"the older epoch's answer must not resolve the request"
16041		);
16042
16043		switch.reject(Error::Unroutable);
16044		let mut result = None;
16045		settle(|| {
16046			result = (&mut fresh).now_or_never();
16047			result.is_some()
16048		})
16049		.await;
16050		assert!(matches!(result.unwrap(), Err(Error::Unroutable)));
16051		drop(newer);
16052	}
16053
16054	/// A pool host that is full withdraws its route: a path it won moves to another host's
16055	/// identity, so its broadcast ends and `follow` yields the other host's. A path the
16056	/// other host won stays where it is.
16057	#[kio::test]
16058	#[cfg(feature = "async")]
16059	async fn a_full_pool_host_withdraws_its_paths() {
16060		let producer = origin(1).produce();
16061		let consumer = producer.consume();
16062		let host = |name: &str, hop| {
16063			producer
16064				.forward(
16065					"pool",
16066					RouteInfo::new()
16067						.with_identity(name.parse().unwrap(), 0)
16068						.with_hops(hops(&[hop])),
16069				)
16070				.unwrap()
16071		};
16072		// Pinned in `spread_hash_matches_js`: `a` wins `pool/job-0`.
16073		let a = host("a", 10);
16074		let b = host("b", 11);
16075
16076		let mut follow = consumer.follow("pool/job-0", None).unwrap();
16077		let (first, ()) = futures::join!(follow.available(), async {
16078			queued(&a).await.serve(broadcast::Info::new().produce());
16079		});
16080		let first = first.unwrap().unwrap();
16081		assert_eq!(first.info().identity, Some("a".parse().unwrap()));
16082
16083		drop(a);
16084		let (second, ()) = futures::join!(follow.available(), async {
16085			queued(&b).await.serve(broadcast::Info::new().produce());
16086		});
16087		let second = second.unwrap().unwrap();
16088		assert_eq!(second.info().identity, Some("b".parse().unwrap()));
16089		assert!(!second.is_clone(&first));
16090	}
16091
16092	/// Letting go of the broadcast `follow` handed out retires it, which is no change to
16093	/// the path: the follower neither asks its host again nor hands the same identity out
16094	/// again. Its identity withdrawing later still hands out the next one.
16095	#[kio::test]
16096	#[cfg(feature = "async")]
16097	async fn a_follower_dropping_its_broadcast_waits_for_another_identity() {
16098		let producer = origin(1).produce();
16099		let consumer = producer.consume();
16100		let host = |name: &str, hop| {
16101			producer
16102				.forward(
16103					"pool",
16104					RouteInfo::new()
16105						.with_identity(name.parse().unwrap(), 0)
16106						.with_hops(hops(&[hop])),
16107				)
16108				.unwrap()
16109		};
16110		// Pinned in `spread_hash_matches_js`: `a` wins `pool/job-0`.
16111		let a = host("a", 10);
16112		let b = host("b", 11);
16113
16114		let mut follow = consumer.follow("pool/job-0", None).unwrap();
16115		let (first, ()) = futures::join!(follow.available(), async {
16116			queued(&a).await.serve(broadcast::Info::new().produce());
16117		});
16118		let first = first.unwrap().unwrap();
16119		let weak = first.weak();
16120		drop(first);
16121		settle(|| weak.consume().poll_closed(&kio::Waiter::noop()).is_ready()).await;
16122
16123		for _ in 0..3 {
16124			kio::clock::sleep(Duration::from_secs(20)).await;
16125			assert!(
16126				follow.poll_available(&kio::Waiter::noop()).is_pending(),
16127				"the same identity handed out again"
16128			);
16129			kio::clock::sim::yield_now().await;
16130			assert!(
16131				a.poll_requested(&kio::Waiter::noop()).is_pending(),
16132				"the host asked again"
16133			);
16134		}
16135
16136		drop(a);
16137		let (second, ()) = futures::join!(follow.available(), async {
16138			queued(&b).await.serve(broadcast::Info::new().produce());
16139		});
16140		assert_eq!(second.unwrap().unwrap().info().identity, Some("b".parse().unwrap()));
16141	}
16142
16143	/// Write one single-frame group and read it back through `subscription`.
16144	#[cfg(feature = "async")]
16145	async fn deliver(track: &track::Producer, subscription: &mut track::Subscriber, payload: &'static [u8]) {
16146		let mut group = track.append_next().unwrap();
16147		group.write_frame(Frame::new(group.key_time(), payload)).unwrap();
16148		group.finish().unwrap();
16149		let mut group = next_group(subscription).await.unwrap().expect("track ended early");
16150		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], payload);
16151	}
16152
16153	/// Another identity is another stream: a better route under one does not move the
16154	/// subscription, and when its own route goes it ends rather than resuming elsewhere.
16155	#[kio::test]
16156	#[cfg(feature = "async")]
16157	async fn another_identity_never_resumes_the_subscription() {
16158		let producer = origin(1).produce();
16159		let consumer = producer.consume();
16160		let first = producer
16161			.forward("room", RouteInfo::new().with_hops(hops(&[10])).with_cost(5))
16162			.unwrap();
16163		let pending = consumer.request("room/alice", None);
16164		let source = broadcast::Info::new().produce();
16165		let track = source.create_track("video", crate::track::Info::timed()).unwrap();
16166		queued(&first).await.serve(&source);
16167		let resolved = pending.await.expect("resolves");
16168		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
16169		deliver(&track, &mut subscription, b"first").await;
16170
16171		let second = producer
16172			.forward("room", RouteInfo::new().with_hops(hops(&[11])).with_cost(1))
16173			.unwrap();
16174		deliver(&track, &mut subscription, b"pinned").await;
16175
16176		drop(first);
16177		drop(track);
16178		drop(source);
16179		assert!(
16180			next_group(&mut subscription).await.is_err(),
16181			"the track ends with its route"
16182		);
16183		settle(|| resolved.is_closed()).await;
16184		assert!(
16185			second.poll_requested(&kio::Waiter::noop()).is_pending(),
16186			"a route of another identity is never asked to resume"
16187		);
16188	}
16189
16190	/// Another identity winning the path takes new requests, while the subscriptions on
16191	/// the old one stay with it until its route goes.
16192	#[kio::test]
16193	#[cfg(feature = "async")]
16194	async fn another_identity_leaves_the_broadcast_in_flight() {
16195		let producer = origin(1).produce();
16196		let consumer = producer.consume();
16197		let old = producer
16198			.route(
16199				"room/alice",
16200				RouteOptions::default()
16201					.with_identity(crate::Identity::random(), 0)
16202					.with_cost(9),
16203			)
16204			.unwrap();
16205		let old_track = old
16206			.broadcast()
16207			.create_track("video", crate::track::Info::timed())
16208			.unwrap();
16209		let resolved = consumer.request("room/alice", None).await.expect("resolves");
16210		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
16211		deliver(&old_track, &mut subscription, b"old").await;
16212
16213		let new = producer
16214			.route(
16215				"room/alice",
16216				RouteOptions::default()
16217					.with_identity(crate::Identity::random(), 0)
16218					.with_cost(1),
16219			)
16220			.unwrap();
16221		let new_track = new
16222			.broadcast()
16223			.create_track("video", crate::track::Info::timed())
16224			.unwrap();
16225		deliver(&old_track, &mut subscription, b"sticky").await;
16226
16227		let replaced = consumer.request("room/alice", None).await.expect("resolves");
16228		assert!(!replaced.is_clone(&resolved));
16229		let mut fresh = replaced.track("video").unwrap().subscribe(None).await.unwrap();
16230		deliver(&new_track, &mut fresh, b"new").await;
16231		deliver(&old_track, &mut subscription, b"still").await;
16232
16233		// The old publisher goes, and its subscription with it.
16234		drop(old_track);
16235		drop(old);
16236		assert!(
16237			!matches!(next_group(&mut subscription).await, Ok(Some(_))),
16238			"the old subscription outlived its route"
16239		);
16240		deliver(&new_track, &mut fresh, b"after").await;
16241	}
16242
16243	/// A request in the same tick as another identity's announcement is never handed
16244	/// the old front: its watcher has not noticed the replacement yet, but the
16245	/// request mints a front on the new identity instead of joining the replaced one.
16246	#[kio::test]
16247	#[cfg(feature = "async")]
16248	async fn a_request_racing_a_new_identity_skips_the_old_front() {
16249		let producer = origin(1).produce();
16250		let consumer = producer.consume();
16251		let first = crate::Identity::random();
16252		let old = producer
16253			.route("room/alice", RouteOptions::default().with_identity(first.clone(), 0))
16254			.unwrap();
16255		let _old_track = old
16256			.broadcast()
16257			.create_track("video", crate::track::Info::timed())
16258			.unwrap();
16259		let resolved = consumer.request("room/alice", None).await.expect("resolves");
16260		assert_eq!(
16261			resolved.info().identity.as_ref(),
16262			Some(&first),
16263			"an unpinned request names what it resolved"
16264		);
16265
16266		let identity = crate::Identity::random();
16267		let new = producer
16268			.route("room/alice", RouteOptions::default().with_identity(identity.clone(), 0))
16269			.unwrap();
16270		let new_track = new
16271			.broadcast()
16272			.create_track("video", crate::track::Info::timed())
16273			.unwrap();
16274		let named = consumer.request("room/alice", identity.clone());
16275		let bare = consumer.request("room/alice", None);
16276
16277		let named = named.await.expect("the new identity resolves");
16278		let bare = bare.await.expect("the new identity resolves");
16279		assert!(
16280			!named.is_clone(&resolved),
16281			"a request naming the new identity got the old one"
16282		);
16283		assert!(!bare.is_clone(&resolved), "a bare request joined the replaced front");
16284		assert!(named.is_clone(&bare), "both share the new front");
16285		assert_eq!(
16286			bare.info().identity.as_ref(),
16287			Some(&identity),
16288			"an unpinned request names the new identity"
16289		);
16290		let mut subscription = named.track("video").unwrap().subscribe(None).await.unwrap();
16291		deliver(&new_track, &mut subscription, b"new").await;
16292	}
16293
16294	/// Another identity winning while the front's first request is in flight beats that
16295	/// route: its late answer is not what requesters resolve to.
16296	#[kio::test]
16297	#[cfg(feature = "async")]
16298	async fn an_answer_racing_a_new_identity_resolves_the_winner() {
16299		let producer = origin(1).produce();
16300		let consumer = producer.consume();
16301		let old = producer
16302			.forward("room", RouteInfo::new().with_identity(crate::Identity::random(), 0))
16303			.unwrap();
16304		let pending = consumer.request("room/alice", None);
16305		let request = queued(&old).await;
16306
16307		// The answer and the new identity land in the same tick.
16308		let new = producer
16309			.route(
16310				"room/alice",
16311				RouteOptions::default().with_identity(crate::Identity::random(), 0),
16312			)
16313			.unwrap();
16314		let new_track = new
16315			.broadcast()
16316			.create_track("video", crate::track::Info::timed())
16317			.unwrap();
16318		let stale = broadcast::Info::new().produce();
16319		let _stale_track = stale.create_track("video", crate::track::Info::timed()).unwrap();
16320		request.serve(&stale);
16321
16322		let resolved = pending.await.expect("resolves the winner");
16323		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
16324		deliver(&new_track, &mut subscription, b"new").await;
16325	}
16326
16327	/// A request held when its route changes identity carries over: the handler is asked
16328	/// again under the new identity rather than the requester failing. The old answer is
16329	/// neither served under the new identity nor cached for the next request, and a request
16330	/// pinned to the old identity is refused. `answer_first` lands the old answer just
16331	/// before the change instead of after, before the front takes it.
16332	#[cfg(feature = "async")]
16333	async fn held_request_across_an_identity_change(answer_first: bool) {
16334		let producer = origin(1).produce();
16335		let consumer = producer.consume();
16336		let old = crate::Identity::random();
16337		let dynamic = producer
16338			.forward("room", RouteInfo::new().with_identity(old.clone(), 0))
16339			.unwrap();
16340		let pending = consumer.request("room/alice", None);
16341		let pinned = consumer.request("room/alice", old);
16342		let request = queued(&dynamic).await;
16343
16344		let stale = broadcast::Info::new().produce();
16345		let _stale_track = stale.create_track("video", crate::track::Info::timed()).unwrap();
16346		let identity = crate::Identity::random();
16347		if answer_first {
16348			request.serve(&stale);
16349			dynamic
16350				.update(dynamic.route().unwrap().with_identity(identity.clone(), 0))
16351				.unwrap();
16352		} else {
16353			dynamic
16354				.update(dynamic.route().unwrap().with_identity(identity.clone(), 0))
16355				.unwrap();
16356			request.serve(&stale);
16357		}
16358
16359		let request = queued(&dynamic).await;
16360		let fresh = broadcast::Info::new().produce();
16361		let fresh_track = fresh.create_track("video", crate::track::Info::timed()).unwrap();
16362		request.serve(&fresh);
16363		let resolved = pending.await.expect("the request carries over to the new identity");
16364		assert_eq!(resolved.info().identity.as_ref(), Some(&identity));
16365		assert!(
16366			matches!(pinned.await, Err(Error::Unroutable)),
16367			"a request pinned to the old identity resolved"
16368		);
16369		let cached = dynamic.server().lock().served.get(&Path::from_static("room/alice"));
16370		assert!(
16371			cached.is_some_and(|cached| cached.consume().is_clone(&fresh.consume())),
16372			"the old answer was cached"
16373		);
16374		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
16375		deliver(&fresh_track, &mut subscription, b"new").await;
16376	}
16377
16378	#[kio::test]
16379	#[cfg(feature = "async")]
16380	async fn a_request_held_across_an_identity_change_is_asked_again() {
16381		held_request_across_an_identity_change(false).await;
16382	}
16383
16384	#[kio::test]
16385	#[cfg(feature = "async")]
16386	async fn an_answer_before_an_identity_change_is_asked_again() {
16387		held_request_across_an_identity_change(true).await;
16388	}
16389
16390	/// A refusal that lands just before an identity change, before the front takes it,
16391	/// was the old identity's answer: the request is asked again, not ended.
16392	#[kio::test]
16393	#[cfg(feature = "async")]
16394	async fn a_refusal_before_an_identity_change_is_asked_again() {
16395		let producer = origin(1).produce();
16396		let consumer = producer.consume();
16397		let dynamic = producer
16398			.forward("room", RouteInfo::new().with_identity(crate::Identity::random(), 0))
16399			.unwrap();
16400		let pending = consumer.request("room/alice", None);
16401		queued(&dynamic).await.reject(Error::NotFound);
16402		let identity = crate::Identity::random();
16403		dynamic
16404			.update(dynamic.route().unwrap().with_identity(identity.clone(), 0))
16405			.unwrap();
16406
16407		let fresh = broadcast::Info::new().produce();
16408		let fresh_track = fresh.create_track("video", crate::track::Info::timed()).unwrap();
16409		queued(&dynamic).await.serve(&fresh);
16410		let resolved = pending.await.expect("the request carries over");
16411		assert_eq!(resolved.info().identity.as_ref(), Some(&identity));
16412		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
16413		deliver(&fresh_track, &mut subscription, b"new").await;
16414	}
16415
16416	/// A release is not undone by the identity coming back before the front looks: a
16417	/// request held across A to B to A is asked again, not refused.
16418	#[kio::test]
16419	#[cfg(feature = "async")]
16420	async fn a_request_held_across_an_identity_round_trip_is_asked_again() {
16421		let producer = origin(1).produce();
16422		let consumer = producer.consume();
16423		let old = crate::Identity::random();
16424		let dynamic = producer
16425			.forward("room", RouteInfo::new().with_identity(old.clone(), 0))
16426			.unwrap();
16427		let pending = consumer.request("room/alice", None);
16428		let request = queued(&dynamic).await;
16429
16430		dynamic
16431			.update(dynamic.route().unwrap().with_identity(crate::Identity::random(), 0))
16432			.unwrap();
16433		dynamic
16434			.update(dynamic.route().unwrap().with_identity(old.clone(), 0))
16435			.unwrap();
16436		let stale = broadcast::Info::new().produce();
16437		let _stale_track = stale.create_track("video", crate::track::Info::timed()).unwrap();
16438		request.serve(&stale);
16439
16440		let fresh = broadcast::Info::new().produce();
16441		let fresh_track = fresh.create_track("video", crate::track::Info::timed()).unwrap();
16442		queued(&dynamic).await.serve(&fresh);
16443		let resolved = pending.await.expect("the request carries over");
16444		assert_eq!(resolved.info().identity.as_ref(), Some(&old));
16445		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
16446		deliver(&fresh_track, &mut subscription, b"new").await;
16447	}
16448
16449	/// Announce cursors follow an identity's newest epoch over a cheaper older one, and
16450	/// deliver the change as an update: the same stream, continued.
16451	#[kio::test]
16452	#[cfg(feature = "async")]
16453	async fn the_newest_epoch_is_announced_in_place() {
16454		let producer = origin(1).produce();
16455		let mut announced = producer.consume().routes();
16456		let identity = crate::Identity::random();
16457		let _old = producer
16458			.route(
16459				"room/alice",
16460				RouteOptions::default().with_identity(identity.clone(), 1).with_cost(1),
16461			)
16462			.unwrap();
16463		assert_eq!(announced.expect_next_active("room/alice").await.cost, Cost::new(1));
16464
16465		let new = producer
16466			.route(
16467				"room/alice",
16468				RouteOptions::default().with_identity(identity.clone(), 2).with_cost(9),
16469			)
16470			.unwrap();
16471		let newest = announced.expect_next_active("room/alice").await;
16472		assert_eq!(
16473			(newest.identity, newest.epoch, newest.cost),
16474			(Some(identity.clone()), 2, Cost::new(9))
16475		);
16476
16477		// The older one still stands, so it comes back once the newer one goes.
16478		drop(new);
16479		let back = announced.expect_next_active("room/alice").await;
16480		assert_eq!((back.identity, back.epoch), (Some(identity), 1));
16481	}
16482
16483	/// A peer naming one publisher identity is never handed another.
16484	#[kio::test]
16485	#[cfg(feature = "async")]
16486	async fn a_request_for_another_identity_is_refused() {
16487		let producer = origin(1).produce();
16488		let consumer = producer.consume();
16489		let _broadcast = producer
16490			.route("room/alice", RouteOptions::default().with_identity(identity(), 0))
16491			.unwrap();
16492
16493		let other: crate::Identity = "01900000-0000-7000-8000-000000000002".parse().unwrap();
16494		let refused = consumer.request("room/alice", other).await;
16495		assert!(matches!(refused, Err(Error::Unroutable)));
16496		let named = consumer
16497			.request("room/alice", identity())
16498			.await
16499			.expect("the named identity resolves");
16500		assert_eq!(named.info().identity.as_ref(), Some(&identity()));
16501	}
16502
16503	/// The driver's completion contract: it resolves once every producer handle
16504	/// drops, however many read handles remain.
16505	#[kio::test]
16506	#[cfg(feature = "async")]
16507	async fn driver_resolves_with_live_consumers() {
16508		let (producer, driver) = Producer::new(Config::from(origin(1)));
16509		let consumer = producer.consume();
16510		let run = crate::time::run(driver);
16511		drop(producer);
16512		kio::clock::timeout(Duration::from_secs(5), run)
16513			.await
16514			.expect("driver must finish once the producers are gone");
16515		drop(consumer);
16516	}
16517
16518	/// A source claiming the same content cannot change immutable track metadata:
16519	/// the successor is refused instead of the subscriber's samples being read on
16520	/// a different grid, and the verdict outlives the aborted logical track.
16521	#[kio::test]
16522	#[cfg(feature = "async")]
16523	async fn incompatible_successor_is_refused() {
16524		for replacement in [
16525			track::Info::default().with_timescale(crate::Timescale::MICRO),
16526			track::Info::timed().with_priority(7),
16527			track::Info::timed().with_max_age(Duration::from_secs(7)),
16528		] {
16529			let (mut rig, incumbent, source) = ResumeRig::new(&[10]).await;
16530			let standby_server = rig.standby(&[10, 20]);
16531			drop(incumbent);
16532			drop(source);
16533
16534			// The front re-requests through the standby, but its copy of the track is
16535			// on another grid. The incumbent's copy serves until it runs out, then the
16536			// refusal stands.
16537			let request = queued(&standby_server).await;
16538			let successor = broadcast::Info::new().produce();
16539			let track = successor.create_track("video", replacement).unwrap();
16540			let mut group = track.append_next().unwrap();
16541			group
16542				.write_frame(Frame::new(group.key_time(), b"before".as_ref()))
16543				.unwrap();
16544			group.finish().unwrap();
16545			request.serve(&successor);
16546			rig.incumbent_track.clone().abort(Error::Dropped).unwrap();
16547
16548			assert!(
16549				matches!(rig.subscription.recv_group().await, Err(Error::Unsupported)),
16550				"the subscription must abort rather than resume onto incompatible metadata"
16551			);
16552
16553			// Reopening the aborted logical track must not forget the broadcast's metadata.
16554			let reopened = rig.resolved.track("video").unwrap();
16555			assert!(matches!(reopened.info().await, Err(Error::Unsupported)));
16556			assert!(matches!(reopened.subscribe(None).await, Err(Error::Unsupported)));
16557		}
16558	}
16559
16560	/// Routes with one identity serve one broadcast: when the serving route dies, the
16561	/// subscription resumes through another with that identity, whatever its first hop,
16562	/// or with none at all.
16563	#[kio::test]
16564	#[cfg(feature = "async")]
16565	async fn any_route_at_the_path_resumes_the_subscription() {
16566		let cases = [
16567			(&[10][..], &[10, 20][..]),
16568			(&[10][..], &[11][..]),
16569			(&[][..], &[][..]),
16570			(&[0][..], &[12][..]),
16571		];
16572		for (first, other) in cases {
16573			let (mut rig, incumbent, source) = ResumeRig::new(first).await;
16574			let standby = rig.standby(other);
16575
16576			drop(incumbent);
16577			drop(source);
16578			rig.incumbent_track.clone().abort(Error::Dropped).unwrap();
16579
16580			assert_resumes(&mut rig, &standby).await;
16581		}
16582	}
16583
16584	#[kio::test]
16585	#[cfg(feature = "async")]
16586	async fn a_replacement_query_carries_the_readers_resume_floor() {
16587		let (mut rig, incumbent, source) = ResumeRig::new(&[10]).await;
16588		let mut group = rig
16589			.incumbent_track
16590			.create_empty(crate::group::Info { start: 5 })
16591			.unwrap();
16592		group
16593			.write_frame(Frame::new(group.key_time(), b"five".as_ref()))
16594			.unwrap();
16595		group.finish().unwrap();
16596		assert_eq!(rig.subscription.recv_group().await.unwrap().unwrap().start, 5);
16597		let standby = rig.standby(&[10, 20]);
16598		drop(incumbent);
16599		drop(source);
16600		rig.incumbent_track.clone().abort(Error::Dropped).unwrap();
16601		let replacement = broadcast::Info::new().produce();
16602		let mut handler = replacement.requests();
16603		queued(&standby).await.serve(&replacement);
16604		let request = handler.requested_track().await.unwrap();
16605		assert_eq!(request.subscription().unwrap().start(), Some(5));
16606		let track = request.accept(crate::track::Info::timed());
16607		let preferences = rig.subscription.subscription().prioritized(7);
16608		rig.subscription.update(preferences).unwrap();
16609		settle(|| track.subscription().is_some_and(|sub| sub.policy().priority == 7)).await;
16610		assert_eq!(track.subscription().unwrap().start(), Some(5));
16611	}
16612
16613	/// A route updated in place to a new first hop still serves the same broadcast:
16614	/// the subscription carries on through it, and a new request joins the front.
16615	#[kio::test]
16616	#[cfg(feature = "async")]
16617	async fn a_first_hop_update_keeps_serving() {
16618		for first in [&[][..], &[0][..], &[10][..]] {
16619			let (mut rig, server, _source) = ResumeRig::new(first).await;
16620			let standby = rig.standby(&[10, 20]);
16621			server.update(RouteInfo::new().with_hops(hops(&[11]))).unwrap();
16622
16623			let mut group = rig.incumbent_track.append_next().unwrap();
16624			group
16625				.write_frame(Frame::new(group.key_time(), b"after".as_ref()))
16626				.unwrap();
16627			group.finish().unwrap();
16628			let mut group = next_group(&mut rig.subscription)
16629				.await
16630				.expect("the subscription survives the update")
16631				.expect("track ended early");
16632			let frame = group.read_frame().await.expect("read frame").expect("frame");
16633			assert_eq!(&frame.payload[..], b"after", "first hop {first:?}");
16634
16635			let resolved = rig.producer.consume().request("room/alice", None).await.unwrap();
16636			assert!(resolved.is_clone(&rig.resolved), "first hop {first:?} left the front");
16637			assert!(
16638				standby.poll_requested(&kio::Waiter::noop()).is_pending(),
16639				"first hop {first:?} moved off a route that still serves"
16640			);
16641		}
16642	}
16643
16644	/// A session never subscribes to itself: when the route serving a peer dies, its
16645	/// front never resumes onto a route through that peer, even one from the same
16646	/// publisher. A reader that can see the route resumes there.
16647	#[kio::test]
16648	#[cfg(feature = "async")]
16649	async fn resume_never_routes_through_the_requester() {
16650		for peer in [Some(origin(7)), None] {
16651			let producer = origin(1).produce();
16652			let consumer = match peer {
16653				Some(peer) => producer.consume().excluding(peer),
16654				None => producer.consume(),
16655			};
16656			let incumbent = producer
16657				.forward(
16658					"room",
16659					RouteInfo::new().with_identity(identity(), 0).with_hops(hops(&[10])),
16660				)
16661				.unwrap();
16662			// The same publisher, reached through the requesting peer.
16663			let echo = producer
16664				.forward(
16665					"room",
16666					RouteInfo::new().with_identity(identity(), 0).with_hops(hops(&[10, 7])),
16667				)
16668				.unwrap();
16669
16670			let pending = consumer.request("room/alice", None);
16671			let request = queued(&incumbent).await;
16672			let source = broadcast::Info::new().produce();
16673			let track = source.create_track("video", crate::track::Info::timed()).unwrap();
16674			let mut group = track.append_next().unwrap();
16675			group
16676				.write_frame(Frame::new(group.key_time(), b"before".as_ref()))
16677				.unwrap();
16678			group.finish().unwrap();
16679			request.serve(&source);
16680
16681			let resolved = pending.await.expect("resolves through the incumbent");
16682			let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
16683			let mut group = next_group(&mut subscription).await.unwrap().expect("first group");
16684			assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"before");
16685
16686			// The serving route dies, like a session.
16687			drop(incumbent);
16688			drop(source);
16689			track.abort(Error::Dropped).unwrap();
16690
16691			match peer {
16692				Some(_) => {
16693					let err = next_group(&mut subscription).await.err().expect("subscription ends");
16694					assert!(matches!(err, Error::Dropped), "unexpected end: {err}");
16695					assert!(
16696						echo.poll_requested(&kio::Waiter::noop()).is_pending(),
16697						"the front asked the requester for its own copy"
16698					);
16699				}
16700				None => {
16701					let request = queued(&echo).await;
16702					let replacement = broadcast::Info::new().produce();
16703					let track = replacement.create_track("video", crate::track::Info::timed()).unwrap();
16704					let mut group = track.append_next().unwrap();
16705					group
16706						.write_frame(Frame::new(group.key_time(), b"before".as_ref()))
16707						.unwrap();
16708					group.finish().unwrap();
16709					request.serve(&replacement);
16710					let mut group = track.append_next().unwrap();
16711					group
16712						.write_frame(Frame::new(group.key_time(), b"resumed".as_ref()))
16713						.unwrap();
16714					group.finish().unwrap();
16715
16716					let mut group = next_group(&mut subscription).await.unwrap().expect("resumed group");
16717					assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"resumed");
16718				}
16719			}
16720		}
16721	}
16722
16723	/// An anonymous publisher that dies without unannouncing is replaced by the
16724	/// next anonymous session at the same path: a subscriber on a third session
16725	/// gets the newcomer's media immediately, not a lingering dead front.
16726	///
16727	/// The front closes with its last source, so the newcomer attaches a fresh
16728	/// one and the subscriber resolves it without parking.
16729	#[kio::test]
16730	#[cfg(feature = "async")]
16731	async fn anonymous_handoff_serves_the_newcomer_immediately() {
16732		let producer = origin(1).produce();
16733
16734		// Session A: an assigned anonymous hop serving the path.
16735		let server_a = producer
16736			.forward("room", RouteInfo::new().with_hops(hops(&[10])))
16737			.unwrap();
16738
16739		// Session C: a third anonymous session, excluding the hop the server
16740		// minted for it, the same split-horizon a live session applies.
16741		let consumer = producer.consume().excluding(origin(30));
16742		let pending = consumer.request("room/alice", None);
16743		let request = queued(&server_a).await;
16744		let source_a = broadcast::Info::new().produce();
16745		let track_a = source_a.create_track("video", crate::track::Info::timed()).unwrap();
16746		let mut group = track_a.append_next().unwrap();
16747		group
16748			.write_frame(Frame::new(group.key_time(), b"from-a".as_ref()))
16749			.unwrap();
16750		group.finish().unwrap();
16751		request.serve(&source_a);
16752
16753		let resolved_a = pending.await.expect("resolves");
16754		let mut sub_a = resolved_a
16755			.track("video")
16756			.unwrap()
16757			.subscribe(None)
16758			.await
16759			.expect("subscribe");
16760		let mut group = sub_a
16761			.recv_group()
16762			.await
16763			.expect("recv group")
16764			.expect("track ended early");
16765		assert_eq!(
16766			&group.read_frame().await.expect("read frame").expect("frame").payload[..],
16767			b"from-a"
16768		);
16769
16770		// A dies without an unannounce: the source and its route drop together,
16771		// the way a lost session retracts rather than sending ANNOUNCE_END.
16772		drop(track_a);
16773		drop(source_a);
16774		drop(server_a);
16775
16776		// The front closed with A's last source.
16777		let err = sub_a.recv_group().await.err().expect("front closed");
16778		assert!(matches!(err, Error::Dropped), "unexpected end: {err}");
16779
16780		// No stale front at the leaf, and a repeat request does not join the
16781		// corpse: nothing covers the path, so it is Unroutable rather than
16782		// parked on a linger or 404 `dropped` from the dead front.
16783		settle(|| consumer.get_broadcast("room/alice").is_none()).await;
16784		settle(|| {
16785			matches!(
16786				consumer.request("room/alice", None).now_or_never(),
16787				Some(Err(Error::Unroutable))
16788			)
16789		})
16790		.await;
16791
16792		// Session B attaches at the same path. Its front is served immediately.
16793		let server_b = producer
16794			.forward("room", RouteInfo::new().with_hops(hops(&[20])))
16795			.unwrap();
16796		let pending = consumer.request("room/alice", None);
16797		let request = queued(&server_b).await;
16798		let source_b = broadcast::Info::new().produce();
16799		let track_b = source_b.create_track("video", crate::track::Info::timed()).unwrap();
16800		let mut group = track_b.append_next().unwrap();
16801		group
16802			.write_frame(Frame::new(group.key_time(), b"from-b".as_ref()))
16803			.unwrap();
16804		group.finish().unwrap();
16805		request.serve(&source_b);
16806
16807		let resolved_b = pending.await.expect("B's front is served immediately");
16808		assert!(
16809			!resolved_b.is_clone(&resolved_a),
16810			"B must not splice into A's closed front"
16811		);
16812
16813		let mut sub_b = resolved_b
16814			.track("video")
16815			.unwrap()
16816			.subscribe(None)
16817			.await
16818			.expect("subscribe");
16819		let mut group = sub_b
16820			.recv_group()
16821			.await
16822			.expect("recv group")
16823			.expect("track ended early");
16824		assert_eq!(
16825			&group.read_frame().await.expect("read frame").expect("frame").payload[..],
16826			b"from-b"
16827		);
16828	}
16829
16830	#[kio::test]
16831	#[cfg(feature = "async")]
16832	async fn reprice_is_invisible_to_the_subscription() {
16833		let (rig, incumbent, source) = ResumeRig::new(&[10]).await;
16834
16835		// A metadata-only reprice of the only route: nothing re-requests and the
16836		// subscription keeps flowing from the same source.
16837		incumbent
16838			.update(RouteInfo::new().with_hops(hops(&[10])).with_cost(9))
16839			.unwrap();
16840
16841		let track = source.create_track("audio", crate::track::Info::timed()).unwrap();
16842		let mut group = track.append_next().unwrap();
16843		group
16844			.write_frame(Frame::new(group.key_time(), b"steady".as_ref()))
16845			.unwrap();
16846		group.finish().unwrap();
16847
16848		let mut audio = rig
16849			.resolved
16850			.track("audio")
16851			.unwrap()
16852			.subscribe(None)
16853			.await
16854			.expect("subscribe survives the reprice");
16855		let mut group = audio
16856			.recv_group()
16857			.await
16858			.expect("recv group")
16859			.expect("track ended early");
16860		let frame = group.read_frame().await.expect("read frame").expect("frame");
16861		assert_eq!(&frame.payload[..], b"steady");
16862	}
16863
16864	#[kio::test]
16865	#[cfg(feature = "async")]
16866	async fn a_drain_migrates_before_the_session_dies() {
16867		let (mut rig, incumbent, source) = ResumeRig::new(&[10]).await;
16868		let standby_server = rig.standby(&[10, 20]);
16869
16870		// The serving route drains: ranked last, at its real cost, while its session
16871		// keeps serving. The front migrates to the standby without waiting for
16872		// the death.
16873		incumbent
16874			.update(
16875				RouteInfo::new()
16876					.with_identity(identity(), 0)
16877					.with_hops(hops(&[10]))
16878					.with_draining(true),
16879			)
16880			.unwrap();
16881
16882		assert_resumes(&mut rig, &standby_server).await;
16883
16884		// The drained source outlived the migration.
16885		drop(incumbent);
16886		drop(source);
16887	}
16888
16889	/// A second broadcast at the path under another identity is another identity: new
16890	/// requests resolve it on a fresh front, rather than join the first one's.
16891	#[kio::test]
16892	#[cfg(feature = "async")]
16893	async fn a_newer_local_source_gets_a_fresh_front() {
16894		let producer = origin(1).produce();
16895		let consumer = producer.consume();
16896
16897		let first = producer.route("room/alice", RouteOptions::default()).unwrap();
16898		let resolved = consumer.request("room/alice", None).await.expect("resolves");
16899
16900		let second = producer.route("room/alice", RouteOptions::default()).unwrap();
16901		let again = consumer.request("room/alice", None).await.expect("resolves");
16902		assert!(!again.is_clone(&resolved));
16903
16904		// Losing one source leaves the path served; losing both frees it.
16905		second.broadcast().close();
16906		settle(|| consumer.get_broadcast("room/alice").is_some()).await;
16907		first.broadcast().close();
16908		settle(|| consumer.get_broadcast("room/alice").is_none()).await;
16909
16910		// The path is free again for a fresh broadcast.
16911		let _third = producer.route("room/alice", RouteOptions::default()).unwrap();
16912		assert!(consumer.get_broadcast("room/alice").is_some());
16913	}
16914
16915	/// A front still resolving an identity that another has since beaten takes no new
16916	/// requester: it may already hold the beaten identity's source, and would hand it to a
16917	/// request that saw it lose, which no later announcement corrects.
16918	#[kio::test]
16919	#[cfg(feature = "async")]
16920	async fn a_request_skips_a_front_resolving_a_beaten_identity() {
16921		let producer = origin(1).produce();
16922		let consumer = producer.consume();
16923		let server = producer
16924			.forward("room", RouteInfo::new().with_hops(hops(&[10])))
16925			.unwrap();
16926
16927		// The front selected the covering route and waits on its answer.
16928		let pending = consumer.request("room/alice", None);
16929		let _request = queued(&server).await;
16930
16931		// The exact path beats the covering route before the front resolves.
16932		let _winner = producer.route("room/alice", RouteOptions::default()).unwrap();
16933		let again = consumer.request("room/alice", None).await.expect("resolves");
16934		let first = pending.await.expect("the first front moves to the winner");
16935		assert!(!again.is_clone(&first), "joined a front resolving the beaten route");
16936	}
16937
16938	/// A front that moved to the new winner before resolving takes requesters for it, so
16939	/// they share it rather than each minting a front on the winner.
16940	#[kio::test]
16941	#[cfg(feature = "async")]
16942	async fn a_request_joins_a_front_resolving_the_winner() {
16943		let producer = origin(1).produce();
16944		let consumer = producer.consume();
16945		let covering = producer
16946			.forward("room", RouteInfo::new().with_hops(hops(&[10])))
16947			.unwrap();
16948		let pending = consumer.request("room/alice", None);
16949		let _beaten = queued(&covering).await;
16950
16951		// The exact path wins, and the front asks it in turn.
16952		let exact = producer
16953			.forward("room/alice", RouteInfo::new().with_hops(hops(&[10])))
16954			.unwrap();
16955		let request = queued(&exact).await;
16956		let again = consumer.request("room/alice", None);
16957
16958		let upstream = broadcast::Info::new().produce();
16959		request.serve(&upstream);
16960		let first = pending.await.expect("resolves");
16961		let again = again.await.expect("resolves");
16962		assert!(
16963			again.is_clone(&first),
16964			"a request skipped the front resolving its winner"
16965		);
16966	}
16967
16968	/// The publisher finishes a track, then its broadcast. A subscription already in
16969	/// flight must conclude normally: the track's last group, then the end. moq-lite,
16970	/// ANNOUNCE_END: "Retraction does not disturb subscriptions already in flight,
16971	/// which conclude normally with SUBSCRIBE_END."
16972	///
16973	/// The runtime is single-threaded and the publisher's whole ending has no await in
16974	/// it, so the outcome does not depend on timing.
16975	#[kio::test]
16976	#[cfg(feature = "async")]
16977	async fn a_finished_broadcast_concludes_in_flight_subscriptions() {
16978		let producer = origin(1).produce();
16979		let consumer = producer.consume();
16980
16981		let broadcast = producer.route("room/alice", RouteOptions::default()).unwrap();
16982		let track = broadcast
16983			.broadcast()
16984			.create_track("video", crate::track::Info::timed())
16985			.unwrap();
16986
16987		let resolved = consumer.request("room/alice", None).await.expect("resolves");
16988		let mut subscription = resolved
16989			.track("video")
16990			.unwrap()
16991			.subscribe(None)
16992			.await
16993			.expect("subscribe");
16994		// A textbook clean end, innermost first: the group, the track, the broadcast.
16995		let mut group = track.append_next().unwrap();
16996		group
16997			.write_frame(Frame::new(group.key_time(), b"tail".as_ref()))
16998			.unwrap();
16999		group.finish().unwrap();
17000		let track = track.finish().unwrap();
17001		drop(track);
17002		broadcast.broadcast().close();
17003
17004		let mut group = next_group(&mut subscription)
17005			.await
17006			.expect("a cleanly finished track was served as an error")
17007			.expect("the track ended before its last group");
17008		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"tail");
17009		drop(group);
17010
17011		let end = next_group(&mut subscription)
17012			.await
17013			.expect("a cleanly finished track ended as an error");
17014		assert!(end.is_none(), "a group followed the final one");
17015	}
17016
17017	/// A route served from upstream is retracted (what the lite subscriber does on
17018	/// ANNOUNCE_END: finish the source it minted, drop the route) while the track's
17019	/// last group and end are still on their way. The subscription already in flight
17020	/// must still conclude normally. moq-lite, ANNOUNCE_END: "Retraction does not
17021	/// disturb subscriptions already in flight, which conclude normally with
17022	/// SUBSCRIBE_END."
17023	#[kio::test]
17024	#[cfg(feature = "async")]
17025	async fn a_retracted_route_concludes_in_flight_subscriptions() {
17026		let producer = origin(1).produce();
17027		let consumer = producer.consume();
17028		let server = producer
17029			.forward("room", RouteInfo::new().with_hops(hops(&[10])))
17030			.unwrap();
17031
17032		let pending = consumer.request("room/alice", None);
17033		let request = queued(&server).await;
17034		let source = broadcast::Info::new().produce();
17035		let track = source.create_track("video", crate::track::Info::timed()).unwrap();
17036		request.serve(&source);
17037
17038		let resolved = pending.await.expect("resolves");
17039		let mut subscription = resolved
17040			.track("video")
17041			.unwrap()
17042			.subscribe(None)
17043			.await
17044			.expect("subscribe");
17045
17046		// ANNOUNCE_END overtakes the track's end: the route is retracted, and the front
17047		// has acted on it, before the track's last group and end arrive.
17048		source.close();
17049		drop(server);
17050		settle(|| resolved.is_closed()).await;
17051		let mut group = track.append_next().unwrap();
17052		group
17053			.write_frame(Frame::new(group.key_time(), b"tail".as_ref()))
17054			.unwrap();
17055		group.finish().unwrap();
17056		let track = track.finish().unwrap();
17057		drop(track);
17058
17059		let mut group = next_group(&mut subscription)
17060			.await
17061			.expect("a retracted route's track was served as an error")
17062			.expect("the track ended before its last group");
17063		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"tail");
17064		drop(group);
17065
17066		let end = next_group(&mut subscription)
17067			.await
17068			.expect("a cleanly finished track ended as an error");
17069		assert!(end.is_none(), "a group followed the final one");
17070	}
17071
17072	/// A standing route outlives the source it produced: the front ends instead of
17073	/// asking that route for the broadcast that just closed.
17074	#[kio::test]
17075	#[cfg(feature = "async")]
17076	async fn a_closed_source_is_not_requested_again_from_its_standing_route() {
17077		let producer = origin(1).produce();
17078		let server = producer
17079			.forward("room", RouteInfo::new().with_hops(hops(&[10])))
17080			.unwrap();
17081		let pending = producer.consume().request("room/alice", None);
17082		let source = broadcast::Info::new().produce();
17083		queued(&server).await.serve(&source);
17084		let resolved = pending.await.unwrap();
17085
17086		source.close();
17087		settle(|| resolved.is_closed()).await;
17088		assert!(
17089			server.poll_requested(&kio::Waiter::noop()).is_pending(),
17090			"the closed source was requested again"
17091		);
17092	}
17093
17094	/// An origin front drops the source track as soon as its last reader leaves,
17095	/// so the publisher's demand goes unwanted far below `track::IDLE_LINGER`.
17096	/// Cached groups stay on the front for the linger; a returning reader
17097	/// replays them and asks the source again for groups past that edge.
17098	#[kio::test]
17099	#[cfg(feature = "async")]
17100	async fn origin_front_drops_the_source_when_unused() {
17101		let producer = origin(1).produce();
17102		let consumer = producer.consume();
17103
17104		let broadcast = producer.route("room/alice", RouteOptions::default()).unwrap();
17105		let track = broadcast
17106			.broadcast()
17107			.create_track("video", crate::track::Info::timed())
17108			.unwrap();
17109		let mut group = track.append_next().unwrap();
17110		group
17111			.write_frame(Frame::new(group.key_time(), b"cached".as_ref()))
17112			.unwrap();
17113		group.finish().unwrap();
17114
17115		let resolved = consumer.request("room/alice", None).await.expect("resolves");
17116		let mut subscription = resolved
17117			.track("video")
17118			.unwrap()
17119			.subscribe(None)
17120			.await
17121			.expect("subscribe");
17122		let mut group = subscription.recv_group().await.unwrap().unwrap();
17123		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"cached");
17124		drop(group);
17125		drop(subscription);
17126
17127		kio::clock::timeout(Duration::from_secs(1), track.demand().until(|wanted| !wanted))
17128			.await
17129			.expect("source unused should resolve far below track::IDLE_LINGER")
17130			.expect("source closed");
17131
17132		// Cached groups stay on the front for the linger; a returning reader
17133		// replays them without waiting out the window.
17134		let mut again = resolved
17135			.track("video")
17136			.unwrap()
17137			.subscribe(track::Subscription::default().with_max(Duration::from_secs(3600)))
17138			.await
17139			.expect("resubscribe");
17140		let mut group = kio::clock::timeout(Duration::from_secs(1), again.recv_group())
17141			.await
17142			.expect("cached group is still on the front")
17143			.expect("recv group")
17144			.expect("track ended early");
17145		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"cached");
17146
17147		kio::clock::timeout(Duration::from_secs(1), track.demand().until(|wanted| wanted))
17148			.await
17149			.expect("returning reader re-splices the source")
17150			.expect("source closed");
17151
17152		let mut group = track.append_next().unwrap();
17153		group
17154			.write_frame(Frame::new(group.key_time(), b"live".as_ref()))
17155			.unwrap();
17156		group.finish().unwrap();
17157		let mut group = kio::clock::timeout(Duration::from_secs(1), again.recv_group())
17158			.await
17159			.expect("groups past the cached edge come from the re-splice")
17160			.expect("recv group")
17161			.expect("track ended early");
17162		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"live");
17163	}
17164
17165	/// A reader still holding an open group after its track goes unread gets the rest
17166	/// of the group: parking the track reads no new group, but the upstream stays
17167	/// subscribed until the held one ends.
17168	#[kio::test]
17169	#[cfg(feature = "async")]
17170	async fn a_held_group_continues_after_its_track_goes_unread() {
17171		let producer = origin(1).produce();
17172		let server = producer
17173			.forward("live", RouteInfo::new().with_hops(hops(&[10])))
17174			.unwrap();
17175		let pending = producer.consume().request("live", None);
17176		let source = broadcast::Info::new().produce();
17177		let track = source.create_track("video", crate::track::Info::timed()).unwrap();
17178		queued(&server).await.serve(&source);
17179		let resolved = pending.await.unwrap();
17180
17181		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
17182		let mut writing = track.append_next().unwrap();
17183		writing
17184			.write_frame(Frame::new(writing.key_time(), b"head".as_ref()))
17185			.unwrap();
17186		let mut reading = subscription.recv_group().await.unwrap().unwrap();
17187		assert_eq!(&reading.read_frame().await.unwrap().unwrap().payload[..], b"head");
17188
17189		drop(subscription);
17190		kio::clock::sleep(Duration::from_millis(10)).await;
17191		writing
17192			.write_frame(Frame::new(writing.key_time(), b"tail".as_ref()))
17193			.unwrap();
17194		writing.finish().unwrap();
17195
17196		let tail = kio::clock::timeout(Duration::from_secs(1), reading.read_frame())
17197			.await
17198			.expect("the held group lost its source")
17199			.unwrap()
17200			.expect("the group ended early");
17201		assert_eq!(&tail.payload[..], b"tail");
17202		let end = kio::clock::timeout(Duration::from_secs(1), reading.read_frame()).await;
17203		assert!(matches!(end, Ok(Ok(None))), "the group should finish: {end:?}");
17204		kio::clock::timeout(Duration::from_secs(1), track.demand().until(|wanted| !wanted))
17205			.await
17206			.expect("the front lets the source go once the held group ends")
17207			.expect("source closed");
17208	}
17209
17210	/// A source that aborts one group while its track carries on ends that group for
17211	/// the reader too, rather than leaving it waiting for a route change that never
17212	/// comes.
17213	#[kio::test]
17214	#[cfg(feature = "async")]
17215	async fn a_group_the_source_aborts_ends_while_the_track_lives() {
17216		let producer = origin(1).produce();
17217		let broadcast = producer.route("live", RouteOptions::default()).unwrap();
17218		let track = broadcast
17219			.broadcast()
17220			.create_track("video", crate::track::Info::timed())
17221			.unwrap();
17222		let resolved = producer.consume().request("live", None).await.unwrap();
17223		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
17224
17225		let mut aborted = track.append_next().unwrap();
17226		aborted
17227			.write_frame(Frame::new(aborted.key_time(), b"head".as_ref()))
17228			.unwrap();
17229		let mut reading = subscription.recv_group().await.unwrap().unwrap();
17230		assert_eq!(&reading.read_frame().await.unwrap().unwrap().payload[..], b"head");
17231		aborted.abort(Error::Cancel).unwrap();
17232
17233		let end = kio::clock::timeout(Duration::from_secs(1), reading.read_frame()).await;
17234		assert!(matches!(end, Ok(Err(_))), "the group should fail: {end:?}");
17235
17236		// The track carries on.
17237		let mut next = track.append_next().unwrap();
17238		next.write_frame(Frame::new(next.key_time(), b"next".as_ref())).unwrap();
17239		next.finish().unwrap();
17240		let mut group = kio::clock::timeout(Duration::from_secs(1), subscription.recv_group())
17241			.await
17242			.expect("the next group")
17243			.unwrap()
17244			.unwrap();
17245		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"next");
17246	}
17247
17248	/// A front serving from another front still drops upstream on the unused edge,
17249	/// so the publisher's demand goes unwanted far below `track::IDLE_LINGER` through
17250	/// the whole chain, and a returning reader reaches the publisher's cache afresh.
17251	#[kio::test]
17252	#[cfg(feature = "async")]
17253	async fn chained_front_drops_the_source_when_unused() {
17254		let leaf = origin(1).produce();
17255		let leaf_consumer = leaf.consume();
17256
17257		let broadcast = leaf.route("room/alice", RouteOptions::default()).unwrap();
17258		let track = broadcast
17259			.broadcast()
17260			.create_track("video", crate::track::Info::timed())
17261			.unwrap();
17262		let mut group = track.append_next().unwrap();
17263		group
17264			.write_frame(Frame::new(group.key_time(), b"cached".as_ref()))
17265			.unwrap();
17266		group.finish().unwrap();
17267
17268		// The leaf's front view, which the next front serves from.
17269		let leaf_front = leaf_consumer.request("room/alice", None).await.expect("resolves");
17270
17271		let mid = origin(2).produce();
17272		let mid_server = mid.forward("room", RouteInfo::new().with_hops(hops(&[10]))).unwrap();
17273		let mid_pending = mid.consume().request("room/alice", None);
17274		queued(&mid_server).await.serve(&leaf_front);
17275		let mid_resolved = mid_pending.await.expect("mid resolves");
17276
17277		let edge = origin(3).produce();
17278		let edge_server = edge.forward("room", RouteInfo::new().with_hops(hops(&[20]))).unwrap();
17279		let edge_pending = edge.consume().request("room/alice", None);
17280		queued(&edge_server).await.serve(&mid_resolved);
17281		let edge_resolved = edge_pending.await.expect("edge resolves");
17282
17283		let mut subscription = edge_resolved
17284			.track("video")
17285			.unwrap()
17286			.subscribe(None)
17287			.await
17288			.expect("subscribe");
17289		let mut group = subscription.recv_group().await.unwrap().unwrap();
17290		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"cached");
17291		drop(group);
17292		drop(subscription);
17293
17294		kio::clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| !wanted))
17295			.await
17296			.expect("chained unused should resolve far below track::IDLE_LINGER")
17297			.expect("source closed");
17298
17299		// A budget spanning the cache, so the returning reader replays it.
17300		let mut subscription = edge_resolved
17301			.track("video")
17302			.unwrap()
17303			.subscribe(track::Subscription::default().with_max(Duration::from_secs(3600)))
17304			.await
17305			.expect("resubscribe");
17306		kio::clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| wanted))
17307			.await
17308			.expect("resubscribe should reach the leaf")
17309			.expect("source open");
17310		let mut group = track.append_next().unwrap();
17311		group
17312			.write_frame(Frame::new(group.key_time(), b"live".as_ref()))
17313			.unwrap();
17314		group.finish().unwrap();
17315		// Both held at once, the newest goes first.
17316		let mut group = subscription.recv_group().await.unwrap().unwrap();
17317		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"live");
17318		drop(group);
17319		let mut group = subscription.recv_group().await.unwrap().unwrap();
17320		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"cached");
17321		drop(group);
17322		drop(subscription);
17323
17324		kio::clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| !wanted))
17325			.await
17326			.expect("second chained unused should resolve far below track::IDLE_LINGER")
17327			.expect("source closed");
17328
17329		// A group the leaf produced while every front was parked: the fetch re-splices
17330		// each hop to reach the leaf.
17331		let mut group = track.append_next().unwrap();
17332		group
17333			.write_frame(Frame::new(group.key_time(), b"fetched".as_ref()))
17334			.unwrap();
17335		group.finish().unwrap();
17336		let fetch = edge_resolved.track("video").unwrap().fetch_group(2, None);
17337		let mut fetch = std::pin::pin!(fetch);
17338		assert!(futures::poll!(fetch.as_mut()).is_pending(), "fetch should re-splice");
17339		kio::clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| wanted))
17340			.await
17341			.expect("fetch should reach the leaf")
17342			.expect("source open");
17343		let mut group = kio::clock::timeout(Duration::from_secs(5), fetch)
17344			.await
17345			.expect("re-spliced source should answer the fetch")
17346			.expect("fetch succeeds");
17347		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"fetched");
17348	}
17349
17350	/// A newer local source wins dispatch the moment it attaches, but one whose copy
17351	/// of the track carries different metadata is refused: the incumbent keeps
17352	/// serving, and the refusal is never retried once the incumbent leaves.
17353	#[kio::test]
17354	#[cfg(feature = "async")]
17355	async fn incompatible_local_source_keeps_the_incumbent() {
17356		let producer = origin(1).produce();
17357		let consumer = producer.consume();
17358
17359		let first = producer
17360			.route("room/alice", RouteOptions::default().with_identity(identity(), 0))
17361			.unwrap();
17362		let track = first
17363			.broadcast()
17364			.create_track("video", crate::track::Info::timed())
17365			.unwrap();
17366		let resolved = consumer.request("room/alice", None).await.expect("resolves");
17367		let mut subscription = resolved
17368			.track("video")
17369			.unwrap()
17370			.subscribe(None)
17371			.await
17372			.expect("subscribe");
17373		let mut group = track.append_next().unwrap();
17374		group
17375			.write_frame(Frame::new(group.key_time(), b"before".as_ref()))
17376			.unwrap();
17377		group.finish().unwrap();
17378		let mut group = subscription.recv_group().await.unwrap().unwrap();
17379		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"before");
17380
17381		// The newest source is dispatched the track, and refused for its metadata.
17382		let second = producer
17383			.route("room/alice", RouteOptions::default().with_identity(identity(), 0))
17384			.unwrap();
17385		let _incompatible = second
17386			.broadcast()
17387			.create_track("video", track::Info::default().with_timescale(crate::Timescale::MICRO))
17388			.unwrap();
17389		for _ in 0..10 {
17390			kio::clock::sim::yield_now().await;
17391		}
17392
17393		// Still spliced to the incumbent, still delivering.
17394		let mut group = track.append_next().unwrap();
17395		group
17396			.write_frame(Frame::new(group.key_time(), b"still".as_ref()))
17397			.unwrap();
17398		group.finish().unwrap();
17399		let mut group = subscription.recv_group().await.unwrap().unwrap();
17400		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"still");
17401
17402		// The incumbent leaving exhausts the table: the refusal is never retried.
17403		drop(track);
17404		first.broadcast().close();
17405		assert!(matches!(subscription.recv_group().await, Err(Error::Unsupported)));
17406	}
17407
17408	/// A remote front serving "room/alice" with one read track, "video", whose first
17409	/// group was delivered. Returns the producer, the incumbent's track, and the reader.
17410	#[cfg(feature = "async")]
17411	async fn remote_front() -> (Producer, Claim, broadcast::Producer, track::Producer, track::Subscriber) {
17412		let producer = origin(1).produce();
17413		let server = producer
17414			.forward(
17415				"room",
17416				RouteInfo::new().with_identity(identity(), 0).with_hops(hops(&[10])),
17417			)
17418			.unwrap();
17419		let pending = producer.consume().request("room/alice", None);
17420		let upstream = broadcast::Info::new().produce();
17421		let old = upstream.create_track("video", crate::track::Info::timed()).unwrap();
17422		queued(&server).await.serve(&upstream);
17423		let resolved = pending.await.expect("resolves");
17424		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
17425		let mut group = old.append_next().unwrap();
17426		group
17427			.write_frame(Frame::new(group.key_time(), b"before".as_ref()))
17428			.unwrap();
17429		group.finish().unwrap();
17430		let mut group = next_group(&mut subscription).await.unwrap().expect("first group");
17431		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"before");
17432		(producer, server, upstream, old, subscription)
17433	}
17434
17435	/// A local newcomer takes over while its answer for "video" is pending, so the track
17436	/// drains the incumbent. The reader leaves: the incumbent's copy is dropped at once,
17437	/// like any unread track's, not held until the linger.
17438	#[kio::test]
17439	#[cfg(feature = "async")]
17440	async fn an_unread_draining_track_releases_the_old_source() {
17441		let (producer, _server, _upstream, old, subscription) = remote_front().await;
17442
17443		let newcomer = producer
17444			.route("room/alice", RouteOptions::hidden().with_identity(identity(), 0))
17445			.unwrap();
17446		let mut handler = newcomer.broadcast().requests();
17447		newcomer.announce().unwrap();
17448		let _unanswered = kio::clock::timeout(Duration::from_secs(1), handler.requested_track())
17449			.await
17450			.expect("the front asked the newcomer")
17451			.expect("request");
17452
17453		drop(subscription);
17454		kio::clock::timeout(Duration::from_secs(1), old.demand().until(|wanted| !wanted))
17455			.await
17456			.expect("the draining source stays subscribed with nobody reading")
17457			.expect("open");
17458	}
17459
17460	/// A fetch holds a finished track whose group its route lost, and the replacement neither
17461	/// has the track nor takes requests: refused at the lookup itself, that concludes the
17462	/// track as a refused query would, so the fetch fails rather than wait out its budget.
17463	#[kio::test]
17464	#[cfg(feature = "async")]
17465	async fn a_finished_tracks_fetch_fails_when_the_replacement_lacks_the_track() {
17466		let producer = origin(1).produce();
17467		let server = producer
17468			.forward(
17469				"room",
17470				RouteInfo::new().with_identity(identity(), 0).with_hops(hops(&[10])),
17471			)
17472			.unwrap();
17473		let pending = producer.consume().request("room/alice", None);
17474		let upstream = broadcast::Info::new().produce();
17475		let old = upstream.create_track("video", crate::track::Info::timed()).unwrap();
17476		let fills = old.requests();
17477		queued(&server).await.serve(&upstream);
17478		let resolved = pending.await.expect("resolves");
17479		let video = resolved.track("video").unwrap();
17480		let mut open = old.append_next().unwrap();
17481		open.write_frame(Frame::new(open.key_time(), b"a".as_ref())).unwrap();
17482		let finished = old.finish().unwrap();
17483		let mut fetched = video.fetch_group(0, None).await.unwrap();
17484		assert_eq!(&fetched.read_frame().await.unwrap().unwrap().payload[..], b"a");
17485
17486		// The route loses the rest of the group and refuses to fill it.
17487		open.abort(Error::Cancel).unwrap();
17488		assert!(fetched.read_frame().now_or_never().is_none());
17489		let request = kio::clock::timeout(Duration::from_secs(1), fills.requested_fill_group())
17490			.await
17491			.expect("the fetch asked the route to fill the group")
17492			.expect("request");
17493		request.reject(Error::Cancel);
17494		drop((fills, finished));
17495		for _ in 0..10 {
17496			kio::clock::sim::yield_now().await;
17497		}
17498		assert!(
17499			fetched.read_frame().now_or_never().is_none(),
17500			"the fetch waits for another route"
17501		);
17502
17503		let newcomer = producer
17504			.route("room/alice", RouteOptions::hidden().with_identity(identity(), 0))
17505			.unwrap();
17506		let _other = newcomer
17507			.broadcast()
17508			.create_track("audio", crate::track::Info::timed())
17509			.unwrap();
17510		newcomer.announce().unwrap();
17511		let res = kio::clock::timeout(Duration::from_secs(1), fetched.read_frame())
17512			.await
17513			.expect("the fetch fails once the replacement refused the track");
17514		assert!(res.is_err(), "{res:?}");
17515	}
17516
17517	/// A finished track that something still reads outlives its linger, so a replacement
17518	/// route is still asked for it, for a read that has to move off a dying route. Once
17519	/// nothing holds it, it lingers and is forgotten as before.
17520	#[kio::test]
17521	#[cfg(feature = "async")]
17522	async fn a_held_finished_track_outlives_its_linger() {
17523		let (producer, _server, _upstream, old, mut subscription) = remote_front().await;
17524		drop(old.finish().unwrap());
17525		assert!(matches!(next_group(&mut subscription).await, Ok(None)));
17526
17527		// Held past the linger: a replacement is asked for the track.
17528		kio::clock::sleep(Duration::from_secs(60)).await;
17529		let newcomer = producer
17530			.route("room/alice", RouteOptions::hidden().with_identity(identity(), 0))
17531			.unwrap();
17532		let mut handler = newcomer.broadcast().requests();
17533		newcomer.announce().unwrap();
17534		let request = kio::clock::timeout(Duration::from_secs(1), handler.requested_track())
17535			.await
17536			.expect("the front rerouted the held track")
17537			.expect("request");
17538		assert_eq!(request.name(), "video");
17539		drop(request);
17540
17541		// Unheld, it is forgotten after the linger: a later route is asked nothing.
17542		drop(subscription);
17543		kio::clock::sleep(Duration::from_secs(60)).await;
17544		drop(newcomer);
17545		let third = producer
17546			.route("room/alice", RouteOptions::hidden().with_identity(identity(), 0))
17547			.unwrap();
17548		let mut handler = third.broadcast().requests();
17549		third.announce().unwrap();
17550		assert!(
17551			kio::clock::timeout(Duration::from_secs(1), handler.requested_track())
17552				.await
17553				.is_err(),
17554			"an unheld finished track was rerouted after its linger"
17555		);
17556	}
17557
17558	/// The newcomer answers "video" with matching metadata but aborts before delivering a
17559	/// group, all before the front polls the answer: that is a refusal, so the incumbent
17560	/// keeps serving rather than the track ending on the newcomer's error.
17561	#[kio::test]
17562	#[cfg(feature = "async")]
17563	async fn a_replacement_aborted_without_history_keeps_the_incumbent() {
17564		let (producer, _server, _upstream, old, mut subscription) = remote_front().await;
17565
17566		let newcomer = producer
17567			.route("room/alice", RouteOptions::hidden().with_identity(identity(), 0))
17568			.unwrap();
17569		let mut handler = newcomer.broadcast().requests();
17570		newcomer.announce().unwrap();
17571		let request = kio::clock::timeout(Duration::from_secs(1), handler.requested_track())
17572			.await
17573			.expect("the front asked the newcomer")
17574			.expect("request");
17575		request
17576			.accept(crate::track::Info::timed())
17577			.abort(Error::App(7))
17578			.unwrap();
17579		for _ in 0..10 {
17580			kio::clock::sim::yield_now().await;
17581		}
17582
17583		let mut group = old.append_next().unwrap();
17584		group
17585			.write_frame(Frame::new(group.key_time(), b"still".as_ref()))
17586			.unwrap();
17587		group.finish().unwrap();
17588		let mut group = next_group(&mut subscription)
17589			.await
17590			.expect("the incumbent keeps serving")
17591			.expect("track open");
17592		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"still");
17593
17594		// The incumbent's clean end is the track's, not the newcomer's error.
17595		let _old = old.finish().unwrap();
17596		assert!(matches!(next_group(&mut subscription).await, Ok(None)));
17597	}
17598
17599	/// The serving route is withdrawn while its copy of the track is still open, and the
17600	/// next route for the same publisher no longer has the broadcast: its refusal must not
17601	/// end the track, which takes the incumbent's remaining groups and clean end.
17602	#[kio::test]
17603	#[cfg(feature = "async")]
17604	async fn a_refused_replacement_keeps_a_withdrawn_incumbent_open() {
17605		// The incumbent arrives from relay 2, a stale standby from relay 3, both for
17606		// publisher 9, so withdrawing relay 2 leaves the standby standing.
17607		let producer = origin(1).produce();
17608		let server = producer
17609			.forward(
17610				"room",
17611				RouteInfo::new().with_identity(identity(), 0).with_hops(hops(&[9, 2])),
17612			)
17613			.unwrap();
17614		let standby = producer
17615			.forward(
17616				"room",
17617				RouteInfo::new()
17618					.with_identity(identity(), 0)
17619					.with_hops(hops(&[9, 5, 3])),
17620			)
17621			.unwrap();
17622		let pending = producer.consume().request("room/alice", None);
17623		let upstream = broadcast::Info::new().produce();
17624		let old = upstream.create_track("video", crate::track::Info::timed()).unwrap();
17625		queued(&server).await.serve(&upstream);
17626		let resolved = pending.await.expect("resolves");
17627		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
17628		let mut group = old.append_next().unwrap();
17629		group
17630			.write_frame(Frame::new(group.key_time(), b"before".as_ref()))
17631			.unwrap();
17632		group.finish().unwrap();
17633		let mut group = next_group(&mut subscription).await.unwrap().expect("first group");
17634		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"before");
17635
17636		// The peer withdraws the broadcast: the route retracts and its source closes,
17637		// while the subscription already in flight stays open.
17638		server.withdrawn();
17639		upstream.close();
17640
17641		let successor = broadcast::Info::new().produce();
17642		let mut handler = successor.requests();
17643		queued(&standby).await.serve(&successor);
17644		let request = kio::clock::timeout(Duration::from_secs(1), handler.requested_track())
17645			.await
17646			.expect("the front asked the standby")
17647			.expect("request");
17648		request.reject(Error::Unroutable);
17649		for _ in 0..10 {
17650			kio::clock::sim::yield_now().await;
17651		}
17652
17653		let mut group = old.append_next().unwrap();
17654		group
17655			.write_frame(Frame::new(group.key_time(), b"last".as_ref()))
17656			.unwrap();
17657		group.finish().unwrap();
17658		let mut group = next_group(&mut subscription)
17659			.await
17660			.expect("the incumbent keeps serving")
17661			.expect("track open");
17662		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"last");
17663
17664		let _old = old.finish().unwrap();
17665		let end = next_group(&mut subscription)
17666			.await
17667			.map(|group| group.map(|group| group.start));
17668		assert!(matches!(end, Ok(None)), "the incumbent's clean end, not {end:?}");
17669	}
17670
17671	/// The newcomer answers "video" with matching metadata, the front reads that answer,
17672	/// and only then does the newcomer abort, before its first group: still a refusal, so
17673	/// the incumbent keeps serving.
17674	#[kio::test]
17675	#[cfg(feature = "async")]
17676	async fn a_replacement_aborted_after_its_answer_keeps_the_incumbent() {
17677		let (producer, _server, _upstream, old, mut subscription) = remote_front().await;
17678
17679		let newcomer = producer
17680			.route("room/alice", RouteOptions::hidden().with_identity(identity(), 0))
17681			.unwrap();
17682		let mut handler = newcomer.broadcast().requests();
17683		newcomer.announce().unwrap();
17684		let request = kio::clock::timeout(Duration::from_secs(1), handler.requested_track())
17685			.await
17686			.expect("the front asked the newcomer")
17687			.expect("request");
17688		let replacement = request.accept(crate::track::Info::timed());
17689		for _ in 0..10 {
17690			kio::clock::sim::yield_now().await;
17691		}
17692		replacement.abort(Error::App(7)).unwrap();
17693		for _ in 0..10 {
17694			kio::clock::sim::yield_now().await;
17695		}
17696
17697		let mut group = old.append_next().unwrap();
17698		group
17699			.write_frame(Frame::new(group.key_time(), b"still".as_ref()))
17700			.unwrap();
17701		group.finish().unwrap();
17702		let mut group = next_group(&mut subscription)
17703			.await
17704			.expect("the incumbent keeps serving")
17705			.expect("track open");
17706		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"still");
17707
17708		// The incumbent's clean end is the track's, not the newcomer's error.
17709		let _old = old.finish().unwrap();
17710		assert!(matches!(next_group(&mut subscription).await, Ok(None)));
17711	}
17712
17713	/// The incumbent delivers its last group and finishes, and only then does the newcomer
17714	/// abort before its first group: the incumbent's clean end is the track's.
17715	#[kio::test]
17716	#[cfg(feature = "async")]
17717	async fn a_replacement_aborted_after_the_incumbent_finished_ends_the_track_cleanly() {
17718		let (producer, _server, _upstream, old, mut subscription) = remote_front().await;
17719
17720		let newcomer = producer
17721			.route("room/alice", RouteOptions::hidden().with_identity(identity(), 0))
17722			.unwrap();
17723		let mut handler = newcomer.broadcast().requests();
17724		newcomer.announce().unwrap();
17725		let request = kio::clock::timeout(Duration::from_secs(1), handler.requested_track())
17726			.await
17727			.expect("the front asked the newcomer")
17728			.expect("request");
17729		let replacement = request.accept(crate::track::Info::timed());
17730		for _ in 0..10 {
17731			kio::clock::sim::yield_now().await;
17732		}
17733		let mut group = old.append_next().unwrap();
17734		group
17735			.write_frame(Frame::new(group.key_time(), b"last".as_ref()))
17736			.unwrap();
17737		group.finish().unwrap();
17738		let _old = old.finish().unwrap();
17739		replacement.abort(Error::App(7)).unwrap();
17740
17741		let mut group = next_group(&mut subscription)
17742			.await
17743			.expect("the incumbent's last group")
17744			.expect("track open");
17745		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"last");
17746		assert!(matches!(next_group(&mut subscription).await, Ok(None)));
17747	}
17748
17749	/// The incumbent finishes and the newcomer aborts before its first group: a reader whose
17750	/// range starts past the last group, which contains its start, and one joining while the
17751	/// newcomer is awaited, each read that group and end cleanly.
17752	#[kio::test]
17753	#[cfg(feature = "async")]
17754	async fn readers_owed_nothing_below_the_incumbents_end_end_cleanly() {
17755		let (producer, _server, _upstream, old, _subscription) = remote_front().await;
17756		let resolved = producer.consume().request("room/alice", None).await.unwrap();
17757		let video = resolved.track("video").unwrap();
17758		let mut group = old.append_next().unwrap();
17759		group
17760			.write_frame(Frame::new(group.key_time(), b"last".as_ref()))
17761			.unwrap();
17762		group.finish().unwrap();
17763		let mut later = video
17764			.subscribe(crate::track::Subscription {
17765				ranges: vec![crate::track::Range {
17766					start: crate::track::Start::Time(3),
17767					end: None,
17768					..Default::default()
17769				}],
17770				..Default::default()
17771			})
17772			.await
17773			.unwrap();
17774
17775		let newcomer = producer
17776			.route("room/alice", RouteOptions::hidden().with_identity(identity(), 0))
17777			.unwrap();
17778		let mut handler = newcomer.broadcast().requests();
17779		newcomer.announce().unwrap();
17780		let request = kio::clock::timeout(Duration::from_secs(1), handler.requested_track())
17781			.await
17782			.expect("the front asked the newcomer")
17783			.expect("request");
17784		let replacement = request.accept(crate::track::Info::timed());
17785		for _ in 0..10 {
17786			kio::clock::sim::yield_now().await;
17787		}
17788		let mut joiner = video.subscribe(None).await.unwrap();
17789		for _ in 0..10 {
17790			kio::clock::sim::yield_now().await;
17791		}
17792		let _old = old.finish().unwrap();
17793		replacement.abort(Error::App(7)).unwrap();
17794
17795		for reader in [&mut later, &mut joiner] {
17796			let mut group = next_group(reader)
17797				.await
17798				.expect("the incumbent's latest group")
17799				.expect("track open");
17800			assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"last");
17801			assert!(matches!(next_group(reader).await, Ok(None)));
17802		}
17803	}
17804
17805	/// While the front waits for the newcomer's first group, a reader changing its
17806	/// preferences reaches the newcomer's copy, which may otherwise never send that group.
17807	#[kio::test]
17808	#[cfg(feature = "async")]
17809	async fn an_awaited_replacement_follows_the_readers_demand() {
17810		let (producer, _server, _upstream, _old, mut subscription) = remote_front().await;
17811
17812		let newcomer = producer
17813			.route("room/alice", RouteOptions::hidden().with_identity(identity(), 0))
17814			.unwrap();
17815		let mut handler = newcomer.broadcast().requests();
17816		newcomer.announce().unwrap();
17817		let request = kio::clock::timeout(Duration::from_secs(1), handler.requested_track())
17818			.await
17819			.expect("the front asked the newcomer")
17820			.expect("request");
17821		let replacement = request.accept(crate::track::Info::timed());
17822		for _ in 0..10 {
17823			kio::clock::sim::yield_now().await;
17824		}
17825		assert_eq!(
17826			replacement.subscription().map(|wanted| wanted.policy().priority),
17827			Some(0)
17828		);
17829
17830		subscription.update(subscription.subscription().prioritized(9)).unwrap();
17831		for _ in 0..10 {
17832			kio::clock::sim::yield_now().await;
17833		}
17834		assert_eq!(
17835			replacement.subscription().map(|wanted| wanted.policy().priority),
17836			Some(9)
17837		);
17838	}
17839
17840	/// Before the incumbent delivered anything, the newcomer answers "video" with matching
17841	/// metadata and then finishes without a group: a deliberate end of the broadcast's
17842	/// track, so the track ends rather than the front waiting on a group that never comes.
17843	#[kio::test]
17844	#[cfg(feature = "async")]
17845	async fn a_replacement_finished_without_a_group_ends_the_track() {
17846		let producer = origin(1).produce();
17847		let server = producer
17848			.forward(
17849				"room",
17850				RouteInfo::new().with_identity(identity(), 0).with_hops(hops(&[10])),
17851			)
17852			.unwrap();
17853		let pending = producer.consume().request("room/alice", None);
17854		let upstream = broadcast::Info::new().produce();
17855		let _old = upstream.create_track("video", crate::track::Info::timed()).unwrap();
17856		queued(&server).await.serve(&upstream);
17857		let resolved = pending.await.expect("resolves");
17858		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
17859
17860		let newcomer = producer
17861			.route("room/alice", RouteOptions::hidden().with_identity(identity(), 0))
17862			.unwrap();
17863		let mut handler = newcomer.broadcast().requests();
17864		newcomer.announce().unwrap();
17865		let request = kio::clock::timeout(Duration::from_secs(1), handler.requested_track())
17866			.await
17867			.expect("the front asked the newcomer")
17868			.expect("request");
17869		let replacement = request.accept(crate::track::Info::timed());
17870		for _ in 0..10 {
17871			kio::clock::sim::yield_now().await;
17872		}
17873		let replacement = replacement.finish().unwrap();
17874
17875		assert!(matches!(next_group(&mut subscription).await, Ok(None)));
17876		drop(replacement);
17877	}
17878
17879	/// The newcomer is asked while only an info lookup wants "video", so its copy has no
17880	/// subscription. A live reader joining while the front waits on its first group
17881	/// subscribes it, or that group may never come.
17882	#[kio::test]
17883	#[cfg(feature = "async")]
17884	async fn an_awaited_replacement_asked_without_readers_subscribes_when_one_joins() {
17885		let (producer, _server, _upstream, _old, subscription) = remote_front().await;
17886		let resolved = producer.consume().request("room/alice", None).await.unwrap();
17887		let video = resolved.track("video").unwrap();
17888		let _info = video.info();
17889		drop(subscription);
17890		for _ in 0..10 {
17891			kio::clock::sim::yield_now().await;
17892		}
17893
17894		let newcomer = producer
17895			.route("room/alice", RouteOptions::hidden().with_identity(identity(), 0))
17896			.unwrap();
17897		let mut handler = newcomer.broadcast().requests();
17898		newcomer.announce().unwrap();
17899		let request = kio::clock::timeout(Duration::from_secs(1), handler.requested_track())
17900			.await
17901			.expect("the front asked the newcomer")
17902			.expect("request");
17903		let replacement = request.accept(crate::track::Info::timed());
17904		for _ in 0..10 {
17905			kio::clock::sim::yield_now().await;
17906		}
17907		assert!(replacement.subscription().is_none(), "nobody reads the track yet");
17908
17909		let _again = video.subscribe(None).await.unwrap();
17910		for _ in 0..10 {
17911			kio::clock::sim::yield_now().await;
17912		}
17913		assert!(
17914			replacement.subscription().is_some(),
17915			"the awaited copy never got the reader's demand"
17916		);
17917	}
17918
17919	/// The newcomer refuses "video", so the track drains the incumbent. The reader leaves
17920	/// (the park drops the incumbent's copy), a third source that also lacks the track
17921	/// takes over, and the reader returns: it gets an outcome rather than waiting on the
17922	/// dropped copy.
17923	#[kio::test]
17924	#[cfg(feature = "async")]
17925	async fn a_returning_reader_is_not_stranded_on_a_dropped_copy() {
17926		let (producer, _server, upstream, old, mut subscription) = remote_front().await;
17927		let resolved = producer.consume().request("room/alice", None).await.unwrap();
17928
17929		// No handler and no track: refuses "video" with NotFound.
17930		let _second = producer
17931			.route("room/alice", RouteOptions::default().with_identity(identity(), 0))
17932			.unwrap();
17933		for _ in 0..10 {
17934			kio::clock::sim::yield_now().await;
17935		}
17936		let mut group = old.append_next().unwrap();
17937		group
17938			.write_frame(Frame::new(group.key_time(), b"draining".as_ref()))
17939			.unwrap();
17940		group.finish().unwrap();
17941		let mut group = next_group(&mut subscription).await.unwrap().expect("draining group");
17942		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"draining");
17943		drop(group);
17944
17945		drop(subscription);
17946		kio::clock::timeout(Duration::from_secs(1), old.demand().until(|wanted| !wanted))
17947			.await
17948			.expect("parked")
17949			.expect("open");
17950
17951		let _third = producer
17952			.route("room/alice", RouteOptions::default().with_identity(identity(), 0))
17953			.unwrap();
17954		for _ in 0..10 {
17955			kio::clock::sim::yield_now().await;
17956		}
17957
17958		let mut again = resolved.track("video").unwrap().subscribe(None).await.unwrap();
17959		let mut group = old.append_next().unwrap();
17960		group
17961			.write_frame(Frame::new(group.key_time(), b"after".as_ref()))
17962			.unwrap();
17963		group.finish().unwrap();
17964		let outcome = kio::clock::timeout(Duration::from_secs(5), async {
17965			loop {
17966				match again.recv_group().await {
17967					Ok(Some(mut group)) => {
17968						if &group.read_frame().await.unwrap().unwrap().payload[..] == b"after" {
17969							return Ok(());
17970						}
17971					}
17972					Ok(None) => return Ok(()),
17973					Err(err) => return Err(err),
17974				}
17975			}
17976		})
17977		.await;
17978		assert!(outcome.is_ok(), "the returning reader waits on a copy the park dropped");
17979		drop(upstream);
17980	}
17981
17982	/// The reader leaves, parking the track. A fetch of a whole group the parked copy
17983	/// caches answers at once, without the front serving the copy again; an open group
17984	/// still waits on the front, and is served once the copy is back.
17985	#[kio::test]
17986	#[cfg(feature = "async")]
17987	async fn a_parked_track_serves_whole_groups_from_its_copy() {
17988		let (producer, _server, _upstream, old, subscription) = remote_front().await;
17989		let resolved = producer.consume().request("room/alice", None).await.unwrap();
17990		let mut open = old.append_next().unwrap();
17991		open.write_frame(Frame::new(open.key_time(), b"open".as_ref())).unwrap();
17992		drop(subscription);
17993		kio::clock::timeout(Duration::from_secs(1), old.demand().until(|wanted| !wanted))
17994			.await
17995			.expect("parked")
17996			.expect("open");
17997
17998		let track = resolved.track("video").unwrap();
17999		let mut whole = track
18000			.fetch_group(0, None)
18001			.now_or_never()
18002			.expect("a whole group needs no front")
18003			.unwrap();
18004		assert_eq!(&whole.read_frame().await.unwrap().unwrap().payload[..], b"before");
18005
18006		let mut fetching = track.fetch_group(1, None);
18007		assert!(
18008			(&mut fetching).now_or_never().is_none(),
18009			"an open group needs the route"
18010		);
18011		open.finish().unwrap();
18012		let mut group = fetching.await.unwrap();
18013		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"open");
18014	}
18015
18016	/// A new source takes over a parked track: a whole group its old copy caches is no
18017	/// longer served from that copy, but asked of the new route, which lacks it.
18018	#[kio::test]
18019	#[cfg(feature = "async")]
18020	async fn a_new_source_unparks_the_old_copy() {
18021		let (producer, _server, _upstream, old, subscription) = remote_front().await;
18022		let resolved = producer.consume().request("room/alice", None).await.unwrap();
18023		drop(subscription);
18024		kio::clock::timeout(Duration::from_secs(1), old.demand().until(|wanted| !wanted))
18025			.await
18026			.expect("parked")
18027			.expect("open");
18028
18029		let newcomer = producer
18030			.route("room/alice", RouteOptions::default().with_identity(identity(), 0))
18031			.unwrap();
18032		let _video = newcomer
18033			.broadcast()
18034			.create_track("video", crate::track::Info::timed())
18035			.unwrap();
18036		for _ in 0..10 {
18037			kio::clock::sim::yield_now().await;
18038		}
18039
18040		let mut fetching = resolved.track("video").unwrap().fetch_group(0, None);
18041		assert!(
18042			(&mut fetching).now_or_never().is_none(),
18043			"served from the detached copy"
18044		);
18045		assert!(matches!(fetching.await, Err(Error::NotFound)));
18046	}
18047
18048	/// A newer local source's copy of "video" is refused for its metadata while the
18049	/// incumbent keeps serving: the refused copy is let go, not kept subscribed.
18050	#[kio::test]
18051	#[cfg(feature = "async")]
18052	async fn a_refused_copy_is_not_kept_subscribed() {
18053		let producer = origin(1).produce();
18054		let consumer = producer.consume();
18055		let first = producer
18056			.route("room/alice", RouteOptions::default().with_identity(identity(), 0))
18057			.unwrap();
18058		let track = first
18059			.broadcast()
18060			.create_track("video", crate::track::Info::timed())
18061			.unwrap();
18062		let resolved = consumer.request("room/alice", None).await.expect("resolves");
18063		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
18064		let mut group = track.append_next().unwrap();
18065		group
18066			.write_frame(Frame::new(group.key_time(), b"before".as_ref()))
18067			.unwrap();
18068		group.finish().unwrap();
18069		let mut group = subscription.recv_group().await.unwrap().unwrap();
18070		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"before");
18071
18072		let second = producer
18073			.route("room/alice", RouteOptions::default().with_identity(identity(), 0))
18074			.unwrap();
18075		let incompatible = second
18076			.broadcast()
18077			.create_track("video", track::Info::default().with_timescale(crate::Timescale::MICRO))
18078			.unwrap();
18079		for _ in 0..10 {
18080			kio::clock::sim::yield_now().await;
18081		}
18082		assert!(
18083			!incompatible.demand().is_wanted(),
18084			"the refused copy is still subscribed"
18085		);
18086
18087		// The refusal happened: the incumbent leaving surfaces it.
18088		drop(track);
18089		first.broadcast().close();
18090		assert!(matches!(subscription.recv_group().await, Err(Error::Unsupported)));
18091	}
18092
18093	/// As above, the newer source's copy was refused and the incumbent keeps serving.
18094	/// Then both withdraw and the front ends: the track in flight carries on with the
18095	/// incumbent, never the refused copy.
18096	#[kio::test]
18097	#[cfg(feature = "async")]
18098	async fn the_end_never_feeds_a_refused_copy() {
18099		let producer = origin(1).produce();
18100		let consumer = producer.consume();
18101		let first = producer
18102			.route("room/alice", RouteOptions::default().with_identity(identity(), 0))
18103			.unwrap();
18104		let track = first
18105			.broadcast()
18106			.create_track("video", crate::track::Info::timed())
18107			.unwrap();
18108		let resolved = consumer.request("room/alice", None).await.expect("resolves");
18109		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
18110		let mut group = track.append_next().unwrap();
18111		group
18112			.write_frame(Frame::new(group.key_time(), b"before".as_ref()))
18113			.unwrap();
18114		group.finish().unwrap();
18115		let mut group = subscription.recv_group().await.unwrap().unwrap();
18116		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"before");
18117		drop(group);
18118
18119		let second = producer
18120			.route("room/alice", RouteOptions::default().with_identity(identity(), 0))
18121			.unwrap();
18122		let incompatible = second
18123			.broadcast()
18124			.create_track("video", track::Info::default().with_timescale(crate::Timescale::MICRO))
18125			.unwrap();
18126		for _ in 0..10 {
18127			kio::clock::sim::yield_now().await;
18128		}
18129
18130		first.withdraw();
18131		second.withdraw();
18132		settle(|| resolved.is_closed()).await;
18133
18134		let mut group = track.append_next().unwrap();
18135		group
18136			.write_frame(Frame::new(group.key_time(), b"still".as_ref()))
18137			.unwrap();
18138		group.finish().unwrap();
18139		for payload in [b"wrong0".as_ref(), b"wrong1".as_ref()] {
18140			let mut group = incompatible.append_next().unwrap();
18141			group.write_frame(Frame::new(group.key_time(), payload)).unwrap();
18142			group.finish().unwrap();
18143		}
18144
18145		let mut group = next_group(&mut subscription)
18146			.await
18147			.expect("the in-flight track carries on")
18148			.expect("track ended early");
18149		let frame = group.read_frame().await.unwrap().unwrap();
18150		assert_eq!(
18151			&frame.payload[..],
18152			b"still",
18153			"the front's end spliced the copy it refused"
18154		);
18155	}
18156
18157	/// The track drains the incumbent while a newer source's answer is pending, then both
18158	/// withdraw and the front ends: the track carries on with the incumbent's copy rather
18159	/// than the unanswered one.
18160	#[kio::test]
18161	#[cfg(feature = "async")]
18162	async fn the_end_keeps_the_copy_still_serving() {
18163		let producer = origin(1).produce();
18164		let consumer = producer.consume();
18165		let first = producer
18166			.route("room/alice", RouteOptions::default().with_identity(identity(), 0))
18167			.unwrap();
18168		let track = first
18169			.broadcast()
18170			.create_track("video", crate::track::Info::timed())
18171			.unwrap();
18172		let resolved = consumer.request("room/alice", None).await.expect("resolves");
18173		let mut subscription = resolved.track("video").unwrap().subscribe(None).await.unwrap();
18174		let mut group = track.append_next().unwrap();
18175		group
18176			.write_frame(Frame::new(group.key_time(), b"before".as_ref()))
18177			.unwrap();
18178		group.finish().unwrap();
18179		let mut group = subscription.recv_group().await.unwrap().unwrap();
18180		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"before");
18181		drop(group);
18182
18183		let second = producer
18184			.route("room/alice", RouteOptions::hidden().with_identity(identity(), 0))
18185			.unwrap();
18186		let mut handler = second.broadcast().requests();
18187		second.announce().unwrap();
18188		let request = kio::clock::timeout(Duration::from_secs(1), handler.requested_track())
18189			.await
18190			.expect("the front asked the newcomer")
18191			.expect("request");
18192
18193		first.withdraw();
18194		second.withdraw();
18195		settle(|| resolved.is_closed()).await;
18196
18197		let mut group = track.append_next().unwrap();
18198		group
18199			.write_frame(Frame::new(group.key_time(), b"still".as_ref()))
18200			.unwrap();
18201		group.finish().unwrap();
18202		request.reject(Error::NotFound);
18203
18204		let mut group = next_group(&mut subscription)
18205			.await
18206			.expect("the in-flight track carries on")
18207			.expect("track ended early");
18208		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"still");
18209	}
18210
18211	#[kio::test]
18212	async fn multiple_scopes_present_one_broad_prefix() {
18213		let producer = origin(1).produce();
18214		let _a = producer.announce("", RouteInfo::new()).unwrap();
18215
18216		let consumer = producer
18217			.consume()
18218			.scope("", &scopes(&["alpha", "beta"]))
18219			.unwrap()
18220			.covering();
18221		let mut announced = consumer.routes();
18222		announced.expect_next_active("").await;
18223		announced.assert_next_wait();
18224	}
18225
18226	#[kio::test]
18227	async fn scope_takes_prefixes_each_covering_its_subtree() {
18228		let producer = origin(1).produce();
18229
18230		// The empty prefix grants everything.
18231		let root = producer.scope("", &Prefixes::all()).unwrap();
18232		assert_eq!(root.allowed(), Prefixes::all());
18233
18234		let scoped = producer.scope("", &scopes(&["room"])).unwrap();
18235		assert_eq!(scoped.allowed(), scopes(&["room"]));
18236		assert!(scoped.route("room", RouteOptions::default()).is_ok());
18237		assert!(scoped.route("room/alice", RouteOptions::default()).is_ok());
18238		assert!(matches!(
18239			scoped.route("roomy", RouteOptions::default()),
18240			Err(Error::Unauthorized)
18241		));
18242
18243		// Multiple prefixes round-trip, with nested ones collapsed.
18244		let multi = producer.scope("", &scopes(&["room", "room/chat", "anon"])).unwrap();
18245		assert_eq!(multi.allowed(), scopes(&["room", "anon"]));
18246
18247		// The consumer side reports the same way.
18248		let consumer = producer.consume().scope("", &scopes(&["room"])).unwrap();
18249		assert_eq!(consumer.allowed(), scopes(&["room"]));
18250
18251		// A root no prefix can spell is refused, not read as a pattern.
18252		assert!(matches!(
18253			producer.scope("room/*", &Prefixes::all()),
18254			Err(Error::BoundsExceeded(_))
18255		));
18256	}
18257
18258	#[kio::test]
18259	async fn route_table_prunes_to_empty() {
18260		let producer = origin(1).produce();
18261		let consumer = producer.consume();
18262
18263		// Routes and cursors hang at their prefixes; the nodes on the way exist
18264		// only while something is there.
18265		let cursor = consumer
18266			.scope("", &scopes(&["room/a", "other/deep/head"]))
18267			.unwrap()
18268			.routes();
18269		let route = producer.announce("room/a/b/c", RouteInfo::new()).unwrap();
18270		{
18271			let table = producer.shared.lock();
18272			assert!(
18273				table
18274					.routes
18275					.root
18276					.find(Path::from_static("room/a/b/c").parts())
18277					.is_some()
18278			);
18279			assert!(
18280				table
18281					.routes
18282					.root
18283					.find(Path::from_static("other/deep/head").parts())
18284					.is_some()
18285			);
18286			assert_eq!(table.routes.root.cursors_below, 2);
18287		}
18288
18289		drop(route);
18290		drop(cursor);
18291		let table = producer.shared.lock();
18292		assert!(table.routes.root.is_empty());
18293		assert_eq!(table.routes.root.cursors_below, 0);
18294	}
18295
18296	/// A session handed an `origin::Producer` drops it once it has its own
18297	/// handles, so the driver must keep running while a published broadcast
18298	/// lives, and finish once the last one is gone.
18299	#[kio::test]
18300	async fn a_published_broadcast_keeps_the_driver_running() {
18301		let (producer, mut driver) = Producer::new(Config::from(origin(1)));
18302		let waiter = kio::Waiter::noop();
18303		let broadcast = producer.route("room/a", RouteOptions::hidden()).unwrap();
18304		drop(producer);
18305		assert!(
18306			driver.poll(Instant::now(), &waiter).is_ok(),
18307			"the broadcast is lifecycle work"
18308		);
18309		drop(broadcast);
18310		assert!(matches!(driver.poll(Instant::now(), &waiter), Err(Error::Closed)));
18311	}
18312
18313	/// The task feeding a route node never keeps the driver running: it finishes once
18314	/// the last owner drops, whatever read handles remain, and still feeds the node the
18315	/// withdrawals that last drop queued.
18316	#[kio::test]
18317	async fn a_route_node_never_keeps_the_driver_running() {
18318		let (producer, mut driver) = Producer::new(Config::from(origin(1)));
18319		let waiter = kio::Waiter::noop();
18320		let consumer = producer.consume();
18321		let alice = producer.announce("room/alice", RouteInfo::new()).unwrap();
18322		let stream = route_stream(&consumer.route_node());
18323		assert!(
18324			driver.poll(Instant::now(), &waiter).is_ok(),
18325			"the producer owns the origin"
18326		);
18327		while stream.try_wire().is_some() {}
18328		drop(alice);
18329		drop(producer);
18330		assert!(matches!(driver.poll(Instant::now(), &waiter), Err(Error::Closed)));
18331		let changes = route_changes(&stream);
18332		assert!(
18333			changes
18334				.iter()
18335				.any(|(path, live)| path.as_str() == "room/alice" && !live),
18336			"the stream is told the withdrawal: {changes:?}"
18337		);
18338	}
18339
18340	/// A handler holding only its `Route` keeps serving once every producer
18341	/// handle drops, and the driver finishes once the handler is gone too.
18342	#[kio::test]
18343	#[cfg(feature = "async")]
18344	async fn a_dynamic_keeps_the_driver_running() {
18345		let (producer, driver) = Producer::new(Config::from(origin(1)));
18346		let run = kio::clock::sim::spawn(crate::time::run(driver));
18347		let consumer = producer.consume();
18348		let server = producer.forward("room", RouteInfo::new()).unwrap();
18349		drop(producer);
18350
18351		let pending = consumer.request("room/alice", None);
18352		let request = queued(&server).await;
18353		let source = broadcast::Info::new().produce();
18354		request.serve(&source);
18355		let resolved = pending.await.expect("the dynamic still serves");
18356
18357		drop(resolved);
18358		drop(source);
18359		drop(server);
18360		kio::clock::timeout(Duration::from_secs(5), run)
18361			.await
18362			.expect("driver must finish once the dynamic is gone")
18363			.unwrap();
18364		drop(consumer);
18365	}
18366
18367	/// A reader still on a retracted broadcast's track keeps its front draining, but
18368	/// never keeps the driver from finishing once nothing owns the origin.
18369	#[kio::test]
18370	#[cfg(feature = "async")]
18371	async fn a_retracted_reader_never_holds_the_driver() {
18372		let (producer, driver) = Producer::new(Config::from(origin(1)));
18373		let run = kio::clock::sim::spawn(crate::time::run(driver));
18374		let consumer = producer.consume();
18375		let broadcast = producer.route("room/alice", RouteOptions::default()).unwrap();
18376		let track = broadcast
18377			.broadcast()
18378			.create_track("video", crate::track::Info::timed())
18379			.unwrap();
18380		let resolved = consumer.request("room/alice", None).await.expect("resolves");
18381		let sub = resolved.track("video").unwrap().subscribe(None).await.unwrap();
18382
18383		broadcast.withdraw();
18384		settle(|| resolved.is_closed()).await;
18385		drop(broadcast);
18386		drop(producer);
18387		kio::clock::timeout(Duration::from_secs(5), run)
18388			.await
18389			.expect("driver must finish once the producers are gone")
18390			.unwrap();
18391		drop(sub);
18392		drop(track);
18393	}
18394
18395	/// A subscriber that asked before the retraction but was not polled yet still finds
18396	/// the copy after the origin is orphaned and its driver finishes.
18397	#[kio::test]
18398	#[cfg(feature = "async")]
18399	async fn an_orphaned_front_keeps_the_copy_for_a_pending_subscriber() {
18400		let (producer, driver) = Producer::new(Config::from(origin(1)));
18401		let run = kio::clock::sim::spawn(crate::time::run(driver));
18402		let consumer = producer.consume();
18403		let broadcast = producer.route("room/alice", RouteOptions::default()).unwrap();
18404		let mut track = broadcast
18405			.broadcast()
18406			.create_track("video", crate::track::Info::timed())
18407			.unwrap();
18408		let resolved = consumer.request("room/alice", None).await.expect("resolves");
18409		let sub = resolved.track("video").unwrap().subscribe(None).await.unwrap();
18410		let pending = resolved.track("video").unwrap().subscribe(None);
18411
18412		broadcast.withdraw();
18413		settle(|| resolved.is_closed()).await;
18414		drop(broadcast);
18415		drop(producer);
18416		kio::clock::timeout(Duration::from_secs(5), run)
18417			.await
18418			.expect("driver must finish once the producers are gone")
18419			.unwrap();
18420		track
18421			.write_frame(Frame::new(crate::Timestamp::ZERO, b"late".as_ref()))
18422			.unwrap();
18423		let mut late = pending.await.expect("subscribes");
18424		let mut group = late.recv_group().await.expect("recv").expect("the source's group");
18425		assert_eq!(&group.read_frame().await.unwrap().unwrap().payload[..], b"late");
18426		drop(sub);
18427	}
18428
18429	/// A track whose last reader leaves as its broadcast ends, before the front parks it,
18430	/// lets go of its copy: the source is not kept subscribed for nobody.
18431	#[kio::test]
18432	#[cfg(feature = "async")]
18433	async fn a_track_unread_as_its_broadcast_ends_releases_its_source() {
18434		let producer = origin(1).produce();
18435		let consumer = producer.consume();
18436		let broadcast = producer.route("room/alice", RouteOptions::default()).unwrap();
18437		let track = broadcast
18438			.broadcast()
18439			.create_track("video", crate::track::Info::timed())
18440			.unwrap();
18441		let resolved = consumer.request("room/alice", None).await.expect("resolves");
18442		let sub = resolved.track("video").unwrap().subscribe(None).await.unwrap();
18443		kio::clock::timeout(Duration::from_secs(1), track.demand().until(|wanted| wanted))
18444			.await
18445			.expect("the front subscribed the source")
18446			.unwrap();
18447
18448		// The front looks at a closed source before demand edges, so it ends with the
18449		// track unread and its copy not parked yet.
18450		drop(sub);
18451		drop(broadcast);
18452		settle(|| resolved.is_closed()).await;
18453
18454		kio::clock::timeout(Duration::from_secs(5), track.demand().until(|wanted| !wanted))
18455			.await
18456			.expect("the ended copy must not keep the source subscribed")
18457			.unwrap();
18458	}
18459
18460	#[kio::test]
18461	async fn source_selection_leases_survive_reprices_but_never_revive_pending_work() {
18462		let producer = origin(1).produce();
18463		let broad = producer.forward("room", RouteInfo::new().with_via(origin(2))).unwrap();
18464		let selected = broad.request_validity(&Path::from_static("room/a")).unwrap();
18465		let pending = selected.current();
18466		assert!(!pending.is_closed());
18467		broad.update(broad.route().unwrap().with_cost(Cost::from(7))).unwrap();
18468		assert!(!pending.is_closed());
18469		// Another peer's winning route cannot change what a request on peer 2 names.
18470		let other = producer
18471			.forward("room/a", RouteInfo::new().with_via(origin(3)))
18472			.unwrap();
18473		assert!(!pending.is_closed());
18474		let replacement = producer
18475			.forward("room/a", RouteInfo::new().with_via(origin(2)))
18476			.unwrap();
18477		assert!(pending.is_closed());
18478		assert!(selected.current().is_closed());
18479		// No waiter has polled between these changes: the old lease must still be dead.
18480		drop(replacement);
18481		let fresh = selected.current();
18482		assert!(!fresh.is_closed());
18483		assert!(pending.is_closed());
18484		drop(other);
18485		assert!(!fresh.is_closed());
18486		drop(broad);
18487		assert!(fresh.is_closed());
18488	}
18489
18490	/// The answering lease outlives a withdrawal, since the peer still answers for the
18491	/// identity it retracted, and ends once another identity takes the path.
18492	#[kio::test]
18493	async fn source_selection_answering_ends_only_on_a_replacement() {
18494		let producer = origin(1).produce();
18495		let path = Path::from_static("room/a");
18496		let first = producer.forward("room", RouteInfo::new().with_via(origin(2))).unwrap();
18497		let selected = first.request_validity(&path).unwrap();
18498		let answering = selected.answering();
18499		// A route that loses to the selected one replaces nothing.
18500		let worse = producer
18501			.forward("room", RouteInfo::new().with_via(origin(2)).with_cost(Cost::from(7)))
18502			.unwrap();
18503		assert!(!answering.is_closed());
18504		drop(worse);
18505
18506		let replacement = producer
18507			.forward("room/a", RouteInfo::new().with_via(origin(2)))
18508			.unwrap();
18509		assert!(answering.is_closed());
18510		// Winning again opens a new lease, which a withdrawal leaves open.
18511		drop(replacement);
18512		let answering = selected.answering();
18513		assert!(!answering.is_closed());
18514		drop(first);
18515		assert!(selected.current().is_closed());
18516		assert!(!answering.is_closed());
18517
18518		// Announced again, the path has a new identity: a replacement.
18519		let _again = producer.forward("room", RouteInfo::new().with_via(origin(2))).unwrap();
18520		assert!(answering.is_closed());
18521	}
18522
18523	#[kio::test]
18524	async fn source_selection_unregisters_without_retaining_the_source() {
18525		let producer = origin(1).produce();
18526		let route = producer.forward("room", RouteInfo::new().with_via(origin(2))).unwrap();
18527		let path = Path::from_static("room/a");
18528		let selected = route.request_validity(&path).unwrap();
18529		let lease = selected.current();
18530		drop(selected);
18531		assert!(lease.is_closed());
18532		let table = producer.shared.lock();
18533		assert_eq!(table.routes.root.watches_below, 0);
18534	}
18535
18536	#[kio::test]
18537	async fn watch_wakes_only_for_covering_changes() {
18538		let producer = origin(1).produce();
18539		let waiter = kio::Waiter::noop();
18540		let watch = producer
18541			.shared
18542			.lock()
18543			.watch(&producer.shared, &Path::from_static("room/a"));
18544		let seen = watch.seen();
18545
18546		// A route beside the path or beneath it covers nothing at the path.
18547		let _other = producer.announce("other", RouteInfo::new()).unwrap();
18548		let _below = producer.announce("room/a/b", RouteInfo::new()).unwrap();
18549		assert!(watch.poll_changed(&waiter, seen).is_pending());
18550
18551		// A route above it does, and so does its retraction.
18552		let above = producer.announce("room", RouteInfo::new()).unwrap();
18553		assert!(watch.poll_changed(&waiter, seen).is_ready());
18554		let seen = watch.seen();
18555		drop(above);
18556		assert!(watch.poll_changed(&waiter, seen).is_ready());
18557		let seen = watch.seen();
18558
18559		// A local broadcast attaching at the exact path does; one beside it does not.
18560		let _beside = producer.route("room/b", RouteOptions::hidden()).unwrap();
18561		assert!(watch.poll_changed(&waiter, seen).is_pending());
18562		let _here = producer.route("room/a", RouteOptions::hidden()).unwrap();
18563		assert!(watch.poll_changed(&waiter, seen).is_ready());
18564
18565		// Dropping the watch takes it out of the table.
18566		drop(watch);
18567		let table = producer.shared.lock();
18568		let node = table
18569			.routes
18570			.root
18571			.find(Path::from_static("room/a").parts())
18572			.expect("route below keeps the node");
18573		assert!(node.watches.is_empty());
18574		assert_eq!(table.routes.root.watches_below, 0);
18575	}
18576
18577	#[kio::test]
18578	async fn a_discarded_front_task_unregisters_its_watch() {
18579		let (producer, _driver) = Producer::new(Config::from(origin(1)));
18580		let consumer = producer.consume();
18581		let _served = producer.forward("room", RouteInfo::new()).unwrap();
18582		// A consumer outlives its producer by design, so the task set can refuse
18583		// submissions while the origin is still open. The front's task is then
18584		// dropped on the spot, taking its `Watch` with it: the request must not
18585		// still be holding the table lock the watch unregisters under.
18586		drop(producer);
18587		let _pending = consumer.request("room/a", None);
18588	}
18589
18590	#[kio::test]
18591	async fn published_names_refuse_navigation_segments() {
18592		let producer = origin(1).produce();
18593		for path in ["room/./cam", "room/../cam", ".", ".."] {
18594			assert!(producer.route(path, RouteOptions::hidden()).is_err(), "created {path}");
18595			assert!(producer.announce(path, RouteInfo::new()).is_err(), "announced {path}");
18596		}
18597		let scoped = producer.scope("room/..", &Prefixes::all()).unwrap();
18598		assert!(scoped.route("cam", RouteOptions::hidden()).is_err());
18599		for path in ["room/.pro/cam", "room/a..b", "room/cam"] {
18600			let _route = producer.route(path, RouteOptions::hidden()).unwrap();
18601		}
18602	}
18603
18604	/// A `*` names no prefix, so no broadcast, claim, mount point, or lookup may hold one.
18605	#[kio::test]
18606	async fn a_star_is_refused_everywhere_a_path_is_named() {
18607		let producer = origin(1).produce();
18608		let consumer = producer.consume();
18609		for path in ["room/*", "room/cam*1", "**"] {
18610			assert!(matches!(
18611				producer.route(path, RouteOptions::default()),
18612				Err(Error::InvalidPath)
18613			));
18614			assert!(matches!(
18615				producer.announce(path, RouteInfo::new()),
18616				Err(Error::InvalidPath)
18617			));
18618			assert!(matches!(producer.mount(path, "room"), Err(Error::InvalidPath)));
18619			assert!(matches!(consumer.follow(path, None), Err(Error::InvalidPath)));
18620		}
18621	}
18622
18623	/// A lookup whose rooted path exceeds the wire's depth is refused before it registers an
18624	/// interest no session could encode.
18625	#[kio::test]
18626	async fn a_lookup_past_the_depth_limit_is_refused() {
18627		let producer = origin(1).produce();
18628		let half = vec!["a"; Path::MAX_PARTS / 2 + 1].join("/");
18629		let rooted = producer.consume().scope(half.as_str(), &Prefixes::all()).unwrap();
18630		assert!(matches!(
18631			rooted.follow(half.as_str(), None),
18632			Err(Error::BoundsExceeded(_))
18633		));
18634	}
18635
18636	#[kio::test]
18637	async fn scope_empty_union_grants_nothing() {
18638		let producer = origin(1).produce();
18639
18640		// An empty set grants nothing: scoping is refused, like a disjoint prefix.
18641		assert!(matches!(producer.scope("", &Prefixes::new()), Err(Error::Unauthorized)));
18642		assert!(matches!(
18643			producer.consume().scope("", &Prefixes::new()),
18644			Err(Error::Unauthorized)
18645		));
18646	}
18647
18648	#[kio::test]
18649	async fn scope_nests_and_rebases_roots() {
18650		let producer = origin(1).produce();
18651
18652		// Narrowing twice intersects; the grant stays in the new vocabulary.
18653		let scoped = producer.scope("", &scopes(&["room"])).unwrap();
18654		let nested = scoped.scope("", &scopes(&["room/chat"])).unwrap();
18655		assert_eq!(nested.allowed(), scopes(&["room/chat"]));
18656
18657		// A disjoint nesting is refused, not widened.
18658		assert!(matches!(
18659			scoped.scope("", &scopes(&["other"])),
18660			Err(Error::Unauthorized)
18661		));
18662
18663		// A literal root rebases the grant without changing its meaning.
18664		let rooted = nested.scope("room/chat", &Prefixes::all()).unwrap();
18665		assert_eq!(rooted.allowed(), scopes(&[""]));
18666
18667		// Publishing through the nested view lands where the root says.
18668		let broadcast = nested.route("room/chat/live", RouteOptions::hidden()).unwrap();
18669		assert!(producer.consume().get_broadcast("room/chat/live").is_some());
18670		broadcast.broadcast().close();
18671	}
18672
18673	#[kio::test]
18674	async fn scope_intersects_and_rebases_prefixes() {
18675		let producer = origin(1).produce();
18676		// Narrowing keeps the deeper of two nested prefixes, whichever side holds it.
18677		let rooms = producer.scope("", &scopes(&["room", "lobby/a"])).unwrap();
18678		let both = rooms.scope("", &scopes(&["room/chat", "lobby"])).unwrap();
18679		assert_eq!(both.allowed(), scopes(&["room/chat", "lobby/a"]));
18680
18681		let alice = producer.scope("", &scopes(&["room/alice"])).unwrap();
18682		let rooted = alice.scope("room", &Prefixes::all()).unwrap();
18683		assert_eq!(rooted.allowed(), scopes(&["alice"]));
18684		assert!(matches!(
18685			alice.scope("room/bob", &Prefixes::all()),
18686			Err(Error::Unauthorized)
18687		));
18688
18689		// A prefix covers its whole subtree, so what lies beneath publishes too.
18690		let broadcast = alice.route("room/alice", RouteOptions::hidden()).unwrap();
18691		let cam = alice.route("room/alice/cam", RouteOptions::hidden()).unwrap();
18692		assert!(matches!(
18693			alice.route("room/bob", RouteOptions::hidden()),
18694			Err(Error::Unauthorized)
18695		));
18696		assert!(producer.consume().get_broadcast("room/alice").is_some());
18697		drop((broadcast, cam));
18698	}
18699
18700	#[kio::test]
18701	async fn announced_lists_full_names_in_replay_and_live_changes() {
18702		let producer = origin(1).produce();
18703		let consumer = producer.consume().scope("project", &Prefixes::all()).unwrap();
18704		let cam = producer.announce("project/cam.hang", RouteInfo::new()).unwrap();
18705		let chat = producer.announce("project/lobby.chat", RouteInfo::new()).unwrap();
18706		let _other = producer.announce("elsewhere/lobby.chat", RouteInfo::new()).unwrap();
18707		let mut selected = consumer.routes();
18708		selected.expect_next_active("cam.hang").await;
18709		selected.expect_next_active("lobby.chat").await;
18710		selected.assert_next_wait();
18711
18712		let nested = producer.announce("project/room/lobby.chat", RouteInfo::new()).unwrap();
18713		selected.expect_next_active("room/lobby.chat").await;
18714		drop(nested);
18715		selected.expect_next_ended("room/lobby.chat").await;
18716		drop(cam);
18717		drop(chat);
18718	}
18719
18720	#[kio::test]
18721	async fn announced_keeps_lifecycle_and_filters_before_rerooting() {
18722		let producer = origin(1).produce();
18723		let consumer = producer.consume().scope("room/alice", &Prefixes::all()).unwrap();
18724		let broad = producer.announce("room", RouteInfo::new()).unwrap();
18725		let mut selected = consumer.routes();
18726		selected.assert_next_wait();
18727
18728		let first_identity = crate::Identity::random();
18729		let exact = producer
18730			.announce("room/alice", RouteInfo::new().with_identity(first_identity.clone(), 0))
18731			.unwrap();
18732		assert!(
18733			matches!(selected.expect_next().await, RouteEvent { kind: RouteKind::Start, announce: a } if a.prefix.is_empty())
18734		);
18735		exact
18736			.update(RouteInfo::new().with_identity(first_identity, 0).with_cost(2))
18737			.unwrap();
18738		assert!(
18739			matches!(selected.expect_next().await, RouteEvent { kind: RouteKind::Update, announce: a } if a.route.cost == Cost::new(2))
18740		);
18741		exact
18742			.update(RouteInfo::new().with_identity(crate::Identity::random(), 0))
18743			.unwrap();
18744		assert!(matches!(
18745			selected.expect_next().await,
18746			RouteEvent {
18747				kind: RouteKind::Restart,
18748				..
18749			}
18750		));
18751		drop(exact);
18752		selected.expect_next_ended("").await;
18753		selected.assert_next_wait();
18754		let _again = producer.announce("room/alice", RouteInfo::new()).unwrap();
18755		assert!(matches!(
18756			selected.expect_next().await,
18757			RouteEvent {
18758				kind: RouteKind::Start,
18759				..
18760			}
18761		));
18762		drop(broad);
18763		selected.assert_next_wait();
18764		drop(selected);
18765		let table = producer.shared.lock();
18766		assert!(table.cursors.is_empty());
18767		assert!(table.routes.interests_from(&Path::empty()).is_empty());
18768	}
18769
18770	#[kio::test]
18771	async fn announced_matches_mounted_names_and_keeps_exclusions() {
18772		let producer = origin(1).produce();
18773		let _broad = producer.announce(".svc", RouteInfo::new()).unwrap();
18774		let _hidden = producer
18775			.announce(".svc/p1/.private/lobby.chat", RouteInfo::new())
18776			.unwrap();
18777		let _excluded = producer
18778			.announce(".svc/p1/private/lobby.chat", RouteInfo::new())
18779			.unwrap();
18780		let project = mounted(&producer, "p1", &[""])
18781			.with_hidden(true)
18782			.exclude(".svc/private")
18783			.unwrap();
18784		let mut selected = project.routes();
18785		selected.expect_next_active(".svc/.private/lobby.chat").await;
18786		selected.assert_next_wait();
18787		let mut inside = project.scope(".svc", &Prefixes::all()).unwrap().routes();
18788		inside.expect_next_active(".private/lobby.chat").await;
18789		inside.assert_next_wait();
18790		let live = producer.announce(".svc/p1/lobby.chat", RouteInfo::new()).unwrap();
18791		selected.expect_next_active(".svc/lobby.chat").await;
18792		inside.expect_next_active("lobby.chat").await;
18793		drop(live);
18794		selected.expect_next_ended(".svc/lobby.chat").await;
18795		inside.expect_next_ended("lobby.chat").await;
18796	}
18797
18798	#[kio::test]
18799	#[cfg(feature = "async")]
18800	async fn announced_requests_covering_routes_and_preserves_shared_fronts_and_stats() {
18801		let registry = stats::Registry::new(stats::Config::new());
18802		let producer = origin(1).produce();
18803		let local = producer.route("project/cam.chat", RouteOptions::default()).unwrap();
18804		let overlap = producer.forward("project/room", RouteInfo::new()).unwrap();
18805		// Scoped to two paths beneath `project`, so the route at `project/room` covers one of
18806		// them without being listed.
18807		let consumer = (producer.consume())
18808			.scope("project", &scopes(&["cam.chat", "room/lobby.chat"]))
18809			.unwrap()
18810			.local()
18811			.with_stats(
18812				registry
18813					.tier(stats::Tier::default())
18814					.session(crate::stats::SessionInfo::new(Path::from_static("project"))),
18815			);
18816		let mut selected = consumer.routes();
18817		selected.expect_next_active("cam.chat").await;
18818		selected.assert_next_wait();
18819		let resolved = consumer.request("cam.chat", None).await.unwrap();
18820		let original = producer
18821			.consume()
18822			.local()
18823			.request("project/cam.chat", None)
18824			.await
18825			.unwrap();
18826		assert!(
18827			resolved.is_clone(&original),
18828			"the view shares the origin's existing front"
18829		);
18830		let track = local
18831			.broadcast()
18832			.create_track("video", crate::track::Info::timed())
18833			.unwrap();
18834		let mut written = track.append_next().unwrap();
18835		written
18836			.write_frame(Frame::new(written.key_time(), b"frame".as_ref()))
18837			.unwrap();
18838		written.finish().unwrap();
18839		let _track = track.finish().unwrap();
18840		let mut reader = resolved.track("video").unwrap().subscribe(None).await.unwrap();
18841		let mut group = reader.recv_group().await.unwrap().unwrap();
18842		assert_eq!(group.read_frame().await.unwrap().unwrap().payload.as_ref(), b"frame");
18843		let mut report = stats::Report::default();
18844		registry.report(&mut report, crate::time::Instant::now());
18845		assert_eq!(report.traffic.len(), 1);
18846		assert_eq!(report.traffic[0].path.as_str(), "project/cam.chat");
18847		assert_eq!(report.traffic[0].publisher.announces_started, 1);
18848		assert_eq!(report.traffic[0].publisher.bytes, 5);
18849		drop(selected);
18850		registry.report(&mut report, crate::time::Instant::now());
18851		assert_eq!(report.traffic[0].publisher.announces_ended, 1);
18852
18853		// Discovery of a request still sees a covering route that enumeration omits.
18854		let mut routes = consumer.path_routes("room/lobby.chat").unwrap();
18855		assert!(routes.next().await.is_some());
18856		drop(routes);
18857		drop(overlap);
18858		let source = producer.claim("project/room", RouteOptions::default()).unwrap();
18859		let pending = consumer.request("room/lobby.chat", None);
18860		let request = source.requested().await.unwrap();
18861		request.serve(local.broadcast().consume());
18862		pending.await.unwrap();
18863	}
18864
18865	#[kio::test]
18866	async fn local_broadcast_wins_announcement_ties() {
18867		let producer = origin(1).produce();
18868		let remote = producer.announce("room/alice", RouteInfo::new().with_cost(9)).unwrap();
18869		let local = producer.route("room/alice", RouteOptions::hidden()).unwrap();
18870		local.announce().unwrap();
18871
18872		let mut announced = producer.consume().routes();
18873		let Some(RouteEvent {
18874			kind: RouteKind::Start,
18875			announce: update,
18876		}) = announced.try_next()
18877		else {
18878			panic!("expected one winning route");
18879		};
18880		assert_eq!(update.prefix.as_str(), "room/alice");
18881		assert_eq!(update.route.cost, Cost::default());
18882		announced.assert_next_wait();
18883
18884		drop(local);
18885		drop(remote);
18886	}
18887
18888	/// Charging a link accumulates onto the static price, saturating rather than wrapping
18889	/// so a bogus peer sorts last, not first. The ceiling is the largest cost a
18890	/// varint can carry, so whatever a peer advertises, the sum we forward still
18891	/// encodes.
18892	#[kio::test]
18893	async fn cost_charge_saturates() {
18894		assert_eq!(Cost::new(4).charged(5), Cost::new(9));
18895		assert_eq!(Cost::new(u64::MAX).charged(10), Cost::new(MAX_COST));
18896
18897		assert_eq!(Cost::UNKNOWN.charged(3), Cost::new(3));
18898	}
18899
18900	/// Mint an origin whose pool reclaims idle content after `expiry`.
18901	#[cfg(feature = "async")]
18902	fn expiring_origin(expiry: Duration) -> Producer {
18903		let pool = cache::Pool::new(cache::Config::default().with_expiry(expiry));
18904		Config {
18905			pool,
18906			..Config::default()
18907		}
18908		.produce()
18909	}
18910
18911	/// A publisher that stalls with a group still open runs no write path, so the
18912	/// track's own write-driven expiry never fires and a reader parked in that group
18913	/// is never told. The driver's wall-clock sweep is the bound.
18914	#[kio::test]
18915	#[cfg(feature = "async")]
18916	async fn stalled_publisher_open_group_is_reclaimed() {
18917		let expiry = Duration::from_secs(1);
18918		let origin = expiring_origin(expiry);
18919		let broadcast = origin.route("test", RouteOptions::hidden()).unwrap();
18920		let track = broadcast
18921			.broadcast()
18922			.create_track("video", crate::track::Info::timed())
18923			.unwrap();
18924
18925		let mut stalled = track.append_next().unwrap();
18926		stalled
18927			.write_frame(Frame::new(stalled.key_time(), b"x".as_slice()))
18928			.unwrap();
18929		// A successor, so the stalled group is not the protected live edge. Its
18930		// timestamp is inside the max age, so the stalled group stays fresh and
18931		// subscription expiry never skips it: only reclamation can bound it.
18932		let _successor = track.append_next().unwrap();
18933
18934		let mut reading = stalled.consume();
18935		assert!(reading.read_frame().await.unwrap().is_some());
18936
18937		// Production goes quiet: nothing writes to this track again. Bounded so a
18938		// regression fails rather than parking forever, which is the bug itself. Time
18939		// is simulated, so the wait costs nothing.
18940		let reclaimed = kio::clock::timeout(Duration::from_secs(60), reading.read_frame()).await;
18941		assert!(
18942			matches!(reclaimed, Ok(Err(Error::Old))),
18943			"the sweep must reclaim an idle open group and surface the gap, got {reclaimed:?}"
18944		);
18945	}
18946
18947	/// Reclamation is the pool's policy, not the origin's: a pool with no expiry
18948	/// window keeps idle content until byte pressure takes it, sweep or no sweep.
18949	#[kio::test]
18950	#[cfg(feature = "async")]
18951	async fn sweep_respects_a_disabled_expiry() {
18952		let origin = Config {
18953			pool: cache::Pool::unbounded(),
18954			..Config::default()
18955		}
18956		.produce();
18957		let broadcast = origin.route("test", RouteOptions::hidden()).unwrap();
18958		let track = broadcast
18959			.broadcast()
18960			.create_track("video", crate::track::Info::timed())
18961			.unwrap();
18962
18963		let mut stalled = track.append_next().unwrap();
18964		stalled
18965			.write_frame(Frame::new(stalled.key_time(), b"x".as_slice()))
18966			.unwrap();
18967		let _successor = track.append_next().unwrap();
18968
18969		let mut reading = stalled.consume();
18970		assert!(reading.read_frame().await.unwrap().is_some());
18971
18972		kio::clock::sim::advance(Duration::from_secs(3600)).await;
18973
18974		assert!(
18975			reading.read_frame().now_or_never().is_none(),
18976			"a pool without an expiry window never reclaims"
18977		);
18978	}
18979}