Skip to main content

moq_mux/
source.rs

1//! Export input: an origin plus the catalog broadcast that drives the export.
2//!
3//! A hang catalog rendition may reference a track published in *another*
4//! broadcast via its `broadcast` field (a path relative to the catalog's
5//! broadcast, e.g. `./source`). Resolving that reference needs the catalog
6//! broadcast's own path and an [`moq_net::origin::Consumer`] to fetch the
7//! referenced broadcast from. [`Source`] bundles the two, and resolves every
8//! referenced broadcast through the same origin so
9//! [`request`](moq_net::origin::Consumer::request) deduplicates
10//! shared subscriptions.
11
12use std::collections::HashMap;
13use std::sync::{Arc, Mutex};
14use std::task::{Poll, ready};
15
16/// The broadcast held for each path, shared by a source's clones and its requests.
17type Pins = Arc<Mutex<HashMap<moq_net::Path, moq_net::broadcast::Consumer>>>;
18
19#[derive(Default)]
20struct Priorities {
21	value: i8,
22	controls: HashMap<usize, std::sync::Weak<moq_net::track::Control>>,
23}
24
25/// A program's control registration, removed with the subscription that owns it.
26pub(crate) struct Priority {
27	control: Arc<moq_net::track::Control>,
28	shared: Arc<Mutex<Priorities>>,
29}
30
31impl Drop for Priority {
32	fn drop(&mut self) {
33		self.shared
34			.lock()
35			.expect("priorities poisoned")
36			.controls
37			.remove(&(Arc::as_ptr(&self.control) as usize));
38	}
39}
40
41/// The subscription side of an export: an origin and the catalog broadcast that drives it.
42///
43/// Every rendition (including ones whose catalog `broadcast` field references a sibling
44/// broadcast) resolves against `origin`, so a source can always follow a cross-broadcast
45/// reference. Build one with [`Source::new`].
46///
47/// A source serves its own path from the broadcast it was built from, and keeps the first
48/// broadcast it resolves for each sibling, waiting for the sibling's first announcement if
49/// nothing serves it yet. Every later request for a path is served from that handle
50/// ([`broadcast`](Self::broadcast), [`catalog`](Self::catalog), [`resolve`](Self::resolve),
51/// [`bind`](Self::bind), [`subscribe_track`](Self::subscribe_track), and an export's track
52/// requests). A route replaced after that is never resolved, one identity or not, so two publishers
53/// never splice into one export; a request on a held broadcast that has ended fails instead of
54/// waiting for the next one. Clones share the held broadcasts.
55///
56/// A reader that follows a sibling's announcements instead, restarting on each new identity,
57/// uses [`follow`](Self::follow), which holds nothing.
58#[derive(Clone)]
59pub struct Source {
60	origin: moq_net::origin::Consumer,
61	path: moq_net::Path,
62	pins: Pins,
63	priority: Arc<Mutex<Priorities>>,
64	/// What each rendition an export reads through this source has received. See
65	/// [`stats`](Self::stats).
66	received: Arc<crate::stats::Registry<crate::stats::Received>>,
67	/// Whether the export reading through this source counts each frame's payload toward the
68	/// origin's stats as it emits the frame, rather than as it reads it. See [`Self::bill`].
69	billed: bool,
70}
71
72impl Source {
73	/// A source driven by the catalog of `broadcast`, resolving its references through `origin`.
74	///
75	/// `broadcast` is the catalog broadcast as resolved through `origin`: a rendition's relative
76	/// `broadcast` reference resolves against its [path](moq_net::broadcast::Info::path), and the
77	/// referenced broadcast is fetched via
78	/// [`origin.request`](moq_net::origin::Consumer::request), so it must be
79	/// reachable through `origin` (by exact path, or served by a dynamic handler). A standalone
80	/// broadcast has an empty path, so it is its own root and any `..` reference escapes.
81	pub fn new(origin: moq_net::origin::Consumer, broadcast: moq_net::broadcast::Consumer) -> Self {
82		let path = broadcast.info().path.clone();
83		let pins = HashMap::from([(path.clone(), broadcast)]);
84		Self {
85			origin,
86			path,
87			pins: Arc::new(Mutex::new(pins)),
88			priority: Arc::default(),
89			received: Default::default(),
90			billed: false,
91		}
92	}
93
94	/// This source holding nothing but `broadcast` at its own path: an export switching to
95	/// another identity starts over from the broadcast it switched to. Its counters carry on.
96	pub(crate) fn switched(&self, broadcast: &moq_net::broadcast::Consumer) -> Self {
97		let pins = HashMap::from([(self.path.clone(), broadcast.clone())]);
98		Self {
99			origin: self.origin.clone(),
100			path: self.path.clone(),
101			pins: Arc::new(Mutex::new(pins)),
102			priority: Arc::default(),
103			received: self.received.clone(),
104			billed: self.billed,
105		}
106	}
107
108	/// Count each frame's payload as the export emits it, rather than as it reads it: for an
109	/// export that drops some of what it reads, such as a jitter buffer trimming a join.
110	pub(crate) fn bill(&mut self) {
111		self.billed = true;
112	}
113
114	/// Whether exports reading through this source count payload as they emit it.
115	pub(crate) fn billed(&self) -> bool {
116		self.billed
117	}
118
119	/// Give one export its own delivery preferences while sharing bindings and counters.
120	pub(crate) fn isolate(&mut self) {
121		self.priority = Arc::default();
122	}
123
124	/// Set the subscriber priority of this program's current and future tracks.
125	pub(crate) fn priority(&self, value: i8) -> moq_net::Result<()> {
126		let mut priority = self.priority.lock().expect("priorities poisoned");
127		priority.value = value;
128		for control in priority.controls.values().filter_map(std::sync::Weak::upgrade) {
129			match control.update(prioritized(control.subscription(), value)) {
130				Ok(()) | Err(moq_net::Error::Closed) => {}
131				Err(err) => return Err(err),
132			}
133		}
134		Ok(())
135	}
136
137	/// Start a new track at the program's current priority.
138	pub(crate) fn subscription(&self, subscription: moq_net::track::Subscription) -> moq_net::track::Subscription {
139		prioritized(subscription, self.priority.lock().expect("priorities poisoned").value)
140	}
141
142	/// Keep a track at its program's priority until the returned registration drops.
143	pub(crate) fn control(&self, control: moq_net::track::Control) -> moq_net::Result<Priority> {
144		let mut priority = self.priority.lock().expect("priorities poisoned");
145		match control.update(prioritized(control.subscription(), priority.value)) {
146			Ok(()) | Err(moq_net::Error::Closed) => {}
147			Err(err) => return Err(err),
148		}
149		let control = Arc::new(control);
150		priority
151			.controls
152			.insert(Arc::as_ptr(&control) as usize, Arc::downgrade(&control));
153		Ok(Priority {
154			control,
155			shared: self.priority.clone(),
156		})
157	}
158
159	/// The counters an export reading rendition `name` bumps.
160	pub(crate) fn received(&self, name: &str) -> Arc<crate::stats::Received> {
161		self.received.track(name)
162	}
163
164	/// What each rendition exported through this source (and its clones) has received, keyed by
165	/// rendition ID in the catalog that listed it, including renditions referenced from another
166	/// broadcast.
167	///
168	/// Counters are cumulative for the life of the source, across resubscriptions and a
169	/// [`Follower`](crate::container::ts::Follower) switching identities, so a rendition no export
170	/// reads any more keeps its final counts, until 1,024 renditions are held: then those no export
171	/// reads make way for new ones. Fold this into an
172	/// [`echo::Snapshot`](hang::echo::Snapshot) on the feedback interval.
173	pub fn stats(&self) -> std::collections::BTreeMap<String, hang::echo::Rendition> {
174		self.received.received()
175	}
176
177	/// Serve this source's own path from `broadcast` from now on, as when the same identity
178	/// returns on a new route and the old broadcast's routes are gone.
179	pub(crate) fn pin(&self, broadcast: &moq_net::broadcast::Consumer) {
180		let mut pins = self.pins.lock().expect("pins poisoned");
181		pins.insert(self.path.clone(), broadcast.clone());
182	}
183
184	pub(crate) fn origin(&self) -> &moq_net::origin::Consumer {
185		&self.origin
186	}
187
188	pub(crate) fn path(&self) -> &moq_net::Path {
189		&self.path
190	}
191
192	/// The catalog broadcast, the one at this source's path.
193	pub fn broadcast(&self) -> moq_net::broadcast::Consumer {
194		let pins = self.pins.lock().expect("pins poisoned");
195		pins.get(&self.path).expect("the own path is always held").clone()
196	}
197
198	/// Subscribe to this broadcast's catalog.
199	///
200	/// The stream rejects a catalog carrying a `broadcast` reference that walks above the root
201	/// (see [`Error::EscapingBroadcast`](crate::Error::EscapingBroadcast)), so every snapshot a
202	/// consumer sees is one whose references all name a broadcast it may reach.
203	#[cfg(feature = "async")]
204	pub async fn catalog<E: crate::catalog::hang::CatalogExt>(
205		&self,
206		format: crate::catalog::CatalogFormat,
207	) -> crate::Result<crate::catalog::Consumer<E>> {
208		let mut subscribing = crate::catalog::Subscribing::new(&self.broadcast(), format);
209		kio::wait(|waiter| subscribing.poll_ok(waiter)).await
210	}
211
212	/// The catalog broadcast, as a binding.
213	pub(crate) fn request_catalog(&self) -> Binding {
214		Binding::new(self.broadcast())
215	}
216
217	/// The broadcast `path` is pinned to, or a lookup that waits for the path's first
218	/// announcement and pins its answer.
219	pub(crate) fn request_path(&self, path: &moq_net::Path) -> Binding {
220		let pinned = self.pins.lock().expect("pins poisoned").get(path).cloned();
221		let bound = match pinned {
222			Some(pinned) => Bound::Ready(pinned),
223			None => {
224				let mut following = self.origin.follow(path, None);
225				// Issue the request now: a handler answers it whether or not anyone reads yet.
226				match poll_first(&mut following, &kio::Waiter::noop()) {
227					// The follower hands an identity out once, so an answer on hand is pinned now.
228					Poll::Ready(Ok(broadcast)) => {
229						let mut pins = self.pins.lock().expect("pins poisoned");
230						Bound::Ready(pins.entry(path.clone()).or_insert(broadcast).clone())
231					}
232					_ => Bound::Requested {
233						following: Box::new(Mutex::new(following)),
234						pins: self.pins.clone(),
235						path: path.clone(),
236					},
237				}
238			}
239		};
240		Binding {
241			bound,
242			sibling: *path != self.path,
243		}
244	}
245
246	/// Resolve a rendition's optional broadcast reference to an origin path.
247	///
248	/// A missing or empty reference returns the catalog broadcast path. A valid reference
249	/// may return the empty root path, which still names a broadcast. `None` means the
250	/// reference walked above the root and names nothing.
251	pub fn resolve_reference(&self, rel: Option<&moq_net::path::Relative>) -> Option<moq_net::Path> {
252		match rel.filter(|rel| !rel.is_empty()) {
253			Some(rel) => self.path.try_resolve(rel),
254			None => Some(self.path.clone()),
255		}
256	}
257
258	/// The path of the broadcast a rendition's `broadcast` reference names.
259	///
260	/// The erroring counterpart to [`Self::resolve_reference`], for the consumer side, where
261	/// an escaping reference is a fault to report rather than a rendition to drop.
262	fn target(&self, rel: Option<&moq_net::path::Relative>) -> crate::Result<moq_net::Path> {
263		self.resolve_reference(rel).ok_or_else(|| {
264			let rel = rel.map_or("", |rel| rel.as_str());
265			tracing::error!(rel, catalog = %self.path, "broadcast reference escapes the root");
266			crate::Error::EscapingBroadcast(rel.to_string())
267		})
268	}
269
270	/// Remove the renditions an export must not select: a disabled one (catalog
271	/// `enabled: false`), or one whose broadcast reference escapes above the origin root.
272	///
273	/// Every export runs this on each catalog snapshot, so a disabled rendition reads as
274	/// absent: one that is disabled later leaves the snapshot, and one that re-enables
275	/// returns to it. Every section carrying renditions must be listed here; one left out
276	/// silently exempts its renditions from the containment check, exactly as on the
277	/// consumer side.
278	pub(crate) fn retain_selectable<E: crate::catalog::hang::CatalogExt>(
279		&self,
280		catalog: &mut crate::catalog::hang::Catalog<E>,
281	) {
282		catalog.video.renditions.retain(|_, config| config.enabled);
283		catalog.audio.renditions.retain(|_, config| config.enabled);
284		self.retain_valid_references("video", &mut catalog.video.renditions);
285		self.retain_valid_references("audio", &mut catalog.audio.renditions);
286		self.retain_valid_references("text", &mut catalog.text.renditions);
287		self.retain_valid_references("json", &mut catalog.json.tracks);
288		self.retain_valid_references("binary", &mut catalog.binary.tracks);
289	}
290
291	fn retain_valid_references<C: hang::catalog::Reference>(
292		&self,
293		kind: &'static str,
294		renditions: &mut std::collections::BTreeMap<String, C>,
295	) {
296		renditions.retain(|name, config| {
297			let valid = self.resolve_reference(config.broadcast()).is_some();
298			if !valid {
299				tracing::warn!(
300					rendition = name,
301					kind,
302					"ignoring rendition whose broadcast escapes above the root"
303				);
304			}
305			valid
306		});
307	}
308
309	/// Resolve an optional cross-broadcast reference to its broadcast.
310	///
311	/// `rel` is a rendition's catalog `broadcast` field: `None` (or an empty reference)
312	/// resolves the catalog broadcast itself; anything else fetches the referenced
313	/// broadcast from the origin, waiting for its first announcement if nothing serves it yet.
314	/// Use it when you need the broadcast handle itself (e.g. to FETCH individual groups) rather
315	/// than a subscription.
316	///
317	/// A reference that escapes above the origin root is
318	/// [`Error::EscapingBroadcast`](crate::Error::EscapingBroadcast): the rendition names
319	/// no broadcast, so there is nothing to resolve.
320	#[cfg(feature = "async")]
321	pub async fn resolve(&self, rel: Option<&moq_net::path::Relative>) -> crate::Result<moq_net::broadcast::Consumer> {
322		let binding = self.bind(rel)?;
323		kio::wait(|waiter| binding.poll_broadcast(waiter)).await
324	}
325
326	/// Start one broadcast request now and retain its result for repeated reads.
327	///
328	/// Unlike [`resolve`](Self::resolve), this issues the request without awaiting or polling.
329	/// A path nothing announces yet resolves once something does, and a remote or dynamic
330	/// handler may answer later. A client session that only discovers what is watched is asked
331	/// about the path while the binding waits. Once answered, the binding never resolves the path again, even
332	/// after its publisher is replaced or goes; [`follow`](Self::follow) does.
333	///
334	/// A path this source already resolved binds to that broadcast; otherwise the origin is
335	/// asked, deduplicating repeat requests for one path so the catalog and every rendition share
336	/// one upstream subscription, and its answer is pinned. Use [`Binding::new`] when the
337	/// intended broadcast is already in hand.
338	///
339	/// Rejects an escaping reference exactly as [`resolve`](Self::resolve) does.
340	pub fn bind(&self, rel: Option<&moq_net::path::Relative>) -> crate::Result<Binding> {
341		Ok(self.request_path(&self.target(rel)?))
342	}
343
344	/// Resolve an optional cross-broadcast reference and subscribe to track `name`,
345	/// awaiting SUBSCRIBE_OK.
346	///
347	/// `rel` is a rendition's catalog `broadcast` field: `None` (or an empty reference)
348	/// subscribes on the catalog broadcast; anything else is resolved as in
349	/// [`resolve`](Self::resolve), waiting for its first announcement. A reference that escapes
350	/// above the origin root is [`Error::EscapingBroadcast`](crate::Error::EscapingBroadcast).
351	///
352	/// This is the async counterpart to the poll-driven container exporters: consumers
353	/// that wrap a raw [`moq_net::track::Subscriber`] themselves
354	/// use it to honor cross-broadcast renditions without reimplementing the path math.
355	#[cfg(feature = "async")]
356	pub async fn subscribe_track(
357		&self,
358		rel: Option<&moq_net::path::Relative>,
359		name: &str,
360	) -> crate::Result<moq_net::track::Subscriber> {
361		let mut subscribe = self.subscribe(rel, name)?;
362		kio::wait(|waiter| subscribe.poll(waiter)).await
363	}
364
365	/// Start [`subscribe_track`](Self::subscribe_track) for a caller that polls.
366	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
367	pub(crate) fn subscribe(&self, rel: Option<&moq_net::path::Relative>, name: &str) -> crate::Result<Subscribe> {
368		Ok(Subscribe::Binding {
369			binding: self.bind(rel)?,
370			name: name.to_string(),
371		})
372	}
373
374	/// Follow the broadcast a rendition's reference names across its announcements.
375	///
376	/// Holds nothing: each identity serving a sibling is handed out as it comes online or takes
377	/// over, and its end is reported, so a reader restarts the rendition on each one. A
378	/// reference to the catalog broadcast itself hands out only the broadcast this source was
379	/// built from and never reports its end, since a reader follows its catalog's own end and
380	/// restarts by building a new source.
381	///
382	/// Rejects an escaping reference exactly as [`resolve`](Self::resolve) does.
383	pub fn follow(&self, rel: Option<&moq_net::path::Relative>) -> crate::Result<crate::follow::Identities> {
384		let path = self.target(rel)?;
385		Ok(match path == self.path {
386			true => crate::follow::Identities::fixed(self.broadcast()),
387			false => crate::follow::Identities::following(self.origin.follow(&path, None)?),
388		})
389	}
390}
391
392/// A held broadcast or the retained result of one eagerly issued broadcast request.
393///
394/// A pending request waits for a path nothing announces yet and rides out route churn until it
395/// resolves (see [`follow`](moq_net::origin::Consumer::follow)). Once the
396/// path is pinned, reading the binding answers that pin and never looks the path up again, even
397/// after its publisher is replaced or goes. Issuing a request does not establish an identity
398/// relationship with a separate catalog broadcast.
399///
400/// Build one with [`Source::bind`], or with [`Binding::new`] for a broadcast already in hand.
401pub struct Binding {
402	bound: Bound,
403	/// The reference names another broadcast than the catalog's.
404	sibling: bool,
405}
406
407enum Bound {
408	/// A broadcast the caller already holds.
409	Ready(moq_net::broadcast::Consumer),
410	/// A request issued when the binding was made, resolved once something announces the path,
411	/// or the failure it ended with.
412	Requested {
413		following: Box<Mutex<Following>>,
414		/// Where the answer is pinned, the first for its path winning.
415		pins: Pins,
416		path: moq_net::Path,
417	},
418}
419
420impl Binding {
421	/// Bind to a broadcast already in hand, for a reference that named it.
422	pub fn new(broadcast: moq_net::broadcast::Consumer) -> Self {
423		Self {
424			bound: Bound::Ready(broadcast),
425			sibling: false,
426		}
427	}
428
429	/// Whether the reference names another broadcast than the catalog's.
430	pub(crate) fn sibling(&self) -> bool {
431		self.sibling
432	}
433
434	/// The bound broadcast, once the origin answers.
435	///
436	/// Concurrent reads and cancelled waits retain the same request and result.
437	#[cfg_attr(feature = "async", kio::wrapper)]
438	pub fn poll_broadcast(&self, waiter: &kio::Waiter) -> Poll<crate::Result<moq_net::broadcast::Consumer>> {
439		let broadcast = match &self.bound {
440			Bound::Ready(broadcast) => broadcast.clone(),
441			Bound::Requested { following, pins, path } => {
442				// The follower stays locked until its answer is pinned: it hands each identity
443				// out once, so a concurrent read that polled it in between would wait for the next.
444				let mut following = following.lock().expect("following poisoned");
445				// Once a path is pinned, its pin is the answer: a request that raced another for
446				// the path takes the one pinned first, and the follower is never polled again, since
447				// it would wait out the gap after the pinned identity goes.
448				if let Some(pinned) = pins.lock().expect("pins poisoned").get(path) {
449					pinned.clone()
450				} else {
451					let broadcast = ready!(poll_first(&mut following, waiter))?;
452					// The path's first answer is pinned, so no later reference resolves the path
453					// independently.
454					let mut pins = pins.lock().expect("pins poisoned");
455					pins.entry(path.clone()).or_insert(broadcast).clone()
456				}
457			}
458		};
459		Poll::Ready(Ok(broadcast))
460	}
461}
462
463/// A track subscription waiting for its broadcast, then for SUBSCRIBE_OK.
464#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
465pub(crate) enum Subscribe {
466	Binding {
467		binding: Binding,
468		name: String,
469	},
470	// The broadcast and track handles stay live until the subscription answers.
471	Subscribing {
472		_broadcast: moq_net::broadcast::Consumer,
473		_track: moq_net::track::Consumer,
474		subscribing: moq_net::track::Subscribing,
475	},
476	Done,
477}
478
479#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
480impl Subscribe {
481	/// The track subscriber, once its broadcast resolves and the subscription is confirmed.
482	pub(crate) fn poll(&mut self, waiter: &kio::Waiter) -> Poll<crate::Result<moq_net::track::Subscriber>> {
483		if let Self::Binding { binding, name } = self {
484			let broadcast = ready!(binding.poll_broadcast(waiter));
485			let subscribing = broadcast.and_then(|broadcast| {
486				let track = broadcast.track(name)?;
487				let subscribing = track.subscribe(None).into_inner();
488				Ok((broadcast, track, subscribing))
489			});
490			// The binding drops as soon as it answers, so its request ends with it.
491			match subscribing {
492				Ok((broadcast, track, subscribing)) => {
493					*self = Self::Subscribing {
494						_broadcast: broadcast,
495						_track: track,
496						subscribing,
497					}
498				}
499				Err(err) => {
500					*self = Self::Done;
501					return Poll::Ready(Err(err));
502				}
503			}
504		}
505		let Self::Subscribing { subscribing, .. } = self else {
506			panic!("polled a finished track subscription");
507		};
508		let result = ready!(subscribing.poll_ok(waiter)).map_err(Into::into);
509		*self = Self::Done;
510		Poll::Ready(result)
511	}
512}
513
514/// `subscription` with every range at the program's `priority`.
515fn prioritized(mut subscription: moq_net::track::Subscription, priority: i8) -> moq_net::track::Subscription {
516	for range in &mut subscription.ranges {
517		range.priority = priority;
518	}
519	subscription
520}
521
522/// A binding's follower, or the failure it ended with.
523type Following = Result<moq_net::origin::Following, moq_net::Error>;
524
525/// Poll a binding's follower for its first identity, keeping the failure it ends with so every
526/// later read answers the same.
527fn poll_first(
528	following: &mut Following,
529	waiter: &kio::Waiter,
530) -> Poll<Result<moq_net::broadcast::Consumer, moq_net::Error>> {
531	let result = match following {
532		// The first change is always an identity: an end follows only one handed out.
533		Ok(following) => loop {
534			match ready!(following.poll_available(waiter)) {
535				Ok(Some(broadcast)) => break Ok(broadcast),
536				Ok(None) => continue,
537				Err(err) => break Err(err),
538			}
539		},
540		Err(err) => Err(err.clone()),
541	};
542	if let Err(err) = &result {
543		*following = Err(err.clone());
544	}
545	Poll::Ready(result)
546}
547
548/// Test helper: build an origin producer, spawning its driver on the ambient runtime.
549#[cfg(test)]
550pub(crate) fn produce_origin() -> moq_net::origin::Producer {
551	let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::default());
552	if tokio::runtime::Handle::try_current().is_ok() {
553		tokio::spawn(moq_net::time::run(driver));
554	} else {
555		// A sync test: nothing polls the driver, and dropping it would tear
556		// the origin down, so leak it and rely on the synchronous half.
557		std::mem::forget(driver);
558	}
559	producer
560}
561
562/// Test helper: a [`Source`] for the broadcast at `path`, resolved through `origin`.
563#[cfg(test)]
564pub(crate) async fn resolved(origin: &moq_net::origin::Producer, path: &str) -> Source {
565	let consumer = origin.consume();
566	let broadcast = consumer.request(path, None).await.expect("the broadcast resolves");
567	Source::new(consumer, broadcast)
568}
569
570/// Test helper: a [`Source`] for a standalone `broadcast`, resolving its references through
571/// a throwaway origin that serves nothing. The origin is leaked so its driver runs for the
572/// source's lifetime (harmless in a test binary).
573#[cfg(test)]
574pub(crate) async fn announced(broadcast: &moq_net::broadcast::Consumer) -> Source {
575	let origin = produce_origin();
576	let source = Source::new(origin.consume(), broadcast.clone());
577	Box::leak(Box::new(origin));
578	source
579}
580
581#[cfg(test)]
582mod tests {
583	use super::*;
584	use hang::catalog::{H264, VideoConfig};
585	use moq_net::path::Relative;
586
587	/// Priorities belong to one export, follow late tracks, preserve delivery bounds, and
588	/// retain no subscription once its owning reader drops.
589	#[tokio::test(start_paused = true)]
590	async fn export_priorities_follow_subscription_ownership() {
591		let origin = produce_origin();
592		let source = created(&origin);
593		let mut independent = source.clone();
594		independent.isolate();
595		let broadcast = moq_net::broadcast::Info::new().produce();
596		let track = broadcast.create_track("audio", None).unwrap();
597		let preferences = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range {
598			start: moq_net::track::Start::Time(5),
599			end: Some(10),
600			..Default::default()
601		}]);
602		let first = track.subscribe(preferences.clone());
603		let held = source.control(first.control()).unwrap();
604		let other = track.subscribe(preferences.clone());
605		let _other = independent.control(other.control()).unwrap();
606
607		source.priority(-1).unwrap();
608		assert_eq!(first.subscription(), prioritized(preferences.clone(), -1));
609		assert_eq!(other.subscription(), preferences);
610		let late = track.subscribe(source.subscription(preferences.clone()));
611		let late_held = source.control(late.control()).unwrap();
612		assert_eq!(late.subscription(), first.subscription());
613		source.priority(0).unwrap();
614		assert_eq!(first.subscription(), preferences);
615		assert_eq!(late.subscription(), preferences);
616		drop(track.clone().finish().unwrap());
617		source.priority(-1).unwrap(); // A closed track has no priority left to change.
618		drop((held, late_held));
619		assert!(source.priority.lock().unwrap().controls.is_empty());
620		drop((first, late, other, _other));
621		assert!(track.subscription().is_none());
622	}
623
624	/// Let the origin's driver run the fronts that requests and announcements
625	/// started: they serve asynchronously, shortly after the call returns.
626	async fn settle() {
627		for _ in 0..10 {
628			tokio::task::yield_now().await;
629		}
630	}
631
632	#[tokio::test]
633	async fn binding_retains_a_pending_request_across_cancelled_and_repeated_reads() {
634		let origin = produce_origin();
635		let _catalog = origin.route("pub", Default::default()).unwrap();
636		settle().await;
637		let source = resolved(&origin, "pub").await;
638		let dynamic = origin.claim("media", moq_net::origin::RouteOptions::default()).unwrap();
639		let binding = source.bind(Some(&Relative::new("media").unwrap())).unwrap();
640		let request = dynamic.requested().await.unwrap();
641
642		assert!(
643			binding.poll_broadcast(&kio::Waiter::noop()).is_pending(),
644			"the handler has not answered"
645		);
646
647		tokio::select! {
648			biased;
649			_ = binding.broadcast() => panic!("the handler has not answered"),
650			_ = std::future::ready(()) => {}
651		}
652
653		let route = request.route(moq_net::origin::RouteOptions::hidden()).unwrap();
654		let (first, second, ()) = tokio::join!(binding.broadcast(), binding.broadcast(), async {
655			route.announce().unwrap()
656		});
657		let first = first.unwrap();
658		assert!(!first.is_closed());
659		assert!(first.is_clone(&second.unwrap()));
660		drop((route, dynamic));
661		first.closed().await;
662		assert!(first.is_clone(&binding.broadcast().await.unwrap()));
663	}
664
665	/// A binding made before anything announces its sibling resolves on the first announcement
666	/// and keeps that identity: past its replacement, and once it goes, answering the ended
667	/// identity at once rather than waiting for the next one.
668	#[tokio::test(start_paused = true)]
669	async fn a_binding_waits_for_the_first_announcement_and_keeps_it() {
670		let origin = produce_origin();
671		let _catalog = origin.route("pub", Default::default()).unwrap();
672		settle().await;
673		let source = resolved(&origin, "pub").await;
674		let media = Relative::new("media").unwrap();
675		let binding = source.bind(Some(&media)).unwrap();
676		settle().await;
677		assert!(binding.poll_broadcast(&kio::Waiter::noop()).is_pending());
678
679		let first_publisher = origin.route("media", Default::default()).unwrap();
680		let first = binding.broadcast().await.unwrap();
681		assert!(!first.is_closed());
682
683		let _second = origin.route("media", Default::default()).unwrap();
684		settle().await;
685		assert!(binding.broadcast().await.unwrap().is_clone(&first));
686		assert!(source.resolve(Some(&media)).await.unwrap().is_clone(&first));
687
688		drop(first_publisher);
689		first.closed().await;
690		assert!(binding.broadcast().await.unwrap().is_clone(&first));
691		let late = source.bind(Some(&media)).unwrap();
692		assert!(
693			late.broadcast().await.unwrap().is_clone(&first),
694			"a later binding reads the pin"
695		);
696
697		// A new catalog identity starts fresh pins, which resolve the replacement.
698		let fresh = source.switched(&source.broadcast());
699		assert!(!fresh.resolve(Some(&media)).await.unwrap().is_closed());
700	}
701
702	/// A source serves its path from the broadcast it was built from, even when a replacement
703	/// already won the path: a track only the replacement carries is not read from it.
704	#[tokio::test(start_paused = true)]
705	async fn a_source_keeps_the_broadcast_it_was_built_from() {
706		let origin = produce_origin();
707		let _old = origin.route("live", Default::default()).unwrap();
708		settle().await;
709		let consumer = origin.consume();
710		let first = consumer.request("live", None).await.unwrap();
711
712		let new = origin.route("live", Default::default()).unwrap();
713		let _late = new.broadcast().create_track("late", None).unwrap();
714		settle().await;
715		let source = Source::new(consumer, first.clone());
716		assert!(source.broadcast().is_clone(&first));
717		assert!(source.resolve(None).await.unwrap().is_clone(&first));
718		assert!(
719			source.subscribe_track(None, "late").await.is_err(),
720			"the replacement's track is never read"
721		);
722	}
723
724	/// A sibling resolves through the session that announces it, even while another lazily
725	/// discovering session on the origin never answers its announce request.
726	#[tokio::test(start_paused = true)]
727	async fn a_stalled_session_does_not_hold_up_a_sibling() {
728		use crate::container::test_util::Link;
729
730		let healthy = produce_origin();
731		let _catalog = healthy.route("a/pub", Default::default()).unwrap();
732		let _sibling = healthy.route("a/source", Default::default()).unwrap();
733		let stalled = produce_origin();
734		let subscriber = produce_origin();
735		let _healthy = Link::lazy(&healthy, &subscriber, true).await;
736		let _stalled = Link::lazy(&stalled, &subscriber, false).await;
737
738		let timeout = std::time::Duration::from_secs(5);
739		let consumer = subscriber.consume();
740		let catalog = kio::clock::timeout(timeout, consumer.follow("a/pub", None).unwrap().available())
741			.await
742			.expect("the catalog resolves")
743			.unwrap()
744			.unwrap();
745		let source = Source::new(consumer, catalog);
746		let sibling = kio::clock::timeout(timeout, source.resolve(Some(&Relative::new("./source").unwrap())))
747			.await
748			.expect("the sibling resolves without the stalled session")
749			.unwrap();
750		assert!(!sibling.is_closed());
751
752		// Nothing serves a later sibling yet and the stalled session never syncs, so its
753		// lookup keeps waiting rather than failing, and resolves once it is published.
754		let binding = source.bind(Some(&Relative::new("./late").unwrap())).unwrap();
755		settle().await;
756		assert!(binding.poll_broadcast(&kio::Waiter::noop()).is_pending());
757		let _late = healthy.route("a/late", Default::default()).unwrap();
758		let late = kio::clock::timeout(timeout, binding.broadcast())
759			.await
760			.expect("the later sibling resolves")
761			.unwrap();
762		assert!(!late.is_closed());
763	}
764
765	/// A sibling reference stays on the broadcast it first resolved too.
766	#[tokio::test(start_paused = true)]
767	async fn a_source_keeps_the_sibling_it_resolved() {
768		let origin = produce_origin();
769		let _catalog = origin.route("a/pub", Default::default()).unwrap();
770		let _old = origin.route("a/source", Default::default()).unwrap();
771		settle().await;
772		let source = resolved(&origin, "a/pub").await;
773		let sibling = Relative::new("./source").unwrap();
774		let first = source.resolve(Some(&sibling)).await.expect("the sibling resolves");
775
776		let new = origin.route("a/source", Default::default()).unwrap();
777		let _late = new.broadcast().create_track("late", None).unwrap();
778		settle().await;
779		assert!(source.resolve(Some(&sibling)).await.unwrap().is_clone(&first));
780		assert!(
781			source.subscribe_track(Some(&sibling), "late").await.is_err(),
782			"the replacement's track is never read"
783		);
784		let bound = source.bind(Some(&sibling)).unwrap().broadcast().await.unwrap();
785		assert!(bound.is_clone(&first), "a binding honors the pin too");
786	}
787
788	/// Every self-reference serves the broadcast the source was built from, even once it
789	/// ended and a replacement took the path.
790	#[tokio::test(start_paused = true)]
791	async fn self_references_keep_the_catalog_broadcast_after_replacement() {
792		let origin = produce_origin();
793		let old = origin.route("a/live", Default::default()).unwrap();
794		settle().await;
795		let source = resolved(&origin, "a/live").await;
796		drop(old);
797		let _replacement = origin.route("a/live", Default::default()).unwrap();
798		settle().await;
799
800		for reference in [None, Some(""), Some("live"), Some("./live"), Some("../a/live")] {
801			let rel = reference.map(|rel| Relative::new(rel).unwrap());
802			let bound = source.bind(rel.as_ref()).unwrap().broadcast().await.unwrap();
803			assert!(
804				bound.is_closed(),
805				"{reference:?} must keep the original catalog broadcast"
806			);
807		}
808	}
809
810	#[tokio::test]
811	async fn no_override_targets_catalog_broadcast() {
812		let origin = produce_origin();
813		let _producer = origin.route("a/pub", moq_net::origin::RouteOptions::default()).unwrap();
814		settle().await;
815
816		let source = resolved(&origin, "a/pub").await;
817
818		// No reference and an empty reference both resolve to the catalog broadcast.
819		source
820			.bind(None)
821			.expect("no reference is always resolvable")
822			.broadcast()
823			.await
824			.expect("catalog broadcast should resolve");
825		let empty = Relative::empty();
826		source
827			.bind(Some(&empty))
828			.expect("empty reference is always resolvable")
829			.broadcast()
830			.await
831			.expect("empty reference should resolve to the catalog broadcast");
832	}
833
834	#[tokio::test]
835	async fn subscribe_track_resolves_catalog_broadcast() {
836		let origin = produce_origin();
837		let producer = origin.route("a/pub", moq_net::origin::RouteOptions::default()).unwrap();
838		// The track must exist for the subscription to resolve (SUBSCRIBE_OK).
839		let _video = producer.broadcast().create_track("video", None).unwrap();
840		settle().await;
841
842		let source = resolved(&origin, "a/pub").await;
843		source
844			.subscribe_track(None, "video")
845			.await
846			.expect("catalog track should resolve");
847	}
848
849	#[tokio::test]
850	async fn self_reference_targets_catalog_broadcast() {
851		let origin = produce_origin();
852		let producer = origin.route("a/pub", moq_net::origin::RouteOptions::default()).unwrap();
853		let _video = producer.broadcast().create_track("video", None).unwrap();
854		settle().await;
855
856		let source = resolved(&origin, "a/pub").await;
857
858		// Names the catalog within its own parent.
859		let rel = Relative::new("./pub").unwrap();
860		source
861			.subscribe_track(Some(&rel), "video")
862			.await
863			.expect("self-reference should resolve to the catalog broadcast");
864	}
865
866	#[tokio::test]
867	async fn escaping_reference_is_rejected() {
868		let origin = produce_origin();
869
870		let catalog = origin.route("a/pub", moq_net::origin::RouteOptions::default()).unwrap();
871		let _catalog_video = catalog.broadcast().create_track("video", None).unwrap();
872
873		// The broadcast an escaping reference would land on if it clamped at the root.
874		let clamped = origin
875			.route("elsewhere", moq_net::origin::RouteOptions::default())
876			.unwrap();
877		let _clamped_video = clamped.broadcast().create_track("video", None).unwrap();
878		settle().await;
879
880		let source = resolved(&origin, "a/pub").await;
881
882		// A reference resolves against the catalog's parent (`a`), so a second `..` walks
883		// above the root. A lone `..` stops at the root, which still names a broadcast, so
884		// it is not in this set.
885		for reference in ["../../elsewhere", "../..", "../../.."] {
886			let rel = Relative::new(reference).unwrap();
887			assert!(
888				source.resolve_reference(Some(&rel)).is_none(),
889				"{reference} should escape"
890			);
891			assert!(source.bind(Some(&rel)).is_err(), "{reference} should be rejected");
892
893			// Neither `elsewhere` nor the catalog broadcast answers it: the rendition names
894			// no broadcast at all.
895			match source.resolve(Some(&rel)).await {
896				Err(crate::Error::EscapingBroadcast(_)) => {}
897				Err(err) => panic!("{reference} failed with the wrong error: {err:?}"),
898				Ok(_) => panic!("{reference} should not resolve to any broadcast"),
899			}
900			match source.subscribe_track(Some(&rel), "video").await {
901				Err(crate::Error::EscapingBroadcast(_)) => {}
902				Err(err) => panic!("{reference} failed with the wrong error: {err:?}"),
903				Ok(_) => panic!("{reference} should not resolve to any broadcast"),
904			}
905		}
906	}
907
908	/// A source over a broadcast created at `a/pub`, built without awaiting the origin.
909	fn created(origin: &moq_net::origin::Producer) -> Source {
910		let broadcast = origin
911			.route("a/pub", moq_net::origin::RouteOptions::hidden())
912			.unwrap()
913			.broadcast()
914			.consume();
915		Source::new(origin.consume(), broadcast)
916	}
917
918	#[test]
919	fn escaping_rendition_is_removed_while_valid_sibling_remains() {
920		let origin = produce_origin();
921		let source = created(&origin);
922		let mut escaped = VideoConfig::new(H264 {
923			profile: 0x42,
924			constraints: 0,
925			level: 0x1e,
926			inline: false,
927		});
928		escaped.broadcast = Some(Relative::new("../../source").unwrap());
929		let mut sibling = escaped.clone();
930		sibling.broadcast = Some(Relative::new("./source").unwrap());
931
932		let mut catalog = hang::Catalog::<()>::default();
933		catalog.video.renditions.insert("escaped".to_string(), escaped);
934		catalog.video.renditions.insert("sibling".to_string(), sibling);
935		source.retain_selectable(&mut catalog);
936
937		assert!(!catalog.video.renditions.contains_key("escaped"));
938		assert!(catalog.video.renditions.contains_key("sibling"));
939	}
940
941	/// A disabled rendition is never selected, while its enabled sibling is.
942	#[test]
943	fn disabled_rendition_is_removed_while_enabled_sibling_remains() {
944		let origin = produce_origin();
945		let source = created(&origin);
946		let enabled = VideoConfig::new(H264 {
947			profile: 0x42,
948			constraints: 0,
949			level: 0x1e,
950			inline: false,
951		});
952		let mut disabled = enabled.clone();
953		disabled.enabled = false;
954		let mut muted = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 2);
955		muted.enabled = false;
956
957		let mut catalog = hang::Catalog::<()>::default();
958		catalog.video.renditions.insert("disabled".to_string(), disabled);
959		catalog.video.renditions.insert("enabled".to_string(), enabled);
960		catalog.audio.renditions.insert("muted".to_string(), muted);
961		source.retain_selectable(&mut catalog);
962
963		assert_eq!(catalog.video.renditions.keys().collect::<Vec<_>>(), vec!["enabled"]);
964		assert!(catalog.audio.renditions.is_empty());
965	}
966
967	/// The filter covers every section carrying renditions, not just the media ones. Text
968	/// is the section that only exists on one side of the containment check by default, so
969	/// it is the one that silently goes unchecked when the two sides drift.
970	#[test]
971	fn escaping_text_rendition_is_removed() {
972		let origin = produce_origin();
973		let source = created(&origin);
974
975		let mut escaped = hang::catalog::TextConfig::new(hang::catalog::TextFormat::Vtt);
976		escaped.broadcast = Some(Relative::new("../../source").unwrap());
977		let mut sibling = escaped.clone();
978		sibling.broadcast = Some(Relative::new("./source").unwrap());
979
980		let mut catalog = hang::Catalog::<()>::default();
981		catalog.text.renditions.insert("escaped".to_string(), escaped);
982		catalog.text.renditions.insert("sibling".to_string(), sibling);
983		source.retain_selectable(&mut catalog);
984
985		assert!(!catalog.text.renditions.contains_key("escaped"));
986		assert!(catalog.text.renditions.contains_key("sibling"));
987	}
988
989	#[tokio::test]
990	async fn subscribe_track_resolves_referenced_broadcast() {
991		let origin = produce_origin();
992
993		let _catalog = origin.route("a/pub", moq_net::origin::RouteOptions::default()).unwrap();
994
995		let referenced = origin
996			.route("a/source", moq_net::origin::RouteOptions::default())
997			.unwrap();
998		let _video = referenced.broadcast().create_track("video", None).unwrap();
999		settle().await;
1000
1001		let source = resolved(&origin, "a/pub").await;
1002
1003		// The reference resolves to `a/source`, whose "video" track answers the subscribe.
1004		let rel = Relative::new("./source").unwrap();
1005		source
1006			.subscribe_track(Some(&rel), "video")
1007			.await
1008			.expect("referenced track should resolve");
1009	}
1010
1011	#[tokio::test]
1012	async fn dot_resolves_output_parent() {
1013		let origin = produce_origin();
1014
1015		let _catalog = origin
1016			.route("a/source/transcode", moq_net::origin::RouteOptions::default())
1017			.unwrap();
1018
1019		let referenced = origin
1020			.route("a/source", moq_net::origin::RouteOptions::default())
1021			.unwrap();
1022		let _video = referenced.broadcast().create_track("video", None).unwrap();
1023		settle().await;
1024
1025		let source = resolved(&origin, "a/source/transcode").await;
1026		let rel = Relative::new(".").unwrap();
1027		source
1028			.subscribe_track(Some(&rel), "video")
1029			.await
1030			.expect("dot should resolve to the catalog broadcast's parent");
1031	}
1032
1033	#[tokio::test]
1034	async fn dot_resolves_one_segment_catalog_to_root() {
1035		let origin = produce_origin();
1036
1037		let _catalog = origin.route("top", moq_net::origin::RouteOptions::default()).unwrap();
1038
1039		let root = origin.route("", moq_net::origin::RouteOptions::default()).unwrap();
1040		let _video = root.broadcast().create_track("video", None).unwrap();
1041		settle().await;
1042
1043		let source = resolved(&origin, "top").await;
1044		let rel = Relative::new(".").unwrap();
1045		source
1046			.subscribe_track(Some(&rel), "video")
1047			.await
1048			.expect("dot should resolve to the empty root broadcast");
1049	}
1050}