livewire-rust 0.1.3

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
//! One component's signed wire envelope: the state it carries between requests and the checksum
//! that proves the browser did not change it.
//!
//! The client round-trips the envelope as one minified JSON string per component. Its keys are
//! always `data`, `memo`, and `checksum`, in that order, so the same snapshot always encodes to the
//! same bytes. `memo.children` is the one entry the client may rewrite freely — it tracks the
//! nested components the browser holds — so the checksum leaves it out.

use serde::Serialize;
use serde::ser::SerializeMap;
use serde_json::{Map, Value};

use crate::error::LivewireError;

/// A component's state between an initial page render and the browser's next update.
#[derive(Debug, Clone, PartialEq)]
pub struct Snapshot {
    /// The component's wire-public properties, by name, in declaration order.
    pub data: Map<String, Value>,
    /// Everything else an update needs: `id`, then `name`, then the feature memo entries.
    pub memo: Map<String, Value>,
    /// The checksum of [`signed_bytes`](Snapshot::signed_bytes), as lowercase hex.
    pub checksum: String,
}

impl Snapshot {
    /// Parses the envelope, rejecting any structure the protocol does not define.
    ///
    /// # Errors
    ///
    /// [`LivewireError::InvalidSnapshot`] when the string is not a JSON object with an object
    /// `data`, an object `memo` holding string `id` and `name`, and a string `checksum`.
    pub fn parse(json: &str) -> Result<Self, LivewireError> {
        let Value::Object(mut envelope) = serde_json::from_str(json).map_err(|_| LivewireError::InvalidSnapshot)?
        else {
            return Err(LivewireError::InvalidSnapshot);
        };

        let memo = envelope.get("memo");

        let well_formed = matches!(envelope.get("data"), Some(Value::Object(_)))
            && matches!(memo, Some(Value::Object(_)))
            && matches!(envelope.get("checksum"), Some(Value::String(_)))
            && matches!(memo.and_then(|memo| memo.get("id")), Some(Value::String(_)))
            && matches!(memo.and_then(|memo| memo.get("name")), Some(Value::String(_)));

        if !well_formed {
            return Err(LivewireError::InvalidSnapshot);
        }

        let Some(Value::Object(data)) = envelope.remove("data") else {
            return Err(LivewireError::InvalidSnapshot);
        };
        let Some(Value::Object(memo)) = envelope.remove("memo") else {
            return Err(LivewireError::InvalidSnapshot);
        };
        let Some(Value::String(checksum)) = envelope.remove("checksum") else {
            return Err(LivewireError::InvalidSnapshot);
        };

        Ok(Self { data, memo, checksum })
    }

    /// Serializes minified, in envelope order.
    ///
    /// `memo.children` is written as an object whenever the memo holds it, so an empty child list
    /// is `{}` and never `null` or omitted.
    #[must_use]
    pub fn encode(&self) -> String {
        #[derive(Serialize)]
        struct Envelope<'a> {
            data: &'a Map<String, Value>,
            memo: Memo<'a>,
            checksum: &'a str,
        }

        // A JSON object of strings and values always serializes, so this cannot fail.
        serde_json::to_string(&Envelope {
            data: &self.data,
            memo: Memo {
                entries: &self.memo,
                children: Children::Keep,
            },
            checksum: &self.checksum,
        })
        .unwrap_or_default()
    }

    /// The component's ID, `memo.id`.
    ///
    /// # Errors
    ///
    /// [`LivewireError::InvalidSnapshot`] when the memo holds no string `id`.
    pub fn id(&self) -> Result<&str, LivewireError> {
        self.memo
            .get("id")
            .and_then(Value::as_str)
            .ok_or(LivewireError::InvalidSnapshot)
    }

    /// The component's registered name, `memo.name`.
    ///
    /// # Errors
    ///
    /// [`LivewireError::InvalidSnapshot`] when the memo holds no string `name`.
    pub fn name(&self) -> Result<&str, LivewireError> {
        self.memo
            .get("name")
            .and_then(Value::as_str)
            .ok_or(LivewireError::InvalidSnapshot)
    }

    /// `memo.children`, always an object, empty when absent.
    #[must_use]
    pub fn children(&self) -> Map<String, Value> {
        match self.memo.get("children") {
            Some(Value::Object(children)) => children.clone(),
            _ => Map::new(),
        }
    }

    /// Replaces `memo.children`, writing it on [`encode`](Snapshot::encode) even when empty.
    pub fn set_children(&mut self, children: Map<String, Value>) {
        self.memo.insert("children".into(), Value::Object(children));
    }

    /// A memo entry, such as `path`, `method`, `parent`, `release`.
    #[must_use]
    pub fn memo_value(&self, key: &str) -> Option<&Value> {
        self.memo.get(key)
    }

    /// The JSON that the checksum signs: `{data, memo}` with `memo.children` removed.
    ///
    /// The client may rewrite the child list without invalidating the snapshot, so the child list
    /// is the one part of the envelope the checksum does not cover.
    #[must_use]
    pub fn signed_bytes(&self) -> String {
        #[derive(Serialize)]
        struct Signed<'a> {
            data: &'a Map<String, Value>,
            memo: Memo<'a>,
        }

        // A JSON object of strings and values always serializes, so this cannot fail.
        serde_json::to_string(&Signed {
            data: &self.data,
            memo: Memo {
                entries: &self.memo,
                children: Children::Omit,
            },
        })
        .unwrap_or_default()
    }
}

