Skip to main content

livewire/
snapshot.rs

1//! One component's signed wire envelope: the state it carries between requests and the checksum
2//! that proves the browser did not change it.
3//!
4//! The client round-trips the envelope as one minified JSON string per component. Its keys are
5//! always `data`, `memo`, and `checksum`, in that order, so the same snapshot always encodes to the
6//! same bytes. `memo.children` is the one entry the client may rewrite freely — it tracks the
7//! nested components the browser holds — so the checksum leaves it out.
8
9use serde::Serialize;
10use serde::ser::SerializeMap;
11use serde_json::{Map, Value};
12
13use crate::error::LivewireError;
14
15/// A component's state between an initial page render and the browser's next update.
16#[derive(Debug, Clone, PartialEq)]
17pub struct Snapshot {
18    /// The component's wire-public properties, by name, in declaration order.
19    pub data: Map<String, Value>,
20    /// Everything else an update needs: `id`, then `name`, then the feature memo entries.
21    pub memo: Map<String, Value>,
22    /// The checksum of [`signed_bytes`](Snapshot::signed_bytes), as lowercase hex.
23    pub checksum: String,
24}
25
26impl Snapshot {
27    /// Parses the envelope, rejecting any structure the protocol does not define.
28    ///
29    /// # Errors
30    ///
31    /// [`LivewireError::InvalidSnapshot`] when the string is not a JSON object with an object
32    /// `data`, an object `memo` holding string `id` and `name`, and a string `checksum`.
33    pub fn parse(json: &str) -> Result<Self, LivewireError> {
34        let Value::Object(mut envelope) = serde_json::from_str(json).map_err(|_| LivewireError::InvalidSnapshot)?
35        else {
36            return Err(LivewireError::InvalidSnapshot);
37        };
38
39        let memo = envelope.get("memo");
40
41        let well_formed = matches!(envelope.get("data"), Some(Value::Object(_)))
42            && matches!(memo, Some(Value::Object(_)))
43            && matches!(envelope.get("checksum"), Some(Value::String(_)))
44            && matches!(memo.and_then(|memo| memo.get("id")), Some(Value::String(_)))
45            && matches!(memo.and_then(|memo| memo.get("name")), Some(Value::String(_)));
46
47        if !well_formed {
48            return Err(LivewireError::InvalidSnapshot);
49        }
50
51        let Some(Value::Object(data)) = envelope.remove("data") else {
52            return Err(LivewireError::InvalidSnapshot);
53        };
54        let Some(Value::Object(memo)) = envelope.remove("memo") else {
55            return Err(LivewireError::InvalidSnapshot);
56        };
57        let Some(Value::String(checksum)) = envelope.remove("checksum") else {
58            return Err(LivewireError::InvalidSnapshot);
59        };
60
61        Ok(Self { data, memo, checksum })
62    }
63
64    /// Serializes minified, in envelope order.
65    ///
66    /// `memo.children` is written as an object whenever the memo holds it, so an empty child list
67    /// is `{}` and never `null` or omitted.
68    #[must_use]
69    pub fn encode(&self) -> String {
70        #[derive(Serialize)]
71        struct Envelope<'a> {
72            data: &'a Map<String, Value>,
73            memo: Memo<'a>,
74            checksum: &'a str,
75        }
76
77        // A JSON object of strings and values always serializes, so this cannot fail.
78        serde_json::to_string(&Envelope {
79            data: &self.data,
80            memo: Memo {
81                entries: &self.memo,
82                children: Children::Keep,
83            },
84            checksum: &self.checksum,
85        })
86        .unwrap_or_default()
87    }
88
89    /// The component's ID, `memo.id`.
90    ///
91    /// # Errors
92    ///
93    /// [`LivewireError::InvalidSnapshot`] when the memo holds no string `id`.
94    pub fn id(&self) -> Result<&str, LivewireError> {
95        self.memo
96            .get("id")
97            .and_then(Value::as_str)
98            .ok_or(LivewireError::InvalidSnapshot)
99    }
100
101    /// The component's registered name, `memo.name`.
102    ///
103    /// # Errors
104    ///
105    /// [`LivewireError::InvalidSnapshot`] when the memo holds no string `name`.
106    pub fn name(&self) -> Result<&str, LivewireError> {
107        self.memo
108            .get("name")
109            .and_then(Value::as_str)
110            .ok_or(LivewireError::InvalidSnapshot)
111    }
112
113    /// `memo.children`, always an object, empty when absent.
114    #[must_use]
115    pub fn children(&self) -> Map<String, Value> {
116        match self.memo.get("children") {
117            Some(Value::Object(children)) => children.clone(),
118            _ => Map::new(),
119        }
120    }
121
122    /// Replaces `memo.children`, writing it on [`encode`](Snapshot::encode) even when empty.
123    pub fn set_children(&mut self, children: Map<String, Value>) {
124        self.memo.insert("children".into(), Value::Object(children));
125    }
126
127    /// A memo entry, such as `path`, `method`, `parent`, `release`.
128    #[must_use]
129    pub fn memo_value(&self, key: &str) -> Option<&Value> {
130        self.memo.get(key)
131    }
132
133    /// The JSON that the checksum signs: `{data, memo}` with `memo.children` removed.
134    ///
135    /// The client may rewrite the child list without invalidating the snapshot, so the child list
136    /// is the one part of the envelope the checksum does not cover.
137    #[must_use]
138    pub fn signed_bytes(&self) -> String {
139        #[derive(Serialize)]
140        struct Signed<'a> {
141            data: &'a Map<String, Value>,
142            memo: Memo<'a>,
143        }
144
145        // A JSON object of strings and values always serializes, so this cannot fail.
146        serde_json::to_string(&Signed {
147            data: &self.data,
148            memo: Memo {
149                entries: &self.memo,
150                children: Children::Omit,
151            },
152        })
153        .unwrap_or_default()
154    }
155}
156
157/// Whether a memo serialization writes `children`, and how.
158#[derive(Clone, Copy)]
159enum Children {
160    /// Write `children`, as an object, even when the memo holds a non-object there.
161    Keep,
162    /// Leave `children` out, as the checksum does.
163    Omit,
164}
165
166/// A memo written in its own entry order, with `children` kept or dropped.
167struct Memo<'a> {
168    entries: &'a Map<String, Value>,
169    children: Children,
170}
171
172impl Serialize for Memo<'_> {
173    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
174        let mut map = serializer.serialize_map(Some(self.entries.len()))?;
175
176        for (key, value) in self.entries {
177            if key == "children" {
178                match self.children {
179                    Children::Omit => continue,
180                    Children::Keep => match value {
181                        Value::Object(_) => map.serialize_entry(key, value)?,
182                        _ => map.serialize_entry(key, &Value::Object(Map::new()))?,
183                    },
184                }
185            } else {
186                map.serialize_entry(key, value)?;
187            }
188        }
189
190        map.end()
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197    use serde_json::json;
198
199    fn object(value: Value) -> Map<String, Value> {
200        match value {
201            Value::Object(map) => map,
202            other => panic!("expected a JSON object, got {other}"),
203        }
204    }
205
206    fn snapshot() -> Snapshot {
207        Snapshot {
208            data: object(json!({"count": 0, "items": ["a", "b"]})),
209            memo: object(json!({"id": "abc", "name": "counter", "children": {}})),
210            checksum: "0f".into(),
211        }
212    }
213
214    #[test]
215    fn encodes_the_envelope_in_order() {
216        assert_eq!(
217            snapshot().encode(),
218            r#"{"data":{"count":0,"items":["a","b"]},"memo":{"id":"abc","name":"counter","children":{}},"checksum":"0f"}"#
219        );
220    }
221
222    #[test]
223    fn round_trips_byte_identically() {
224        let encoded = snapshot().encode();
225        let reparsed = Snapshot::parse(&encoded).expect("a snapshot it encoded parses");
226
227        assert_eq!(reparsed, snapshot());
228        assert_eq!(reparsed.encode(), encoded);
229    }
230
231    #[test]
232    fn writes_empty_children_as_an_object() {
233        let mut snapshot = snapshot();
234        snapshot.set_children(Map::new());
235
236        assert!(snapshot.encode().contains(r#""children":{}"#));
237        let reparsed = Snapshot::parse(&snapshot.encode()).expect("a snapshot it encoded parses");
238        assert_eq!(reparsed.encode(), snapshot.encode());
239    }
240
241    #[test]
242    fn writes_children_that_arrived_as_null_as_an_object() {
243        let mut snapshot = snapshot();
244        snapshot.memo.insert("children".into(), Value::Null);
245
246        assert!(snapshot.encode().contains(r#""children":{}"#));
247    }
248
249    #[test]
250    fn omits_children_the_memo_never_held() {
251        let mut snapshot = snapshot();
252        snapshot.memo.remove("children");
253
254        assert!(!snapshot.encode().contains("children"));
255    }
256
257    #[test]
258    fn children_default_to_empty_when_absent_or_not_an_object() {
259        let mut snapshot = snapshot();
260        snapshot.memo.remove("children");
261        assert!(snapshot.children().is_empty());
262
263        snapshot.memo.insert("children".into(), json!(["not", "an", "object"]));
264        assert!(snapshot.children().is_empty());
265    }
266
267    #[test]
268    fn children_are_the_memo_object() {
269        let snapshot = snapshot();
270
271        assert_eq!(snapshot.children(), object(json!({})));
272    }
273
274    #[test]
275    fn reads_the_component_identity() {
276        let snapshot = snapshot();
277
278        assert_eq!(snapshot.id(), Ok("abc"));
279        assert_eq!(snapshot.name(), Ok("counter"));
280    }
281
282    #[test]
283    fn reads_memo_entries() {
284        assert_eq!(snapshot().memo_value("name"), Some(&json!("counter")));
285        assert_eq!(snapshot().memo_value("path"), None);
286    }
287
288    #[test]
289    fn signed_bytes_drop_the_checksum_and_the_children() {
290        assert_eq!(
291            snapshot().signed_bytes(),
292            r#"{"data":{"count":0,"items":["a","b"]},"memo":{"id":"abc","name":"counter"}}"#
293        );
294
295        let signed = snapshot().signed_bytes();
296        assert!(signed.find("\"data\":").unwrap() < signed.find("\"memo\":").unwrap());
297    }
298
299    #[test]
300    fn rejects_structures_the_protocol_does_not_define() {
301        let malformed = [
302            "not json",
303            "[]",
304            r#"{"data":{},"memo":{},"checksum":"0f"}"#,
305            r#"{"memo":{},"checksum":"0f"}"#,
306            r#"{"data":[],"memo":{"id":"a","name":"b"},"checksum":"0f"}"#,
307            r#"{"data":{},"checksum":"0f"}"#,
308            r#"{"data":{},"memo":[],"checksum":"0f"}"#,
309            r#"{"data":{},"memo":{"id":"a","name":"b"}}"#,
310            r#"{"data":{},"memo":{"id":"a","name":"b"},"checksum":1}"#,
311            r#"{"data":{},"memo":{"id":1,"name":"b"},"checksum":"0f"}"#,
312            r#"{"data":{},"memo":{"name":"b"},"checksum":"0f"}"#,
313            r#"{"data":{},"memo":{"id":"a","name":null},"checksum":"0f"}"#,
314        ];
315
316        for json in malformed {
317            assert_eq!(Snapshot::parse(json), Err(LivewireError::InvalidSnapshot), "{json}");
318        }
319    }
320}