Skip to main content

moq_json/
lib.rs

1//! JSON publishing over [`moq-net`](moq_net) tracks, in three modes:
2//!
3//! - [`snapshot`]: **lossy**. One JSON value updated over time; `next` yields states in order,
4//!   while `latest` skips to the newest state. Superseded groups are lost.
5//! - [`stream`]: **lossless**. An ordered append-log of self-contained records; every record is
6//!   preserved and delivered in order, nothing is ever superseded.
7//! - [`window`]: **bounded**. An ordered run of records appended to the back and dropped from the
8//!   front, which a reader can join at any point.
9//!
10//! Pick [`snapshot`] when consumers care about "what is the value now" (a catalog, a status
11//! document), [`stream`] when they care about every record of an unbounded log, and [`window`] when
12//! the publisher retires old records and a late reader should start from what is still retained.
13//!
14//! Each mode comes in two layers. `Producer`/`Consumer` own a [`moq_net`] track and manage its
15//! groups. `Encoder`/`Decoder` are the same logic without the track: values in, frame payloads out
16//! (and back), with the encoder saying where the group boundaries fall. Reach for the codec layer
17//! when something else already owns the track, such as a `moq_mux::container::Producer` also
18//! managing a timeline and a catalog estimate.
19//!
20//! The `poll_*` methods are always available. Enable the `async` feature for their generated
21//! async wrappers (`next`, `latest`, and `refresh`); it is off by default.
22
23#![warn(missing_docs)]
24
25mod diff;
26mod merge;
27#[cfg(test)]
28mod on_demand;
29mod refresh;
30pub mod snapshot;
31mod state;
32pub mod stream;
33mod strict;
34mod timed;
35pub mod window;
36
37pub use timed::Timed;
38
39/// Test support for the codec bench, enabled by the `bench` feature: the merge-patch diff.
40#[cfg(feature = "bench")]
41pub mod bench {
42	pub use crate::diff::{Diff, diff};
43}
44
45/// The most a frame, or a group's frames together, may hold: 32 MiB, which moq-net's group cache
46/// also holds, so a larger frame is refused before it is written.
47pub(crate) const MAX_GROUP_BYTES: u64 = 32 * 1024 * 1024;
48
49/// Whether a group whose first frame is at `timestamp`, rescaled to `track`, would start past
50/// every group on `track`, which a new group must: two groups never share a start. A timed group
51/// starts at its first frame's time, and a scale-less one at the key its unscaled timestamp names.
52pub(crate) fn starts_past(track: &moq_net::track::Producer, timestamp: moq_net::Timestamp) -> bool {
53	track.largest().is_none_or(|largest| timestamp.value() > largest.group)
54}
55
56/// `timestamp` for a frame of `group`: a scale-less track's frames carry their group's key, so a
57/// frame appended to an open group carries that group's key, whatever key the caller named.
58pub(crate) fn frame_time(group: &moq_net::group::Producer, timestamp: moq_net::Timestamp) -> moq_net::Timestamp {
59	match timestamp.scale() {
60		Some(_) => timestamp,
61		None => moq_net::Timestamp::unscaled(group.start),
62	}
63}
64
65/// Errors produced while publishing or consuming JSON.
66#[derive(thiserror::Error, Debug, Clone)]
67#[non_exhaustive]
68pub enum Error {
69	/// An error from the underlying track.
70	#[error(transparent)]
71	Net(#[from] moq_net::Error),
72
73	/// A value failed to serialize, deserialize, or apply as a merge patch.
74	///
75	/// Stored as a string since [`serde_json::Error`] is not [`Clone`].
76	#[error("json: {0}")]
77	Json(String),
78
79	/// A merge patch arrived with no snapshot to apply it to.
80	///
81	/// Every group opens with a full snapshot, so this means frames reached
82	/// [`snapshot::Decoder`] out of order, or a group's first frame was routed as a delta.
83	#[error("delta before snapshot")]
84	MissingSnapshot,
85
86	/// A [`stream`] track carried a second group, which a lossless log cannot do.
87	///
88	/// A stream is a single group by construction: a publisher that cannot write a record ends the
89	/// track rather than rolling. A second group therefore means the records that would have
90	/// completed the first one are gone, so the read fails instead of presenting the remainder as
91	/// a continuous log.
92	#[error("stream rolled to a second group")]
93	Rolled,
94
95	/// A decoded frame or reconstructed snapshot exceeded its configured byte budget.
96	#[error("decoded JSON exceeded {0} bytes")]
97	TooLarge(usize),
98
99	/// A decoded frame repeated a key within one JSON object, which parsers resolve differently.
100	#[error("duplicate JSON object key")]
101	DuplicateKey,
102}
103
104impl From<serde_json::Error> for Error {
105	fn from(err: serde_json::Error) -> Self {
106		Error::Json(err.to_string())
107	}
108}
109
110/// A [`Result`](std::result::Result) using this crate's [`Error`].
111pub type Result<T> = std::result::Result<T, Error>;