Skip to main content

moq_net/model/
broadcast.rs

1//! A broadcast is a named collection of tracks, split into a [Producer] and [Consumer] handle.
2//!
3//! A [Producer] creates tracks on demand: a [Consumer] subscribes by name, and the
4//! producer either serves a track it already has or is handed a [`track::Request`] to
5//! fill. Both handles are refcounted clones of one broadcast, which ends on
6//! [`Producer::close`] or when the last producer drops. A broadcast has no finished state:
7//! a publisher ends its content by finishing its tracks, and goes offline by closing.
8//!
9//! [Info] is the broadcast's static metadata, fixed for its lifetime.
10use crate::{cache, datagram, stats, track};
11use std::{
12	collections::{HashSet, VecDeque},
13	sync::{
14		Arc,
15		atomic::{AtomicUsize, Ordering},
16	},
17	task::{Poll, ready},
18};
19
20use crate::Error;
21
22use super::{RequestQueue, WeakCache, WeakEntry};
23
24#[path = "listing.rs"]
25mod listing;
26// Sessions dedup a peer's listings per broadcast; a custom session has no public owner yet.
27#[cfg(feature = "async")]
28pub(crate) use listing::Owner;
29pub use listing::{Kind, Listed, Lister, Tracks, TracksEvent};
30pub(super) use listing::{ListOnAccept, Unlist};
31
32/// A collection of media tracks that can be published and subscribed to.
33///
34/// Create via [`Info::produce`] to obtain both [`Producer`] and [`Consumer`] pair.
35/// This is the broadcast's static identity, fixed for its lifetime.
36#[derive(Clone, Debug)]
37#[non_exhaustive]
38pub struct Info {
39	/// The cache pool this broadcast's tracks and groups inherit.
40	pub pool: cache::Pool,
41
42	/// Local ceiling on each track's max age: how long a superseded group stays fresh here.
43	/// `None` imposes no ceiling.
44	pub cache_duration: Option<std::time::Duration>,
45
46	/// The path this broadcast is named by, which relative references in a catalog it
47	/// serves (hang's `broadcast` field) resolve against.
48	///
49	/// [`origin::Producer::route`](super::origin::Producer::route) stamps
50	/// the path the broadcast was created at, relative to the origin root (including through a
51	/// scoped producer). Every [`Consumer`] an origin hands out is then re-stamped with the path
52	/// *that handle* was requested or announced at, relative to its cursor's root, since the
53	/// same broadcast can be reached under more than one name: a dynamic handler may serve a
54	/// standalone broadcast at any path, and a rooted cursor names a broadcast more tightly
55	/// than the origin does.
56	///
57	/// Empty (the default) for a standalone broadcast with no origin, which is then its own
58	/// root: any `..` reference escapes.
59	pub path: crate::Path,
60
61	/// The identity of the route a [`Consumer`] was resolved through, naming the stream
62	/// it reads.
63	///
64	/// Stamped on every [`Consumer`] an origin resolves, like [`Self::path`]. `None` for a
65	/// handle not resolved through an origin.
66	pub identity: Option<crate::Identity>,
67
68	// What the frames this broadcast's groups are still receiving may allocate up front,
69	// inherited from the origin handle that created it.
70	pub(crate) frames: super::frame::Budget,
71
72	// What the live edges of this broadcast's tracks may hold, shared with the session
73	// ingesting it, inherited from the origin handle that created it.
74	pub(crate) edges: cache::Edges,
75}
76
77impl Default for Info {
78	fn default() -> Self {
79		Self {
80			pool: cache::Pool::new(cache::Config::default().with_expiry(cache::DEFAULT_EXPIRY)),
81			cache_duration: None,
82			path: crate::Path::default(),
83			identity: None,
84			frames: Default::default(),
85			edges: Default::default(),
86		}
87	}
88}
89
90impl Info {
91	/// Create a new broadcast with default metadata.
92	pub fn new() -> Self {
93		Self::default()
94	}
95
96	/// Consume this [Info] to create a producer that carries its metadata.
97	///
98	/// Keep the returned [`Producer`] alive for as long as the broadcast should stay
99	/// available, and end it with [`Producer::close`]. See the note on [`Producer`].
100	pub fn produce(self) -> Producer {
101		Producer::new(self)
102	}
103}
104
105#[derive(Default)]
106struct BroadcastState {
107	// Weak references for deduplication. Doesn't prevent track auto-close.
108	// Keyed by the track's shared `Arc<str>` name (the same Arc the handle holds) and its
109	// copy: a metadata copy is an entry apart from the payload one.
110	// The cache reclaims closed entries incrementally on insert so a long-lived
111	// broadcast churning distinct track names stays bounded by the live count.
112	tracks: WeakCache<track::Key, track::TrackWeak>,
113
114	// Shared across suffixes and producer clones; cache eviction must not reset IDs.
115	unique: u64,
116
117	// Pending requests keyed by track name, coalescing concurrent `track()` calls
118	// and waiting for a dynamic handler to accept or deny them. A request leaves
119	// here once handed out (the handler caches it in `tracks`, so lookups keep
120	// coalescing onto it there).
121	requests: RequestQueue<track::Key, track::Request>,
122
123	// The tracks the broadcast lists, and the readers listing them; see [`Tracks`].
124	listing: listing::ListingState,
125
126	// Set once the broadcast ends: `Producer::close()` or the last producer-side
127	// handle dropping. Every lookup after it answers `Unroutable`.
128	closing: bool,
129
130	// The tracks cached since each [`Demand`] handle last looked, by handle, so a
131	// handle watches each track once rather than rescanning the table.
132	demands: slab::Slab<Vec<track::TrackWeak>>,
133
134	// Datagram tracks, a namespace apart from stream tracks: published, requested, or
135	// served. Weak, so a closed entry is reclaimed like a track's.
136	datagrams: WeakCache<Arc<str>, datagram::Weak>,
137	// Datagram tracks consumers asked for, waiting for a [`DatagramRequests`] to take them.
138	datagram_requests: VecDeque<datagram::Request>,
139	// Live [`DatagramRequests`] handles; a datagram track is requested only while one lives.
140	datagram_handlers: usize,
141	// Set on an origin's front: datagram lookups go to the source it serves from, if any.
142	datagram_source: Option<Option<Consumer>>,
143	// A session's source, relaying a peer's broadcast; see [`Consumer::has_local_datagrams`].
144	relayed: bool,
145	// Whether its handler serves a metadata copy apart from the payload one; see
146	// [`Consumer::track_meta`].
147	meta: bool,
148}
149
150impl BroadcastState {
151	/// Insert a track weak handle into the lookup, returning false if a live track
152	/// already holds the name. A closed entry under the name is reclaimed.
153	fn insert_track(&mut self, weak: track::TrackWeak) -> bool {
154		self.cache_track(weak).is_none()
155	}
156
157	/// Mint a name no live track holds, as [`Producer::unique_name`] documents.
158	fn unique_name(&mut self, suffix: &str) -> String {
159		let separator = if suffix.starts_with(|c: char| c.is_ascii_digit()) {
160			"-"
161		} else {
162			""
163		};
164		loop {
165			let id = self.unique;
166			self.unique = id.checked_add(1).expect("unique track IDs exhausted");
167			let name = format!("{id}{separator}{suffix}");
168			if !self.tracks.contains_key(&track::Key::payload(name.as_str())) {
169				return name;
170			}
171		}
172	}
173
174	/// Cache a track under its name and hand it to every [`Demand`], unless a live track
175	/// already holds the name, which is returned instead.
176	fn cache_track(&mut self, weak: track::TrackWeak) -> Option<track::TrackWeak> {
177		if let Some(live) = self.tracks.insert(weak.key().clone(), weak.clone()) {
178			return Some(live);
179		}
180		for (_, cached) in &mut self.demands {
181			// A handle that stops polling must not pin every track it was handed. Headroom
182			// for as many tracks as survive defers the next scan until the inbox doubles,
183			// so a full inbox losing one track doesn't rescan it on every insert.
184			if cached.len() == cached.capacity() {
185				cached.retain(|track| !track.is_closed());
186				cached.reserve(cached.len());
187			}
188			cached.push(weak.clone());
189		}
190		None
191	}
192
193	/// Resolve every name the broadcast never filled, so subscribers waiting on a
194	/// [`track::Info`] that can no longer arrive fail with `err` instead of parking.
195	///
196	/// Covers a reservation nobody accepted and a request still queued for a handler.
197	/// A request a [`Requests`] already took is left alone: it may be in flight to a peer
198	/// still serving it, and the handler answers or drops it. So is a track that carries
199	/// its info: an end there is that publisher's call, and its cache stays readable.
200	fn reject_unserved(&mut self, err: Error) {
201		for request in self.requests.drain_queued() {
202			request.reject(err.clone());
203		}
204		for request in self.datagram_requests.drain(..) {
205			request.reject(err.clone());
206		}
207		self.datagram_source = None;
208		for track in self.tracks.iter() {
209			track.reject(err.clone());
210		}
211	}
212
213	/// End every listing, reporting each listed track whose producer declared its end as
214	/// finished, though that producer still holds it in the table.
215	fn close_listing(&mut self) {
216		let finished: HashSet<Arc<str>> = self
217			.tracks
218			.iter()
219			.filter(|track| !track.key().meta && track.is_finished())
220			.map(|track| track.name().clone())
221			.collect();
222		self.listing.close(|name| finished.contains(name));
223	}
224
225	/// The live track cached under `key`. Writing through the guard wakes every [`Demand`]
226	/// watcher, so only reclaiming a closed entry writes: a hit or a miss just reads.
227	fn live_track(state: &mut kio::Mut<'_, Self>, key: &track::Key) -> Option<track::TrackWeak> {
228		let live = state.tracks.get(key);
229		if live.is_none() && state.tracks.contains_key(key) {
230			state.tracks.remove(key);
231		}
232		live
233	}
234
235	/// The track serving `key` now, published or requested, read without joining its demand.
236	fn peek(state: &mut kio::Mut<'_, Self>, key: &track::Key) -> Option<kio::ConsumerPassive<track::TrackState>> {
237		if let Some(weak) = Self::live_track(state, key) {
238			return Some(weak.peek());
239		}
240		state.requests.get(key).map(|pending| pending.peek())
241	}
242
243	/// The entry a lookup of `name` reads: the metadata copy only where the handler serves
244	/// one apart, and the payload copy otherwise, whose headers a metadata reader takes.
245	fn key(&self, name: Arc<str>, meta: bool) -> track::Key {
246		track::Key {
247			name,
248			meta: meta && self.meta,
249		}
250	}
251}
252
253/// Manages tracks within a broadcast.
254///
255/// Create tracks up front with [Self::create_track], reserve a name to fill in
256/// later with [Self::reserve_track], or handle on-demand consumer requests via
257/// [Self::requests].
258///
259/// # Lifetime
260///
261/// A broadcast lives until [`Self::close`] or until the last [`Producer`] (or
262/// [`Requests`]) drops, whichever comes first; both end it the same way. A publisher
263/// whose input ended cleanly finishes its tracks first: a subscriber still catching up
264/// drains them after the close. Children
265/// do *not* keep it alive: cloning a [`Consumer`] or holding a [`track::Producer`]
266/// does nothing for the broadcast's lifetime.
267#[derive(Clone)]
268pub struct Producer {
269	// Held behind an Arc so each track born from this broadcast can inherit a shared
270	// handle (threaded down by [`Self::create_track`] / [`Self::reserve_track`]).
271	info: Arc<Info>,
272
273	// Broadcast liveness, shared with every `Requests`. Consumers watch it (read-only)
274	// for close; the guard ends the broadcast when the last of those handles drops.
275	alive: Arc<Alive>,
276
277	// Track registry plus the dynamic request queue, mutated by producers and
278	// consumers alike under one lock.
279	state: kio::Shared<BroadcastState>,
280
281	// Ingress stats scope, set by a tagged `origin::Producer` at
282	// `route`. Inherited by the tracks this producer creates. Empty
283	// (no-op) for an untagged broadcast.
284	stats: stats::Scope,
285}
286
287impl Producer {
288	/// Create a producer for the given broadcast metadata. Prefer [`Info::produce`].
289	pub fn new(info: Info) -> Self {
290		let state = kio::Shared::<BroadcastState>::default();
291		Self {
292			info: Arc::new(info),
293			alive: Alive::new(state.clone()),
294			state,
295			stats: stats::Scope::default(),
296		}
297	}
298
299	/// Attach an ingress stats scope, inherited by the tracks created on this
300	/// broadcast. Set by a tagged `origin::Producer` at `route`.
301	pub(super) fn with_stats(mut self, scope: stats::Scope) -> Self {
302		self.stats = scope;
303		self
304	}
305
306	/// Run `hook` once the broadcast closes: on [`Self::close`], an abort, or the last
307	/// producer-side handle dropping. Runs at once on a broadcast already closed. One hook
308	/// per broadcast: the route that owns it, which retracts when it closes.
309	pub(super) fn on_close(&self, hook: Box<dyn FnOnce() + Send>) {
310		{
311			let mut slot = self.alive.on_close.lock();
312			debug_assert!(slot.is_none(), "a close hook was already installed");
313			if !self.alive.state.lock().closing {
314				*slot = Some(hook);
315				return;
316			}
317		}
318		hook();
319	}
320
321	/// Serve metadata lookups ([`Consumer::track_meta`]) from a metadata copy apart from the
322	/// payload one, which this broadcast's [`Requests`] handler fills with frame headers
323	/// alone. Only a handler that can do so sets it: a lite-07 session, asking upstream with
324	/// a metadata subscription, or an origin front, splicing each copy from its routes.
325	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
326	pub(crate) fn serve_meta(&self) {
327		self.state.lock().meta = true;
328	}
329
330	/// Answer track requests only while `validity` holds, ending the broadcast once it
331	/// lapses. Set when a session mints a source, before any handle is shared.
332	pub(crate) fn with_validity(mut self, validity: RequestValidity) -> Self {
333		Arc::get_mut(&mut self.alive)
334			.expect("validity is set on a fresh broadcast")
335			.validity = validity;
336		self
337	}
338
339	/// The broadcast's static metadata, fixed when it was created.
340	pub fn info(&self) -> &Info {
341		&self.info
342	}
343
344	/// A watch-only handle to whether anyone reads the broadcast. See [`Demand`].
345	pub fn demand(&self) -> Demand {
346		Demand::new(self.alive.token.consume().passive(), self.state.clone())
347	}
348
349	/// Produce a new track and insert it into the broadcast, or `None` while a live track
350	/// holds the name.
351	///
352	/// A track whose last producer dropped while read keeps holding its name until the
353	/// broadcast's [`Requests`] handler answers the renewal. While the renewal is still queued,
354	/// this fulfils it when `info` is the one the track was first accepted with, and otherwise
355	/// replaces it, ending its readers with [`Error::MalformedTrack`](crate::Error::MalformedTrack)
356	/// as an accept with another info would. Once the handler took it, this returns `None`.
357	///
358	/// Pass a name and an optional [`track::Info`], so a bare name works:
359	/// `create_track("video", None)` creates an untimed track.
360	pub fn create_track(
361		&self,
362		name: impl Into<Arc<str>>,
363		info: impl Into<Option<track::Info>>,
364	) -> Option<track::Producer> {
365		// Fulfilling a pending request wakes its readers, who may be polled inline and look this
366		// broadcast up again: hold the wakes until the lock drops.
367		let _hold = kio::hold();
368		let (name, info) = (name.into(), info.into().unwrap_or_default());
369		let mut state = self.state.lock();
370		// A queued renewal this info would change is answered as its handler would answer it,
371		// ending the readers that hold the old info. Under the lock, so the name passes straight
372		// to the new track; the ended track's producer drops after it, since its last guard looks
373		// this broadcast up.
374		let key = track::Key::payload(name.clone());
375		let replaced = match state.requests.get(&key) {
376			Some(request) if request.conflicts(&info) => state
377				.requests
378				.take(&key)
379				.map(|request| request.unlisted().accept(info.clone())),
380			_ => None,
381		};
382		let track = self.insert_created(state, name, info);
383		drop(replaced);
384		track
385	}
386
387	fn insert_created(
388		&self,
389		mut state: kio::Mut<'_, BroadcastState>,
390		name: Arc<str>,
391		info: track::Info,
392	) -> Option<track::Producer> {
393		// A consumer may have requested this name before it existed (a live
394		// [`Requests`] queues such requests). Creating the track fulfills that
395		// request: its consumers resolve against this very producer. Without
396		// this they would be stranded, since the name is taken the moment the
397		// track exists, so no handler could ever serve their queue entry.
398		if let Some(request) = state.requests.take(&track::Key::payload(name.clone())) {
399			// Listed below, under the lock this holds, rather than by the accept.
400			let track = request
401				.unlisted()
402				.with_stats(self.stats.clone())
403				.homed(Home(self.state.clone()))
404				.accept(info.clone());
405			// Cache it like a served request so concurrent lookups coalesce. The
406			// only live same-name entry is the request's own track, as a renewal's.
407			let _ = state.cache_track(track.weak());
408			let unlist = Unlist::list(&self.state, &mut state.listing, name, Listed::Track(info));
409			return Some(track.listed(unlist));
410		}
411
412		let track = track::Producer::new(self.info.clone(), name.clone(), info.clone())
413			.with_stats(self.stats.clone())
414			.homed(Home(self.state.clone()));
415		if !state.insert_track(track.weak()) {
416			return None;
417		}
418		let unlist = Unlist::list(&self.state, &mut state.listing, name, Listed::Track(info));
419		Some(track.listed(unlist))
420	}
421
422	/// Produce a new datagram track and insert it into the broadcast, listed until it ends.
423	///
424	/// Datagram tracks are a namespace apart from stream tracks, so this never conflicts with
425	/// [`Self::create_track`]. Returns `None` while a live datagram track holds the name.
426	///
427	/// Moq-lite 05 and 06 carry it on its name's stream track subscriptions, but only those
428	/// that start once it exists: create it before, or with, a stream track of the same name.
429	/// See [`datagram`](crate::datagram).
430	pub fn create_datagrams(&self, name: impl Into<Arc<str>>, info: datagram::Info) -> Option<datagram::Producer> {
431		self.insert_datagrams(name.into(), info, true)
432	}
433
434	/// [`Self::create_datagrams`] for a track no listing ever names, as a session's datagram
435	/// track riding a stream track's subscription, which serves a request rather than the
436	/// broadcast's inventory.
437	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
438	pub(crate) fn create_unlisted_datagrams(
439		&self,
440		name: impl Into<Arc<str>>,
441		info: datagram::Info,
442	) -> Option<datagram::Producer> {
443		self.insert_datagrams(name.into(), info, false)
444	}
445
446	fn insert_datagrams(&self, name: Arc<str>, info: datagram::Info, listed: bool) -> Option<datagram::Producer> {
447		let mut state = self.state.lock();
448		let producer = match state.datagrams.get(name.as_ref()) {
449			Some(live) => {
450				// A consumer asked for it before it existed, and no handler took the request
451				// yet: creating the track serves those consumers.
452				let queued = state
453					.datagram_requests
454					.iter()
455					.position(|request| live.same_channel(&request.weak()));
456				let queued = queued?;
457				let request = state.datagram_requests.remove(queued).expect("found above");
458				request.with_stats(self.stats.clone()).accept(info)
459			}
460			None => {
461				let producer = datagram::Producer::new(name.clone(), Some(info)).with_stats(self.stats.clone());
462				state.datagrams.insert(name.clone(), producer.weak());
463				producer
464			}
465		};
466		if !listed {
467			return Some(producer);
468		}
469		let unlist = Unlist::list(&self.state, &mut state.listing, name, Listed::Datagrams(info));
470		Some(producer.listed(unlist))
471	}
472
473	/// Answer datagram lookups from `source`, the broadcast an origin's front serves from,
474	/// or refuse them with [`Error::Unroutable`] while it has none.
475	pub(super) fn serve_datagrams_from(&self, source: Option<Consumer>) {
476		self.state.lock().datagram_source = Some(source);
477	}
478
479	/// Reserve a track by name without finalizing its [`track::Info`], or `None` while a
480	/// live track holds the name.
481	///
482	/// Returns a [`track::Request`] already discoverable by consumers; call
483	/// [`track::Request::accept`] to set its info and start producing. Use this when
484	/// the producer can't pick the track's properties (e.g. timescale) until it has
485	/// inspected the media, the same shape as a consumer-driven
486	/// [`Requests::poll_requested_track`].
487	///
488	/// Subscribers wait on the name until it is accepted, so a reservation the producer
489	/// ends up never filling has to be dropped or rejected. Ending the broadcast
490	/// resolves whatever is left.
491	pub fn reserve_track(&self, name: impl Into<Arc<str>>) -> Option<track::Request> {
492		let name = name.into();
493		let mut state = self.state.lock();
494		let request = track::Request::new(self.info.clone(), name.clone())
495			.with_stats(self.stats.clone())
496			.homed(Home(self.state.clone()));
497		if !state.insert_track(request.weak()) {
498			return None;
499		}
500		Some(request.listed(ListOnAccept {
501			state: self.state.clone(),
502			name,
503		}))
504	}
505
506	/// [`Self::reserve_track`] for a track no listing ever names, so only a reader who
507	/// already knows the name finds it, such as a per-session track whose name the two
508	/// sides agreed on.
509	///
510	/// Unlisted controls discovery, not authorization: anyone allowed to subscribe to the
511	/// broadcast can read the track by name.
512	pub fn reserve_unlisted_track(&self, name: impl Into<Arc<str>>) -> Option<track::Request> {
513		let mut state = self.state.lock();
514		let request = track::Request::new(self.info.clone(), name.into())
515			.with_stats(self.stats.clone())
516			.homed(Home(self.state.clone()));
517		state.insert_track(request.weak()).then_some(request)
518	}
519
520	/// Create a track with a unique name using the given suffix.
521	///
522	/// Uses [`Self::unique_name`]; minted names are never reused, even after closure.
523	pub fn unique_track(&self, suffix: &str, info: impl Into<Option<track::Info>>) -> track::Producer {
524		// A consumer may already have requested the minted name: hold the wakes as
525		// `create_track` does.
526		let _hold = kio::hold();
527		let mut state = self.state.lock();
528		let name = state.unique_name(suffix);
529		// Minted under the same lock, so no live track can hold the name.
530		self.insert_created(state, name.into(), info.into().unwrap_or_default())
531			.expect("a minted name is free")
532	}
533
534	/// Generate a unique track name from a suffix without creating the track.
535	///
536	/// Returns `{id}{suffix}` with an increasing ID shared across all suffixes and
537	/// producer clones in this broadcast, skipping names already in the lookup.
538	/// A digit-leading suffix gets a `-` separator so it cannot be confused with the ID.
539	/// Minted names are never reused, even if no track is created or it is closed.
540	/// Explicit calls to [`Self::create_track`] can still reuse names.
541	///
542	/// # Panics
543	///
544	/// Panics if the broadcast exhausts its `u64` IDs.
545	pub fn unique_name(&self, suffix: &str) -> String {
546		self.state.lock().unique_name(suffix)
547	}
548
549	/// Create a dynamic producer that handles on-demand track requests from consumers.
550	pub fn requests(&self) -> Requests {
551		Requests::new(
552			self.info.clone(),
553			self.alive.clone(),
554			self.state.clone(),
555			self.stats.clone(),
556		)
557	}
558
559	/// Create a consumer of this one publisher's broadcast.
560	///
561	/// A view of this broadcast object, not of its path: a new publisher at the same
562	/// path never feeds it, so it ends when this broadcast does. Go through
563	/// an origin for a consumer that should not care which publisher serves the path.
564	pub fn consume(&self) -> Consumer {
565		Consumer {
566			info: self.info.clone(),
567			alive: self.alive.token.consume(),
568			state: self.state.clone(),
569			stats: stats::Scope::default(),
570		}
571	}
572
573	/// End the broadcast for good, whether or not other clones are still alive.
574	///
575	/// Retracts its announcement and local discovery; a later [`super::origin::Route::announce`] fails
576	/// with [`Error::Closed`]. Tracks already handed out carry on and end with their
577	/// own finish or abort. Every later [`Consumer::track`], and every name reserved or
578	/// still queued for a handler, answers [`Error::Unroutable`]: the same answer an
579	/// origin gives for a path nobody publishes. A request a [`Requests`] already took is
580	/// left for that handler to answer.
581	///
582	/// Dropping the last producer does the same. Closing twice is a no-op.
583	pub fn close(&self) {
584		self.alive.close();
585	}
586
587	/// Whether any [`Consumer`] handle exists, which is not itself demand for a track.
588	pub(super) fn is_held(&self) -> bool {
589		self.alive.token.wanted()
590	}
591
592	/// `Ready(Ok)` once a [`Consumer`] handle exists, `Ready(Err)` once the broadcast ended.
593	pub(super) fn poll_held(&self, waiter: &kio::Waiter) -> Poll<Result<(), kio::Closed>> {
594		self.alive.token.poll_wanted_changed(waiter, false).map_ok(drop)
595	}
596
597	/// `Ready(Ok)` once no [`Consumer`] handle is left, `Ready(Err)` once the broadcast ended.
598	pub(crate) fn poll_unheld(&self, waiter: &kio::Waiter) -> Poll<Result<(), kio::Closed>> {
599		self.alive.token.poll_wanted_changed(waiter, true).map_ok(drop)
600	}
601
602	/// [`Self::close`], unless a [`Consumer`] holds the broadcast or a track it asked for
603	/// still waits for a handler. Atomic with minting a consumer, so a holder either keeps
604	/// the broadcast or only ever sees it closed. Returns whether the broadcast is closed.
605	pub(crate) fn close_unheld(&self) -> bool {
606		self.alive.close_unheld()
607	}
608
609	/// Return true if this is the same broadcast identity.
610	pub fn is_clone(&self, other: &Self) -> bool {
611		self.state.is_clone(&other.state)
612	}
613}
614
615/// Ends the broadcast on [`Producer::close`] or when the last [`Producer`] or
616/// [`Requests`] drops, closing the liveness channel every [`Consumer`] watches.
617///
618/// A refcount rather than a "am I the last one?" check inside `Drop`: that answer is
619/// a snapshot, and acting on it is exactly what invalidates it.
620struct Alive {
621	token: kio::Producer<()>,
622	state: kio::Shared<BroadcastState>,
623	// Run once the broadcast ends: on close or the last producer-side handle dropping.
624	// The route owning the broadcast retracts through it. `None` for a standalone broadcast.
625	on_close: kio::Lock<Option<Box<dyn FnOnce() + Send>>>,
626	// How long a session's source still names the identity that minted it. Held on the
627	// producer side, never by a consumer, so the selection it may hold is dropped by its
628	// session rather than wherever the last consumer goes.
629	validity: RequestValidity,
630}
631
632impl Alive {
633	fn new(state: kio::Shared<BroadcastState>) -> Arc<Self> {
634		Arc::new(Self {
635			token: kio::Producer::default(),
636			state,
637			on_close: kio::Lock::new(None),
638			validity: RequestValidity::default(),
639		})
640	}
641
642	/// End the broadcast. See [`Producer::close`].
643	fn close(&self) {
644		{
645			let mut state = self.state.lock();
646			if std::mem::replace(&mut state.closing, true) {
647				return;
648			}
649			// A name that was reserved or queued but never served can't arrive now,
650			// and `Consumer::track` answers `Unroutable` for one asked about after this
651			// point. Say the same to whoever asked earlier.
652			state.reject_unserved(Error::Unroutable);
653			state.close_listing();
654		}
655		let _ = self.token.close();
656		self.retract();
657	}
658
659	/// See [`Producer::close_unheld`].
660	fn close_unheld(&self) -> bool {
661		let token = {
662			let mut state = self.state.lock();
663			if state.closing {
664				return true;
665			}
666			// A queued track is a reader on its way that let go of its handle.
667			if !state.requests.is_empty() || !state.datagram_requests.is_empty() {
668				return false;
669			}
670			// Held under the lock a consumer's first mint takes, so none appears until the
671			// close below lands.
672			let token = match self.token.write_unwanted() {
673				kio::Unwanted::Idle(token) => token,
674				kio::Unwanted::Wanted => return false,
675				kio::Unwanted::Closed => return true,
676			};
677			state.closing = true;
678			state.reject_unserved(Error::Unroutable);
679			state.close_listing();
680			token
681		};
682		token.close();
683		self.retract();
684		true
685	}
686
687	/// Run the close hook, if any. Outside the hook's lock: the route's retraction
688	/// re-syncs the origin's cursors under the origin's own lock.
689	fn retract(&self) {
690		let hook = self.on_close.lock().take();
691		if let Some(hook) = hook {
692			hook();
693		}
694	}
695}
696
697impl Drop for Alive {
698	fn drop(&mut self) {
699		self.close();
700	}
701}
702
703/// Whether a path request still names the source that handed out its track.
704#[derive(Clone, Default)]
705#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
706pub(crate) enum RequestValidity {
707	#[default]
708	Unrestricted,
709	Route(kio::Consumer<()>),
710	Selected(std::sync::Arc<crate::model::origin_impl::Selection>),
711	/// One period of a selection and its answering lease, captured by [`Self::start`].
712	Period(
713		kio::Consumer<()>,
714		kio::Consumer<()>,
715		// Keeps the selection registered, which is what keeps the two periods open.
716		#[expect(dead_code, reason = "held only for its registration")]
717		std::sync::Arc<crate::model::origin_impl::Selection>,
718	),
719}
720
721impl RequestValidity {
722	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
723	pub(crate) fn token(route: Option<kio::Consumer<()>>) -> Self {
724		route.map(Self::Route).unwrap_or_default()
725	}
726
727	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
728	pub(crate) fn for_source(route: &crate::origin::Claim, path: &crate::Path) -> Self {
729		route
730			.request_validity(path)
731			.map(|selected| Self::Selected(std::sync::Arc::new(selected)))
732			.unwrap_or_else(|| Self::Route(kio::Producer::new(()).consume()))
733	}
734
735	/// Capture one selection period so a pending request never revives after a replacement.
736	pub(crate) fn start(&self) -> Self {
737		match self {
738			Self::Selected(selected) => Self::Period(selected.current(), selected.answering(), selected.clone()),
739			other => other.clone(),
740		}
741	}
742
743	pub(crate) fn check(&self, waiter: &kio::Waiter) -> Result<(), crate::Error> {
744		match self {
745			Self::Route(route) if route.poll_closed(waiter).is_ready() => Err(crate::Error::Unroutable),
746			Self::Period(route, _, _) if route.poll_closed(waiter).is_ready() => Err(crate::Error::Unroutable),
747			Self::Selected(_) => self.start().check(waiter),
748			_ => Ok(()),
749		}
750	}
751
752	/// [`Self::check`] for a request already sent but not yet answered: only another
753	/// identity taking the path refuses it. A withdrawal leaves it to its answer, as
754	/// moq-lite has the publisher conclude in-flight requests.
755	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
756	pub(crate) fn check_unanswered(&self, waiter: &kio::Waiter) -> Result<(), crate::Error> {
757		match self {
758			Self::Period(_, answering, _) if answering.poll_closed(waiter).is_ready() => Err(crate::Error::Unroutable),
759			Self::Selected(_) => self.start().check_unanswered(waiter),
760			_ => Ok(()),
761		}
762	}
763}
764
765#[cfg(test)]
766#[expect(missing_docs, reason = "test-only assertion helpers")]
767impl Producer {
768	pub fn assert_create_track(
769		&mut self,
770		name: impl Into<Arc<str>>,
771		info: impl Into<Option<track::Info>>,
772	) -> track::Producer {
773		self.create_track(name, info).expect("should not have errored")
774	}
775}
776
777/// A session-owned source broadcast, closed on drop even while the session's
778/// serve machines still hold its [`Requests`].
779///
780/// A peer's retraction and a dead session end the source the same way: a broadcast
781/// carries no end cause past this hop. Shared by the lite and IETF subscribers.
782#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
783pub(crate) struct SourceGuard(Producer);
784
785impl SourceGuard {
786	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
787	pub fn new(producer: Producer) -> Self {
788		producer.state.lock().relayed = true;
789		Self(producer)
790	}
791}
792
793impl std::ops::Deref for SourceGuard {
794	type Target = Producer;
795
796	fn deref(&self) -> &Producer {
797		&self.0
798	}
799}
800
801impl Drop for SourceGuard {
802	fn drop(&mut self) {
803		self.0.close();
804	}
805}
806
807/// Handles on-demand track creation for a broadcast.
808///
809/// When a consumer requests a track that doesn't exist, the dynamic producer
810/// picks up the request via [`Self::poll_requested_track`] and either
811/// [`track::Request::accept`]s it with a concrete [`track::Info`] or
812/// [`track::Request::reject`]s it. Dropped when no longer needed; pending requests
813/// are automatically aborted.
814#[derive(Clone)]
815pub struct Requests {
816	info: Arc<Info>,
817	// Keeps the broadcast alive while a handler exists (mirrors a producer).
818	alive: Arc<Alive>,
819	state: kio::Shared<BroadcastState>,
820	// Ingress stats scope, applied to the tracks this handler serves. Empty (no-op)
821	// for an untagged broadcast.
822	stats: stats::Scope,
823	// Declared after `alive` so it drops second: when this was the broadcast's last
824	// handle, `Alive` has already ended it and answered every queued request
825	// `Unroutable`, so the handler's own `Dropped` rejection finds nothing left.
826	_handler: Handler,
827}
828
829/// Counts one live [`Requests`], rejecting the queued requests when the last one drops.
830struct Handler(kio::Shared<BroadcastState>);
831
832impl Handler {
833	fn new(state: kio::Shared<BroadcastState>) -> Self {
834		state.lock().requests.add_handler();
835		Self(state)
836	}
837}
838
839impl Clone for Handler {
840	fn clone(&self) -> Self {
841		// Count each live handle, or dropping a clone would flip the handler count to
842		// zero and future `track` calls would return `NotFound`.
843		Self::new(self.0.clone())
844	}
845}
846
847impl Drop for Handler {
848	fn drop(&mut self) {
849		// Decrement and reject under one lock, so a `track` call that saw a live
850		// handler through the same lock can't slip a request past the rejection.
851		let mut state = self.0.lock();
852		if state.requests.remove_handler() {
853			// No handlers left to fulfill pending requests; reject them so consumers
854			// don't block forever on tracks nobody will serve.
855			for request in state.requests.drain_queued() {
856				request.reject(Error::Dropped);
857			}
858		}
859	}
860}
861
862/// The broadcast a track was created or requested in, through which a track its last
863/// producer left while readers still want it is requested again.
864#[derive(Clone)]
865pub(super) struct Home(kio::Shared<BroadcastState>);
866
867impl Home {
868	/// Whether a request queued now would reach a handler: the broadcast is open and one is live.
869	pub(super) fn serves(&self) -> bool {
870		let state = self.0.read();
871		!state.closing && state.requests.has_handlers()
872	}
873
874	/// List `name` again once its request is accepted.
875	pub(super) fn list_on_accept(&self, name: Arc<str>) -> ListOnAccept {
876		ListOnAccept {
877			state: self.0.clone(),
878			name,
879		}
880	}
881
882	/// Queue `request` for a [`Requests`] to serve, as a lookup of its name would, handing it
883	/// back when none can: the broadcast ended, no handler is alive, or another track or
884	/// request holds the name.
885	#[cfg_attr(
886		target_pointer_width = "64",
887		expect(
888			clippy::result_large_err,
889			reason = "hand the request back to end its readers without allocating"
890		)
891	)]
892	pub(super) fn request(&self, request: track::Request) -> Result<(), track::Request> {
893		let mut state = self.0.lock();
894		let weak = request.weak();
895		if state.closing
896			|| state.requests.join(weak.key()).is_some()
897			|| state
898				.tracks
899				.get(weak.key())
900				.is_some_and(|live| !live.same_channel(&weak))
901		{
902			return Err(request);
903		}
904		state.requests.insert(weak.key().clone(), request)
905	}
906}
907
908impl Requests {
909	fn new(info: Arc<Info>, alive: Arc<Alive>, state: kio::Shared<BroadcastState>, stats: stats::Scope) -> Self {
910		Self {
911			info,
912			alive,
913			_handler: Handler::new(state.clone()),
914			state,
915			stats,
916		}
917	}
918
919	/// The broadcast's static metadata, fixed when it was created.
920	pub fn info(&self) -> &Info {
921		&self.info
922	}
923
924	/// The next track a consumer requests, as a [`track::Request`] to serve.
925	///
926	/// Returns [`Error::Closed`] once the broadcast has ended, so a serving loop
927	/// knows to stop and release its handle.
928	#[cfg_attr(feature = "async", kio::wrapper)]
929	pub fn poll_requested_track(&mut self, waiter: &kio::Waiter) -> Poll<Result<track::Request, Error>> {
930		// A source that no longer names the identity that minted it takes no new track:
931		// ending it refuses what is queued with `Unroutable`, while the tracks it handed
932		// out run on. Checked outside the broadcast lock, since the selection reads the origin.
933		if self.alive.validity.check(waiter).is_err() {
934			self.alive.close();
935		}
936		let mut state = ready!(self.state.poll(waiter, |state| {
937			if state.requests.has_queued() || state.closing {
938				Poll::Ready(())
939			} else {
940				Poll::Pending
941			}
942		}));
943
944		if state.closing && !state.requests.has_queued() {
945			return Poll::Ready(Err(Error::Closed));
946		}
947
948		let name = state.requests.pop().expect("predicate guaranteed a request");
949		let pending = state.requests.remove(&name).expect("popped key must be pending");
950		// Cache the served track so concurrent lookups coalesce onto it. If a live track already
951		// holds the name (a publish raced the request), `insert` keeps it rather than shadowing it.
952		let _ = state.cache_track(pending.weak());
953		// Claimed after the lock is released, since claiming wakes the track's subscribers
954		// and an inline executor can re-enter the broadcast from that wake. A close landing
955		// in between rejects the request, as it would one still queued.
956		drop(state);
957		// Attribute the served track to this broadcast's ingress scope (no-op untagged).
958		Poll::Ready(Ok(pending.claim().with_stats(self.stats.clone())))
959	}
960
961	/// Create a consumer that can subscribe to tracks in this broadcast.
962	pub fn consume(&self) -> Consumer {
963		Consumer {
964			info: self.info.clone(),
965			alive: self.alive.token.consume(),
966			state: self.state.clone(),
967			stats: stats::Scope::default(),
968		}
969	}
970
971	/// What a request to the peer for this source must still hold when it goes out, for
972	/// an operation on a track the source already handed out.
973	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
974	pub(crate) fn validity(&self) -> &RequestValidity {
975		&self.alive.validity
976	}
977
978	/// A handler for the datagram tracks consumers ask for. Until one exists, asking for a
979	/// datagram track nothing publishes fails with [`Error::NotFound`].
980	pub fn datagrams(&self) -> DatagramRequests {
981		DatagramRequests::new(self.alive.clone(), self.state.clone(), self.stats.clone())
982	}
983
984	/// Answer the broadcast's track listings, for a handler that knows the tracks it
985	/// would serve, such as a relay listing its upstream's. See [`Lister`].
986	///
987	/// A handler that serves any name on request takes none, so it lists nothing. One
988	/// answer per broadcast: fails with [`Error::Duplicate`] while another lister exists.
989	pub fn lister(&self) -> Result<Lister, Error> {
990		Lister::new(self.state.clone())
991	}
992
993	/// Resolves once the broadcast ends, by [`Producer::close`] or every producer dropping.
994	#[cfg_attr(feature = "async", kio::wrapper)]
995	pub fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<()> {
996		self.alive.token.poll_closed(waiter)
997	}
998
999	/// Return true if this is the same broadcast identity.
1000	pub fn is_clone(&self, other: &Self) -> bool {
1001		self.state.is_clone(&other.state)
1002	}
1003}
1004
1005/// Handles on-demand datagram tracks for a broadcast, like [`Requests`] does stream tracks.
1006///
1007/// Created by [`Requests::datagrams`]. When the last handle drops, the requests it never
1008/// took are rejected with [`Error::Dropped`].
1009pub struct DatagramRequests {
1010	// Keeps the broadcast alive while a handler exists, as `Requests` does.
1011	alive: Arc<Alive>,
1012	state: kio::Shared<BroadcastState>,
1013	stats: stats::Scope,
1014}
1015
1016impl DatagramRequests {
1017	fn new(alive: Arc<Alive>, state: kio::Shared<BroadcastState>, stats: stats::Scope) -> Self {
1018		state.lock().datagram_handlers += 1;
1019		Self { alive, state, stats }
1020	}
1021
1022	/// The next datagram track a consumer asks for, to accept or reject.
1023	///
1024	/// Returns [`Error::Closed`] once the broadcast has ended.
1025	#[cfg_attr(feature = "async", kio::wrapper)]
1026	pub fn poll_requested(&mut self, waiter: &kio::Waiter) -> Poll<Result<datagram::Request, Error>> {
1027		if self.alive.validity.check(waiter).is_err() {
1028			self.alive.close();
1029		}
1030		let mut state = ready!(self.state.poll(waiter, |state| {
1031			match !state.datagram_requests.is_empty() || state.closing {
1032				true => Poll::Ready(()),
1033				false => Poll::Pending,
1034			}
1035		}));
1036		match state.datagram_requests.pop_front() {
1037			Some(request) => Poll::Ready(Ok(request.with_stats(self.stats.clone()))),
1038			None => Poll::Ready(Err(Error::Closed)),
1039		}
1040	}
1041}
1042
1043impl Clone for DatagramRequests {
1044	fn clone(&self) -> Self {
1045		Self::new(self.alive.clone(), self.state.clone(), self.stats.clone())
1046	}
1047}
1048
1049impl Drop for DatagramRequests {
1050	fn drop(&mut self) {
1051		let mut state = self.state.lock();
1052		state.datagram_handlers -= 1;
1053		if state.datagram_handlers == 0 {
1054			for request in state.datagram_requests.drain(..) {
1055				request.reject(Error::Dropped);
1056			}
1057		}
1058	}
1059}
1060
1061#[cfg(test)]
1062use futures::FutureExt;
1063
1064#[cfg(test)]
1065#[expect(missing_docs, reason = "test-only assertion helpers")]
1066impl Requests {
1067	pub fn assert_request(&mut self) -> track::Request {
1068		kio::wait(|waiter| self.poll_requested_track(waiter))
1069			.now_or_never()
1070			.expect("should not have blocked")
1071			.expect("should not have errored")
1072	}
1073
1074	pub fn assert_no_request(&mut self) {
1075		assert!(
1076			kio::wait(|waiter| self.poll_requested_track(waiter))
1077				.now_or_never()
1078				.is_none(),
1079			"should have blocked"
1080		);
1081	}
1082}
1083
1084/// Subscribe to arbitrary broadcast/tracks.
1085///
1086/// Its close signal means this broadcast object ended, not that the path went
1087/// offline: announcements say whether a path is live, and a new publisher may
1088/// announce the same path again.
1089pub struct Consumer {
1090	info: Arc<Info>,
1091	// Broadcast liveness (read-only): watched for close.
1092	alive: kio::Consumer<()>,
1093	// Track registry plus request queue; a track handle's requests read the registry and enqueue.
1094	state: kio::Shared<BroadcastState>,
1095	// Egress stats scope, set by a tagged `origin::Consumer` at the broadcast
1096	// handoff. Inherited by the tracks subscribed through this handle. Empty (no-op)
1097	// for an untagged broadcast.
1098	stats: stats::Scope,
1099}
1100
1101impl Clone for Consumer {
1102	fn clone(&self) -> Self {
1103		Self {
1104			info: self.info.clone(),
1105			alive: self.alive.clone(),
1106			state: self.state.clone(),
1107			stats: self.stats.clone(),
1108		}
1109	}
1110}
1111
1112impl Consumer {
1113	/// Attach an egress stats scope, inherited by the tracks subscribed through this
1114	/// handle. Set by a tagged `origin::Consumer` at the broadcast handoff.
1115	pub(super) fn with_stats(mut self, scope: stats::Scope) -> Self {
1116		self.stats = scope;
1117		self
1118	}
1119
1120	/// Stamp the path this handle was handed out at, overriding [`Info::path`].
1121	///
1122	/// The origin applies it to every broadcast it resolves, because the name belongs to
1123	/// the (broadcast, cursor) pair rather than to the broadcast: what a catalog's relative
1124	/// references resolve against is where the *reader* found the broadcast, not where its
1125	/// producer happened to create it. Free when the two already agree, which is the case
1126	/// for a broadcast created at the path an unrooted cursor asks for.
1127	pub(super) fn with_path(mut self, path: crate::Path) -> Self {
1128		if self.info.path != path {
1129			let mut info = (*self.info).clone();
1130			info.path = path;
1131			self.info = Arc::new(info);
1132		}
1133		self
1134	}
1135
1136	/// Stamp the identity of the route this handle was resolved through, overriding
1137	/// [`Info::identity`].
1138	pub(super) fn with_identity(mut self, identity: Option<crate::Identity>) -> Self {
1139		if self.info.identity != identity {
1140			let mut info = (*self.info).clone();
1141			info.identity = identity;
1142			self.info = Arc::new(info);
1143		}
1144		self
1145	}
1146
1147	/// The broadcast's metadata, as reached through this handle.
1148	pub fn info(&self) -> &Info {
1149		&self.info
1150	}
1151
1152	/// Get a lazy handle to a track on this broadcast.
1153	///
1154	/// Nothing is requested until the handle queries, subscribes, or fetches, each of
1155	/// which looks the name up again. Fails with [`Error::Unroutable`] once the broadcast
1156	/// has ended, and [`Error::NotFound`] when nothing publishes the track and no
1157	/// [`Requests`] would serve a request for it.
1158	pub fn track(&self, name: &str) -> Result<track::Consumer, Error> {
1159		self.lookup(name, false)
1160	}
1161
1162	/// Get a lazy handle to a track's metadata: its groups and each frame's header, without
1163	/// the payload. See [`meta`](crate::meta).
1164	///
1165	/// Fails as [`Self::track`] does.
1166	pub fn meta(&self, name: &str) -> Result<crate::meta::Consumer, Error> {
1167		self.track_meta(name).map(crate::meta::Consumer::new)
1168	}
1169
1170	/// [`Self::track`] for what a metadata subscription reads: the metadata copy where the
1171	/// broadcast's handler serves one apart, as a lite-07 session does with a metadata
1172	/// subscription upstream, and otherwise the payload copy, whose headers the reader takes.
1173	pub(crate) fn track_meta(&self, name: &str) -> Result<track::Consumer, Error> {
1174		self.lookup(name, true)
1175	}
1176
1177	fn lookup(&self, name: &str, meta: bool) -> Result<track::Consumer, Error> {
1178		let (key, current) = {
1179			let mut state = self.state.lock();
1180			// An ended broadcast serves nothing new, not even a track it still has:
1181			// the lookup answers what a fresh `request` for the path would.
1182			// Tracks already handed out are untouched.
1183			if state.closing {
1184				return Err(Error::Unroutable);
1185			}
1186			let key = state.key(name.into(), meta);
1187			let current = BroadcastState::peek(&mut state, &key);
1188			if current.is_none() && !state.requests.has_handlers() {
1189				return Err(Error::NotFound);
1190			}
1191			(key, current)
1192		};
1193		// Bound to *this* handle's view of the broadcast, so a catalog track resolves its
1194		// relative references against the path we were handed out at rather than the one
1195		// the producer was created at, and tagged with this broadcast's egress scope so its
1196		// subscriptions, fetches, and groups are attributed to the same broadcast.
1197		Ok(track::Consumer::lookup(key, self.info.clone(), self.clone(), current).with_stats(self.stats.clone()))
1198	}
1199
1200	/// Consume the datagram track `name`, live from now.
1201	///
1202	/// Joins the track a producer publishes, or asks a [`DatagramRequests`] handler for it,
1203	/// whose answer the consumer reads. Fails with [`Error::Unroutable`] once the broadcast
1204	/// has ended, and [`Error::NotFound`] when nothing publishes the track and no handler
1205	/// would serve a request for it.
1206	pub fn datagrams(&self, name: &str) -> Result<datagram::Consumer, Error> {
1207		let mut state = self.state.lock();
1208		if state.closing {
1209			return Err(Error::Unroutable);
1210		}
1211		if let Some(source) = &state.datagram_source {
1212			let source = source.clone().ok_or(Error::Unroutable)?;
1213			drop(state);
1214			return Ok(source.datagrams(name)?.with_stats(self.stats.clone()));
1215		}
1216		if let Some(live) = state.datagrams.get(name)
1217			&& let Some(consumer) = live.try_consume(self.stats.clone())
1218		{
1219			return Ok(consumer);
1220		}
1221		if state.datagram_handlers == 0 {
1222			return Err(Error::NotFound);
1223		}
1224		let request = datagram::Request::new(name.into());
1225		let consumer = request
1226			.weak()
1227			.try_consume(self.stats.clone())
1228			.expect("a fresh request is open");
1229		state.datagrams.insert(name.into(), request.weak());
1230		// Requests their readers left are withdrawn, so the queue holds only what someone
1231		// still waits for, however long a handler goes without taking any.
1232		state.datagram_requests.retain(|queued| !queued.is_closed());
1233		state.datagram_requests.push_back(request);
1234		Ok(consumer)
1235	}
1236
1237	/// Join the datagram track `name` if one is published or already asked for, asking no
1238	/// handler for it otherwise. The reader adds no demand until `set_priority` is called:
1239	/// an existing stream subscription already carries this forwarding work.
1240	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1241	pub(crate) fn datagrams_live(&self, name: &str) -> Option<datagram::Consumer> {
1242		let state = self.state.lock();
1243		if state.closing {
1244			return None;
1245		}
1246		if let Some(source) = &state.datagram_source {
1247			let source = source.clone()?;
1248			drop(state);
1249			return Some(source.datagrams_live(name)?.with_stats(self.stats.clone()));
1250		}
1251		state.datagrams.get(name)?.observe(self.stats.clone())
1252	}
1253
1254	/// Whether datagram lookups reach a local producer or handler, rather than a session that
1255	/// relays a peer's broadcast, here or at the source an origin serves this broadcast from.
1256	///
1257	/// A session always answers a lookup, and a moq-lite 05/06 one subscribes to the stream
1258	/// track of the same name to answer one, so a lite-05/06 publisher only asks a local one
1259	/// for a name's datagram track before its stream track answers.
1260	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1261	pub(crate) fn has_local_datagrams(&self) -> bool {
1262		let state = self.state.lock();
1263		match &state.datagram_source {
1264			Some(Some(source)) => {
1265				let source = source.clone();
1266				drop(state);
1267				source.has_local_datagrams()
1268			}
1269			Some(None) => false,
1270			None => !state.relayed,
1271		}
1272	}
1273
1274	/// Whether a producer serves the stream track `name`, here or at the source an origin
1275	/// serves this broadcast from, rather than a request still waiting for an answer.
1276	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1277	pub(crate) fn publishes_track(&self, name: &str) -> bool {
1278		let mut state = self.state.lock();
1279		if BroadcastState::live_track(&mut state, &track::Key::payload(name)).is_some_and(|live| live.minted()) {
1280			return true;
1281		}
1282		let Some(Some(source)) = state.datagram_source.clone() else {
1283			return false;
1284		};
1285		drop(state);
1286		source.publishes_track(name)
1287	}
1288
1289	/// Join the demand of the track serving `name`, requesting it from a [`Requests`]
1290	/// when nothing serves it yet. Registers the subscription before exposing demand.
1291	/// Errors as [`Self::track`] does.
1292	pub(super) fn resolve_track(
1293		&self,
1294		key: &track::Key,
1295		subscription: Option<&track::Subscription>,
1296	) -> Result<(kio::Consumer<track::TrackState>, Option<track::Preferences>), Error> {
1297		let mut state = loop {
1298			let mut state = self.state.lock();
1299
1300			if state.closing {
1301				return Err(Error::Unroutable);
1302			}
1303
1304			// Reuse a live producer if one is already publishing the track. A closed entry
1305			// is reclaimed and we fall through to a fresh request.
1306			let Some(weak) = BroadcastState::live_track(&mut state, key) else {
1307				break state;
1308			};
1309			// Join outside the lock: the subscription and the first consumer wake the
1310			// serving session, which may re-enter this broadcast. The track's own lock
1311			// still orders the join against its idle teardown.
1312			drop(state);
1313			if let Some(resolved) = weak.try_consume(subscription) {
1314				return Ok(resolved);
1315			}
1316			// It closed between the liveness probe and the count bump (an idle teardown
1317			// committing under us). Look again: `live_track` reclaims it and the track is
1318			// requested again, rather than handing back a consumer of a dead track.
1319		};
1320
1321		if let Some(pending) = state.requests.join(key) {
1322			// Coalesce onto a queued request for the same name. Joining under the lock
1323			// wakes no subscription observer: only a handler that popped the request
1324			// can watch its subscriptions, and popping moves it to `tracks`.
1325			return Ok(pending.join(subscription));
1326		}
1327
1328		// Allocate the name once and share the same Arc across the request, the
1329		// requests map, and the FIFO order. The request inherits the broadcast's
1330		// cache pool through its `Arc<Info>`, same as a producer-created track.
1331		let request = track::Request::new(self.info.clone(), key.clone()).homed(Home(self.state.clone()));
1332		let resolved = request.join(subscription);
1333
1334		// With no handler alive to serve it, the request is dropped: `NotFound` beats
1335		// handing back a consumer that would only resolve `Dropped`.
1336		if state.requests.insert(key.clone(), request).is_err() {
1337			return Err(Error::NotFound);
1338		}
1339
1340		Ok(resolved)
1341	}
1342
1343	/// Read the track serving `name` now, without joining its demand or requesting it.
1344	/// Once the broadcast has ended, `ended` stands in for a track it no longer serves.
1345	pub(super) fn peek_track(
1346		&self,
1347		key: &track::Key,
1348		ended: Option<&kio::ConsumerPassive<track::TrackState>>,
1349	) -> Option<kio::ConsumerPassive<track::TrackState>> {
1350		let mut state = self.state.lock();
1351		BroadcastState::peek(&mut state, key).or_else(|| ended.filter(|_| state.closing).cloned())
1352	}
1353
1354	/// Returns true once the broadcast has ended.
1355	pub fn is_closed(&self) -> bool {
1356		self.alive.is_closed()
1357	}
1358
1359	/// Whether the broadcast has ended, observed under the state lock. The origin's
1360	/// dispatcher treats a rejection from such a source as imminent detach rather
1361	/// than a strike.
1362	pub(super) fn is_closing(&self) -> bool {
1363		self.state.read().closing
1364	}
1365
1366	/// Resolves once the broadcast ends, by [`Producer::close`] or every producer dropping.
1367	///
1368	/// The poll composes close-detection into a larger one without spawning a task
1369	/// per broadcast.
1370	#[cfg_attr(feature = "async", kio::wrapper)]
1371	pub fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<()> {
1372		self.alive.poll_closed(waiter)
1373	}
1374
1375	/// Check if this is the exact same identity of a broadcast.
1376	pub fn is_clone(&self, other: &Self) -> bool {
1377		self.state.is_clone(&other.state)
1378	}
1379
1380	/// Create a weak reference that doesn't keep the broadcast alive.
1381	///
1382	/// Used to deduplicate dynamically-served broadcasts in the origin: a live weak yields
1383	/// a shared clone, a closed one is discarded so the next request re-serves.
1384	pub(super) fn weak(&self) -> WeakConsumer {
1385		WeakConsumer {
1386			info: self.info.clone(),
1387			alive: self.alive.passive(),
1388			state: self.state.clone(),
1389		}
1390	}
1391}
1392
1393/// A weak reference to a broadcast that doesn't prevent it from closing.
1394///
1395/// Mirrors [`track::TrackWeak`]: held by the origin's dynamic cache to share one
1396/// dynamically-served broadcast across repeat requests without pinning it alive.
1397/// Only the `alive` handle needs to be weak; a [`kio::Shared`] carries no liveness,
1398/// so holding the state outright pins nothing.
1399#[derive(Clone)]
1400pub(super) struct WeakConsumer {
1401	info: Arc<Info>,
1402	alive: kio::ConsumerPassive<()>,
1403	state: kio::Shared<BroadcastState>,
1404}
1405
1406impl WeakConsumer {
1407	/// Upgrade to a full [`Consumer`] sharing the same broadcast state.
1408	pub fn consume(&self) -> Consumer {
1409		Consumer {
1410			info: self.info.clone(),
1411			alive: self.alive.consume(),
1412			state: self.state.clone(),
1413			stats: stats::Scope::default(),
1414		}
1415	}
1416}
1417
1418impl super::WeakEntry for WeakConsumer {
1419	fn is_closed(&self) -> bool {
1420		self.alive.is_closed()
1421	}
1422
1423	fn same_channel(&self, other: &Self) -> bool {
1424		self.state.is_clone(&other.state)
1425	}
1426}
1427
1428/// A cloneable, watch-only handle to whether anyone reads a broadcast.
1429///
1430/// Obtained from [`Producer::demand`]. The broadcast is wanted while any of its tracks is
1431/// ([`track::Demand::wanted`] is `Some`) or a track request waits for a [`Requests`]
1432/// handler, so a publisher can follow its readers without holding every track's producer.
1433/// It's a weak handle: it neither keeps the broadcast alive nor counts as demand.
1434/// Each clone watches on its own, so its first
1435/// [`poll_wanted_changed`](Self::poll_wanted_changed) reports the current value.
1436pub struct Demand {
1437	alive: kio::ConsumerPassive<()>,
1438	state: kio::Shared<BroadcastState>,
1439	// This handle's inbox in [`BroadcastState::demands`].
1440	inbox: usize,
1441	// One watcher per track, each counting its track in `wanted` while the track is wanted,
1442	// so a reader coming or going re-polls only its own track.
1443	watchers: kio::Tasks<Watcher>,
1444	wanted: Arc<AtomicUsize>,
1445	// The value `poll_wanted_changed` last returned, or `None` before it returned any.
1446	prev: Option<bool>,
1447}
1448
1449impl Clone for Demand {
1450	fn clone(&self) -> Self {
1451		Self::new(self.alive.clone(), self.state.clone())
1452	}
1453}
1454
1455impl Demand {
1456	fn new(alive: kio::ConsumerPassive<()>, state: kio::Shared<BroadcastState>) -> Self {
1457		let inbox = {
1458			let mut state = state.lock();
1459			let open = state
1460				.tracks
1461				.iter()
1462				.filter(|track| !track.is_closed())
1463				.cloned()
1464				.collect();
1465			state.demands.insert(open)
1466		};
1467		Self {
1468			alive,
1469			state,
1470			inbox,
1471			watchers: kio::Tasks::new(),
1472			wanted: Arc::default(),
1473			prev: None,
1474		}
1475	}
1476
1477	/// Whether the broadcast is open and any of its tracks is wanted or requested right now.
1478	pub fn wanted(&self) -> bool {
1479		if self.alive.is_closed() {
1480			return false;
1481		}
1482		let state = self.state.read();
1483		!state.requests.is_empty() || state.tracks.iter().any(|track| track.is_wanted())
1484	}
1485
1486	/// Resolves to [`wanted`](Self::wanted) once it differs from what this handle last
1487	/// returned: immediately on the first call, then on each change. Errors once the
1488	/// broadcast closes.
1489	///
1490	/// So `while !demand.wanted_changed().await? {}` waits for a reader, and
1491	/// `while demand.wanted_changed().await? {}` waits for the last one to leave.
1492	#[cfg_attr(feature = "async", kio::wrapper)]
1493	pub fn poll_wanted_changed(&mut self, waiter: &kio::Waiter) -> Poll<Result<bool, Error>> {
1494		if self.alive.poll_closed(waiter).is_ready() {
1495			return Poll::Ready(Err(Error::Dropped));
1496		}
1497		let requested = self.poll_cached(waiter);
1498		// Ready only while no track is watched; the parent waker is registered either way.
1499		let _ = self.watchers.poll(waiter);
1500		let wanted = requested || self.wanted.load(Ordering::Relaxed) > 0;
1501		if self.prev == Some(wanted) {
1502			return Poll::Pending;
1503		}
1504		self.prev = Some(wanted);
1505		Poll::Ready(Ok(wanted))
1506	}
1507
1508	/// Watch the tracks cached since the last look, returning whether a track request is
1509	/// pending. Parks `waiter` on either changing.
1510	fn poll_cached(&mut self, waiter: &kio::Waiter) -> bool {
1511		loop {
1512			let mut requested = false;
1513			let polled = self.state.poll(waiter, |state| {
1514				requested = !state.requests.is_empty();
1515				match state.demands[self.inbox].is_empty() {
1516					true => Poll::Pending,
1517					false => Poll::Ready(()),
1518				}
1519			});
1520			let Poll::Ready(mut state) = polled else {
1521				return requested;
1522			};
1523			let cached = std::mem::take(&mut state.demands[self.inbox]);
1524			drop(state);
1525			for track in cached {
1526				self.watchers.push(Watcher {
1527					track: track.demand(),
1528					counted: false,
1529					wanted: self.wanted.clone(),
1530				});
1531			}
1532		}
1533	}
1534}
1535
1536impl Drop for Demand {
1537	fn drop(&mut self) {
1538		self.state.lock().demands.remove(self.inbox);
1539	}
1540}
1541
1542/// Counts one track in its [`Demand`] while the track is wanted.
1543struct Watcher {
1544	track: track::Demand,
1545	counted: bool,
1546	wanted: Arc<AtomicUsize>,
1547}
1548
1549impl kio::Task for Watcher {
1550	type Output = ();
1551
1552	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> {
1553		let state = self.track.poll_state(waiter);
1554		let wanted = state == track::DemandState::Active;
1555		if wanted != self.counted {
1556			self.counted = wanted;
1557			match wanted {
1558				true => self.wanted.fetch_add(1, Ordering::Relaxed),
1559				false => self.wanted.fetch_sub(1, Ordering::Relaxed),
1560			};
1561		}
1562		match state {
1563			track::DemandState::Closed => Poll::Ready(()),
1564			_ => Poll::Pending,
1565		}
1566	}
1567}
1568
1569#[cfg(test)]
1570#[expect(missing_docs, reason = "test-only assertion helpers")]
1571impl Consumer {
1572	pub fn assert_not_closed(&self) {
1573		assert!(
1574			kio::wait(|waiter| self.poll_closed(waiter)).now_or_never().is_none(),
1575			"should not be closed"
1576		);
1577	}
1578
1579	pub fn assert_closed(&self) {
1580		assert!(
1581			kio::wait(|waiter| self.poll_closed(waiter)).now_or_never().is_some(),
1582			"should be closed"
1583		);
1584	}
1585
1586	/// The tracks still open on the broadcast, whether or not anyone reads them.
1587	pub fn open_tracks(&self) -> usize {
1588		self.state
1589			.read()
1590			.tracks
1591			.iter()
1592			.filter(|track| !track.is_closed())
1593			.count()
1594	}
1595}
1596
1597#[cfg(test)]
1598mod test {
1599	use super::*;
1600	use crate::frame::Frame;
1601
1602	#[test]
1603	fn a_subscription_is_registered_before_its_request_is_visible() {
1604		struct Serve {
1605			dynamic: std::sync::Mutex<Requests>,
1606			request: std::sync::Mutex<Option<track::Request>>,
1607			subscription: std::sync::Mutex<Option<Option<track::Subscription>>>,
1608		}
1609		impl std::task::Wake for Serve {
1610			fn wake(self: Arc<Self>) {
1611				self.wake_by_ref();
1612			}
1613			fn wake_by_ref(self: &Arc<Self>) {
1614				let Poll::Ready(Ok(request)) = self.dynamic.lock().unwrap().poll_requested_track(&kio::Waiter::noop())
1615				else {
1616					return;
1617				};
1618				*self.subscription.lock().unwrap() = Some(request.subscription());
1619				*self.request.lock().unwrap() = Some(request);
1620			}
1621		}
1622
1623		let producer = Info::new().produce();
1624		let serve = Arc::new(Serve {
1625			dynamic: std::sync::Mutex::new(producer.requests()),
1626			request: Default::default(),
1627			subscription: Default::default(),
1628		});
1629		let consumer = producer.consume().track("catalog").unwrap();
1630		let waiter = kio::Waiter::new(std::task::Waker::from(serve.clone()));
1631		assert!(serve.dynamic.lock().unwrap().poll_requested_track(&waiter).is_pending());
1632		let expected = track::Subscription::default().prioritized(3);
1633		let _pending = consumer.subscribe(expected.clone());
1634		assert_eq!(*serve.subscription.lock().unwrap(), Some(Some(expected)));
1635	}
1636
1637	#[test]
1638	fn a_subscription_is_registered_before_its_demand_is_visible() {
1639		struct Inspect {
1640			track: track::Producer,
1641			seen: std::sync::Mutex<Option<Option<track::Subscription>>>,
1642		}
1643		impl std::task::Wake for Inspect {
1644			fn wake(self: Arc<Self>) {
1645				self.wake_by_ref();
1646			}
1647			fn wake_by_ref(self: &Arc<Self>) {
1648				*self.seen.lock().unwrap() = Some(self.track.subscription());
1649			}
1650		}
1651
1652		for lookup in [false, true] {
1653			let producer = Info::new().produce();
1654			let inspect = Arc::new(Inspect {
1655				track: producer.create_track("catalog", None).unwrap(),
1656				seen: Default::default(),
1657			});
1658			let waiter = kio::Waiter::new(std::task::Waker::from(inspect.clone()));
1659			assert_eq!(inspect.track.demand().poll_state(&waiter), track::DemandState::Idle);
1660			let consumer = if lookup {
1661				producer.consume().track("catalog").unwrap()
1662			} else {
1663				inspect.track.consume()
1664			};
1665			let expected = track::Subscription::default().prioritized(3);
1666			let _pending = consumer.subscribe(expected.clone());
1667			assert_eq!(*inspect.seen.lock().unwrap(), Some(Some(expected)), "lookup: {lookup}");
1668		}
1669	}
1670
1671	#[test]
1672	fn a_subscription_wakes_its_observers_outside_the_broadcast_lock() {
1673		struct Reenter {
1674			broadcast: Consumer,
1675			woken: std::sync::atomic::AtomicBool,
1676		}
1677		impl std::task::Wake for Reenter {
1678			fn wake(self: Arc<Self>) {
1679				self.wake_by_ref();
1680			}
1681			fn wake_by_ref(self: &Arc<Self>) {
1682				// Deadlocks if the subscribe that woke us still holds the broadcast lock.
1683				let _ = self.broadcast.track("other");
1684				self.woken.store(true, std::sync::atomic::Ordering::Relaxed);
1685			}
1686		}
1687
1688		let producer = Info::new().produce();
1689		let mut track = producer.create_track("catalog", None).unwrap();
1690		let reenter = Arc::new(Reenter {
1691			broadcast: producer.consume(),
1692			woken: Default::default(),
1693		});
1694		let waiter = kio::Waiter::new(std::task::Waker::from(reenter.clone()));
1695		assert!(track.poll_subscription_changed(&waiter).is_pending());
1696		let consumer = producer.consume().track("catalog").unwrap();
1697		let _pending = consumer.subscribe(track::Subscription::default().prioritized(3));
1698		assert!(reenter.woken.load(std::sync::atomic::Ordering::Relaxed));
1699	}
1700
1701	#[test]
1702	fn unique_names_are_never_reused() {
1703		let producer = Info::new().produce();
1704		let name = producer.unique_name(".opus");
1705		assert_eq!(name, "0.opus");
1706		let track = producer
1707			.create_track(name.clone(), crate::track::Info::timed())
1708			.unwrap();
1709		assert_eq!(producer.unique_name(".opus"), "1.opus");
1710		drop(track);
1711	}
1712
1713	#[test]
1714	fn unique_names_survive_closed_track_pruning() {
1715		let producer = Info::new().produce();
1716		let consumer = producer.consume();
1717		let track = producer.unique_track(".opus", crate::track::Info::timed());
1718		assert_eq!(track.name(), "0.opus");
1719		drop(track);
1720		assert!(matches!(consumer.track("0.opus"), Err(Error::NotFound)));
1721		assert_eq!(producer.unique_name(".opus"), "1.opus");
1722	}
1723
1724	/// A live track holds its name against every creator, a minted name skips it, and the
1725	/// name frees once the track ends.
1726	#[test]
1727	fn a_live_name_is_taken_until_its_track_ends() {
1728		let producer = Info::new().produce();
1729		let track = producer.create_track("0.opus", crate::track::Info::timed()).unwrap();
1730		assert!(producer.create_track("0.opus", None).is_none());
1731		assert!(producer.reserve_track("0.opus").is_none());
1732		assert!(producer.reserve_unlisted_track("0.opus").is_none());
1733		assert_eq!(producer.unique_track(".opus", None).name(), "1.opus");
1734
1735		drop(track);
1736		assert!(producer.create_track("0.opus", None).is_some());
1737	}
1738
1739	/// A track handle reads what an open broadcast serves now, so a track that went away
1740	/// reads empty rather than its stale cache.
1741	#[test]
1742	fn a_handle_forgets_a_track_its_open_broadcast_dropped() {
1743		let producer = Info::new().produce();
1744		let consumer = producer.consume();
1745		let track = producer.create_track("a", crate::track::Info::timed()).unwrap();
1746		let _open = track.append_next().unwrap();
1747		let handle = consumer.track("a").unwrap();
1748		assert_eq!(handle.latest_key(), Some(0));
1749		drop(track);
1750		assert_eq!(handle.latest_key(), None);
1751	}
1752
1753	/// A handle's largest reads the identity its open broadcast serves now, without asking
1754	/// for it, and ends once nothing is served under the name.
1755	#[test]
1756	fn a_handle_follows_the_largest_its_broadcast_serves() {
1757		let producer = Info::new().produce();
1758		let consumer = producer.consume();
1759		let track = producer.create_track("a", crate::track::Info::default()).unwrap();
1760		let mut group = track.append_next().unwrap();
1761		group
1762			.write_frame(Frame::new(crate::Timestamp::unscaled(group.start), &b"a"[..]))
1763			.unwrap();
1764		let mut handle = consumer.track("a").unwrap();
1765		let waiter = kio::Waiter::noop();
1766		assert_eq!(
1767			handle.poll_largest(&waiter),
1768			std::task::Poll::Ready(Some(crate::track::Position { group: 0, frame: 0 }))
1769		);
1770		assert!(handle.poll_largest(&waiter).is_pending(), "nothing newer yet");
1771		drop(group);
1772		drop(track);
1773		assert_eq!(handle.poll_largest(&waiter), std::task::Poll::Ready(None));
1774	}
1775
1776	/// Once the broadcast ends, a handle keeps reading the track it saw when it was made.
1777	#[test]
1778	fn a_handle_keeps_its_track_once_the_broadcast_ends() {
1779		let producer = Info::new().produce();
1780		let consumer = producer.consume();
1781		let track = producer.create_track("a", crate::track::Info::timed()).unwrap();
1782		let _open = track.append_next().unwrap();
1783		let handle = consumer.track("a").unwrap();
1784		producer.close();
1785		drop(track);
1786		assert_eq!(handle.latest_key(), Some(0));
1787	}
1788
1789	#[test]
1790	fn unique_name_skips_a_live_collision() {
1791		let producer = Info::new().produce();
1792		let track = producer.create_track("0.opus", crate::track::Info::timed()).unwrap();
1793		assert_eq!(producer.unique_name(".opus"), "1.opus");
1794		drop(track);
1795		assert_eq!(producer.unique_name(".opus"), "2.opus");
1796	}
1797
1798	#[test]
1799	fn unique_names_share_a_counter() {
1800		let producer = Info::new().produce();
1801		assert_eq!(producer.unique_name("-video"), "0-video");
1802		assert_eq!(producer.clone().unique_name("-audio"), "1-audio");
1803		assert_eq!(producer.unique_name("-video"), "2-video");
1804	}
1805
1806	#[test]
1807	fn unique_names_separate_numeric_suffixes() {
1808		let producer = Info::new().produce();
1809		assert_eq!(producer.unique_name(""), "0");
1810		let name = producer.unique_name("2");
1811		assert_eq!(name, "1-2");
1812		for _ in 2..12 {
1813			producer.unique_name("");
1814		}
1815		assert_eq!(producer.unique_name(""), "12");
1816	}
1817
1818	/// Records whether it was woken.
1819	#[derive(Default)]
1820	struct Flag(std::sync::atomic::AtomicBool);
1821
1822	impl std::task::Wake for Flag {
1823		fn wake(self: Arc<Self>) {
1824			self.0.store(true, Ordering::Relaxed);
1825		}
1826	}
1827
1828	impl Flag {
1829		fn waiter(self: &Arc<Self>) -> kio::Waiter {
1830			kio::Waiter::new(self.clone().into())
1831		}
1832
1833		fn take(&self) -> bool {
1834			self.0.swap(false, Ordering::Relaxed)
1835		}
1836	}
1837
1838	/// Poll `demand` for a change with `waiter`, without waiting.
1839	fn wanted_changed(demand: &mut Demand, waiter: &kio::Waiter) -> Option<bool> {
1840		match demand.poll_wanted_changed(waiter) {
1841			Poll::Ready(res) => Some(res.unwrap()),
1842			Poll::Pending => None,
1843		}
1844	}
1845
1846	/// Looking up a track the broadcast holds live, whether a bare handle, a read through it,
1847	/// or a subscription, only reads the table, so it wakes no [`Demand`] watcher.
1848	#[test]
1849	fn a_live_lookup_wakes_no_demand() {
1850		let producer = Info::new().produce();
1851		let consumer = producer.consume();
1852		let video = producer.create_track("video", None).unwrap();
1853		let _reader = video.subscribe(None);
1854		let mut demand = producer.demand();
1855		let flag = Arc::new(Flag::default());
1856		let waiter = flag.waiter();
1857		assert_eq!(wanted_changed(&mut demand, &waiter), Some(true));
1858		assert_eq!(wanted_changed(&mut demand, &waiter), None);
1859
1860		let track = consumer.track("video").unwrap();
1861		assert!(track.declared_end().is_none());
1862		let _subscriber = track.subscribe(None);
1863		assert!(!flag.take(), "a live lookup woke a demand watcher");
1864		assert_eq!(wanted_changed(&mut demand, &waiter), None);
1865	}
1866
1867	/// Any track's demand is the broadcast's, whether the track existed before the handle or
1868	/// came after it, and a reader arriving straight through a track producer, which never
1869	/// touches the broadcast's state, still wakes it. It stays wanted until the last wanted
1870	/// track goes.
1871	#[test]
1872	fn demand_follows_every_track() {
1873		let producer = Info::new().produce();
1874		let video = producer.create_track("video", None).unwrap();
1875		let mut demand = producer.demand();
1876		let audio = producer.create_track("audio", None).unwrap();
1877		let flag = Arc::new(Flag::default());
1878		let waiter = flag.waiter();
1879		assert_eq!(
1880			wanted_changed(&mut demand, &waiter),
1881			Some(false),
1882			"the first call reports"
1883		);
1884
1885		let _bare = producer.consume().track("audio").unwrap();
1886		assert_eq!(
1887			wanted_changed(&mut demand, &waiter),
1888			None,
1889			"a bare handle is not demand"
1890		);
1891
1892		flag.take();
1893		let reading_audio = audio.subscribe(None);
1894		assert!(flag.take(), "a reader wakes the parked poll");
1895		assert_eq!(wanted_changed(&mut demand, &waiter), Some(true));
1896		assert!(demand.wanted());
1897
1898		let reading_video = video.subscribe(None);
1899		assert_eq!(wanted_changed(&mut demand, &waiter), None, "already wanted");
1900		drop(reading_audio);
1901		assert_eq!(wanted_changed(&mut demand, &waiter), None, "video is still read");
1902		flag.take();
1903		drop(reading_video);
1904		assert!(flag.take(), "the last reader leaving wakes the parked poll");
1905		assert_eq!(wanted_changed(&mut demand, &waiter), Some(false));
1906		assert!(!demand.wanted());
1907
1908		// A clone reports the current value first, whatever the original last returned.
1909		let _reading = video.subscribe(None);
1910		assert_eq!(wanted_changed(&mut demand.clone(), &waiter), Some(true));
1911	}
1912
1913	/// A request waiting for a handler is demand, and handing it out moves that demand onto
1914	/// the track it became without a gap, until its subscriber leaves.
1915	#[test]
1916	fn a_pending_request_is_demand_until_its_reader_leaves() {
1917		let producer = Info::new().produce();
1918		let mut requests = producer.requests();
1919		let mut demand = producer.demand();
1920		let waiter = kio::Waiter::noop();
1921		assert_eq!(wanted_changed(&mut demand, &waiter), Some(false));
1922
1923		let subscribing = producer.consume().track("video").unwrap().subscribe(None);
1924		assert_eq!(wanted_changed(&mut demand, &waiter), Some(true), "queued");
1925
1926		let Poll::Ready(Ok(request)) = requests.poll_requested_track(&waiter) else {
1927			panic!("the request was not queued");
1928		};
1929		assert_eq!(wanted_changed(&mut demand, &waiter), None, "handed out, still read");
1930		let _track = request.accept(None);
1931		assert_eq!(wanted_changed(&mut demand, &waiter), None, "accepted, still read");
1932
1933		drop(subscribing);
1934		assert_eq!(wanted_changed(&mut demand, &waiter), Some(false));
1935	}
1936
1937	/// A closed track is never demand, even while a reader lingers to drain it.
1938	#[test]
1939	fn a_closed_track_is_not_demand() {
1940		let producer = Info::new().produce();
1941		let video = producer.create_track("video", None).unwrap();
1942		let mut demand = producer.demand();
1943		let _reading = video.subscribe(None);
1944		let waiter = kio::Waiter::noop();
1945		assert_eq!(wanted_changed(&mut demand, &waiter), Some(true));
1946
1947		video.abort(Error::Cancel).unwrap();
1948		assert_eq!(wanted_changed(&mut demand, &waiter), Some(false));
1949		assert!(!demand.wanted());
1950	}
1951
1952	/// The handle reports the broadcast closing, wanted or not.
1953	#[test]
1954	fn demand_errors_once_closed() {
1955		let producer = Info::new().produce();
1956		let video = producer.create_track("video", None).unwrap();
1957		let _reading = video.subscribe(None);
1958		let mut demand = producer.demand();
1959		producer.close();
1960		assert!(!demand.wanted());
1961		assert!(matches!(
1962			demand.poll_wanted_changed(&kio::Waiter::noop()),
1963			Poll::Ready(Err(Error::Dropped))
1964		));
1965	}
1966
1967	/// A reader of a frame keeps its group wanted, the group its track, and the track the
1968	/// broadcast, after every handle above it is gone.
1969	#[test]
1970	fn a_frame_read_keeps_the_broadcast_wanted() {
1971		let producer = Info::new().produce();
1972		let video = producer.create_track("video", track::Info::timed()).unwrap();
1973		let mut demand = producer.demand();
1974		let waiter = kio::Waiter::noop();
1975		let mut subscriber = video.subscribe(None);
1976		let mut writing = video.append_next().unwrap();
1977		writing
1978			.write_frame(Frame::new(crate::Timestamp::ZERO, &b"key"[..]))
1979			.unwrap();
1980		assert_eq!(wanted_changed(&mut demand, &waiter), Some(true));
1981
1982		let mut group = subscriber.assert_group();
1983		drop(subscriber);
1984		assert_eq!(wanted_changed(&mut demand, &waiter), None, "the group is read");
1985		assert!(video.demand().wanted());
1986
1987		let Poll::Ready(Ok(Some(frame))) = group.poll_next_frame(&waiter) else {
1988			panic!("the frame was written");
1989		};
1990		drop(group);
1991		assert!(writing.demand().wanted(), "the frame's reader reads the group");
1992		assert_eq!(wanted_changed(&mut demand, &waiter), None, "the frame is read");
1993
1994		drop(frame);
1995		assert!(!writing.demand().wanted());
1996		assert_eq!(video.demand().wanted_start(), None);
1997		assert_eq!(wanted_changed(&mut demand, &waiter), Some(false));
1998	}
1999
2000	/// Subscribe and assert the result hasn't resolved yet (it stays pending until
2001	/// a publisher accepts). Returns the pending subscription to resolve after accepting.
2002	macro_rules! subscribe_pending {
2003		($consumer:expr, $name:expr) => {{
2004			let pending = $consumer.track($name).unwrap().subscribe(None);
2005			assert!(
2006				pending.poll_ok(&kio::Waiter::noop()).is_pending(),
2007				"subscribe should stay pending until the request is accepted"
2008			);
2009			pending
2010		}};
2011	}
2012
2013	#[kio::test]
2014	#[cfg(feature = "async")]
2015	async fn insert() {
2016		let mut producer = Info::new().produce();
2017
2018		// Create the track before any consumer exists.
2019		let track1 = producer.assert_create_track("track1", crate::track::Info::timed());
2020		track1.append_next().unwrap().finish().unwrap();
2021
2022		let consumer = producer.consume();
2023
2024		// The track already exists, so subscribe resolves immediately.
2025		let mut track1_sub = consumer.track("track1").unwrap().subscribe(None).await.unwrap();
2026		track1_sub.assert_group();
2027
2028		let track2 = producer.assert_create_track("track2", crate::track::Info::timed());
2029
2030		let consumer2 = producer.consume();
2031		let mut track2_consumer = consumer2.track("track2").unwrap().subscribe(None).await.unwrap();
2032		track2_consumer.assert_no_group();
2033
2034		track2.append_next().unwrap().finish().unwrap();
2035
2036		track2_consumer.assert_group();
2037	}
2038
2039	#[kio::test]
2040	#[cfg(feature = "async")]
2041	async fn closed() {
2042		let mut producer = Info::new().produce();
2043		let dynamic = producer.requests();
2044
2045		let consumer = producer.consume();
2046		consumer.assert_not_closed();
2047
2048		// Create a new track and insert it into the broadcast (resolves immediately).
2049		let track1 = producer.assert_create_track("track1", crate::track::Info::timed());
2050		let mut track1c = consumer.track("track1").unwrap().subscribe(None).await.unwrap();
2051
2052		// A track nobody publishes stays pending until accepted.
2053		let track2_fut = subscribe_pending!(consumer, "track2");
2054
2055		// Dropping the last dynamic handler rejects pending requests, but must NOT
2056		// cascade to externally-owned tracks.
2057		drop(dynamic);
2058
2059		// track2 was a pending dynamic request, so its subscribe surfaces the rejection.
2060		assert!(track2_fut.await.is_err());
2061
2062		// track1's producer is held outside the broadcast, so it survives.
2063		assert!(!track1.is_closed());
2064		track1c.assert_not_closed();
2065	}
2066
2067	/// `close()` ends the broadcast for every clone at once, and a second close is a no-op.
2068	#[kio::test]
2069	#[cfg(feature = "async")]
2070	async fn close_ends_every_clone() {
2071		let producer = Info::new().produce();
2072		let clone = producer.clone();
2073		let consumer = producer.consume();
2074
2075		producer.close();
2076		consumer.closed().await;
2077		assert!(matches!(consumer.track("video"), Err(Error::Unroutable)));
2078		assert!(matches!(clone.consume().track("video"), Err(Error::Unroutable)));
2079
2080		clone.close();
2081		producer.close();
2082	}
2083
2084	/// Dropping the last producer ends the broadcast exactly like `close()`.
2085	#[kio::test]
2086	#[cfg(feature = "async")]
2087	async fn drop_ends_like_close() {
2088		let producer = Info::new().produce();
2089		let consumer = producer.consume();
2090		drop(producer);
2091		consumer.closed().await;
2092		assert!(matches!(consumer.track("video"), Err(Error::Unroutable)));
2093	}
2094
2095	#[kio::test]
2096	#[cfg(feature = "async")]
2097	async fn requests() {
2098		let mut producer = Info::new().produce().requests();
2099
2100		let consumer = producer.consume();
2101		let consumer2 = consumer.clone();
2102
2103		// Two subscribers to the same name coalesce into one request.
2104		let track1_fut = subscribe_pending!(consumer, "track1");
2105		let track2_fut = subscribe_pending!(consumer2, "track1");
2106
2107		// There should be exactly one request to serve.
2108		let request = producer.assert_request();
2109		producer.assert_no_request();
2110		assert_eq!(request.name(), "track1");
2111
2112		// Accept it, which resolves both waiting subscribers.
2113		let track3 = request.accept(crate::track::Info::timed());
2114		let mut track1 = track1_fut.await.unwrap();
2115		let mut track2 = track2_fut.await.unwrap();
2116
2117		track1.assert_not_closed();
2118		track1.assert_is_clone(&track2);
2119		track3.subscribe(None).assert_is_clone(&track1);
2120
2121		// Append a group and make sure they all get it.
2122		track3.append_next().unwrap().finish().unwrap();
2123		track1.assert_group();
2124		track2.assert_group();
2125
2126		// A pending request is cancelled when the dynamic producer is dropped.
2127		let track4_fut = subscribe_pending!(consumer, "track2");
2128		drop(producer);
2129		assert!(track4_fut.await.is_err());
2130
2131		// With no dynamic producer left, requesting the handle fails outright.
2132		let track5 = consumer2.track("track3");
2133		assert!(track5.is_err(), "should have errored");
2134	}
2135
2136	#[kio::test]
2137	#[cfg(feature = "async")]
2138	async fn stale_producer() {
2139		let mut broadcast = Info::new().produce().requests();
2140		let consumer = broadcast.consume();
2141
2142		// Subscribe to a track and serve it.
2143		let track1_fut = subscribe_pending!(consumer, "track1");
2144		let producer1 = broadcast.assert_request().accept(crate::track::Info::timed());
2145		let mut track1 = track1_fut.await.unwrap();
2146
2147		// Close the producer (simulating publisher disconnect).
2148		producer1.append_next().unwrap().finish().unwrap();
2149		let producer1 = producer1.finish().unwrap();
2150		drop(producer1);
2151
2152		// The consumer should see the track as closed.
2153		track1.assert_closed();
2154
2155		// Subscribe again to the same track: should get a NEW producer, not the stale one.
2156		let track2_fut = subscribe_pending!(consumer, "track1");
2157		let producer2 = broadcast.assert_request().accept(crate::track::Info::timed());
2158		let mut track2 = track2_fut.await.unwrap();
2159		track2.assert_not_closed();
2160		track2.assert_not_clone(&track1);
2161
2162		// The new consumer should receive the new group, which continues past the first's.
2163		producer2
2164			.create_empty(crate::group::Info { start: 1 })
2165			.unwrap()
2166			.finish()
2167			.unwrap();
2168		track2.assert_group();
2169	}
2170
2171	/// A broadcast keeps nothing of a name once its track is gone: a replacement numbers and
2172	/// times its groups from scratch, and the application owns keeping them past its
2173	/// predecessor's.
2174	#[test]
2175	fn replacement_starts_over() {
2176		let at = |millis| crate::Timestamp::from_millis(millis).unwrap();
2177		let producer = Info::new().produce();
2178		let mut dynamic = producer.requests();
2179		let consumer = producer.consume();
2180
2181		let track = consumer.track("media").unwrap().subscribe(None);
2182		let first = dynamic.assert_request().accept(crate::track::Info::timed());
2183		let mut group = first.create_empty(crate::group::Info { start: 8 }).unwrap();
2184		group.write_frame(Frame::new(at(1000), b"a".as_slice())).unwrap();
2185		group.finish().unwrap();
2186		let first = first.finish().unwrap();
2187		drop((first, track));
2188
2189		let track = consumer.track("media").unwrap().subscribe(None);
2190		let second = dynamic.assert_request().accept(crate::track::Info::timed());
2191		let mut group = second.append_next().unwrap();
2192		assert_eq!(group.start, 0);
2193		group.write_frame(Frame::new(at(500), b"b".as_slice())).unwrap();
2194		// Nobody reads it when it goes, so nothing asks for it again.
2195		drop((track, group, second));
2196
2197		let mut third = producer.create_track("media", crate::track::Info::timed()).unwrap();
2198		third.finish_at(crate::track::Position::group(0)).unwrap();
2199	}
2200
2201	/// Names that are gone leave nothing behind, served or not, so churning distinct names
2202	/// keeps the broadcast bounded by its live tracks.
2203	#[test]
2204	fn gone_names_are_forgotten() {
2205		let producer = Info::new().produce();
2206		let mut dynamic = producer.requests();
2207		let consumer = producer.consume();
2208		for i in 0..1000 {
2209			let track = consumer.track(&format!("requested/{i}")).unwrap().subscribe(None);
2210			let served = dynamic.assert_request().accept(crate::track::Info::timed());
2211			served.append_next().unwrap().finish().unwrap();
2212			drop((served, track));
2213
2214			let track = consumer.track(&format!("refused/{i}")).unwrap().subscribe(None);
2215			drop((dynamic.assert_request(), track));
2216
2217			let created = producer
2218				.create_track(format!("created/{i}"), crate::track::Info::timed())
2219				.unwrap();
2220			created.append_next().unwrap().finish().unwrap();
2221		}
2222		let state = producer.state.lock();
2223		assert!(state.tracks.len() < 16, "{} names retained", state.tracks.len());
2224	}
2225
2226	#[kio::test]
2227	#[cfg(feature = "async")]
2228	async fn requested_unused() {
2229		let mut broadcast = Info::new().produce().requests();
2230		let bc = broadcast.consume();
2231
2232		// Subscribe to a track that doesn't exist yet, then serve it.
2233		let c1_fut = subscribe_pending!(bc, "unknown_track");
2234		let producer1 = broadcast.assert_request().accept(crate::track::Info::timed());
2235		let consumer1 = c1_fut.await.unwrap();
2236
2237		// The producer should NOT be unused yet because there's a consumer.
2238		assert!(producer1.demand().wanted(), "track producer should be used");
2239
2240		// A second subscriber reuses the live producer (fast path / dedup).
2241		let consumer2 = bc.track("unknown_track").unwrap().subscribe(None).await.unwrap();
2242		consumer2.assert_is_clone(&consumer1);
2243
2244		drop(consumer1);
2245		assert!(producer1.demand().wanted(), "track producer should be used");
2246
2247		drop(consumer2);
2248		assert!(
2249			!producer1.demand().wanted(),
2250			"track producer should be unused after all consumers are dropped"
2251		);
2252
2253		// While the producer is still alive, re-subscribing to the same name reuses
2254		// it (no new request). This is what lets the relay linger upstream
2255		// subscriptions across transient consumer churn.
2256		let consumer3 = bc.track("unknown_track").unwrap().subscribe(None).await.unwrap();
2257		consumer3.assert_is_clone(&producer1.subscribe(None));
2258		broadcast.assert_no_request();
2259		drop(consumer3);
2260
2261		// Aborting the producer closes its lookup entry; the next subscribe sees the
2262		// stale weak, evicts it, and creates a fresh request.
2263		producer1.abort(Error::Cancel).unwrap();
2264
2265		let c4_fut = subscribe_pending!(bc, "unknown_track");
2266		let producer2 = broadcast.assert_request().accept(crate::track::Info::timed());
2267		let consumer4 = c4_fut.await.unwrap();
2268		drop(consumer4);
2269		assert!(
2270			!producer2.demand().wanted(),
2271			"new track producer should be unused after its consumer is dropped"
2272		);
2273	}
2274
2275	/// Creating a track a consumer already requested fulfills that request: the
2276	/// waiting subscriber resolves against the created producer, and no handler
2277	/// ever sees the (now-taken) name. Without this the requester is stranded:
2278	/// the name exists the moment the track does, so the queue entry could
2279	/// never be served under it.
2280	#[kio::test]
2281	#[cfg(feature = "async")]
2282	async fn create_track_fulfills_queued_request() {
2283		let producer = Info::new().produce();
2284		let mut dynamic = producer.requests();
2285		let bc = dynamic.consume();
2286
2287		// Queue a request for a track that doesn't exist yet.
2288		let subscribing = subscribe_pending!(bc, "video");
2289
2290		// The producer creates the track before any handler drains the queue.
2291		let track = producer.create_track("video", crate::track::Info::timed()).unwrap();
2292		let mut sub = subscribing.await.expect("fulfilled by create_track");
2293
2294		// The fulfilled subscription is live against this very producer.
2295		track.append_next().unwrap().finish().unwrap();
2296		sub.recv_group().await.expect("recv").expect("group");
2297
2298		// The handler never sees the request; a fresh subscribe reuses the track.
2299		dynamic.assert_no_request();
2300		let again = bc.track("video").unwrap().subscribe(None).await.unwrap();
2301		again.assert_is_clone(&track.subscribe(None));
2302	}
2303
2304	// Cloning a `Requests` and dropping the clone must not flip the handler
2305	// count to zero. The relay's lite subscriber clones the
2306	// dynamic per spawned subscribe; if Clone skipped the increment, the
2307	// first finished subscribe would tear down the broadcast and any
2308	// follow-up `track` would return `NotFound`.
2309	#[test]
2310	fn dynamic_clone_keeps_alive() {
2311		let broadcast = Info::new().produce().requests();
2312		let consumer = broadcast.consume();
2313
2314		let clone = broadcast.clone();
2315		drop(clone);
2316
2317		// Original handle is still live, so the request registers (stays pending)
2318		// instead of failing with NotFound.
2319		let _fut = subscribe_pending!(consumer, "track1");
2320	}
2321
2322	/// Closing an unheld broadcast yields to a consumer handle, and to a track a reader
2323	/// asked for before letting go, which no handler has taken yet. A handle minted from a
2324	/// weak once it closes sees it closed, so it never holds a broadcast that is ending.
2325	#[test]
2326	fn close_unheld_yields_to_holders() {
2327		let producer = Info::new().produce();
2328		let mut dynamic = producer.requests();
2329		let consumer = producer.consume();
2330		let weak = consumer.weak();
2331		assert!(producer.is_held());
2332		assert!(!producer.close_unheld(), "closed under a holder");
2333
2334		let track = consumer.track("video").unwrap();
2335		drop(consumer);
2336		assert!(producer.is_held(), "a track handle holds its broadcast");
2337		let subscribing = track.subscribe(None);
2338		drop(track);
2339		drop(subscribing);
2340		assert!(!producer.is_held());
2341		assert!(!producer.close_unheld(), "closed under a track on its way");
2342
2343		let request = dynamic.assert_request();
2344		drop(request);
2345		assert!(producer.close_unheld());
2346		assert!(weak.consume().is_closed());
2347		assert!(producer.close_unheld(), "closing twice is a no-op");
2348	}
2349
2350	/// A reserved name nobody accepts is the parking case a publisher has to be able to
2351	/// end. Ending the broadcast is where it does: `Consumer::track` answers
2352	/// `Unroutable` for a name asked about after this point, so whoever asked earlier gets
2353	/// the same answer instead of waiting on info that can never arrive.
2354	#[kio::test]
2355	#[cfg(feature = "async")]
2356	async fn close_resolves_a_reserved_name() {
2357		let producer = Info::new().produce();
2358		let consumer = producer.consume();
2359
2360		let _request = producer.reserve_track("track1").unwrap();
2361		let pending = subscribe_pending!(consumer, "track1");
2362
2363		producer.close();
2364		assert!(matches!(pending.await, Err(Error::Unroutable)));
2365	}
2366
2367	/// A request still queued for a handler is the same parking case reached from the
2368	/// consumer side, so it ends the same way.
2369	#[kio::test]
2370	#[cfg(feature = "async")]
2371	async fn close_resolves_a_queued_request() {
2372		let producer = Info::new().produce();
2373		let dynamic = producer.requests();
2374		let consumer = dynamic.consume();
2375
2376		let pending = subscribe_pending!(consumer, "track1");
2377
2378		producer.close();
2379		assert!(matches!(pending.await, Err(Error::Unroutable)));
2380		drop(dynamic);
2381	}
2382
2383	/// A queued request answers the same when the broadcast ends by its last handle
2384	/// dropping, even when that handle is the `Requests` that would have served it.
2385	#[kio::test]
2386	#[cfg(feature = "async")]
2387	async fn dropping_the_last_handle_resolves_a_queued_request() {
2388		let dynamic = Info::new().produce().requests();
2389		let consumer = dynamic.consume();
2390
2391		let pending = subscribe_pending!(consumer, "track1");
2392
2393		drop(dynamic);
2394		assert!(matches!(pending.await, Err(Error::Unroutable)));
2395	}
2396
2397	/// A source that no longer names the identity that minted it takes no new track, even
2398	/// from a handler that checks nothing: its request stream ends and every later request
2399	/// answers `Unroutable`, while the track it accepted earlier runs on.
2400	#[kio::test]
2401	#[cfg(feature = "async")]
2402	async fn a_lapsed_source_refuses_new_tracks() {
2403		let route = kio::Producer::new(());
2404		let producer = Info::new()
2405			.produce()
2406			.with_validity(RequestValidity::Route(route.consume()));
2407		let mut dynamic = producer.requests();
2408		let consumer = producer.consume();
2409
2410		let pending = subscribe_pending!(consumer, "accepted");
2411		let served = dynamic.assert_request().accept(crate::track::Info::timed());
2412		let mut accepted = pending.await.unwrap();
2413		let queued = subscribe_pending!(consumer, "queued");
2414
2415		drop(route);
2416		assert!(matches!(dynamic.requested_track().await, Err(Error::Closed)));
2417		assert!(matches!(queued.await, Err(Error::Unroutable)));
2418		assert!(matches!(consumer.track("later"), Err(Error::Unroutable)));
2419
2420		served.append_next().unwrap().finish().unwrap();
2421		accepted.assert_group();
2422	}
2423
2424	/// With a producer still alive, losing the last handler is not the broadcast ending:
2425	/// the queued request fails as `Dropped`.
2426	#[kio::test]
2427	#[cfg(feature = "async")]
2428	async fn dropping_the_last_handler_resolves_a_queued_request_dropped() {
2429		let producer = Info::new().produce();
2430		let dynamic = producer.requests();
2431		let consumer = dynamic.consume();
2432
2433		let pending = subscribe_pending!(consumer, "track1");
2434
2435		drop(dynamic);
2436		assert!(matches!(pending.await, Err(Error::Dropped)));
2437		producer.close();
2438	}
2439
2440	/// A request a handler already took is the handler's to answer: it may be in flight
2441	/// to a peer, and a retraction does not disturb subscriptions already in flight.
2442	/// Whatever the handler decides still reaches the consumer.
2443	#[kio::test]
2444	#[cfg(feature = "async")]
2445	async fn close_leaves_a_claimed_request_to_its_handler() {
2446		let producer = Info::new().produce();
2447		let mut dynamic = producer.requests();
2448		let consumer = dynamic.consume();
2449
2450		let accepted = subscribe_pending!(consumer, "track1");
2451		let request = dynamic.requested_track().await.unwrap();
2452		let dropped = subscribe_pending!(consumer, "track2");
2453		let abandoned = dynamic.requested_track().await.unwrap();
2454
2455		producer.close();
2456		assert!(
2457			accepted.poll_ok(&kio::Waiter::noop()).is_pending(),
2458			"close rejected a claimed request"
2459		);
2460		assert!(
2461			dropped.poll_ok(&kio::Waiter::noop()).is_pending(),
2462			"close rejected a claimed request"
2463		);
2464
2465		let _track = request.accept(crate::track::Info::timed());
2466		assert!(accepted.await.is_ok(), "the handler's accept reaches the consumer");
2467		drop(abandoned);
2468		assert!(dropped.await.is_err(), "the handler dropping it rejects the consumer");
2469		drop(dynamic);
2470	}
2471
2472	/// A reverse fetch can install the track metadata before the live request is
2473	/// accepted, but it does not create a live publisher. Closing the broadcast
2474	/// must still reject that name so an arrival-order subscriber does not park on
2475	/// backfill that is deliberately absent from its queue.
2476	#[kio::test]
2477	#[cfg(feature = "async")]
2478	async fn close_resolves_an_unaccepted_track_with_fetched_info() {
2479		let producer = Info::new().produce();
2480		let consumer = producer.consume();
2481
2482		let request = producer.reserve_track("track1").unwrap();
2483		let dynamic = request.requests();
2484		let track = consumer.track("track1").unwrap();
2485		let pending_fetch = track.fetch_group(0, None);
2486		let fetch = dynamic.requested_fill_group().await.unwrap();
2487		let group = fetch
2488			.accept(crate::track::Info::timed())
2489			.unwrap()
2490			.expect("a fresh group");
2491		group.finish().unwrap();
2492		pending_fetch.await.unwrap();
2493
2494		let mut subscriber = track.subscribe(None).await.unwrap();
2495		producer.close();
2496		assert!(matches!(subscriber.recv_group().await, Err(Error::Unroutable)));
2497
2498		let stale = request.accept(crate::track::Info::timed());
2499		assert!(stale.append_next().is_err());
2500	}
2501
2502	/// A staged track resolves no subscriber until it commits, and then with what was
2503	/// written meanwhile.
2504	#[kio::test]
2505	#[cfg(feature = "async")]
2506	async fn a_staged_track_resolves_subscribers_at_commit() {
2507		let producer = Info::new().produce();
2508		let request = producer.reserve_track("track1").unwrap();
2509		let track = producer.consume().track("track1").unwrap();
2510		let mut subscribing = std::pin::pin!(track.subscribe(None));
2511		assert!(futures::poll!(subscribing.as_mut()).is_pending());
2512
2513		let mut staged = request.stage(crate::track::Info::timed());
2514		staged
2515			.write_frame(Frame::new(crate::Timestamp::ZERO, b"x".as_slice()))
2516			.unwrap();
2517		kio::clock::sim::yield_now().await;
2518		assert!(futures::poll!(subscribing.as_mut()).is_pending(), "still staged");
2519
2520		let _track = staged.commit();
2521		let mut subscriber = subscribing.await.unwrap();
2522		assert_eq!(subscriber.recv_group().await.unwrap().unwrap().start, 0);
2523	}
2524
2525	/// Dropping a staged track uncommitted rejects the request, so its subscribers fail
2526	/// rather than wait on a track nobody will publish.
2527	#[kio::test]
2528	#[cfg(feature = "async")]
2529	async fn dropping_a_staged_track_rejects_the_request() {
2530		let producer = Info::new().produce();
2531		let request = producer.reserve_track("track1").unwrap();
2532		let track = producer.consume().track("track1").unwrap();
2533		let subscribing = track.subscribe(None);
2534
2535		let mut staged = request.stage(crate::track::Info::timed());
2536		staged
2537			.write_frame(Frame::new(crate::Timestamp::ZERO, b"x".as_slice()))
2538			.unwrap();
2539		drop(staged);
2540		assert!(matches!(subscribing.await, Err(Error::Dropped)));
2541	}
2542
2543	/// Dropping a staged track uncommitted aborts a group still being written through it, so
2544	/// its writer fails rather than fill a track nobody will read.
2545	#[kio::test]
2546	#[cfg(feature = "async")]
2547	async fn dropping_a_staged_track_aborts_its_open_groups() {
2548		let producer = Info::new().produce();
2549		let request = producer.reserve_track("track1").unwrap();
2550		let staged = request.stage(crate::track::Info::timed());
2551		let mut group = staged.append_next().unwrap();
2552		drop(staged);
2553		let write = group.write_frame(Frame::new(crate::Timestamp::ZERO, b"x".as_slice()));
2554		assert!(matches!(write, Err(Error::Dropped)), "{write:?}");
2555	}
2556
2557	/// Ending the broadcast doesn't cascade into a track someone is publishing: it keeps
2558	/// its cache and its publisher decides when it ends. Only a new lookup is refused.
2559	#[kio::test]
2560	#[cfg(feature = "async")]
2561	async fn close_spares_a_served_track() {
2562		let producer = Info::new().produce();
2563		let consumer = producer.consume();
2564
2565		let track = producer.create_track("track1", crate::track::Info::timed()).unwrap();
2566		let mut subscriber = consumer.track("track1").unwrap().subscribe(None).await.unwrap();
2567
2568		producer.close();
2569		assert!(matches!(consumer.track("track1"), Err(Error::Unroutable)));
2570
2571		track.append_next().unwrap().finish().unwrap();
2572		subscriber.assert_group();
2573		let _track = track.finish().unwrap();
2574	}
2575
2576	/// The publisher may still be holding the `track::Request` for a name the broadcast
2577	/// just gave up on. Accepting it afterwards must not resurrect the track, or a
2578	/// subscriber that was told `Unroutable` could be contradicted by a later one.
2579	#[kio::test]
2580	#[cfg(feature = "async")]
2581	async fn close_leaves_a_stale_reservation_inert() {
2582		let producer = Info::new().produce();
2583		let consumer = producer.consume();
2584
2585		let request = producer.reserve_track("track1").unwrap();
2586		let pending = subscribe_pending!(consumer, "track1");
2587
2588		producer.close();
2589		assert!(matches!(pending.await, Err(Error::Unroutable)));
2590
2591		let track = request.accept(crate::track::Info::timed());
2592		assert!(track.append_next().is_err());
2593		let mut subscriber = track.subscribe(None);
2594		assert!(matches!(subscriber.recv_group().await, Err(Error::Unroutable)));
2595		assert!(consumer.track("track1").is_err());
2596	}
2597
2598	/// Dropping a `track::Request` is not a verdict about the name, so it resolves as
2599	/// `Dropped` (a handler lost to a crashed publisher or a dead transport), never as
2600	/// `NotFound`. Only an explicit rejection may claim the track is absent.
2601	#[kio::test]
2602	#[cfg(feature = "async")]
2603	async fn dropping_a_reserved_request_resolves_dropped() {
2604		let producer = Info::new().produce();
2605		let consumer = producer.consume();
2606
2607		let request = producer.reserve_track("track1").unwrap();
2608		let pending = subscribe_pending!(consumer, "track1");
2609
2610		drop(request);
2611		assert!(matches!(pending.await, Err(Error::Dropped)));
2612		producer.close();
2613	}
2614
2615	/// `track::Request::reject` carries its reason the same way, which is what lets a
2616	/// subscriber tell "no such track" from "the publisher went away".
2617	#[kio::test]
2618	#[cfg(feature = "async")]
2619	async fn rejecting_a_reserved_request_carries_the_reason() {
2620		let producer = Info::new().produce();
2621		let consumer = producer.consume();
2622
2623		let request = producer.reserve_track("track1").unwrap();
2624		let pending = subscribe_pending!(consumer, "track1");
2625
2626		request.reject(Error::NotFound);
2627		assert!(matches!(pending.await, Err(Error::NotFound)));
2628		producer.close();
2629	}
2630
2631	/// The interleave every unused-driven teardown has to survive: a wire subscriber
2632	/// observes zero consumers, and a viewer looks the track up again before the
2633	/// teardown commits. The returning viewer keeps the track alive, and once it
2634	/// really does commit the cached handle is reclaimed rather than handed out
2635	/// cancelled.
2636	#[kio::test]
2637	#[cfg(feature = "async")]
2638	async fn an_idle_teardown_yields_to_a_returning_viewer() {
2639		let producer = Info::new().produce();
2640		let consumer = producer.consume();
2641		let track = producer.create_track("video", crate::track::Info::timed()).unwrap();
2642
2643		// The unused wake a teardown acts on.
2644		assert!(!track.demand().wanted());
2645
2646		// Demand returns in the gap before it commits.
2647		let viewer = consumer.track("video").unwrap().subscribe(None);
2648		let track = track
2649			.abort_unwanted(Error::Cancel)
2650			.expect_err("viewer keeps the track alive");
2651
2652		// So the viewer holds a live track, not a cancelled one.
2653		assert!(!track.is_closed());
2654		let mut subscriber = viewer.await.unwrap();
2655		subscriber.assert_no_group();
2656		track.append_next().unwrap().finish().unwrap();
2657		assert!(subscriber.recv_group().await.unwrap().is_some());
2658
2659		// Once the viewer really leaves, the same teardown commits, and the lookup
2660		// re-requests the track instead of resolving the closed one.
2661		drop(subscriber);
2662		assert!(track.abort_unwanted(Error::Cancel).is_ok());
2663		assert!(matches!(consumer.track("video"), Err(Error::NotFound)));
2664
2665		producer.close();
2666	}
2667
2668	/// The race a safe drop closes: the publisher sees nobody wants the track, a reader looks
2669	/// it up before the producer drops, and the drop hands that reader to a fresh request
2670	/// rather than failing it. A lookup handle made before the drop reads the replacement on
2671	/// its next request too.
2672	#[kio::test]
2673	#[cfg(feature = "async")]
2674	async fn a_drop_hands_a_joining_reader_to_the_next_producer() {
2675		let producer = Info::new().produce();
2676		let mut dynamic = producer.requests();
2677		let consumer = producer.consume();
2678		let handle = consumer.track("video").unwrap();
2679
2680		let first = handle.subscribe(None);
2681		let track = dynamic.assert_request().accept(crate::track::Info::timed());
2682		let mut first = first.await.unwrap();
2683		track.append_next().unwrap().finish().unwrap();
2684		assert_eq!(first.recv_group().await.unwrap().unwrap().start, 0);
2685		drop(first);
2686
2687		// The idle report the publisher acts on, then a reader joining before the drop.
2688		let mut demand = track.demand();
2689		assert!(!demand.wanted_changed().await.unwrap());
2690		let joined = consumer.track("video").unwrap().subscribe(None);
2691		drop((demand, track));
2692
2693		let next = dynamic.assert_request().accept(crate::track::Info::timed());
2694		dynamic.assert_no_request();
2695		let mut joined = joined.await.unwrap();
2696		next.append_next().unwrap().finish().unwrap();
2697		let mut starts = Vec::new();
2698		while starts.last() != Some(&1) {
2699			starts.push(joined.recv_group().await.unwrap().unwrap().start);
2700		}
2701
2702		let mut later = handle.subscribe(None).await.unwrap();
2703		next.append_next().unwrap().finish().unwrap();
2704		while later.recv_group().await.unwrap().unwrap().start != 2 {}
2705		dynamic.assert_no_request();
2706	}
2707
2708	/// A renewal accepted with an info its reader doesn't hold aborts the track with `MalformedTrack`,
2709	/// for the reader and the producer alike, and a later lookup asks for the track afresh.
2710	#[kio::test]
2711	#[cfg(feature = "async")]
2712	async fn a_renewal_with_another_info_aborts_the_track() {
2713		let producer = Info::new().produce();
2714		let mut dynamic = producer.requests();
2715		let consumer = producer.consume();
2716
2717		let first = consumer.track("video").unwrap().subscribe(None);
2718		let track = dynamic.assert_request().accept(crate::track::Info::timed());
2719		drop(first);
2720		let mut joined = consumer.track("video").unwrap().subscribe(None).await.unwrap();
2721		drop(track);
2722
2723		let compressed = crate::track::Info::timed().with_compression(crate::track::Compression::Deflate);
2724		let next = dynamic.assert_request().accept(compressed.clone());
2725		assert!(matches!(next.append_next(), Err(Error::MalformedTrack)));
2726		assert!(matches!(joined.recv_group().await, Err(Error::MalformedTrack)));
2727
2728		let later = consumer.track("video").unwrap().subscribe(None);
2729		let _fresh = dynamic.assert_request().accept(compressed.clone());
2730		assert_eq!(later.await.unwrap().info(), &compressed);
2731	}
2732
2733	/// Creating a track whose renewal is still queued, with an info its reader doesn't hold,
2734	/// replaces it: the reader ends as a conflicting accept ends it, and later ones read the new
2735	/// track at once.
2736	#[kio::test]
2737	#[cfg(feature = "async")]
2738	async fn creating_over_a_queued_renewal_with_another_info_replaces_it() {
2739		let producer = Info::new().produce();
2740		let mut dynamic = producer.requests();
2741		let consumer = producer.consume();
2742
2743		let track = producer.create_track("video", crate::track::Info::timed()).unwrap();
2744		let mut joined = consumer.track("video").unwrap().subscribe(None).await.unwrap();
2745		drop(track);
2746
2747		let compressed = crate::track::Info::timed().with_compression(crate::track::Compression::Deflate);
2748		let next = producer
2749			.create_track("video", compressed.clone())
2750			.expect("replaces the renewal");
2751		assert!(matches!(joined.recv_group().await, Err(Error::MalformedTrack)));
2752		dynamic.assert_no_request();
2753
2754		let mut later = consumer.track("video").unwrap().subscribe(None).await.unwrap();
2755		assert_eq!(later.info(), &compressed);
2756		next.append_next().unwrap().finish().unwrap();
2757		assert_eq!(later.recv_group().await.unwrap().unwrap().start, 0);
2758	}
2759
2760	/// A conflicting renewal also ends the unfinished groups its request filled before the
2761	/// accept, so their readers read `MalformedTrack` instead of waiting on a writer nobody serves.
2762	#[kio::test]
2763	#[cfg(feature = "async")]
2764	async fn a_conflicting_renewal_aborts_the_groups_its_request_filled() {
2765		let producer = Info::new().produce();
2766		let mut dynamic = producer.requests();
2767		let consumer = producer.consume();
2768
2769		let first = consumer.track("video").unwrap().subscribe(None);
2770		let track = dynamic.assert_request().accept(crate::track::Info::timed());
2771		drop(first);
2772		let handle = consumer.track("video").unwrap();
2773		let _joined = handle.subscribe(None).await.unwrap();
2774		drop(track);
2775
2776		let request = dynamic.assert_request();
2777		let fills = request.requests();
2778		let fetch = handle.fetch_group(5, None);
2779		let fill = fills.requested_fill().await.unwrap();
2780		let mut group = fill.accept(5, None).unwrap().expect("a fresh group");
2781		group
2782			.write_frame(Frame::new(crate::Timestamp::from_millis(5).unwrap(), b"a".as_slice()))
2783			.unwrap();
2784		let mut held = fetch.await.unwrap();
2785		assert!(held.read_frame().await.unwrap().is_some());
2786
2787		let compressed = crate::track::Info::timed().with_compression(crate::track::Compression::Deflate);
2788		let _next = request.accept(compressed);
2789		assert!(matches!(held.read_frame().await, Err(Error::MalformedTrack)));
2790		drop(group);
2791	}
2792
2793	/// `create_track` with the info a queued renewal's reader holds fulfils it, so the reader
2794	/// reads on.
2795	#[kio::test]
2796	#[cfg(feature = "async")]
2797	async fn create_track_fulfils_a_renewal_with_the_same_info() {
2798		let producer = Info::new().produce();
2799		let _dynamic = producer.requests();
2800		let consumer = producer.consume();
2801		let track = producer.create_track("video", crate::track::Info::timed()).unwrap();
2802		let mut reader = consumer.track("video").unwrap().subscribe(None).await.unwrap();
2803		drop(track);
2804
2805		let next = producer.create_track("video", crate::track::Info::timed()).unwrap();
2806		next.append_next().unwrap().finish().unwrap();
2807		assert_eq!(reader.recv_group().await.unwrap().unwrap().start, 0);
2808	}
2809
2810	/// `create_track` wakes a renewed track's reader once the broadcast unlocks, so an inline
2811	/// executor can look the broadcast up again from the wake.
2812	#[kio::test]
2813	#[cfg(feature = "async")]
2814	async fn create_track_wakes_a_renewed_reader_after_unlocking() {
2815		struct Reenter {
2816			consumer: Consumer,
2817			woken: std::sync::atomic::AtomicBool,
2818		}
2819		impl std::task::Wake for Reenter {
2820			fn wake(self: Arc<Self>) {
2821				let _ = self.consumer.track("other");
2822				self.woken.store(true, std::sync::atomic::Ordering::SeqCst);
2823			}
2824		}
2825
2826		let producer = Info::new().produce();
2827		let _dynamic = producer.requests();
2828		let consumer = producer.consume();
2829		let track = producer.create_track("video", crate::track::Info::timed()).unwrap();
2830		let mut reader = consumer.track("video").unwrap().subscribe(None).await.unwrap();
2831		drop(track);
2832
2833		let reenter = Arc::new(Reenter {
2834			consumer: consumer.clone(),
2835			woken: false.into(),
2836		});
2837		let waiter = kio::Waiter::new(std::task::Waker::from(reenter.clone()));
2838		assert!(reader.poll_recv_group(&waiter).is_pending());
2839		let _next = producer.create_track("video", crate::track::Info::timed()).unwrap();
2840		assert!(reenter.woken.load(std::sync::atomic::Ordering::SeqCst));
2841	}
2842
2843	/// `unique_track` minting a name a consumer already requested fulfils that request, and
2844	/// wakes its subscriber only once the broadcast unlocks.
2845	#[kio::test]
2846	#[cfg(feature = "async")]
2847	async fn unique_track_wakes_a_queued_subscriber_after_unlocking() {
2848		struct Reenter {
2849			consumer: Consumer,
2850			woken: std::sync::atomic::AtomicBool,
2851		}
2852		impl std::task::Wake for Reenter {
2853			fn wake(self: Arc<Self>) {
2854				let _ = self.consumer.track("other");
2855				self.woken.store(true, std::sync::atomic::Ordering::SeqCst);
2856			}
2857		}
2858
2859		let producer = Info::new().produce();
2860		let _dynamic = producer.requests();
2861		let consumer = producer.consume();
2862		let pending = consumer.track("0.opus").unwrap().subscribe(None);
2863
2864		let reenter = Arc::new(Reenter {
2865			consumer: consumer.clone(),
2866			woken: false.into(),
2867		});
2868		let waiter = kio::Waiter::new(std::task::Waker::from(reenter.clone()));
2869		assert!(pending.poll_ok(&waiter).is_pending());
2870		let track = producer.unique_track(".opus", crate::track::Info::timed());
2871		assert_eq!(track.name(), "0.opus");
2872		assert!(reenter.woken.load(std::sync::atomic::Ordering::SeqCst));
2873	}
2874
2875	/// A reader that joined in the race and holds the group the producer left open reads that
2876	/// group's end as superseded, as past a group gone old, then the next producer's group.
2877	#[kio::test]
2878	#[cfg(feature = "async")]
2879	async fn a_joining_reader_moves_past_the_group_a_drop_left_open() {
2880		let producer = Info::new().produce();
2881		let mut dynamic = producer.requests();
2882		let consumer = producer.consume();
2883
2884		let first = consumer.track("video").unwrap().subscribe(None);
2885		let track = dynamic.assert_request().accept(crate::track::Info::timed());
2886		drop(first);
2887		let mut open = track.append_next().unwrap();
2888		open.write_frame(Frame::new(crate::Timestamp::from_millis(0).unwrap(), b"a".as_slice()))
2889			.unwrap();
2890
2891		let mut joined = consumer.track("video").unwrap().subscribe(None).await.unwrap();
2892		let mut held = joined.recv_group().await.unwrap().unwrap();
2893		assert!(held.read_frame().await.unwrap().is_some());
2894		drop((track, open));
2895
2896		assert!(matches!(held.read_frame().await, Err(Error::Old)));
2897		let next = dynamic.assert_request().accept(crate::track::Info::timed());
2898		next.append_next().unwrap().finish().unwrap();
2899		assert_eq!(joined.recv_group().await.unwrap().unwrap().start, 1);
2900	}
2901
2902	/// A track nobody wants ends cleanly when its producer drops, with no `Dropped` for a
2903	/// handle still watching, and a later lookup asks for it afresh.
2904	#[kio::test]
2905	#[cfg(feature = "async")]
2906	async fn an_unwanted_drop_ends_cleanly() {
2907		let producer = Info::new().produce();
2908		let mut dynamic = producer.requests();
2909		let consumer = producer.consume();
2910
2911		let reader = consumer.track("video").unwrap().subscribe(None);
2912		let track = dynamic.assert_request().accept(crate::track::Info::timed());
2913		drop(reader.await.unwrap());
2914		track.append_next().unwrap().finish().unwrap();
2915		let open = track.append_next().unwrap();
2916		let demand = track.demand();
2917		drop(track);
2918
2919		assert!(matches!(demand.closed().await, Ok(())));
2920		assert!(open.is_aborted(), "nobody can finish the open group");
2921		dynamic.assert_no_request();
2922		let _again = consumer.track("video").unwrap().subscribe(None);
2923		dynamic.assert_request();
2924	}
2925
2926	/// An abandoned track ends as a drop does while nobody wants it: cleanly, and a later lookup
2927	/// asks for it afresh. A clone or fill handler still held doesn't keep it open.
2928	#[kio::test]
2929	#[cfg(feature = "async")]
2930	async fn an_unwanted_abandon_ends_cleanly() {
2931		let producer = Info::new().produce();
2932		let mut dynamic = producer.requests();
2933		let consumer = producer.consume();
2934
2935		let reader = consumer.track("video").unwrap().subscribe(None);
2936		let track = dynamic.assert_request().accept(crate::track::Info::timed());
2937		drop(reader.await.unwrap());
2938		let open = track.append_next().unwrap();
2939		let demand = track.demand();
2940		let (kept, _fills) = (track.clone(), track.requests());
2941		track.abandon();
2942
2943		assert!(matches!(demand.closed().await, Ok(())));
2944		assert!(open.is_aborted(), "nobody can finish the open group");
2945		assert!(kept.append_next().is_err(), "the clone can't extend it");
2946		dynamic.assert_no_request();
2947		let _again = consumer.track("video").unwrap().subscribe(None);
2948		dynamic.assert_request();
2949	}
2950
2951	/// Unlike a drop, abandoning a track a reader still wants is never asked for again: the
2952	/// reader, and one holding only the open group, read `Dropped`, even while a clone or fill
2953	/// handler is still held.
2954	#[kio::test]
2955	#[cfg(feature = "async")]
2956	async fn an_abandoned_track_fails_its_reader_rather_than_renew() {
2957		let producer = Info::new().produce();
2958		let mut dynamic = producer.requests();
2959		let consumer = producer.consume();
2960
2961		let reader = consumer.track("video").unwrap().subscribe(None);
2962		let track = dynamic.assert_request().accept(crate::track::Info::timed());
2963		let mut reader = reader.await.unwrap();
2964		let mut open = track.append_next().unwrap();
2965		open.write_frame(Frame::new(crate::Timestamp::from_millis(0).unwrap(), b"a".as_slice()))
2966			.unwrap();
2967		let mut held = reader.recv_group().await.unwrap().unwrap();
2968		assert!(held.read_frame().await.unwrap().is_some());
2969		let demand = track.demand();
2970		let (kept, _fills) = (track.clone(), track.requests());
2971		track.abandon();
2972
2973		dynamic.assert_no_request();
2974		assert!(matches!(held.read_frame().await, Err(Error::Dropped)));
2975		assert!(matches!(reader.recv_group().await, Err(Error::Dropped)));
2976		assert!(matches!(demand.closed().await, Err(Error::Dropped)));
2977		assert!(kept.append_next().is_err(), "the clone can't extend it");
2978	}
2979
2980	/// A track the producer created follows the same rule: a reader still holding it when it
2981	/// drops is served by the broadcast's handler, as a later lookup of the name would be.
2982	#[kio::test]
2983	#[cfg(feature = "async")]
2984	async fn a_created_track_dropped_while_read_is_requested_again() {
2985		let producer = Info::new().produce();
2986		let mut dynamic = producer.requests();
2987		let consumer = producer.consume();
2988		let track = producer.create_track("video", crate::track::Info::timed()).unwrap();
2989		let mut reader = consumer.track("video").unwrap().subscribe(None).await.unwrap();
2990		drop(track);
2991
2992		let next = dynamic.assert_request().accept(crate::track::Info::timed());
2993		next.append_next().unwrap().finish().unwrap();
2994		assert_eq!(reader.recv_group().await.unwrap().unwrap().start, 0);
2995	}
2996
2997	/// With no handler to ask, a reader still holding a dropped track reads `Dropped`, as before,
2998	/// and so does one holding only the group the producer left open.
2999	#[kio::test]
3000	#[cfg(feature = "async")]
3001	async fn a_drop_nothing_can_request_again_fails_its_reader() {
3002		let producer = Info::new().produce();
3003		let consumer = producer.consume();
3004		let track = producer.create_track("video", crate::track::Info::timed()).unwrap();
3005		let mut reader = consumer.track("video").unwrap().subscribe(None).await.unwrap();
3006		let mut open = track.append_next().unwrap();
3007		open.write_frame(Frame::new(crate::Timestamp::from_millis(0).unwrap(), b"a".as_slice()))
3008			.unwrap();
3009		let mut held = reader.recv_group().await.unwrap().unwrap();
3010		assert!(held.read_frame().await.unwrap().is_some());
3011		drop((track, open));
3012		assert!(matches!(held.read_frame().await, Err(Error::Dropped)));
3013		assert!(matches!(reader.recv_group().await, Err(Error::Dropped)));
3014	}
3015
3016	/// A drop nothing can request again keeps the position its teardown found, so a replacement
3017	/// route continues the group the producer left open rather than skip past it.
3018	#[kio::test]
3019	#[cfg(feature = "async")]
3020	async fn a_refused_renewal_resumes_where_the_producer_stopped() {
3021		let at = |millis| crate::Timestamp::from_millis(millis).unwrap();
3022		let producer = Info::new().produce();
3023		let consumer = producer.consume();
3024		let track = producer.create_track("video", crate::track::Info::timed()).unwrap();
3025		let handle = track.consume();
3026		let _reader = consumer.track("video").unwrap().subscribe(None).await.unwrap();
3027		let mut open = track.append_next().unwrap();
3028		open.write_frame(Frame::new(at(0), b"a".as_slice())).unwrap();
3029		open.write_frame(Frame::new(at(1), b"b".as_slice())).unwrap();
3030		drop((track, open));
3031		assert_eq!(
3032			handle.resume_position(),
3033			Some(crate::track::Position { group: 0, frame: 2 })
3034		);
3035	}
3036
3037	/// A renewal queued for a handler that then refuses it still resumes where the producer
3038	/// stopped, though the group it stopped in is gone.
3039	#[kio::test]
3040	#[cfg(feature = "async")]
3041	async fn a_queued_renewal_refused_later_resumes_where_the_producer_stopped() {
3042		let at = |millis| crate::Timestamp::from_millis(millis).unwrap();
3043		let producer = Info::new().produce();
3044		let mut dynamic = producer.requests();
3045		let consumer = producer.consume();
3046		let track = producer.create_track("video", crate::track::Info::timed()).unwrap();
3047		let handle = track.consume();
3048		let _reader = consumer.track("video").unwrap().subscribe(None).await.unwrap();
3049		let mut open = track.append_next().unwrap();
3050		open.write_frame(Frame::new(at(0), b"a".as_slice())).unwrap();
3051		open.write_frame(Frame::new(at(1), b"b".as_slice())).unwrap();
3052		drop((track, open));
3053
3054		dynamic.assert_request().reject(Error::Unroutable);
3055		assert_eq!(
3056			handle.resume_position(),
3057			Some(crate::track::Position { group: 0, frame: 2 })
3058		);
3059	}
3060
3061	/// A renewal spends the budget its readers' joins refilled, however much its producer then
3062	/// writes: dropping that producer while the same reader still reads ends it with `Dropped`
3063	/// instead of asking again, so a handler failing each time cannot loop. Another reader joining
3064	/// refills the budget for one more renewal.
3065	#[kio::test]
3066	#[cfg(feature = "async")]
3067	async fn a_renewal_is_asked_for_again_only_after_a_reader_joins() {
3068		let producer = Info::new().produce();
3069		let mut dynamic = producer.requests();
3070		let consumer = producer.consume();
3071		let track = producer.create_track("video", crate::track::Info::timed()).unwrap();
3072		let mut reader = consumer.track("video").unwrap().subscribe(None).await.unwrap();
3073		track.append_next().unwrap().finish().unwrap();
3074		drop(track);
3075
3076		let next = dynamic.assert_request().accept(crate::track::Info::timed());
3077		next.append_next().unwrap().finish().unwrap();
3078		let mut joined = consumer.track("video").unwrap().subscribe(None).await.unwrap();
3079		drop(next);
3080
3081		let last = dynamic.assert_request().accept(crate::track::Info::timed());
3082		last.append_next().unwrap().finish().unwrap();
3083		drop(last);
3084		dynamic.assert_no_request();
3085		for reader in [&mut reader, &mut joined] {
3086			loop {
3087				match reader.recv_group().await {
3088					Ok(Some(_)) => continue,
3089					result => break assert!(matches!(result, Err(Error::Dropped)), "{:?}", result.err()),
3090				}
3091			}
3092		}
3093
3094		// A lookup after that asks for the track afresh.
3095		let subscribing = subscribe_pending!(consumer, "video");
3096		let fresh = dynamic.assert_request().accept(crate::track::Info::timed());
3097		let mut reader = subscribing.await.unwrap();
3098		fresh.append_next().unwrap().finish().unwrap();
3099		assert_eq!(reader.recv_group().await.unwrap().unwrap().start, 0);
3100	}
3101
3102	/// A renewal's producer replaying fewer frames of the group its predecessor left open does
3103	/// not move the resume back, before or after it drops.
3104	#[kio::test]
3105	#[cfg(feature = "async")]
3106	async fn a_renewal_replaying_fewer_frames_keeps_the_resume() {
3107		let at = |millis| crate::Timestamp::from_millis(millis).unwrap();
3108		let producer = Info::new().produce();
3109		let mut dynamic = producer.requests();
3110		let consumer = producer.consume();
3111		let track = producer.create_track("video", crate::track::Info::timed()).unwrap();
3112		let handle = track.consume();
3113		let _reader = consumer.track("video").unwrap().subscribe(None).await.unwrap();
3114		let mut open = track.append_next().unwrap();
3115		open.write_frame(Frame::new(at(0), b"a".as_slice())).unwrap();
3116		open.write_frame(Frame::new(at(1), b"b".as_slice())).unwrap();
3117		drop((track, open));
3118
3119		let next = dynamic.assert_request().accept(crate::track::Info::timed());
3120		let mut again = next.create_empty(crate::group::Info { start: 0 }).unwrap();
3121		again.write_frame(Frame::new(at(0), b"a".as_slice())).unwrap();
3122		let stopped = Some(crate::track::Position { group: 0, frame: 2 });
3123		assert_eq!(handle.resume_position(), stopped);
3124		drop((next, again));
3125		assert_eq!(handle.resume_position(), stopped);
3126	}
3127
3128	#[test]
3129	fn abort_unwanted_accepts_an_already_closed_track_with_consumers() {
3130		let producer = Info::new().produce();
3131		let consumer = producer.consume();
3132		let track = producer.create_track("video", crate::track::Info::timed()).unwrap();
3133		let _viewer = consumer.track("video").unwrap().subscribe(None);
3134		assert!(track.demand().is_wanted());
3135		track.clone().abort(Error::Cancel).unwrap();
3136		assert!(!track.demand().is_wanted());
3137		assert!(track.abort_unwanted(Error::Cancel).is_ok());
3138		producer.close();
3139	}
3140
3141	fn recv_datagram(consumer: &mut datagram::Consumer) -> Poll<Result<Option<crate::datagram::Datagram>, Error>> {
3142		consumer.poll_recv(&kio::Waiter::noop())
3143	}
3144
3145	fn received(consumer: &mut datagram::Consumer) -> u64 {
3146		match recv_datagram(consumer) {
3147			Poll::Ready(Ok(Some(datagram))) => datagram.sequence,
3148			other => panic!("expected a datagram, got {other:?}"),
3149		}
3150	}
3151
3152	/// A datagram track shares no name with a stream track, and holds its own while live.
3153	#[test]
3154	fn datagram_tracks_are_a_namespace_apart() {
3155		let producer = Info::new().produce();
3156		let consumer = producer.consume();
3157		let _track = producer.create_track("audio", crate::track::Info::timed()).unwrap();
3158		let mut datagrams = producer.create_datagrams("audio", datagram::Info::default()).unwrap();
3159		assert!(producer.create_datagrams("audio", datagram::Info::default()).is_none());
3160
3161		let mut reader = consumer.datagrams("audio").unwrap();
3162		datagrams.append(crate::Timestamp::unscaled(0), "x").unwrap();
3163		assert_eq!(received(&mut reader), 0);
3164
3165		// Once it ends, the name is free again, and a reader no longer joins it.
3166		datagrams.finish();
3167		assert!(matches!(recv_datagram(&mut reader), Poll::Ready(Ok(None))));
3168		assert!(matches!(consumer.datagrams("audio"), Err(Error::NotFound)));
3169		producer.create_datagrams("audio", datagram::Info::default()).unwrap();
3170	}
3171
3172	/// A datagram track nothing publishes is asked of a handler, once however many readers
3173	/// want it, and the handler's answer reaches them all.
3174	#[test]
3175	fn a_datagram_request_resolves_with_its_answer() {
3176		let producer = Info::new().produce();
3177		let consumer = producer.consume();
3178		assert!(matches!(consumer.datagrams("audio"), Err(Error::NotFound)));
3179
3180		let mut handler = producer.requests().datagrams();
3181		let requested = |handler: &mut DatagramRequests| handler.poll_requested(&kio::Waiter::noop());
3182		let mut first = consumer.datagrams("audio").unwrap();
3183		let mut second = consumer.datagrams("audio").unwrap();
3184		assert!(first.poll_info(&kio::Waiter::noop()).is_pending());
3185		let Poll::Ready(Ok(request)) = requested(&mut handler) else {
3186			panic!("expected a request");
3187		};
3188		assert!(requested(&mut handler).is_pending(), "the readers share one request");
3189		assert_eq!(request.name(), "audio");
3190
3191		let info = datagram::Info::default().with_priority(2);
3192		let mut served = request.accept(info);
3193		assert!(matches!(second.poll_info(&kio::Waiter::noop()), Poll::Ready(Ok(got)) if got == info));
3194		served.append(crate::Timestamp::unscaled(0), "x").unwrap();
3195		assert_eq!(received(&mut first), 0);
3196		assert_eq!(received(&mut second), 0);
3197
3198		let mut refused = consumer.datagrams("video").unwrap();
3199		let Poll::Ready(Ok(request)) = requested(&mut handler) else {
3200			panic!("expected a request");
3201		};
3202		request.reject(Error::NotFound);
3203		assert!(matches!(recv_datagram(&mut refused), Poll::Ready(Err(Error::NotFound))));
3204	}
3205
3206	/// Creating a datagram track serves the readers already asking for it, before any
3207	/// handler takes their request.
3208	#[test]
3209	fn create_datagrams_fulfills_a_queued_request() {
3210		let producer = Info::new().produce();
3211		let mut handler = producer.requests().datagrams();
3212		let mut reader = producer.consume().datagrams("audio").unwrap();
3213
3214		let info = datagram::Info::default().with_priority(2);
3215		let mut datagrams = producer.create_datagrams("audio", info).unwrap();
3216		assert!(matches!(reader.poll_info(&kio::Waiter::noop()), Poll::Ready(Ok(got)) if got == info));
3217		datagrams.append(crate::Timestamp::unscaled(0), "x").unwrap();
3218		assert_eq!(received(&mut reader), 0);
3219		assert!(handler.poll_requested(&kio::Waiter::noop()).is_pending());
3220	}
3221
3222	/// Closing the broadcast refuses its queued datagram requests and every later one, and
3223	/// ends its handlers.
3224	#[test]
3225	fn close_refuses_datagram_requests() {
3226		let producer = Info::new().produce();
3227		let mut handler = producer.requests().datagrams();
3228		let consumer = producer.consume();
3229		let mut queued = consumer.datagrams("audio").unwrap();
3230
3231		producer.close();
3232		assert!(matches!(
3233			recv_datagram(&mut queued),
3234			Poll::Ready(Err(Error::Unroutable))
3235		));
3236		assert!(matches!(consumer.datagrams("audio"), Err(Error::Unroutable)));
3237		assert!(matches!(
3238			handler.poll_requested(&kio::Waiter::noop()),
3239			Poll::Ready(Err(Error::Closed))
3240		));
3241	}
3242
3243	/// A request whose readers all left is withdrawn, so a handler that never polls holds
3244	/// only the requests someone still waits for.
3245	#[test]
3246	fn a_datagram_request_nobody_waits_for_is_withdrawn() {
3247		let producer = Info::new().produce();
3248		let _handler = producer.requests().datagrams();
3249		let consumer = producer.consume();
3250		for name in ["a", "b", "c", "d"] {
3251			let left = consumer.datagrams(name).unwrap();
3252			drop(left);
3253		}
3254		let mut waiting = consumer.datagrams("e").unwrap();
3255		assert_eq!(producer.state.lock().datagram_requests.len(), 1);
3256		assert!(recv_datagram(&mut waiting).is_pending());
3257		// A withdrawn name is asked for afresh.
3258		let _again = consumer.datagrams("a").unwrap();
3259		assert_eq!(producer.state.lock().datagram_requests.len(), 2);
3260	}
3261
3262	/// Losing the last datagram handler drops the requests it never took, and readers find
3263	/// nothing to ask after.
3264	#[test]
3265	fn dropping_the_datagram_handler_drops_its_queue() {
3266		let producer = Info::new().produce();
3267		let handler = producer.requests().datagrams();
3268		let consumer = producer.consume();
3269		let mut queued = consumer.datagrams("audio").unwrap();
3270
3271		drop(handler.clone());
3272		assert!(recv_datagram(&mut queued).is_pending(), "a clone still handles it");
3273		drop(handler);
3274		assert!(matches!(recv_datagram(&mut queued), Poll::Ready(Err(Error::Dropped))));
3275		assert!(matches!(consumer.datagrams("audio"), Err(Error::NotFound)));
3276	}
3277}