Skip to main content

moq_json/stream/
encoder.rs

1//! The track-free half of stream publishing: records in, frame payloads out.
2
3use std::marker::PhantomData;
4
5use bytes::Bytes;
6use serde::Serialize;
7
8use crate::Result;
9
10/// Codec options for an [`Encoder`], and so for the [`Producer`](super::Producer) wrapping one.
11///
12/// Empty for now. Build from [`Default`]; the struct is `#[non_exhaustive]`, so new options stay
13/// additive.
14#[derive(Debug, Clone, Default)]
15#[non_exhaustive]
16pub struct Config {}
17
18/// An encoded record the caller has not yet acknowledged writing.
19///
20/// Returned by [`Encoder::encode`]. Write the [`payload`](Self::payload), then
21/// [`commit`](Self::commit).
22///
23/// A frame that is never committed never reached the wire. Each record stands alone, so a dropped
24/// one leaves a gap in the log but nothing undecodable, and encoding continues.
25#[must_use = "write and commit the record"]
26pub struct Pending<'a, T> {
27	_encoder: &'a mut Encoder<T>,
28	payload: Bytes,
29}
30
31impl<T> Pending<'_, T> {
32	/// The frame payload to write.
33	pub fn payload(&self) -> &Bytes {
34		&self.payload
35	}
36
37	/// Acknowledge that the record reached the wire.
38	///
39	/// Only call this once the write has actually succeeded.
40	pub fn commit(self) {}
41}
42
43/// Encodes JSON records into frame payloads.
44///
45/// The track-free core of [`Producer`](super::Producer). Unlike
46/// [`snapshot::Encoder`](crate::snapshot::Encoder) there are no group boundaries to report: a log is
47/// an unbroken sequence of self-contained records, so every payload is simply the next frame.
48///
49/// Payloads must reach the wire in order. A group has no size cap, so the encoder keeps no budget.
50pub struct Encoder<T> {
51	/// The most bytes one record may hold. A field rather than the constant so a test can shrink it
52	/// to a size it can reach.
53	pub(super) max_frame_bytes: u64,
54
55	_marker: PhantomData<fn(T)>,
56}
57
58impl<T> Encoder<T> {
59	/// Create an encoder.
60	pub fn new(_config: Config) -> Self {
61		Self {
62			max_frame_bytes: crate::MAX_GROUP_BYTES,
63			_marker: PhantomData,
64		}
65	}
66}
67
68impl<T: Serialize> Encoder<T> {
69	/// Encode one record into the next frame payload.
70	///
71	/// The record comes back as a [`Pending`] the caller writes and then
72	/// [`commit`](Pending::commit)s.
73	///
74	/// Errors with [`moq_net::Error::FrameTooLarge`] if the record is larger than one frame may be
75	/// (32 MiB, what moq-net's group cache holds), and with [`crate::Error::Json`] if it nests too
76	/// deeply for a decoder to read. The refused record leaves the encoder untouched.
77	pub fn encode(&mut self, value: &T) -> Result<Pending<'_, T>> {
78		let payload = Bytes::from(crate::strict::to_vec(value, 0)?);
79		if payload.len() as u64 > self.max_frame_bytes {
80			return Err(moq_net::Error::FrameTooLarge.into());
81		}
82
83		Ok(Pending {
84			_encoder: self,
85			payload,
86		})
87	}
88}