/// Whether a memo serialization writes `children`, and how.
#[derive(Clone, Copy)]
enum Children {
    /// Write `children`, as an object, even when the memo holds a non-object there.
    Keep,
    /// Leave `children` out, as the checksum does.
    Omit,
}

/// A memo written in its own entry order, with `children` kept or dropped.
struct Memo<'a> {
    entries: &'a Map<String, Value>,
    children: Children,
}

impl Serialize for Memo<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut map = serializer.serialize_map(Some(self.entries.len()))?;

        for (key, value) in self.entries {
            if key == "children" {
                match self.children {
                    Children::Omit => continue,
                    Children::Keep => match value {
                        Value::Object(_) => map.serialize_entry(key, value)?,
                        _ => map.serialize_entry(key, &Value::Object(Map::new()))?,
                    },
                }
            } else {
                map.serialize_entry(key, value)?;
            }
        }

        map.end()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn object(value: Value) -> Map<String, Value> {
        match value {
            Value::Object(map) => map,
            other => panic!("expected a JSON object, got {other}"),
        }
    }

    fn snapshot() -> Snapshot {
        Snapshot {
            data: object(json!({"count": 0, "items": ["a", "b"]})),
            memo: object(json!({"id": "abc", "name": "counter", "children": {}})),
            checksum: "0f".into(),
        }
    }

    #[test]
    fn encodes_the_envelope_in_order() {
        assert_eq!(
            snapshot().encode(),
            r#"{"data":{"count":0,"items":["a","b"]},"memo":{"id":"abc","name":"counter","children":{}},"checksum":"0f"}"#
        );
    }

    #[test]
    fn round_trips_byte_identically() {
        let encoded = snapshot().encode();
        let reparsed = Snapshot::parse(&encoded).expect("a snapshot it encoded parses");

        assert_eq!(reparsed, snapshot());
        assert_eq!(reparsed.encode(), encoded);
    }

    #[test]
    fn writes_empty_children_as_an_object() {
        let mut snapshot = snapshot();
        snapshot.set_children(Map::new());

        assert!(snapshot.encode().contains(r#""children":{}"#));
        let reparsed = Snapshot::parse(&snapshot.encode()).expect("a snapshot it encoded parses");
        assert_eq!(reparsed.encode(), snapshot.encode());
    }

    #[test]
    fn writes_children_that_arrived_as_null_as_an_object() {
        let mut snapshot = snapshot();
        snapshot.memo.insert("children".into(), Value::Null);

        assert!(snapshot.encode().contains(r#""children":{}"#));
    }

    #[test]
    fn omits_children_the_memo_never_held() {
        let mut snapshot = snapshot();
        snapshot.memo.remove("children");

        assert!(!snapshot.encode().contains("children"));
    }

    #[test]
    fn children_default_to_empty_when_absent_or_not_an_object() {
        let mut snapshot = snapshot();
        snapshot.memo.remove("children");
        assert!(snapshot.children().is_empty());

        snapshot.memo.insert("children".into(), json!(["not", "an", "object"]));
        assert!(snapshot.children().is_empty());
    }

    #[test]
    fn children_are_the_memo_object() {
        let snapshot = snapshot();

        assert_eq!(snapshot.children(), object(json!({})));
    }

    #[test]
    fn reads_the_component_identity() {
        let snapshot = snapshot();

        assert_eq!(snapshot.id(), Ok("abc"));
        assert_eq!(snapshot.name(), Ok("counter"));
    }

    #[test]
    fn reads_memo_entries() {
        assert_eq!(snapshot().memo_value("name"), Some(&json!("counter")));
        assert_eq!(snapshot().memo_value("path"), None);
    }

    #[test]
    fn signed_bytes_drop_the_checksum_and_the_children() {
        assert_eq!(
            snapshot().signed_bytes(),
            r#"{"data":{"count":0,"items":["a","b"]},"memo":{"id":"abc","name":"counter"}}"#
        );

        let signed = snapshot().signed_bytes();
        assert!(signed.find("\"data\":").unwrap() < signed.find("\"memo\":").unwrap());
    }

    #[test]
    fn rejects_structures_the_protocol_does_not_define() {
        let malformed = [
            "not json",
            "[]",
            r#"{"data":{},"memo":{},"checksum":"0f"}"#,
            r#"{"memo":{},"checksum":"0f"}"#,
            r#"{"data":[],"memo":{"id":"a","name":"b"},"checksum":"0f"}"#,
            r#"{"data":{},"checksum":"0f"}"#,
            r#"{"data":{},"memo":[],"checksum":"0f"}"#,
            r#"{"data":{},"memo":{"id":"a","name":"b"}}"#,
            r#"{"data":{},"memo":{"id":"a","name":"b"},"checksum":1}"#,
            r#"{"data":{},"memo":{"id":1,"name":"b"},"checksum":"0f"}"#,
            r#"{"data":{},"memo":{"name":"b"},"checksum":"0f"}"#,
            r#"{"data":{},"memo":{"id":"a","name":null},"checksum":"0f"}"#,
        ];

        for json in malformed {
            assert_eq!(Snapshot::parse(json), Err(LivewireError::InvalidSnapshot), "{json}");
        }
    }
}