Skip to main content

moq_mux/
json.rs

1//! JSON track publish/subscribe.
2//!
3//! A JSON track is application data a broadcast publishes alongside its media: a chat log, a
4//! telemetry feed, a status document. The catalog entry
5//! ([`hang::catalog::JsonConfig`]) says how to read it, so a consumer needs the track name and
6//! nothing else about the application.
7//!
8//! The write and read sides are shaped differently on purpose. A publisher knows its mode at
9//! compile time, so [`Snapshot`] and [`Stream`] are distinct types and `append`-on-a-snapshot can't
10//! be written. A consumer only learns the mode from the catalog, so there is one [`Consumer`] that
11//! reads either; it exposes [`mode`](Consumer::mode) for a reader that needs to know.
12//!
13//! Mint a producer from the catalog:
14//!
15//! ```no_run
16//! # use serde::{Deserialize, Serialize};
17//! # #[derive(Serialize, Deserialize)]
18//! # struct Message { text: String }
19//! # fn example(
20//! #     broadcast: &mut moq_net::broadcast::Producer,
21//! #     catalog: &moq_mux::catalog::Producer,
22//! # ) -> moq_mux::Result<()> {
23//! // A timed track, since every write is stamped. JSON is small and repetitive, so compress it.
24//! let info = moq_net::track::Info::default()
25//!     .with_timescale(moq_net::Timescale::MILLI)
26//!     .with_compression(moq_net::track::Compression::Deflate);
27//! let track = broadcast.create_track("chat", info).ok_or(moq_net::Error::Duplicate)?;
28//! let mut chat = catalog.json_stream::<Message>(track, moq_mux::json::Config::default())?;
29//! chat.append(&Message { text: "hello".to_string() }, catalog.clock().now())?;
30//! # Ok(())
31//! # }
32//! ```
33//!
34//! The catalog entry is written when the producer is created and removed when it drops, so a track
35//! is never advertised without a publisher behind it.
36//!
37//! Every write takes a timestamp on the broadcast [`Clock`](crate::Clock), the epoch every track
38//! in the broadcast shares, so the track must have a timescale. A value is written at that
39//! timestamp as given, and the entry advertises how late values reach the transport as its
40//! `jitter` and `delay`, the way a media rendition does. A capture
41//! [`Instant`](kio::clock::Instant) converts with [`Clock::capture`](crate::Clock::capture) on the
42//! catalog's clock:
43//!
44//! ```no_run
45//! # fn example(
46//! #     catalog: &moq_mux::catalog::Producer,
47//! #     gps: &mut moq_mux::json::Stream<serde_json::Value>,
48//! #     fix: serde_json::Value,
49//! #     received: kio::clock::Instant,
50//! # ) -> moq_mux::Result<()> {
51//! let at = catalog.clock().capture(received)?;
52//! gps.append(&fix, at)?;
53//! # Ok(())
54//! # }
55//! ```
56//!
57//! A timestamp carried over from elsewhere, such as a source's own timestamp or the `at` of a
58//! consumed [`Timed`] the value was derived from, is published unchanged too. It lines up with
59//! media only on a broadcast sharing the source's clock mapping.
60//!
61//! Read one back off the catalog, naming it once:
62//!
63//! ```no_run
64//! # use serde::{Deserialize, Serialize};
65//! # #[derive(Serialize, Deserialize)]
66//! # struct Message { text: String }
67//! # async fn example(
68//! #     source: &moq_mux::Source,
69//! #     catalog: &moq_mux::catalog::hang::Catalog,
70//! # ) -> moq_mux::Result<()> {
71//! let config = catalog.json.tracks.get("chat").expect("no chat track");
72//! let entry = moq_mux::catalog::Entry::new("chat", config);
73//! let mut chat = entry.subscribe::<Message>(source).await?;
74//! while let Some(message) = chat.next().await? {
75//!     // ...
76//! }
77//! # Ok(())
78//! # }
79//! ```
80
81use std::task::{Poll, ready};
82
83use moq_json::Timed;
84use serde::Serialize;
85use serde::de::DeserializeOwned;
86
87#[cfg(feature = "async")]
88use hang::catalog::Reference;
89use hang::catalog::{JsonConfig, Mode};
90
91use crate::catalog::hang::CatalogExt;
92use crate::catalog::{IntoRendition, Listing, RenditionConfig};
93
94/// Everything a JSON track declares about itself, beyond its mode and name.
95///
96/// Start from [`default`](Default::default) and chain the setters. The mode is not in here: it is
97/// fixed by which producer you create. To list the track in an application's own catalog section
98/// instead of `json`, pass that section's entry (see [`IntoRendition`]).
99#[derive(Debug, Clone, Default)]
100#[non_exhaustive]
101pub struct Config {
102	/// An optional identifier for the shape of each value, typically a JSON Schema URL.
103	pub schema: Option<String>,
104}
105
106impl Config {
107	/// Set [`schema`](Self::schema) (a builder, since the struct is `#[non_exhaustive]`).
108	pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
109		self.schema = Some(schema.into());
110		self
111	}
112}
113
114/// How a [`Snapshot`] encodes its frames, beyond what its catalog entry declares.
115///
116/// Start from [`default`](Default::default) and chain the setters. None of this is written into
117/// the catalog entry: every consumer decodes the frames the same way, so a reader needs nothing
118/// from the entry to follow them.
119#[derive(Debug, Clone)]
120#[non_exhaustive]
121pub struct Options {
122	/// Whether changes ride as merge-patch deltas (see [`moq_json::snapshot::Config::deltas`]).
123	/// Defaults to `true`.
124	pub deltas: bool,
125}
126
127impl Default for Options {
128	fn default() -> Self {
129		Self { deltas: true }
130	}
131}
132
133impl Options {
134	/// Set [`deltas`](Self::deltas) (a builder, since the struct is `#[non_exhaustive]`).
135	pub fn with_deltas(mut self, deltas: bool) -> Self {
136		self.deltas = deltas;
137		self
138	}
139}
140
141impl<E: CatalogExt> IntoRendition<E, JsonConfig> for Config {
142	type Config = JsonConfig;
143
144	fn into_rendition(self) -> JsonConfig {
145		// The producer overwrites the mode with the one it publishes in.
146		let mut entry = JsonConfig::new(Mode::Snapshot);
147		entry.schema = self.schema;
148		entry
149	}
150}
151
152/// Fix `config`'s mode.
153///
154/// Errors on a `broadcast` reference, which would point consumers away from the track this
155/// publishes, and with [`moq_net::Error::TimestampMismatch`] on a track without a timescale, which
156/// would refuse every timestamped write.
157fn prepare(track: &moq_net::track::Producer, config: &mut impl AsMut<JsonConfig>, mode: Mode) -> crate::Result<()> {
158	if track.info().timescale.is_none() {
159		return Err(moq_net::Error::TimestampMismatch.into());
160	}
161	let json = config.as_mut();
162	if json.broadcast.is_some() {
163		return Err(crate::Error::ForeignBroadcast);
164	}
165	json.mode = mode;
166	Ok(())
167}
168
169/// Publishes a latest-value JSON track, advertised in the catalog for as long as this handle lives.
170///
171/// Every [`update`](Self::update) supersedes the last, so a consumer reads only the newest value.
172/// For a log where every record survives, use [`Stream`].
173pub struct Snapshot<T> {
174	// Dropped before the track, so a handler asked for the track again finds the name free.
175	listing: Listing,
176	inner: moq_json::snapshot::Producer<T>,
177}
178
179impl<T: Serialize> Snapshot<T> {
180	pub(crate) fn new<E: CatalogExt, C: RenditionConfig<E> + AsMut<JsonConfig>>(
181		track: moq_net::track::Producer,
182		rendition: crate::catalog::Rendition<E, C>,
183		mut config: C,
184		options: Options,
185	) -> crate::Result<Self> {
186		prepare(&track, &mut config, Mode::Snapshot)?;
187		let json = moq_json::snapshot::Config::default().with_deltas(options.deltas);
188		let inner = moq_json::snapshot::Producer::new(track, json);
189		let listing = Listing::new(rendition, config)?;
190		Ok(Self { inner, listing })
191	}
192
193	/// The track name, which is also the catalog key.
194	pub fn name(&self) -> &str {
195		self.listing.name()
196	}
197
198	/// Create a subscriber for the underlying track.
199	pub fn consume(&self) -> moq_net::track::Subscriber {
200		self.inner.consume()
201	}
202
203	/// A watch-only handle to whether this track has subscribers.
204	pub fn demand(&self) -> moq_net::track::Demand {
205		self.inner.demand()
206	}
207
208	/// Wait for a joiner to want a fresh group, then restate the value in one; see
209	/// [`moq_json::snapshot::Producer::poll_refresh`].
210	///
211	/// A restatement is not a new value, so it measures neither `jitter` nor `delay`.
212	#[cfg_attr(feature = "async", kio::wrapper)]
213	pub fn poll_refresh(&self, waiter: &kio::Waiter) -> std::task::Poll<crate::Result<()>> {
214		self.inner.poll_refresh(waiter).map_err(Into::into)
215	}
216
217	/// Publish a new value at `timestamp` on the broadcast clock, superseding the previous one.
218	///
219	/// The value is written at that timestamp and measures the entry's `jitter` and `delay`; one
220	/// ahead of now measures as zero delay. An unchanged value writes nothing and measures nothing.
221	pub fn update(&mut self, value: &T, timestamp: moq_net::Timestamp) -> crate::Result<()> {
222		match self.inner.update(value, timestamp)? {
223			Some(size) => self.listing.record(size, Some(timestamp)),
224			None => Ok(()),
225		}
226	}
227
228	/// Finish the track and retire its catalog entry.
229	///
230	/// Consumes the handle, so a write after finishing cannot be expressed. Leaving the entry
231	/// advertising a closed track would only mislead a consumer that subscribed afterwards, so
232	/// dropping the handle without finishing retires the entry too.
233	pub fn finish(self) -> crate::Result<()> {
234		// Retired along with the entry, as promised.
235		drop(self.inner.finish()?);
236		Ok(())
237	}
238
239	/// Abort the track with `err`, which consumers see in place of a clean end, and retire its
240	/// catalog entry.
241	pub fn abort(self, err: moq_net::Error) -> crate::Result<()> {
242		Ok(self.inner.abort(err)?)
243	}
244}
245
246/// Publishes an append-log JSON track, advertised in the catalog for as long as this handle lives.
247///
248/// Every [`append`](Self::append) is preserved and delivered in order. For a latest-value document,
249/// use [`Snapshot`].
250pub struct Stream<T> {
251	/// Cleared when a terminal failure ends the track, which retires the catalog entry with it. An
252	/// entry advertising a track that can no longer accept records only misleads a consumer that
253	/// discovers it afterwards. Dropped before the track, so a handler asked for the track again
254	/// finds the name free.
255	listing: Option<Listing>,
256
257	inner: moq_json::stream::Producer<T>,
258	name: String,
259}
260
261impl<T: Serialize> Stream<T> {
262	pub(crate) fn new<E: CatalogExt, C: RenditionConfig<E> + AsMut<JsonConfig>>(
263		track: moq_net::track::Producer,
264		rendition: crate::catalog::Rendition<E, C>,
265		mut config: C,
266	) -> crate::Result<Self> {
267		prepare(&track, &mut config, Mode::Stream)?;
268		let inner = moq_json::stream::Producer::new(track, moq_json::stream::Config::default());
269		let listing = Listing::new(rendition, config)?;
270		Ok(Self {
271			inner,
272			name: listing.name().to_string(),
273			listing: Some(listing),
274		})
275	}
276
277	/// The track name, which is also the catalog key.
278	pub fn name(&self) -> &str {
279		&self.name
280	}
281
282	/// Create a subscriber for the underlying track.
283	///
284	/// Still hands one back once a failed write has ended the log: the subscriber surfaces the abort
285	/// on its first read.
286	pub fn consume(&self) -> moq_net::track::Subscriber {
287		self.inner.consume()
288	}
289
290	/// A watch-only handle to whether this track has subscribers.
291	pub fn demand(&self) -> moq_net::track::Demand {
292		self.inner.demand()
293	}
294
295	/// Append one record to the log at `timestamp` on the broadcast clock.
296	///
297	/// A record that cannot be written ends the track (see [`moq_json::stream::Producer::append`])
298	/// and retires the catalog entry with it. A record refused with
299	/// [`moq_net::Error::FrameTooLarge`], [`moq_net::Error::GroupTooLarge`], or
300	/// [`moq_net::Error::TimestampMismatch`] leaves both intact, since nothing was written. A catalog
301	/// error publishing the measured bitrate is returned after the record was written, so the track
302	/// stays open and a retry would duplicate it.
303	pub fn append(&mut self, value: &T, timestamp: moq_net::Timestamp) -> crate::Result<()> {
304		let size = match self.inner.append(value, timestamp) {
305			Ok(size) => size,
306			// Refused before anything was written, so the log and its entry carry on.
307			Err(
308				err @ moq_json::Error::Net(
309					moq_net::Error::FrameTooLarge | moq_net::Error::GroupTooLarge | moq_net::Error::TimestampMismatch,
310				),
311			) => {
312				return Err(err.into());
313			}
314			Err(err) => {
315				// The inner producer has already ended the track. Dropping the listing retires the
316				// catalog entry: waiting for the handle to drop would keep advertising a track that
317				// can no longer accept records, so a consumer discovering it now would subscribe to
318				// an already-ended log.
319				self.listing = None;
320				return Err(err.into());
321			}
322		};
323
324		match &mut self.listing {
325			Some(listing) => listing.record(size, Some(timestamp)),
326			None => Ok(()),
327		}
328	}
329
330	/// Finish the track and retire its catalog entry.
331	///
332	/// Consumes the handle, so a write after finishing cannot be expressed. Leaving the entry
333	/// advertising a closed track would only mislead a consumer that subscribed afterwards, so
334	/// dropping the handle without finishing retires the entry too.
335	pub fn finish(self) -> crate::Result<()> {
336		// Retired along with the entry, as promised.
337		drop(self.inner.finish()?);
338		Ok(())
339	}
340
341	/// Abort the track with `err`, which consumers see in place of a clean end, and retire its
342	/// catalog entry.
343	pub fn abort(self, err: moq_net::Error) -> crate::Result<()> {
344		Ok(self.inner.abort(err)?)
345	}
346}
347
348/// Reads a JSON track, in whichever mode its catalog entry declares.
349///
350/// One type rather than one per mode: both modes hand the caller the same thing, a sequence of `T`
351/// ending when the track does, so a reader writes one loop either way. What differs is loss
352/// semantics, and that is a property to ask about ([`mode`](Self::mode)) rather than a fork every
353/// caller pays for. A reader that genuinely requires losslessness checks the mode and bails.
354pub struct Consumer<T> {
355	inner: Inner<T>,
356	mode: Mode,
357}
358
359/// Which moq-json consumer is doing the reading. Private: the caller sees one `Consumer`.
360enum Inner<T> {
361	// Boxed: the two readers differ in size by hundreds of bytes.
362	Snapshot(Box<moq_json::snapshot::Consumer<T>>),
363	Stream(Box<moq_json::stream::Consumer<T>>),
364}
365
366impl<T: DeserializeOwned> Consumer<T> {
367	/// Subscribe to a track and read it as its catalog entry declares.
368	///
369	/// The escape hatch for a caller that resolved the track itself. Prefer
370	/// [`Entry::subscribe`](crate::catalog::Entry::subscribe), which resolves the track (including a
371	/// cross-broadcast [`broadcast`](JsonConfig::broadcast) reference) from the catalog for you.
372	/// A snapshot reader subscribes itself (see [`moq_json::snapshot::Consumer::new`]); a stream
373	/// waits for its subscription here.
374	///
375	/// Errors if the entry declares a mode this build doesn't implement, which is a track a consumer
376	/// must skip rather than guess at.
377	#[cfg(feature = "async")]
378	pub async fn from_track(track: moq_net::track::Consumer, config: &JsonConfig) -> crate::Result<Self> {
379		let mut opening = Opening::new(track, config)?;
380		kio::wait(|waiter| opening.poll(waiter)).await
381	}
382
383	/// The mode the publisher chose.
384	///
385	/// [`Mode::Snapshot`] is lossy: a group is skipped once a newer one supersedes it. [`Mode::Stream`] preserves every record a reader keeps up with; one that falls
386	/// behind a group's retained tail sees `Evicted`. Check this when the application can only
387	/// work with one of them.
388	pub fn mode(&self) -> &Mode {
389		&self.mode
390	}
391
392	/// Get the next value, or `None` once the track ends.
393	#[cfg_attr(feature = "async", kio::wrapper)]
394	pub fn poll_next(&mut self, waiter: &kio::Waiter) -> std::task::Poll<crate::Result<Option<Timed<T>>>> {
395		let result = match &mut self.inner {
396			Inner::Snapshot(consumer) => consumer.poll_next(waiter),
397			Inner::Stream(consumer) => consumer.poll_next(waiter),
398		};
399
400		match result {
401			std::task::Poll::Ready(value) => std::task::Poll::Ready(value.map_err(Into::into)),
402			std::task::Poll::Pending => std::task::Poll::Pending,
403		}
404	}
405
406	/// Skip to the newest snapshot state; stream mode returns `UnsupportedMode` rather than
407	/// discard records from a lossless stream.
408	#[cfg_attr(feature = "async", kio::wrapper)]
409	pub fn poll_latest(&mut self, waiter: &kio::Waiter) -> std::task::Poll<crate::Result<Option<Timed<T>>>> {
410		match &mut self.inner {
411			Inner::Snapshot(consumer) => consumer.poll_latest(waiter).map(|result| result.map_err(Into::into)),
412			Inner::Stream(_) => std::task::Poll::Ready(Err(crate::Error::UnsupportedMode(self.mode.to_string()))),
413		}
414	}
415}
416
417impl crate::catalog::Entry<'_, JsonConfig> {
418	/// Subscribe to this track and read it as the entry declares.
419	///
420	/// Resolves the track through `source`, so an entry whose [`broadcast`](JsonConfig::broadcast)
421	/// field names a sibling broadcast is followed rather than silently read from the catalog's own.
422	///
423	/// Errors if the entry declares a mode this build doesn't implement.
424	#[cfg(feature = "async")]
425	pub async fn subscribe<T: DeserializeOwned>(&self, source: &crate::Source) -> crate::Result<Consumer<T>> {
426		let binding = source.bind(self.config().broadcast.as_ref())?;
427		let mut subscribe = EntrySubscribe::Binding {
428			binding,
429			name: self.config().track(self.name()).to_string(),
430			config: self.config().clone(),
431		};
432		kio::wait(|waiter| subscribe.poll(waiter)).await
433	}
434}
435
436/// A [`Consumer`] waiting for its subscription: a stream's here, a snapshot's on its first read.
437struct Opening<T> {
438	mode: Mode,
439	state: OpeningState<T>,
440}
441
442enum OpeningState<T> {
443	Snapshot(Option<Box<moq_json::snapshot::Consumer<T>>>),
444	Stream(Box<moq_net::track::Subscribing>),
445}
446
447#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
448impl<T: DeserializeOwned> Opening<T> {
449	/// Errors if the entry declares a mode this build doesn't implement.
450	fn new(track: moq_net::track::Consumer, config: &JsonConfig) -> crate::Result<Self> {
451		let state = match &config.mode {
452			Mode::Snapshot => OpeningState::Snapshot(Some(Box::new(moq_json::snapshot::Consumer::new(
453				track,
454				Default::default(),
455			)))),
456			Mode::Stream => OpeningState::Stream(Box::new(track.subscribe(None).into_inner())),
457			other => return Err(crate::Error::UnsupportedMode(other.to_string())),
458		};
459		Ok(Self {
460			mode: config.mode.clone(),
461			state,
462		})
463	}
464
465	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<crate::Result<Consumer<T>>> {
466		let inner = match &mut self.state {
467			OpeningState::Snapshot(consumer) => Inner::Snapshot(consumer.take().expect("resolves once")),
468			OpeningState::Stream(subscribing) => {
469				let track = ready!(subscribing.poll_ok(waiter))?;
470				Inner::Stream(Box::new(moq_json::stream::Consumer::new(track, Default::default())))
471			}
472		};
473		Poll::Ready(Ok(Consumer {
474			inner,
475			mode: self.mode.clone(),
476		}))
477	}
478}
479
480/// [`Entry::subscribe`](crate::catalog::Entry::subscribe): the entry's broadcast, then its track.
481#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
482#[expect(clippy::large_enum_variant, reason = "a machine's enum is its storage")]
483enum EntrySubscribe<T> {
484	Binding {
485		binding: crate::Binding,
486		name: String,
487		config: JsonConfig,
488	},
489	Opening(Opening<T>),
490}
491
492#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
493impl<T: DeserializeOwned> EntrySubscribe<T> {
494	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<crate::Result<Consumer<T>>> {
495		if let Self::Binding { binding, name, config } = self {
496			let broadcast = ready!(binding.poll_broadcast(waiter))?;
497			// The binding drops as soon as it answers, so its request ends with it.
498			*self = Self::Opening(Opening::new(broadcast.track(name)?, config)?);
499		}
500		let Self::Opening(opening) = self else {
501			unreachable!("bound above");
502		};
503		opening.poll(waiter)
504	}
505}
506
507#[cfg(test)]
508mod test {
509	use std::task::Poll;
510
511	use futures::FutureExt;
512	use serde_json::{Value, json};
513
514	use super::*;
515
516	/// A millisecond track: the frames written here carry timestamps.
517	fn timed() -> moq_net::track::Info {
518		moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI)
519	}
520
521	fn catalog() -> (moq_net::broadcast::Producer, crate::catalog::Producer) {
522		let mut broadcast = moq_net::broadcast::Info::new().produce();
523		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
524		(broadcast, catalog)
525	}
526
527	/// Create the moq-net track a data producer publishes on, as a caller does for a media track.
528	fn track(broadcast: &mut moq_net::broadcast::Producer, name: &str) -> moq_net::track::Producer {
529		broadcast
530			.create_track(name, timed().with_compression(moq_net::track::Compression::Deflate))
531			.unwrap()
532	}
533
534	fn entry(catalog: &crate::catalog::Producer, name: &str) -> JsonConfig {
535		catalog
536			.snapshot()
537			.json
538			.tracks
539			.get(name)
540			.expect("missing catalog entry")
541			.clone()
542	}
543
544	/// Drain every value a consumer currently has, without blocking.
545	///
546	/// One loop whichever mode the publisher chose, which is the point of the single `Consumer`.
547	/// [`Consumer::from_track`] on an in-process track, whose subscription resolves at once.
548	fn read(track: moq_net::track::Consumer, config: &JsonConfig) -> crate::Result<Consumer<Value>> {
549		Consumer::from_track(track, config)
550			.now_or_never()
551			.expect("in-process subscription")
552	}
553
554	fn drain(mut consumer: Consumer<Value>) -> Vec<Value> {
555		let waiter = kio::Waiter::noop();
556		let mut out = Vec::new();
557		while let Poll::Ready(Ok(Some(value))) = if consumer.mode() == &Mode::Snapshot {
558			consumer.poll_latest(&waiter)
559		} else {
560			consumer.poll_next(&waiter)
561		} {
562			out.push(value.value);
563		}
564		out
565	}
566
567	#[test]
568	fn a_stream_track_roundtrips() {
569		let (mut broadcast, catalog) = catalog();
570		let mut chat = catalog
571			.json_stream::<Value>(track(&mut broadcast, "chat"), Config::default())
572			.unwrap();
573
574		// The catalog is the only thing the reader is told; the mode comes from it.
575		let entry = entry(&catalog, "chat");
576		let track = broadcast.consume().track("chat").unwrap();
577		let consumer = read(track, &entry).unwrap();
578		let expected: Vec<Value> = (0..3).map(|n| json!({ "n": n })).collect();
579		for value in &expected {
580			chat.append(value, catalog.clock().now()).unwrap();
581		}
582		chat.finish().unwrap();
583
584		assert_eq!(consumer.mode(), &Mode::Stream);
585		assert_eq!(drain(consumer), expected);
586	}
587
588	#[test]
589	fn a_snapshot_track_roundtrips() {
590		let (mut broadcast, catalog) = catalog();
591		let mut status = catalog
592			.json_snapshot::<Value>(track(&mut broadcast, "status"), Config::default(), Options::default())
593			.unwrap();
594
595		let entry = entry(&catalog, "status");
596		let track = broadcast.consume().track("status").unwrap();
597		let consumer = read(track, &entry).unwrap();
598		status.update(&json!({ "live": false }), catalog.clock().now()).unwrap();
599		status.update(&json!({ "live": true }), catalog.clock().now()).unwrap();
600		status.finish().unwrap();
601
602		// The reader only sees the newest value, which is the point of snapshot mode.
603		assert_eq!(consumer.mode(), &Mode::Snapshot);
604		assert_eq!(drain(consumer), vec![json!({ "live": true })]);
605	}
606
607	/// A track registered before an importer's first frame fixes the clock, so an importer starting
608	/// an hour in shifts onto it: the publisher keeps stamping on the clock it started with.
609	#[test]
610	fn an_importer_joins_the_data_tracks_clock() {
611		let (mut broadcast, catalog) = catalog();
612		let mut status = catalog
613			.json_snapshot::<Value>(track(&mut broadcast, "status"), Config::default(), Options::default())
614			.unwrap();
615		let mut chat = catalog
616			.json_stream::<Value>(track(&mut broadcast, "chat"), Config::default())
617			.unwrap();
618		let mut subscribers = [status.consume(), chat.consume()];
619
620		let published = catalog.snapshot().sync.clock;
621		let before = catalog.clock().now();
622		// The stream starts an hour in, far from the ten seconds a fresh clock reads.
623		let first = catalog
624			.timebase()
625			.shift(moq_net::Timestamp::from_micros(3_600_000_000).unwrap())
626			.unwrap();
627		assert_eq!(catalog.snapshot().sync.clock, published, "the clock never moves");
628		assert!(before <= first, "the importer lands at now: {before:?} {first:?}");
629		status.update(&json!({ "live": true }), catalog.clock().now()).unwrap();
630		chat.append(&json!({ "n": 1 }), catalog.clock().now()).unwrap();
631		let after = catalog.clock().now();
632
633		let waiter = kio::Waiter::noop();
634		for subscriber in &mut subscribers {
635			let mut stamps = Vec::new();
636			while let Poll::Ready(Ok(Some(mut group))) = subscriber.poll_recv_group(&waiter) {
637				while let Poll::Ready(Ok(Some(frame))) = group.poll_read_frame(&waiter) {
638					stamps.push(frame.timestamp.as_millis().unwrap());
639				}
640			}
641			assert_eq!(stamps.len(), 1);
642			assert!(
643				// The track stores milliseconds.
644				first.as_millis().unwrap() <= stamps[0] && stamps[0] <= after.as_millis().unwrap(),
645				"{first:?} {stamps:?} {after:?}"
646			);
647		}
648	}
649
650	/// `deltas` reaches the encoder whatever the catalog entry, including one that is not a
651	/// [`Config`]. Without deltas each value is its own group; with them the next value joins
652	/// that group.
653	#[test]
654	fn the_deltas_option_reaches_the_encoder() {
655		let (mut broadcast, catalog) = catalog();
656		let mut full = catalog
657			.json_snapshot::<Value>(
658				track(&mut broadcast, "full"),
659				JsonConfig::new(Mode::Snapshot),
660				Options::default().with_deltas(false),
661			)
662			.unwrap();
663		let mut delta = catalog
664			.json_snapshot::<Value>(track(&mut broadcast, "delta"), Config::default(), Options::default())
665			.unwrap();
666
667		let mut full_track = full.consume();
668		let mut delta_track = delta.consume();
669		// A millisecond apart: a group starts at its value's time, and starts strictly increase.
670		let now = catalog.clock().now();
671		for (ms, value) in [json!({ "n": 1 }), json!({ "n": 2 })].into_iter().enumerate() {
672			let at = moq_net::Timestamp::from_micros(now.as_micros().unwrap() as u64 + ms as u64 * 1_000).unwrap();
673			full.update(&value, at).unwrap();
674			delta.update(&value, at).unwrap();
675		}
676		full.finish().unwrap();
677		delta.finish().unwrap();
678
679		// The default subscription budget keeps only the latest group. Without deltas the second value rolled a new group, so that group holds one
680		// frame. With deltas the second value joins the same group.
681		assert_eq!(ready_groups(&mut full_track), vec![1]);
682		assert_eq!(ready_groups(&mut delta_track), vec![2]);
683	}
684
685	fn ready_groups(subscriber: &mut moq_net::track::Subscriber) -> Vec<usize> {
686		let waiter = kio::Waiter::noop();
687		let mut counts = Vec::new();
688		loop {
689			match subscriber.poll_recv_group(&waiter) {
690				Poll::Ready(Ok(Some(group))) => counts.push(group.frame_count()),
691				Poll::Ready(Ok(None)) | Poll::Pending => return counts,
692				Poll::Ready(Err(err)) => panic!("group ended in error: {err}"),
693			}
694		}
695	}
696
697	#[test]
698	fn the_entry_describes_how_to_read_the_track() {
699		let (mut broadcast, catalog) = catalog();
700		let _chat = catalog
701			.json_stream::<Value>(
702				track(&mut broadcast, "chat"),
703				Config::default().with_schema("https://example.com/chat.schema.json"),
704			)
705			.unwrap();
706
707		let entry = entry(&catalog, "chat");
708		assert_eq!(entry.mode, Mode::Stream);
709		assert_eq!(entry.schema.as_deref(), Some("https://example.com/chat.schema.json"));
710		assert_eq!(_chat.name(), "chat");
711	}
712
713	#[test]
714	fn dropping_the_producer_retires_the_entry() {
715		let (mut broadcast, catalog) = catalog();
716		let chat = catalog
717			.json_stream::<Value>(track(&mut broadcast, "chat"), Config::default())
718			.unwrap();
719		assert!(catalog.snapshot().json.tracks.contains_key("chat"));
720
721		drop(chat);
722		assert!(
723			!catalog.snapshot().json.tracks.contains_key("chat"),
724			"a track with no publisher must not stay advertised"
725		);
726	}
727
728	/// A snapshot dropped while read retires its entry before its track is asked for again, so a
729	/// handler serving the renewal can publish it anew under the same name.
730	#[test]
731	fn dropping_a_read_snapshot_retires_the_entry_before_the_renewal() {
732		struct Listed {
733			catalog: crate::catalog::Producer,
734			at_wake: std::sync::Mutex<Option<bool>>,
735		}
736		impl std::task::Wake for Listed {
737			fn wake(self: std::sync::Arc<Self>) {
738				let listed = self.catalog.snapshot().json.tracks.contains_key("status");
739				*self.at_wake.lock().unwrap() = Some(listed);
740			}
741		}
742
743		let (mut broadcast, catalog) = catalog();
744		let mut requests = broadcast.requests();
745		let listed = std::sync::Arc::new(Listed {
746			catalog: catalog.clone(),
747			at_wake: Default::default(),
748		});
749		let status = catalog
750			.json_snapshot::<Value>(track(&mut broadcast, "status"), Config::default(), Options::default())
751			.unwrap();
752		let _reader = status.consume();
753		let waiter = kio::Waiter::new(std::task::Waker::from(listed.clone()));
754		assert!(requests.poll_requested_track(&waiter).is_pending());
755
756		drop(status);
757		assert_eq!(
758			*listed.at_wake.lock().unwrap(),
759			Some(false),
760			"the entry outlived the renewal"
761		);
762		assert!(requests.poll_requested_track(&kio::Waiter::noop()).is_ready());
763	}
764
765	/// `finish` consumes the handle, so the entry goes with it: an entry advertising a closed track
766	/// only misleads a consumer that subscribes afterwards.
767	#[test]
768	fn finishing_retires_the_entry_too() {
769		let (mut broadcast, catalog) = catalog();
770		let chat = catalog
771			.json_stream::<Value>(track(&mut broadcast, "chat"), Config::default())
772			.unwrap();
773		assert!(catalog.snapshot().json.tracks.contains_key("chat"));
774
775		chat.finish().unwrap();
776		assert!(!catalog.snapshot().json.tracks.contains_key("chat"));
777	}
778
779	/// A catalog entry can exist with no local track behind it, e.g. one seeded at construction that
780	/// references a sibling broadcast. Publishing over that name would replace what the entry pointed
781	/// at and then retire it entirely on drop, so the name counts as taken.
782	#[test]
783	fn an_existing_catalog_entry_is_not_replaced() {
784		let mut broadcast = moq_net::broadcast::Info::new().produce();
785
786		let mut existing = JsonConfig::new(Mode::Snapshot);
787		existing.broadcast = Some(moq_net::path::Relative::new("source").unwrap());
788
789		let mut seed = crate::catalog::hang::Catalog::<()>::default();
790		seed.json.tracks.insert("chat".to_string(), existing.clone());
791		let config = crate::catalog::Config::default().with_catalog(seed);
792		let catalog = crate::catalog::Producer::new(&mut broadcast, config).unwrap();
793
794		// Nothing local holds the track name, so `create_track` alone would have let this through.
795		assert!(matches!(
796			catalog.json_stream::<Value>(track(&mut broadcast, "chat"), Config::default()),
797			Err(crate::Error::Hang(hang::Error::Duplicate(_)))
798		));
799		assert_eq!(catalog.snapshot().json.tracks.get("chat"), Some(&existing));
800	}
801
802	/// Writes fill an absent bitrate; one the publisher supplied is left alone.
803	#[test]
804	fn writes_fill_an_absent_bitrate() {
805		let (mut broadcast, catalog) = catalog();
806		let mut gps = catalog
807			.json_stream::<Value>(track(&mut broadcast, "gps"), Config::default())
808			.unwrap();
809		let mut supplied = JsonConfig::new(Mode::Stream);
810		supplied.bitrate = Some(4_200);
811		let mut status = catalog
812			.json_snapshot::<Value>(track(&mut broadcast, "status"), supplied, Options::default())
813			.unwrap();
814
815		// 40ms records of 500 bytes: 100 kbps, over more than the bitrate window.
816		for i in 0..60u64 {
817			let now = moq_net::Timestamp::from_micros(i * 40_000).unwrap();
818			gps.listing.as_mut().unwrap().record_at(now, 500, None).unwrap();
819			status.listing.record_at(now, 500, None).unwrap();
820		}
821
822		assert_eq!(entry(&catalog, "gps").bitrate, Some(100_000));
823		assert_eq!(entry(&catalog, "status").bitrate, Some(4_200));
824		assert_eq!(entry(&catalog, "gps").jitter, None, "write spacing is not jitter");
825	}
826
827	/// An unchanged snapshot value writes no frame, so its capture time must not measure a write
828	/// that never happened. Delay is measured over a second of writes, so each half runs longer.
829	#[tokio::test(start_paused = true)]
830	async fn an_unchanged_snapshot_measures_nothing() {
831		let (mut broadcast, catalog) = catalog();
832		let mut gps = catalog
833			.json_stream::<Value>(track(&mut broadcast, "gps"), Config::default())
834			.unwrap();
835		let mut status = catalog
836			.json_snapshot::<Value>(track(&mut broadcast, "status"), Config::default(), Options::default())
837			.unwrap();
838		let second = moq_net::Timestamp::from_micros(1_000_000).unwrap();
839		let value = serde_json::json!({ "armed": true });
840		status.update(&value, catalog.clock().now()).unwrap();
841
842		// The same value again, captured a second behind gps: nothing is written.
843		for _ in 0..60 {
844			tokio::time::advance(std::time::Duration::from_millis(40)).await;
845			let now = catalog.clock().now();
846			gps.append(&serde_json::json!({ "lat": 0 }), now).unwrap();
847			status.update(&value, now.checked_sub(second).unwrap()).unwrap();
848		}
849		assert_eq!(entry(&catalog, "status").delay, None);
850
851		// The same stale captures on changing values are written behind gps.
852		for i in 0..60 {
853			tokio::time::advance(std::time::Duration::from_millis(40)).await;
854			let now = catalog.clock().now();
855			gps.append(&serde_json::json!({ "lat": 0 }), now).unwrap();
856			let changed = serde_json::json!({ "armed": i % 2 == 0 });
857			status.update(&changed, now.checked_sub(second).unwrap()).unwrap();
858		}
859		let delay = entry(&catalog, "status").delay.expect("a capture behind gps is delay");
860		assert!(delay >= std::time::Duration::from_secs(1), "{delay:?}");
861	}
862
863	/// The catalog is the only thing that announces a data track, so walking it is the discovery
864	/// path. Each entry carries its own name, so nothing has to be threaded alongside it.
865	#[test]
866	fn the_catalog_enumerates_its_tracks() {
867		let (mut broadcast, catalog) = catalog();
868		let _chat = catalog
869			.json_stream::<Value>(track(&mut broadcast, "chat"), Config::default())
870			.unwrap();
871		let _status = catalog
872			.json_snapshot::<Value>(track(&mut broadcast, "status"), Config::default(), Options::default())
873			.unwrap();
874
875		let snapshot = catalog.snapshot();
876		let found: Vec<(&str, &Mode)> = snapshot
877			.json
878			.tracks
879			.iter()
880			.map(|(name, config)| (name.as_str(), &config.mode))
881			.collect();
882		assert_eq!(found, vec![("chat", &Mode::Stream), ("status", &Mode::Snapshot)]);
883
884		// A name the catalog doesn't list has no entry, rather than a config to misread.
885		assert!(!snapshot.json.tracks.contains_key("nope"));
886
887		// Pairing the map key with its config gives consumers one subscription handle.
888		let chat = crate::catalog::Entry::new("chat", snapshot.json.tracks.get("chat").expect("missing entry"));
889		assert_eq!(chat.name(), "chat");
890		assert_eq!(chat.mode, Mode::Stream);
891	}
892
893	/// The whole read path: name the track once, and the entry resolves the subscription (through
894	/// `Source`, so a cross-broadcast reference is followed) and says how to decode it.
895	#[tokio::test]
896	async fn an_entry_subscribes_and_reads() {
897		let mut broadcast = moq_net::broadcast::Info::new().produce();
898		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
899		let source = crate::source::announced(&broadcast.consume()).await;
900
901		let mut chat = catalog
902			.json_stream::<Value>(track(&mut broadcast, "chat"), Config::default())
903			.unwrap();
904		chat.append(&json!({ "text": "hello" }), catalog.clock().now()).unwrap();
905
906		let snapshot = catalog.snapshot();
907		let entry = crate::catalog::Entry::new("chat", snapshot.json.tracks.get("chat").expect("missing entry"));
908		let mut consumer = entry.subscribe::<Value>(&source).await.unwrap();
909		chat.finish().unwrap();
910
911		assert!(matches!(
912			consumer.poll_latest(&kio::Waiter::noop()),
913			Poll::Ready(Err(crate::Error::UnsupportedMode(_)))
914		));
915		assert_eq!(
916			consumer.next().await.unwrap().map(|value| value.value),
917			Some(json!({ "text": "hello" }))
918		);
919		assert_eq!(consumer.next().await.unwrap().map(|value| value.value), None);
920	}
921
922	/// A value that fails to serialize never reaches the track, but the log is missing it all the
923	/// same, so it is as terminal as a rejected write. The entry and the track have to agree: retiring
924	/// the entry while leaving the track writable would let a later valid record land somewhere no
925	/// consumer could discover.
926	#[test]
927	fn an_unserializable_record_ends_the_track_and_the_entry() {
928		struct Record(bool);
929
930		impl Serialize for Record {
931			fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
932				match self.0 {
933					true => Err(serde::ser::Error::custom("cannot serialize")),
934					false => serializer.serialize_u8(0),
935				}
936			}
937		}
938
939		let (mut broadcast, catalog) = catalog();
940		let mut chat = catalog
941			.json_stream::<Record>(track(&mut broadcast, "chat"), Config::default())
942			.unwrap();
943		let mut track = chat.consume();
944
945		assert!(chat.append(&Record(true), catalog.clock().now()).is_err());
946		assert!(!catalog.snapshot().json.tracks.contains_key("chat"));
947
948		assert!(
949			chat.append(&Record(false), catalog.clock().now()).is_err(),
950			"a record after the failure would land on a track the retired entry no longer advertises"
951		);
952
953		let waiter = kio::Waiter::noop();
954		assert!(matches!(track.poll_recv_group(&waiter), Poll::Ready(Err(_))));
955	}
956
957	/// A record past the frame budget is refused before anything is written, so the log stays
958	/// advertised and the next record still lands.
959	#[test]
960	fn an_oversized_record_keeps_the_track_and_the_entry() {
961		let (mut broadcast, catalog) = catalog();
962		let mut chat = catalog
963			.json_stream::<Value>(track(&mut broadcast, "chat"), Config::default())
964			.unwrap();
965		let entry = entry(&catalog, "chat");
966		let consumer = read(broadcast.consume().track("chat").unwrap(), &entry).unwrap();
967
968		let oversized = Value::String("x".repeat(crate::jitter::MAX_BYTES));
969		assert!(matches!(
970			chat.append(&oversized, catalog.clock().now()),
971			Err(crate::Error::Json(moq_json::Error::Net(moq_net::Error::FrameTooLarge)))
972		));
973		assert!(catalog.snapshot().json.tracks.contains_key("chat"));
974
975		chat.append(&json!({ "n": 1 }), catalog.clock().now()).unwrap();
976		chat.finish().unwrap();
977		assert_eq!(drain(consumer), vec![json!({ "n": 1 })]);
978	}
979
980	/// Every write is stamped, so a track without a timescale, which refuses a timestamp, is refused
981	/// up front instead of on every write, and nothing is advertised for it.
982	#[test]
983	fn an_untimed_track_is_refused() {
984		let (mut broadcast, catalog) = catalog();
985		let untimed = |broadcast: &mut moq_net::broadcast::Producer, name: &str| {
986			broadcast.create_track(name, moq_net::track::Info::default()).unwrap()
987		};
988
989		assert!(matches!(
990			catalog.json_stream::<Value>(untimed(&mut broadcast, "chat"), Config::default()),
991			Err(crate::Error::Moq(moq_net::Error::TimestampMismatch))
992		));
993		assert!(matches!(
994			catalog.json_snapshot::<Value>(untimed(&mut broadcast, "status"), Config::default(), Options::default()),
995			Err(crate::Error::Moq(moq_net::Error::TimestampMismatch))
996		));
997		assert!(catalog.snapshot().json.tracks.is_empty());
998	}
999
1000	/// A consumer that can't tell a log from a latest-value document would silently drop records,
1001	/// so an unreadable entry is an error rather than a guess.
1002	#[test]
1003	fn an_unrecognized_mode_is_refused() {
1004		let track = moq_net::broadcast::Info::new()
1005			.produce()
1006			.create_track("chat", timed())
1007			.unwrap();
1008
1009		let config = JsonConfig::new(Mode::Unknown("windowed".to_string()));
1010		assert!(matches!(
1011			read(track.consume(), &config),
1012			Err(crate::Error::UnsupportedMode(_))
1013		));
1014	}
1015}