Skip to main content

moq_mux/catalog/hang/
consumer.rs

1use std::task::Poll;
2
3use super::{Catalog, CatalogExt};
4use crate::Result;
5
6/// A catalog consumer, used to receive catalog updates and discover tracks.
7///
8/// This wraps [`hang::catalog::Consumer`], which reconstructs the JSON catalog from the latest
9/// group's snapshot and checks its renditions, reporting failures as this crate's
10/// [`Error`](crate::Error).
11///
12/// Generic over the application extension `E` (defaulting to `()`); yields each
13/// [`Catalog<E>`](super::Catalog) with the timestamp it takes effect at.
14///
15/// A rendition's `broadcast` field is relative to the path of the broadcast serving the
16/// catalog, taken from the track's [`broadcast::Info::path`](moq_net::broadcast::Info::path).
17/// A catalog that misuses that reference is rejected outright (see [`Self::poll_next`]).
18pub struct Consumer<E: CatalogExt = ()> {
19	inner: hang::catalog::Consumer<E>,
20}
21
22impl<E: CatalogExt> Consumer<E> {
23	/// Create a new catalog consumer reading a `catalog.json` track, compressed or not.
24	///
25	/// Subscribes to the track itself; see [`hang::catalog::Consumer::new`].
26	pub fn new(track: moq_net::track::Consumer) -> Self {
27		Self {
28			inner: hang::catalog::Consumer::new(track, std::time::Duration::ZERO),
29		}
30	}
31
32	/// Wait for the consumer's subscription to resolve, returning the catalog track's info.
33	///
34	/// Fails with [`Error::Moq`](crate::Error::Moq) if the catalog is refused or missing; see
35	/// [`hang::catalog::Consumer::poll_info`].
36	#[cfg_attr(feature = "async", kio::wrapper)]
37	pub fn poll_info(&mut self, waiter: &kio::Waiter) -> Poll<Result<moq_net::track::Info>> {
38		self.inner.poll_info(waiter).map(|info| info.map_err(lift))
39	}
40
41	/// Get the next catalog update and the timestamp it takes effect at, or `None` once the track ends.
42	///
43	/// The timestamp is on the broadcast's media timeline: a derivative republishing that media
44	/// stamps its own catalog change there too.
45	///
46	/// Fails with [`Error::EscapingBroadcast`](crate::Error::EscapingBroadcast) if any rendition's
47	/// `broadcast` reference or echo prefix walks above the root, rejecting the whole catalog
48	/// (see [`hang::catalog::Consumer::poll_next`]). A transport failure is
49	/// [`Error::Moq`](crate::Error::Moq).
50	#[cfg_attr(feature = "async", kio::wrapper)]
51	pub fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<moq_json::Timed<Catalog<E>>>>> {
52		self.inner.poll_next(waiter).map(|next| next.map_err(lift))
53	}
54}
55
56/// Lift a hang error to this crate's variants, which `Source` reports for the same faults.
57fn lift(err: hang::Error) -> crate::Error {
58	match err {
59		hang::Error::Moq(err) => crate::Error::Moq(err),
60		hang::Error::EscapingBroadcast(rel) => crate::Error::EscapingBroadcast(rel),
61		err => crate::Error::Hang(err),
62	}
63}
64
65impl<E: CatalogExt> From<moq_net::track::Consumer> for Consumer<E> {
66	fn from(inner: moq_net::track::Consumer) -> Self {
67		Self::new(inner)
68	}
69}
70
71#[cfg(test)]
72mod test {
73	use crate::container::test_util::Lazy;
74	use std::task::Poll;
75
76	use super::*;
77
78	/// Mint a standalone track for tests via a throwaway broadcast, since tracks are
79	/// born from their broadcast (no public `track::Producer::new`).
80	fn track_producer(
81		name: impl Into<std::sync::Arc<str>>,
82		info: impl Into<Option<moq_net::track::Info>>,
83	) -> moq_net::track::Producer {
84		moq_net::broadcast::Info::new()
85			.produce()
86			.create_track(name, info)
87			.unwrap()
88	}
89
90	// Build a base catalog distinguished by an audio rendition named `name`, plus its JSON payload.
91	fn catalog_payload(name: &str) -> (Catalog, String) {
92		let mut catalog = Catalog::default();
93		catalog.audio.renditions.insert(
94			name.to_string(),
95			hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 2),
96		);
97		let payload = serde_json::to_string(&catalog).expect("catalog should serialize");
98		(catalog, payload)
99	}
100
101	fn expect_catalog(result: Poll<Result<Option<moq_json::Timed<Catalog>>>>) -> Catalog {
102		match result {
103			Poll::Ready(Ok(Some(decoded))) => decoded.value,
104			other => panic!("expected catalog payload, got {other:?}"),
105		}
106	}
107
108	fn opus() -> hang::catalog::AudioConfig {
109		hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 2)
110	}
111
112	fn referencing(rel: &str) -> hang::catalog::AudioConfig {
113		let mut config = opus();
114		config.broadcast = Some(moq_net::path::Relative::new(rel).unwrap());
115		config
116	}
117
118	/// Publish `catalog` as one snapshot on a broadcast at `a/pub` (two segments, so a
119	/// third `..` walks above the root) and return what the stream yields. The broadcast is
120	/// minted through an origin because that is what stamps
121	/// [`broadcast::Info::path`](moq_net::broadcast::Info::path), the base the consumer
122	/// resolves against.
123	fn publish_catalog(published: Catalog<()>) -> Result<Option<Catalog>> {
124		let origin = crate::source::produce_origin();
125		let broadcast = origin
126			.route("a/pub", moq_net::origin::RouteOptions::hidden())
127			.expect("broadcast should create");
128		let track = broadcast
129			.broadcast()
130			.create_track(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info())
131			.expect("catalog track should create");
132		let mut consumer = Consumer::new(track.consume());
133		let mut group = Lazy::appending(&track);
134
135		let payload = serde_json::to_string(&published).expect("catalog should serialize");
136		group
137			.write_frame(moq_net::Timestamp::ZERO, payload)
138			.expect("catalog frame should write");
139		group.finish().expect("catalog group should finish");
140
141		match consumer.poll_next(&kio::Waiter::noop()) {
142			Poll::Ready(result) => result.map(|next| next.map(|timed| timed.value)),
143			Poll::Pending => panic!("a finished catalog group should be ready"),
144		}
145	}
146
147	/// [`publish_catalog`] over audio renditions alone.
148	fn publish(renditions: Vec<(&str, hang::catalog::AudioConfig)>) -> Result<Option<Catalog>> {
149		let mut published = Catalog::<()>::default();
150		for (name, config) in renditions {
151			published.audio.renditions.insert(name.to_string(), config);
152		}
153		publish_catalog(published)
154	}
155
156	/// [`publish_catalog`] against the answer a dynamic handler prepares and publishes at
157	/// `a/pub`, read back through the requesting origin cursor. That is the shape an app
158	/// takes when it answers an origin request.
159	async fn publish_catalog_served(published: Catalog<()>) -> Result<Option<Catalog>> {
160		let origin = crate::source::produce_origin();
161		let dynamic = origin.claim("", moq_net::origin::RouteOptions::default()).unwrap();
162		let requesting = origin.consume().request("a/pub", None);
163		// The handler hands its route back: dropping it would retract the route and end
164		// the broadcast it just served.
165		let handler = tokio::spawn(async move {
166			let route = dynamic
167				.requested()
168				.await
169				.expect("handler should be asked for the path")
170				.route(moq_net::origin::RouteOptions::hidden())
171				.expect("the answer should route");
172			let track = route
173				.broadcast()
174				.create_track(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info())
175				.expect("catalog track should create");
176			route.announce().expect("the answer should announce");
177			(dynamic, route, track)
178		});
179
180		let resolved = requesting.await;
181		let (_dynamic, _route, track) = handler.await.expect("handler task");
182		let catalog_track = resolved
183			.expect("the handler served it")
184			.track(hang::Catalog::DEFAULT_NAME)
185			.expect("catalog track should resolve");
186		let mut consumer = Consumer::new(catalog_track);
187
188		let mut group = Lazy::appending(&track);
189		let payload = serde_json::to_string(&published).expect("catalog should serialize");
190		group
191			.write_frame(moq_net::Timestamp::ZERO, payload)
192			.expect("catalog frame should write");
193		group.finish().expect("catalog group should finish");
194
195		consumer.next().await.map(|next| next.map(|timed| timed.value))
196	}
197
198	/// [`publish_catalog_served`] over one audio rendition carrying `reference`.
199	async fn publish_served(reference: &str) -> Result<Option<Catalog>> {
200		let mut published = Catalog::<()>::default();
201		published
202			.audio
203			.renditions
204			.insert("sibling".to_string(), referencing(reference));
205		publish_catalog_served(published).await
206	}
207
208	fn soliciting(reference: &str) -> Catalog {
209		let (mut catalog, _) = catalog_payload("here");
210		catalog.echo = Some(hang::catalog::Echo::new(
211			moq_net::path::Relative::new(reference).unwrap(),
212		));
213		catalog
214	}
215
216	#[tokio::test]
217	async fn echo_prefix_is_checked_before_the_native_reader_yields() {
218		for reference in ["viewers", "../viewers", ""] {
219			assert!(publish_catalog(soliciting(reference)).unwrap().unwrap().echo.is_some());
220		}
221		for reference in ["../../viewers", "../../../elsewhere"] {
222			let result = publish_catalog(soliciting(reference));
223			assert!(
224				matches!(result, Err(crate::Error::EscapingBroadcast(_))),
225				"{reference}: {result:?}"
226			);
227		}
228	}
229
230	#[tokio::test]
231	async fn echo_prefix_is_checked_against_the_dynamic_served_path() {
232		assert!(
233			publish_catalog_served(soliciting("../viewers"))
234				.await
235				.unwrap()
236				.unwrap()
237				.echo
238				.is_some()
239		);
240		let result = publish_catalog_served(soliciting("../../../elsewhere")).await;
241		assert!(matches!(result, Err(crate::Error::EscapingBroadcast(_))), "{result:?}");
242	}
243
244	/// A reference that stops at or below the root names a broadcast, so the catalog stands.
245	/// `a/pub` resolves against `a`, so `..` is what lands on the root itself.
246	#[tokio::test]
247	async fn accepts_references_within_the_root() {
248		let catalog = publish(vec![
249			("here", opus()),
250			("sibling", referencing("./source")),
251			("root", referencing("..")),
252		])
253		.expect("catalog should be accepted")
254		.expect("catalog should decode");
255
256		let mut names: Vec<&str> = catalog.audio.renditions.keys().map(String::as_str).collect();
257		names.sort_unstable();
258		assert_eq!(names, ["here", "root", "sibling"]);
259	}
260
261	/// A rendition whose `broadcast` reference walks above the root names no broadcast, and
262	/// the root is the consumer's authorized subtree. The whole catalog is rejected rather
263	/// than the one rendition, so a publisher bug is loud instead of surfacing later as a
264	/// track that never fills.
265	#[tokio::test]
266	async fn rejects_a_catalog_whose_broadcast_escapes_the_root() {
267		for reference in ["../../../elsewhere", "../../..", "../../../.."] {
268			// The escaping rendition is published alongside perfectly good ones, which do
269			// not rescue the catalog.
270			let result = publish(vec![
271				("here", opus()),
272				("sibling", referencing("../source")),
273				("escaping", referencing(reference)),
274			]);
275
276			match result {
277				Err(crate::Error::EscapingBroadcast(reported)) => assert_eq!(reported, reference),
278				Err(err) => panic!("{reference} failed with the wrong error: {err:?}"),
279				Ok(_) => panic!("{reference} should reject the catalog"),
280			}
281		}
282	}
283
284	/// A broadcast is named by where its reader found it, not by where its producer created
285	/// it: a standalone broadcast served on demand at `a/pub` resolves `../source` against
286	/// `a/pub`. Naming it by the producer's own (empty) path would make its own root the
287	/// bound, rejecting a reference the requester can perfectly well reach.
288	#[tokio::test]
289	async fn accepts_references_within_the_served_path() {
290		let catalog = publish_served("../source")
291			.await
292			.expect("catalog should be accepted")
293			.expect("catalog should decode");
294
295		let rendition = catalog
296			.audio
297			.renditions
298			.get("sibling")
299			.expect("rendition should survive");
300		assert_eq!(rendition.broadcast.as_ref().unwrap().as_str(), "../source");
301	}
302
303	/// The bound moves with the served path rather than disappearing: a reference that
304	/// walks above `a/pub` still names nothing and still rejects the catalog.
305	#[tokio::test]
306	async fn rejects_references_escaping_the_served_path() {
307		match publish_served("../../../elsewhere").await {
308			Err(crate::Error::EscapingBroadcast(reported)) => assert_eq!(reported, "../../../elsewhere"),
309			Err(err) => panic!("wrong error: {err:?}"),
310			Ok(_) => panic!("an escaping reference should reject the catalog"),
311		}
312	}
313
314	/// The containment check covers every section carrying renditions, not just audio and
315	/// video: an escaping text (caption) reference rejects the catalog the same way.
316	#[tokio::test]
317	async fn rejects_a_catalog_whose_text_broadcast_escapes_the_root() {
318		let mut published = Catalog::<()>::default();
319		published.audio.renditions.insert("here".to_string(), opus());
320
321		let mut text = hang::catalog::TextConfig::new(hang::catalog::TextFormat::Vtt);
322		text.broadcast = Some(moq_net::path::Relative::new("../../../elsewhere").unwrap());
323		published.text.renditions.insert("captions".to_string(), text);
324
325		match publish_catalog(published) {
326			Err(crate::Error::EscapingBroadcast(reported)) => assert_eq!(reported, "../../../elsewhere"),
327			Err(err) => panic!("wrong error: {err:?}"),
328			Ok(_) => panic!("an escaping text reference should reject the catalog"),
329		}
330	}
331
332	/// Data tracks carry a `broadcast` reference like any rendition, so the containment check
333	/// covers them too. Without this the catalog is accepted and the escape surfaces much later,
334	/// when the entry is subscribed.
335	#[tokio::test]
336	async fn rejects_a_catalog_whose_data_broadcast_escapes_the_root() {
337		for section in ["json", "binary"] {
338			let mut published = Catalog::<()>::default();
339			published.audio.renditions.insert("here".to_string(), opus());
340
341			let escaping = moq_net::path::Relative::new("../../../elsewhere");
342			match section {
343				"json" => {
344					let mut config = hang::catalog::JsonConfig::new(hang::catalog::Mode::Stream);
345					config.broadcast = Some(escaping.unwrap());
346					published.json.tracks.insert("chat".to_string(), config);
347				}
348				_ => {
349					let mut config = hang::catalog::BinaryConfig::new(hang::catalog::Mode::Stream);
350					config.broadcast = Some(escaping.unwrap());
351					published.binary.tracks.insert("blobs".to_string(), config);
352				}
353			}
354
355			match publish_catalog(published) {
356				Err(crate::Error::EscapingBroadcast(reported)) => assert_eq!(reported, "../../../elsewhere"),
357				Err(err) => panic!("wrong error for {section}: {err:?}"),
358				Ok(_) => panic!("an escaping {section} reference should reject the catalog"),
359			}
360		}
361	}
362
363	/// A group whose first frame, `payload` at `timestamp`, is still streaming in.
364	fn streaming(
365		track: &moq_net::track::Producer,
366		timestamp: moq_net::Timestamp,
367		payload: &impl AsRef<[u8]>,
368	) -> moq_net::frame::Producer {
369		let size = payload.as_ref().len() as u64;
370		track
371			.append_frame(moq_net::frame::Info { timestamp, size })
372			.expect("catalog frame should open")
373	}
374
375	#[test]
376	fn waits_for_pending_catalog_group_payload() {
377		let track = track_producer(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info());
378		let mut consumer = Consumer::new(track.consume());
379		let mut group = Lazy::appending(&track);
380
381		let waiter = kio::Waiter::noop();
382		assert!(matches!(consumer.poll_next(&waiter), Poll::Pending));
383
384		let (catalog, payload) = catalog_payload("pending");
385		group
386			.write_frame(moq_net::Timestamp::ZERO, payload)
387			.expect("catalog frame should write");
388		group.finish().expect("catalog group should finish");
389
390		assert_eq!(expect_catalog(consumer.poll_next(&waiter)), catalog);
391	}
392
393	#[test]
394	fn a_newer_version_is_a_typed_refusal() {
395		let track = track_producer(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info());
396		let mut consumer: Consumer = Consumer::new(track.consume());
397		let mut group = Lazy::appending(&track);
398		group
399			.write_frame(moq_net::Timestamp::ZERO, r#"{"version":5}"#)
400			.expect("catalog frame should write");
401		group.finish().expect("catalog group should finish");
402
403		assert!(matches!(
404			consumer.poll_next(&kio::Waiter::noop()),
405			Poll::Ready(Err(crate::Error::Hang(hang::Error::UnsupportedVersion(5))))
406		));
407	}
408
409	#[test]
410	fn waits_for_pending_catalog_group_payload_after_track_finish() {
411		let track = track_producer(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info());
412		let mut consumer = Consumer::new(track.consume());
413		let (catalog, payload) = catalog_payload("finished");
414		let mut frame = streaming(&track, moq_net::Timestamp::ZERO, &payload);
415
416		let _track = track.finish().expect("catalog track should finish");
417
418		let waiter = kio::Waiter::noop();
419		assert!(matches!(consumer.poll_next(&waiter), Poll::Pending));
420
421		frame.write(payload).expect("catalog frame should write");
422		frame.finish().unwrap().finish().expect("catalog group should finish");
423
424		assert_eq!(expect_catalog(consumer.poll_next(&waiter)), catalog);
425	}
426
427	#[test]
428	fn returns_latest_complete_catalog_group() {
429		let track = track_producer(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info());
430		let mut consumer = Consumer::new(track.consume());
431		let waiter = kio::Waiter::noop();
432
433		let (_old, old_payload) = catalog_payload("old");
434		let (latest, latest_payload) = catalog_payload("latest");
435
436		let mut old_group = Lazy::appending(&track);
437		old_group
438			.write_frame(moq_net::Timestamp::ZERO, old_payload)
439			.expect("old catalog frame should write");
440		old_group.finish().expect("old catalog group should finish");
441
442		let mut latest_group = Lazy::appending(&track);
443		latest_group
444			.write_frame(moq_net::Timestamp::from_millis(1).unwrap(), latest_payload)
445			.expect("latest catalog frame should write");
446		latest_group.finish().expect("latest catalog group should finish");
447		let _track = track.finish().expect("catalog track should finish");
448
449		assert_eq!(expect_catalog(consumer.poll_next(&waiter)), latest);
450		assert!(matches!(consumer.poll_next(&waiter), Poll::Ready(Ok(None))));
451	}
452
453	#[test]
454	fn waits_for_newer_pending_group_instead_of_returning_older_ready_group() {
455		let track = track_producer(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info());
456		let mut consumer = Consumer::new(track.consume());
457		let waiter = kio::Waiter::noop();
458
459		let (_old, old_payload) = catalog_payload("old");
460		let (latest, latest_payload) = catalog_payload("latest");
461
462		let mut old_group = Lazy::appending(&track);
463		old_group
464			.write_frame(moq_net::Timestamp::ZERO, old_payload)
465			.expect("old catalog frame should write");
466		old_group.finish().expect("old catalog group should finish");
467
468		let mut latest_frame = streaming(&track, moq_net::Timestamp::from_millis(1).unwrap(), &latest_payload);
469
470		assert!(matches!(consumer.poll_next(&waiter), Poll::Pending));
471
472		latest_frame
473			.write(latest_payload)
474			.expect("latest catalog frame should write");
475		latest_frame
476			.finish()
477			.unwrap()
478			.finish()
479			.expect("latest catalog group should finish");
480
481		assert_eq!(expect_catalog(consumer.poll_next(&waiter)), latest);
482	}
483
484	#[test]
485	fn retained_pending_group_is_superseded_by_newer_group() {
486		let track = track_producer(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info());
487		let mut consumer = Consumer::new(track.consume());
488		let waiter = kio::Waiter::noop();
489
490		let (_old, old_payload) = catalog_payload("old");
491		let (latest, latest_payload) = catalog_payload("latest");
492
493		let mut old_frame = streaming(&track, moq_net::Timestamp::ZERO, &old_payload);
494
495		assert!(matches!(consumer.poll_next(&waiter), Poll::Pending));
496
497		let mut latest_group = Lazy::appending(&track);
498		latest_group
499			.write_frame(moq_net::Timestamp::from_millis(1).unwrap(), latest_payload)
500			.expect("latest catalog frame should write");
501		latest_group.finish().expect("latest catalog group should finish");
502		let _track = track.finish().expect("catalog track should finish");
503
504		assert_eq!(expect_catalog(consumer.poll_next(&waiter)), latest);
505
506		old_frame.write(old_payload).expect("old catalog frame should write");
507		old_frame
508			.finish()
509			.unwrap()
510			.finish()
511			.expect("old catalog group should finish");
512
513		assert!(matches!(consumer.poll_next(&waiter), Poll::Ready(Ok(None))));
514	}
515
516	/// A lost catalog track is a transport error, so a caller can hold for the source to return
517	/// instead of failing as if the catalog were malformed.
518	#[test]
519	fn a_lost_track_is_a_transport_error() {
520		let track = track_producer(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info());
521		let mut consumer: Consumer = Consumer::new(track.consume());
522		track.abort(moq_net::Error::Cancel).expect("catalog track should abort");
523
524		assert!(matches!(
525			consumer.poll_next(&kio::Waiter::noop()),
526			Poll::Ready(Err(crate::Error::Moq(moq_net::Error::Cancel)))
527		));
528	}
529
530	#[test]
531	fn returns_none_when_empty_track_finishes() {
532		let track = track_producer(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info());
533		let mut consumer: Consumer = Consumer::new(track.consume());
534		let waiter = kio::Waiter::noop();
535
536		let _track = track.finish().expect("catalog track should finish");
537
538		assert!(matches!(consumer.poll_next(&waiter), Poll::Ready(Ok(None))));
539	}
540}