Skip to main content

moq_ext_json/
lib.rs

1//! A latest-value JSON track writer that stamps each update itself.
2//!
3//! A [`moq_json::snapshot`] track on a timed track needs a timestamp on every
4//! update, and moq-net refuses a group that starts at or before the group
5//! before it. A scalar value, such as a `u64`, starts a group with every
6//! change, so two changes in the same millisecond fail when the caller stamps
7//! them from a clock. [`ValueWriter`] stamps each update from the moq clock
8//! and moves a stamp that does not pass the previous one a tick past it, so
9//! `update(&value)` succeeds however often it is called.
10//!
11//! The writer changes nothing on the wire. Readers use
12//! [`moq_json::snapshot::Consumer`] and see the stamps in
13//! [`Timed::at`](moq_json::Timed::at).
14//!
15//! # Examples
16//!
17//! ```
18//! use moq_ext_json::ValueWriter;
19//! use moq_net::{Timescale, track};
20//!
21//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
22//! let broadcast = moq_net::broadcast::Info::new().produce();
23//! let track = broadcast
24//!     .create_track(
25//!         "latency",
26//!         track::Info::default().with_timescale(Timescale::MILLI),
27//!     )
28//!     .ok_or("the track exists")?;
29//! let latency = ValueWriter::<u64>::new(track, Default::default());
30//! // Both succeed, even within one millisecond.
31//! latency.update(&150)?;
32//! latency.update(&160)?;
33//! # Ok(())
34//! # }
35//! ```
36
37#![forbid(unsafe_code)]
38
39use std::{
40    fmt,
41    sync::{Arc, Mutex, MutexGuard, PoisonError},
42};
43
44use moq_json::snapshot;
45use moq_net::{Timestamp, time::Instant, track};
46use n0_error::stack_error;
47use serde::{Serialize, de::DeserializeOwned};
48
49#[cfg(test)]
50mod tests;
51
52/// An error from a value track: a [`moq_json::Error`] that `?` can convert.
53///
54/// [`ValueWriter`] returns it, and so do the value-track readers built on
55/// this crate. It displays as the [`moq_json::Error`] it wraps, which
56/// [`json`](Self::json) returns for a match on the cause. As a stack error it
57/// converts into an [`n0_error::AnyError`], so `?` works on it in a function
58/// that returns an [`n0_error::Result`], which the moq-json error alone does
59/// not.
60#[stack_error(derive, add_meta)]
61#[error(transparent)]
62#[derive(Clone)]
63pub struct ValueError {
64    #[error(source, from, std_err)]
65    source: moq_json::Error,
66}
67
68impl ValueError {
69    /// Returns the moq-json error behind this one.
70    #[must_use]
71    pub fn json(&self) -> &moq_json::Error {
72        &self.source
73    }
74
75    /// Returns the moq-json error behind this one, consuming it.
76    #[must_use]
77    pub fn into_json(self) -> moq_json::Error {
78        self.source
79    }
80}
81
82impl From<moq_net::Error> for ValueError {
83    #[track_caller]
84    fn from(source: moq_net::Error) -> Self {
85        moq_json::Error::from(source).into()
86    }
87}
88
89/// Writes a latest-value JSON track, stamping each update with the time it is made.
90///
91/// Each update gets the moq clock's time, `Timestamp::from(Instant::now())`
92/// at the track's timescale, or one tick after the previous stamp if the clock
93/// has not moved past it. A tick is a millisecond on a track that counts
94/// milliseconds, as the tracks iroh-live creates do. The stamps strictly
95/// increase, as the track's group starts must, so a burst of updates within
96/// one millisecond runs a few milliseconds ahead of the clock and meets it
97/// again once the updates slow down.
98///
99/// The track must be timed: on a track without a
100/// [`timescale`](track::Info::timescale), every update fails with
101/// [`moq_net::Error::TimestampMismatch`].
102///
103/// Clones share the track and the stamps, and each update stamps and writes
104/// under one lock, so clones on several threads cannot reorder their stamps.
105/// The last clone to drop finishes the track, so readers see it end.
106pub struct ValueWriter<T: Serialize> {
107    shared: Arc<Mutex<Shared<T>>>,
108}
109
110impl<T: Serialize> Clone for ValueWriter<T> {
111    fn clone(&self) -> Self {
112        Self {
113            shared: Arc::clone(&self.shared),
114        }
115    }
116}
117
118impl<T: Serialize> fmt::Debug for ValueWriter<T> {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        f.debug_struct("ValueWriter")
121            .field("last", &self.lock().last)
122            .finish_non_exhaustive()
123    }
124}
125
126/// The state that the clones of one [`ValueWriter`] share.
127struct Shared<T: Serialize> {
128    producer: snapshot::Producer<T>,
129    /// The track's properties, whose timescale the stamps are kept at.
130    info: track::Info,
131    /// The newest stamp written, at the track's timescale, which the next one must pass.
132    last: Option<Timestamp>,
133}
134
135impl<T: Serialize> ValueWriter<T> {
136    /// Creates a writer that publishes to `track`.
137    ///
138    /// The track must be timed, and nothing else should write to it.
139    pub fn new(track: track::Producer, config: snapshot::Config) -> Self {
140        let info = track.info().clone();
141        Self {
142            shared: Arc::new(Mutex::new(Shared {
143                producer: snapshot::Producer::new(track, config),
144                info,
145                last: None,
146            })),
147        }
148    }
149
150    /// Publishes `value`, stamped now.
151    ///
152    /// Returns the encoded size of the frame written, or `None` if `value`
153    /// equals the current value and nothing was written.
154    ///
155    /// # Errors
156    ///
157    /// Fails with [`moq_net::Error::Closed`] once the track is finished,
158    /// with [`moq_net::Error::TimestampMismatch`] on an untimed track, and
159    /// with any error of [`snapshot::Producer::update`].
160    pub fn update(&self, value: &T) -> Result<Option<usize>, ValueError> {
161        let mut shared = self.lock();
162        let at = shared.next(Timestamp::from(Instant::now()))?;
163        let written = shared.producer.update(value, at)?;
164        if written.is_some() {
165            shared.advance(at);
166        }
167        Ok(written)
168    }
169
170    /// Publishes `value` at `at`, a time the caller chose.
171    ///
172    /// The caller owns the order: an `at` that starts a group at or before
173    /// the previous group fails with [`moq_net::Error::TimestampMismatch`]. A
174    /// later [`update`](Self::update) stamps after `at`.
175    ///
176    /// # Errors
177    ///
178    /// As [`update`](Self::update), and fails with
179    /// [`moq_net::Error::TimestampMismatch`] for an `at` the track cannot
180    /// take.
181    pub fn update_at(&self, value: &T, at: Timestamp) -> Result<Option<usize>, ValueError> {
182        let mut shared = self.lock();
183        let at = shared.info.rescale(at)?;
184        let written = shared.producer.update(value, at)?;
185        if written.is_some() {
186            shared.advance(at);
187        }
188        Ok(written)
189    }
190
191    /// Edits the current value in place and publishes it, stamped now.
192    ///
193    /// The closure receives the current value: everything published so far,
194    /// or `T::default()` if nothing has been. An unchanged value publishes
195    /// nothing. See [`snapshot::Producer::mutate`].
196    ///
197    /// # Errors
198    ///
199    /// As [`update`](Self::update), and fails if the current value does not
200    /// deserialize as `T`.
201    pub fn mutate(&self, edit: impl FnOnce(&mut T)) -> Result<(), ValueError>
202    where
203        T: Default + DeserializeOwned,
204    {
205        let mut shared = self.lock();
206        let at = shared.next(Timestamp::from(Instant::now()))?;
207        shared.producer.mutate(edit, at)?;
208        // `mutate` does not say whether it wrote, so count the stamp as used.
209        // A spare tick only moves the next stamp ahead, which is harmless.
210        shared.advance(at);
211        Ok(())
212    }
213
214    /// Finishes the track, so readers see it end.
215    ///
216    /// Clones then fail to update with [`moq_net::Error::Closed`]. Dropping
217    /// the last clone finishes the track too, so call this only to see the
218    /// error or to end the track while clones remain.
219    ///
220    /// # Errors
221    ///
222    /// Fails if the track was aborted, or if finishing it fails.
223    pub fn finish(self) -> Result<(), ValueError> {
224        let producer = self.lock().producer.clone();
225        producer.finish().map(drop).map_err(ValueError::from)
226    }
227
228    /// Returns the moq-json producer, for `poll_refresh`, `cut` or `consume`.
229    ///
230    /// It shares the track with the writer: a write through it bypasses the
231    /// stamps, and the writer's last clone finishes the track for it too.
232    pub fn producer(&self) -> snapshot::Producer<T> {
233        self.lock().producer.clone()
234    }
235
236    /// Locks the shared state.
237    fn lock(&self) -> MutexGuard<'_, Shared<T>> {
238        // The lock is held across the caller's `mutate` closure, so a panic
239        // there poisons it. The state stays consistent, since `last` moves only
240        // after a write, so recover rather than fail every later update.
241        self.shared.lock().unwrap_or_else(PoisonError::into_inner)
242    }
243}
244
245impl<T: Serialize> Shared<T> {
246    /// Returns `now` at the track's timescale, or one tick after the last stamp if `now` is not past it.
247    fn next(&self, now: Timestamp) -> Result<Timestamp, ValueError> {
248        let now = self.info.rescale(now)?;
249        Ok(match self.last {
250            Some(last) if now <= last => tick_after(last).unwrap_or(now),
251            _ => now,
252        })
253    }
254
255    /// Records `at` as written, if it is later than the last stamp.
256    fn advance(&mut self, at: Timestamp) {
257        if self.last.is_none_or(|last| at > last) {
258            self.last = Some(at);
259        }
260    }
261}
262
263impl<T: Serialize> Drop for Shared<T> {
264    /// Finishes the track if no one finished it, so readers see it end.
265    fn drop(&mut self) {
266        // Finishing a finished track does nothing, and an aborted one already
267        // ended with its cause, so the error carries nothing to act on.
268        let _finished = self.producer.clone().finish();
269    }
270}
271
272/// Returns the timestamp one tick of its own scale after `at`, or `None` at the end of the range.
273fn tick_after(at: Timestamp) -> Option<Timestamp> {
274    let scale = at.scale()?;
275    Timestamp::new(at.value().checked_add(1)?, scale).ok()
276}