Skip to main content

moq_json/stream/
producer.rs

1//! Publishing an ordered log over a track: an [`Encoder`] plus the track it writes to.
2
3use moq_net::frame::Frame;
4use std::marker::PhantomData;
5use std::sync::{Arc, Mutex};
6
7use serde::Serialize;
8
9use super::Encoder;
10
11use crate::Result;
12
13pub use super::Config;
14
15/// Publishes an ordered log of JSON records over a track, one record per frame in a single group.
16///
17/// An [`Encoder`] that owns its track. When something else already owns the track, use the
18/// [`Encoder`] directly.
19///
20/// Cheaply clonable: clones share one underlying track and publishing state, so multiple owners
21/// (e.g. several producers feeding one log) append into a single ordered stream.
22///
23/// [`finish`](Self::finish) or [`abort`](Self::abort) a complete or failed log. Dropping the last
24/// clone unfinished closes the track cleanly while nobody reads it, so an on-demand publisher drops
25/// it once its [`demand`](Self::demand) goes idle. Once it published, a
26/// reader still reading reads [`moq_net::Error::Dropped`] instead of being handed to the track's
27/// next producer, which could not continue the log (see
28/// [`moq_net::track::Producer::abandon`]).
29pub struct Producer<T> {
30	inner: Arc<Mutex<Inner<T>>>,
31	_marker: PhantomData<fn(T)>,
32}
33
34impl<T> Clone for Producer<T> {
35	fn clone(&self) -> Self {
36		Self {
37			inner: self.inner.clone(),
38			_marker: PhantomData,
39		}
40	}
41}
42
43impl<T> Producer<T> {
44	/// Create a subscriber for the underlying track.
45	///
46	/// Still hands one back once a failed write has ended the log: the subscriber surfaces the abort
47	/// on its first read, which is what tells a late reader the log is truncated.
48	pub fn consume(&self) -> moq_net::track::Subscriber {
49		self.inner.lock().unwrap().track.inner.subscribe(None)
50	}
51
52	/// A watch-only handle to the underlying track's subscriber demand.
53	///
54	/// Weak, so holding it neither keeps the track open nor contends with publishing.
55	pub fn demand(&self) -> moq_net::track::Demand {
56		self.inner.lock().unwrap().track.inner.demand()
57	}
58}
59
60impl<T: Serialize> Producer<T> {
61	/// Create a producer that publishes to the given track.
62	pub fn new(track: moq_net::track::Producer, config: Config) -> Self {
63		Self {
64			inner: Arc::new(Mutex::new(Inner {
65				track: Track {
66					inner: track,
67					group: None,
68				},
69				encoder: Encoder::new(config),
70			})),
71			_marker: PhantomData,
72		}
73	}
74
75	/// Append one record to the log at `at` (see [`Timed::at`](crate::Timed::at)).
76	///
77	/// The log accepts appends for its track's life. A record larger than a frame may be is refused
78	/// with [`moq_net::Error::FrameTooLarge`] before anything is written, leaving the log intact. A
79	/// timestamp that doesn't match the track's timescale (unscaled on a timed track, scaled on a
80	/// scale-less one, or beyond what its scale can hold) is refused with
81	/// [`moq_net::Error::TimestampMismatch`] the same way, so a corrected append carries on.
82	///
83	/// Any other failure ends the track. A log missing a record is not the lossless log a stream
84	/// promises, and that holds whether the group rejected the record or it never encoded at all, so
85	/// the failure is surfaced rather than papered over with a second group. The track is aborted
86	/// rather than closed cleanly, so a consumer sees the failure instead of a log that merely looks
87	/// complete. Every later append fails on the ended track.
88	///
89	/// Returns the encoded size of the frame written.
90	pub fn append(&mut self, value: &T, at: moq_net::Timestamp) -> Result<usize> {
91		self.inner.lock().unwrap().append(value, at)
92	}
93
94	/// Finish the track, closing the group, and return the [`Finished`] log.
95	///
96	/// Clones sharing the track see it ended: their next [`append`](Self::append) fails.
97	pub fn finish(self) -> Result<Finished<T>> {
98		self.inner.lock().unwrap().finish()?;
99		Ok(Finished {
100			inner: self.inner,
101			_marker: PhantomData,
102		})
103	}
104
105	/// Abort the track with the given error, which consumers see in place of a clean end.
106	///
107	/// Consumes the handle, since nothing can be appended afterwards. Clones sharing the track see
108	/// it closed: their next [`append`](Self::append) fails.
109	pub fn abort(self, err: moq_net::Error) -> Result<()> {
110		self.inner.lock().unwrap().track.abort(err);
111		Ok(())
112	}
113}
114
115/// A log whose producer [finished](Producer::finish) it: it can still be read or aborted, but
116/// not appended to.
117///
118/// Dropping the last handle sharing the track releases it, so new readers can no longer find it.
119///
120/// ```compile_fail,E0599
121/// # fn cannot_append(log: moq_json::stream::Finished<u32>) {
122/// log.append(&1, moq_net::Timestamp::unscaled(0)).unwrap();
123/// # }
124/// ```
125#[must_use = "dropping the last handle releases the track, which new readers can then no longer find"]
126pub struct Finished<T> {
127	inner: Arc<Mutex<Inner<T>>>,
128	_marker: PhantomData<fn(T)>,
129}
130
131impl<T> Finished<T> {
132	/// Create a subscriber for the underlying track.
133	pub fn consume(&self) -> moq_net::track::Subscriber {
134		self.inner.lock().unwrap().track.inner.subscribe(None)
135	}
136
137	/// A watch-only handle to the underlying track's subscriber demand.
138	pub fn demand(&self) -> moq_net::track::Demand {
139		self.inner.lock().unwrap().track.inner.demand()
140	}
141
142	/// Abort the track with `err`; see [`moq_net::track::Finished::abort`]. Readers still draining
143	/// get the clean end instead once every group below the end finished.
144	pub fn abort(self, err: moq_net::Error) -> Result<()> {
145		self.inner.lock().unwrap().track.abort(err);
146		Ok(())
147	}
148}
149
150#[cfg(test)]
151impl<T> Producer<T> {
152	/// Shrink the frame limit to a size a test can reach.
153	pub(super) fn set_max_frame_bytes(&self, bytes: u64) {
154		self.inner.lock().unwrap().encoder.max_frame_bytes = bytes;
155	}
156}
157
158/// Shared publishing state behind [`Producer`]'s `Arc<Mutex>`.
159///
160/// The track and the encoder are separate fields so a [`Pending`](super::Pending) record (which
161/// borrows the encoder) and the write that consumes it (which borrows the track) don't contend for
162/// one `&mut self`.
163struct Inner<T> {
164	track: Track,
165	encoder: Encoder<T>,
166}
167
168impl<T: Serialize> Inner<T> {
169	fn append(&mut self, value: &T, at: moq_net::Timestamp) -> Result<usize> {
170		// Split the borrow so `record` can hold the encoder while `track` is written through.
171		let Inner { track, encoder } = self;
172
173		// A timestamp that doesn't match the track, or that its scale can't hold, is refused before
174		// anything changes: found by `write`, it would be a hole that ends the whole log.
175		let at = track.inner.info().rescale(at)?;
176
177		// Encode first, so a value that can't be serialized doesn't publish an empty group that
178		// subscribers would advance into and wait on. Opening the group afterwards is safe because
179		// `record` guards the window: any failure below drops it uncommitted.
180		let record = match encoder.encode(value) {
181			Ok(record) => record,
182			// Refused before encoding, so nothing is missing from the log and nothing desynced.
183			Err(err @ crate::Error::Net(moq_net::Error::FrameTooLarge)) => return Err(err),
184			Err(err) => {
185				// A record that can't be encoded is as lost as one the group rejects: the log is
186				// missing it either way, and carrying on would present that gap as a complete log.
187				// Nothing was published, so this only has to end the track.
188				track.abort(moq_net::Error::Cancel);
189				return Err(err);
190			}
191		};
192
193		let published = track.group.is_some();
194		if let Err(err) = track.write(at, record.payload()) {
195			// The record never reached the wire either way.
196			drop(record);
197
198			// What differs is whether a consumer could have seen the group. A write failure means the
199			// group is already live, so the record is a hole in the log, and a second group would hand
200			// consumers that gap dressed up as a complete log. End the track, which is what keeps "a
201			// stream is one group" a real invariant rather than the usual case.
202			//
203			// The first record's failure published nothing, since a refused frame 0 leaves no group,
204			// so a later append opens a fresh group. That path also catches an append onto a track
205			// already ended this way, which keeps reporting the error it was aborted with.
206			if published {
207				track.abort(err.clone());
208			}
209
210			return Err(err.into());
211		}
212
213		let size = record.payload().len();
214		record.commit();
215		Ok(size)
216	}
217
218	fn finish(&mut self) -> Result<()> {
219		Ok(self.track.finish()?)
220	}
221}
222
223/// The track half of [`Inner`]: the single group carrying the whole log.
224struct Track {
225	inner: moq_net::track::Producer,
226
227	/// Opened on the first append and never rolled.
228	group: Option<moq_net::group::Producer>,
229}
230
231impl Track {
232	/// Append one encoded record to the log's group at `timestamp`, opening the group with it
233	/// when it is the first.
234	fn write(
235		&mut self,
236		timestamp: moq_net::Timestamp,
237		payload: &bytes::Bytes,
238	) -> std::result::Result<(), moq_net::Error> {
239		match self.group.as_mut() {
240			Some(group) => group.write_frame(Frame::new(crate::frame_time(group, timestamp), payload.clone())),
241			None => {
242				self.group = Some(self.inner.append_group(Frame::new(timestamp, payload.clone()))?);
243				Ok(())
244			}
245		}
246	}
247
248	/// End the track with an error, so a consumer sees the failure rather than a clean end.
249	///
250	/// Aborting the *track* is what a subscriber observes. Aborting only the group drops it from the
251	/// cache and the consumer still reads a clean end, which is exactly what a completed log looks
252	/// like, so a truncated log would be indistinguishable from a whole one.
253	fn abort(&mut self, err: moq_net::Error) {
254		// Abort the group with the same error first. `track::Producer::abort` deliberately leaves an
255		// already-pulled `group::Consumer` independent, so dropping our handle would hand a reader
256		// sitting in the group a generic `Dropped` instead of the failure that ended the log.
257		if let Some(group) = self.group.take() {
258			let _ = group.abort(err.clone());
259		}
260
261		// Abort through a clone, since aborting consumes a handle and the state is shared. Keeping
262		// ours means `consume` still hands back a subscriber, which is how a reader learns the log
263		// ended badly rather than cleanly.
264		let _ = self.inner.clone().abort(err);
265	}
266
267	fn finish(&mut self) -> std::result::Result<(), moq_net::Error> {
268		// Finalize both independently rather than short-circuiting on the group. Returning early
269		// would leave the track open with `group` already taken, so a later append would open a
270		// second group. That is exactly the split log ending the track exists to prevent.
271		let group = match self.group.take() {
272			Some(group) => group.finish().map(drop),
273			None => Ok(()),
274		};
275		// This shared state keeps its own clone, whose appends the end refuses.
276		let track = self.inner.clone().finish().map(drop);
277
278		group?;
279		track?;
280		Ok(())
281	}
282}
283
284// A log is one group, so the next producer of this track could not continue it for a reader
285// handed over: an unfinished log is abandoned instead of being requested again, closing cleanly
286// while nobody reads it and ending with `Dropped` for a reader that still does.
287impl Drop for Track {
288	fn drop(&mut self) {
289		if self.group.is_some() && self.inner.finished().is_none() {
290			self.inner.clone().abandon();
291		}
292	}
293}