Skip to main content

moq_json/snapshot/
decoder.rs

1//! The track-free half of snapshot consuming: frame payloads in, values out.
2
3use std::cell::RefCell;
4use std::marker::PhantomData;
5
6use serde::de::DeserializeOwned;
7use serde_json::Value;
8
9use super::consumer::Config;
10use crate::{Error, Result};
11
12/// Reconstructs a JSON value from the snapshot and delta frames of a group.
13///
14/// The track-free core of [`Consumer`](super::Consumer), and the mirror of
15/// [`Encoder`](super::Encoder). The caller reads frames from wherever it likes and routes each one
16/// by its position in the group: the first frame of every group is a
17/// [`snapshot`](Self::snapshot), the rest are [`delta`](Self::delta)s.
18///
19/// ```ignore
20/// match frame.keyframe {
21///     true => decoder.snapshot(&frame.payload)?,
22///     false => decoder.delta(&frame.payload)?,
23/// }
24/// let value = decoder.decode()?;
25/// ```
26///
27/// Applying and materializing are separate on purpose. Frames must be applied in order (the merge
28/// patches are sequential), but a consumer catching up on a backlog only
29/// wants the value at the head, so it applies every frame and calls [`decode`](Self::decode) once.
30/// A caller that wants a value per frame just calls it every time.
31pub struct Decoder<T> {
32	max_size: Option<usize>,
33
34	/// Reused key buffers for validating remote patches before changing the baseline.
35	check: RefCell<crate::strict::Scratch>,
36
37	/// The reconstructed value, `None` until the first snapshot.
38	current: Option<Value>,
39
40	_marker: PhantomData<fn() -> T>,
41}
42
43impl<T> Decoder<T> {
44	/// Create a decoder with no value, awaiting its first [`snapshot`](Self::snapshot).
45	pub fn new(config: Config) -> Self {
46		Self {
47			max_size: config.max_size,
48			check: RefCell::new(crate::strict::Scratch::default()),
49			current: None,
50			_marker: PhantomData,
51		}
52	}
53
54	/// Apply a group's first frame: a full snapshot that replaces the current value.
55	///
56	/// Call this at every group boundary, not only the first.
57	pub fn snapshot(&mut self, payload: &[u8]) -> Result<()> {
58		self.current = None;
59		if let Some(limit) = self.max_size
60			&& payload.len() > limit
61		{
62			return Err(Error::TooLarge(limit));
63		}
64		crate::strict::check(payload, &self.check)?;
65		self.current = Some(serde_json::from_slice(payload)?);
66		self.check_size()
67	}
68
69	/// Apply a merge patch, refusing frames or reconstructed state beyond the configured budget.
70	/// A failed patch invalidates the baseline; start a new snapshot before applying more deltas.
71	pub fn delta(&mut self, payload: &[u8]) -> Result<()> {
72		if self.current.is_none() {
73			return Err(Error::MissingSnapshot);
74		}
75		let result = (|| {
76			if let Some(limit) = self.max_size
77				&& payload.len() > limit
78			{
79				return Err(Error::TooLarge(limit));
80			}
81			crate::merge::apply_bytes(
82				self.current.as_mut().expect("a snapshot precedes any delta"),
83				payload,
84				&self.check,
85			)?;
86			self.check_size()
87		})();
88		if result.is_err() {
89			self.current = None;
90		}
91		result
92	}
93
94	fn check_size(&mut self) -> Result<()> {
95		let Some(limit) = self.max_size else { return Ok(()) };
96		// Count the compact representation without allocating another full snapshot.
97		// A patch and the prior state are each bounded, and an oversized result is
98		// released before it can be materialized or used by another patch.
99		if serde_json::to_writer(Budget(limit), self.current.as_ref().unwrap()).is_err() {
100			self.current = None;
101			return Err(Error::TooLarge(limit));
102		}
103		Ok(())
104	}
105
106	/// The reconstructed value as raw JSON, or `None` before the first snapshot.
107	pub fn value(&self) -> Option<&Value> {
108		self.current.as_ref()
109	}
110}
111
112struct Budget(usize);
113
114impl std::io::Write for Budget {
115	fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
116		if bytes.len() > self.0 {
117			return Err(std::io::Error::other("JSON size budget exceeded"));
118		}
119		self.0 -= bytes.len();
120		Ok(bytes.len())
121	}
122
123	fn flush(&mut self) -> std::io::Result<()> {
124		Ok(())
125	}
126}
127
128impl<T: DeserializeOwned> Decoder<T> {
129	/// Materialize the reconstructed value as `T`, or `None` before the first snapshot.
130	///
131	/// Deserializing from the reconstructed [`Value`] rather than the frame bytes costs the line and
132	/// column a parse error would carry, so the error is prefixed with the JSON path of the offending
133	/// field instead. Without it a rejected field deep in a document reports only its own complaint,
134	/// with nothing to say where it came from.
135	pub fn decode(&self) -> Result<Option<T>> {
136		let Some(current) = self.current.as_ref() else {
137			return Ok(None);
138		};
139
140		// Tracking the path allocates for every key walked, which dwarfed the decode itself on large
141		// documents, so it only runs again to explain a failure.
142		if let Ok(value) = T::deserialize(current) {
143			return Ok(Some(value));
144		}
145
146		let value = serde_path_to_error::deserialize(current).map_err(|err| {
147			let path = err.path().to_string();
148			match path.as_str() {
149				// The whole document, not a field within it: nothing useful to prefix.
150				"." => Error::Json(err.into_inner().to_string()),
151				_ => Error::Json(format!("{}: {}", path, err.into_inner())),
152			}
153		})?;
154
155		Ok(Some(value))
156	}
157}
158
159#[cfg(test)]
160mod test {
161	use super::super::consumer::Config as ConsumerConfig;
162	use super::super::encoder::MAX_DELTA_FRAMES;
163	use super::super::{Config, Encoder};
164	use super::*;
165	use serde_json::{Value, json};
166
167	/// Round-trip a sequence of values through an encoder and decoder, yielding the value the
168	/// decoder reconstructs after each frame.
169	fn roundtrip(config: Config, values: &[Value]) -> Vec<Value> {
170		let mut encoder = Encoder::<Value>::new(config);
171		let mut decoder = Decoder::<Value>::new(ConsumerConfig::default());
172
173		let mut out = Vec::new();
174		for value in values {
175			let Some(frame) = encoder.update(value).unwrap() else {
176				continue;
177			};
178			match frame.keyframe {
179				true => decoder.snapshot(&frame.payload).unwrap(),
180				false => decoder.delta(&frame.payload).unwrap(),
181			}
182			frame.commit();
183			out.push(decoder.decode().unwrap().unwrap());
184		}
185		out
186	}
187
188	/// A frame that repeats a key is refused rather than resolved to the last copy, so a reader
189	/// can't be handed a different value than a stricter parser would see.
190	#[test]
191	fn duplicate_keys_are_refused() {
192		let vectors = crate::strict::test::vectors();
193		for payload in &vectors.refused {
194			let mut decoder = Decoder::<Value>::new(ConsumerConfig::default());
195			let err = decoder.snapshot(payload.as_bytes()).unwrap_err();
196			assert!(matches!(err, Error::DuplicateKey), "{payload}: {err}");
197			assert!(decoder.value().is_none());
198
199			decoder.snapshot(b"{}").unwrap();
200			let err = decoder.delta(payload.as_bytes()).unwrap_err();
201			assert!(matches!(err, Error::DuplicateKey), "{payload}: {err}");
202			assert!(decoder.value().is_none());
203		}
204		for payload in &vectors.accepted {
205			let mut decoder = Decoder::<Value>::new(ConsumerConfig::default());
206			decoder.snapshot(payload.as_bytes()).unwrap();
207			decoder.delta(payload.as_bytes()).unwrap();
208		}
209	}
210
211	#[test]
212	fn patches_cannot_accumulate_past_the_budget() {
213		let config = ConsumerConfig {
214			max_size: Some(13),
215			..Default::default()
216		};
217		let mut decoder = Decoder::<Value>::new(config);
218		decoder.snapshot(br#"{"a":1}"#).unwrap();
219		decoder.delta(br#"{"b":2}"#).unwrap(); // exactly 13 bytes
220		assert_eq!(decoder.value(), Some(&json!({"a":1,"b":2})));
221		decoder.delta(br#"{"a":null}"#).unwrap(); // deletion frees budget
222		decoder.delta(br#"{"c":3}"#).unwrap();
223		assert!(matches!(decoder.delta(br#"{"d":4}"#), Err(Error::TooLarge(13))));
224		assert!(decoder.value().is_none());
225		assert!(matches!(decoder.delta(b"{}"), Err(Error::MissingSnapshot)));
226		// A fresh group can recover after refusal.
227		decoder.snapshot(b"{}").unwrap();
228	}
229
230	#[test]
231	fn plain_frames_obey_the_budget_before_parsing() {
232		let config = ConsumerConfig {
233			max_size: Some(2),
234			..Default::default()
235		};
236		let mut decoder = Decoder::<Value>::new(config);
237		assert!(matches!(decoder.snapshot(b"not json"), Err(Error::TooLarge(2))));
238		decoder.snapshot(b"{}").unwrap();
239		assert!(matches!(decoder.delta(b"not json"), Err(Error::TooLarge(2))));
240		assert!(decoder.value().is_none());
241	}
242
243	#[test]
244	fn plaintext_roundtrip() {
245		let values = vec![
246			json!({ "a": 1, "b": 1 }),
247			json!({ "a": 1, "b": 2 }),
248			json!({ "a": 5, "b": 2 }),
249		];
250		assert_eq!(roundtrip(Config::default(), &values), values);
251	}
252
253	/// Deltas are per group, so a keyframe mid-stream has to restart the baseline on both sides. An
254	/// encoder that diffed across the boundary would emit patches a joiner starting at the new group
255	/// can't apply.
256	#[test]
257	fn roundtrip_across_a_group_boundary() {
258		let mut encoder = Encoder::<Value>::new(Config::default().with_deltas(true));
259		// One decoder reads every group in turn, and a joiner starts cold at each group, as a late
260		// subscriber does.
261		let mut decoder = Decoder::<Value>::new(ConsumerConfig::default());
262		let mut joiner = Decoder::<Value>::new(ConsumerConfig::default());
263
264		// The frame cap rolls the group partway through, and a restatement rolls it again.
265		let restate = MAX_DELTA_FRAMES + 10;
266		let mut keyframes = 0;
267		for n in 0..=2 * MAX_DELTA_FRAMES {
268			let value = json!({ "n": n });
269			let frame = if n == restate {
270				encoder.update(&value).unwrap().unwrap().commit();
271				encoder.snapshot().unwrap().unwrap()
272			} else {
273				encoder.update(&value).unwrap().unwrap()
274			};
275			if frame.keyframe {
276				keyframes += 1;
277				joiner = Decoder::<Value>::new(ConsumerConfig::default());
278				decoder.snapshot(&frame.payload).unwrap();
279				joiner.snapshot(&frame.payload).unwrap();
280			} else {
281				decoder.delta(&frame.payload).unwrap();
282				joiner.delta(&frame.payload).unwrap();
283			}
284			frame.commit();
285			assert_eq!(decoder.decode().unwrap(), Some(value.clone()), "after update {n}");
286			assert_eq!(joiner.decode().unwrap(), Some(value), "a joiner after update {n}");
287		}
288
289		// The first group, the cap roll, and the restatement.
290		assert_eq!(keyframes, 3, "the stream has to cross group boundaries");
291	}
292
293	#[test]
294	fn no_value_before_the_first_snapshot() {
295		let decoder = Decoder::<Value>::new(ConsumerConfig::default());
296		assert_eq!(decoder.value(), None);
297		assert_eq!(decoder.decode().unwrap(), None);
298	}
299
300	#[test]
301	fn a_delta_before_a_snapshot_is_an_error() {
302		let mut decoder = Decoder::<Value>::new(ConsumerConfig::default());
303		assert!(matches!(decoder.delta(br#"{"a":1}"#), Err(Error::MissingSnapshot)));
304	}
305
306	/// A backlog is applied in full but materialized once: the intermediate reconstructions are
307	/// stale, and deserializing each one is exactly the cost the split exists to avoid.
308	#[test]
309	fn frames_apply_without_materializing() {
310		let mut encoder = Encoder::<Value>::new(Config::default().with_deltas(true));
311		let mut decoder = Decoder::<Value>::new(ConsumerConfig::default());
312
313		for n in 0..=20 {
314			let frame = encoder.update(&json!({ "n": n })).unwrap().unwrap();
315			match frame.keyframe {
316				true => decoder.snapshot(&frame.payload).unwrap(),
317				false => decoder.delta(&frame.payload).unwrap(),
318			}
319			frame.commit();
320		}
321
322		assert_eq!(decoder.decode().unwrap(), Some(json!({ "n": 20 })));
323	}
324
325	#[test]
326	fn a_rejected_field_names_its_path() {
327		#[derive(serde::Deserialize, Debug)]
328		#[allow(dead_code, reason = "the test only checks that deserializing fails")]
329		struct Inner {
330			count: u8,
331		}
332		#[derive(serde::Deserialize, Debug)]
333		#[allow(dead_code, reason = "the test only checks that deserializing fails")]
334		struct Outer {
335			inner: Inner,
336		}
337
338		let mut decoder = Decoder::<Outer>::new(ConsumerConfig::default());
339		decoder.snapshot(br#"{"inner":{"count":300}}"#).unwrap();
340
341		let err = decoder.decode().unwrap_err();
342		assert!(err.to_string().starts_with("json: inner.count: "), "{err}");
343	}
344}