Skip to main content

livewire/synthesizers/
mod.rs

1//! The synthesizers that read and write a field whose wire form differs from its Rust form.
2//!
3//! Most fields cross the wire as plain JSON, and the derive's own per-field code reads and writes
4//! them. A field needs a synthesizer when its JSON form cannot be read back without knowing what it
5//! was: a model reference, a paginator, a form object, or a value that carries a type tag.
6//!
7//! A synthesized field crosses the wire as a two-element tuple, `[value, meta]`, where `meta.s` is
8//! the synthesizer's key. The key comes from the checksum-verified snapshot, never from the update
9//! the browser sent, and is resolved against the synthesizers the application registered — never
10//! against a type named by the input.
11
12use std::fmt;
13
14use serde_json::{Map, Value};
15
16/// Why a synthesizer could not read a value.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum SynthError {
19    /// The value's shape does not match what the synthesizer reads.
20    Corrupt(String),
21    /// The value names a synthesizer the application did not register.
22    UnknownKey(String),
23}
24
25impl SynthError {
26    /// A corrupt value, with what was expected instead.
27    pub fn corrupt(expected: impl Into<String>) -> Self {
28        Self::Corrupt(expected.into())
29    }
30}
31
32impl fmt::Display for SynthError {
33    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Self::Corrupt(message) => formatter.write_str(message),
36            Self::UnknownKey(key) => write!(formatter, "Unable to find synthesizer with key: [{key}]"),
37        }
38    }
39}
40
41impl std::error::Error for SynthError {}
42
43/// The result of a synthesizer's read or write.
44pub type Result<T, E = SynthError> = std::result::Result<T, E>;
45
46/// A value whose wire form needs a type tag to be read back.
47///
48/// `#[livewire(synth(path::to::Synth))]` marks a field, and the derive calls the synthesizer before
49/// it writes the field and after it reads it.
50pub trait Synth: Sized + Send + Sync + 'static {
51    /// The key the wire form carries, which the snapshot's metadata names.
52    const KEY: &'static str;
53
54    /// The field's wire value and metadata, or `None` when plain JSON reads back without help.
55    fn dehydrate(&self) -> Option<(Value, Map<String, Value>)>;
56
57    /// Reads a field back from its wire value and the metadata the snapshot carried.
58    ///
59    /// # Errors
60    ///
61    /// Fails when the value cannot be read as this synthesizer's type.
62    fn hydrate(value: &Value, meta: Option<&Map<String, Value>>) -> Result<Self>;
63}
64
65/// Splits a wire value into the value and the metadata of a synthesized field.
66///
67/// A value that is not a tuple is returned as it is, with no metadata, which is what a field the
68/// snapshot has not seen looks like.
69#[must_use]
70pub fn split_tuple(value: &Value) -> (Value, Option<Map<String, Value>>) {
71    let Value::Array(parts) = value else {
72        return (value.clone(), None);
73    };
74
75    if parts.len() != 2 {
76        return (value.clone(), None);
77    }
78
79    let meta = match &parts[1] {
80        Value::Object(meta) if meta.contains_key(SYNTH_KEY) => Some(meta.clone()),
81        _ => None,
82    };
83
84    match meta {
85        Some(meta) => (parts[0].clone(), Some(meta)),
86        None => (value.clone(), None),
87    }
88}
89
90/// The metadata key that names the synthesizer.
91pub const SYNTH_KEY: &str = "s";
92
93/// A synthesizer that carries its key in the metadata it writes.
94pub(crate) fn with_key(key: &'static str, mut meta: Map<String, Value>) -> Map<String, Value> {
95    meta.insert(SYNTH_KEY.to_owned(), Value::from(key));
96    meta
97}
98
99/// An array, which crosses the wire as an array.
100#[derive(Debug, Clone, Default, PartialEq)]
101pub struct Arr(pub Vec<Value>);
102
103impl Synth for Arr {
104    const KEY: &'static str = "arr";
105
106    fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
107        Some((Value::Array(self.0.clone()), with_key(Self::KEY, Map::new())))
108    }
109
110    fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
111        match value {
112            Value::Array(values) => Ok(Self(values.clone())),
113            _ => Err(SynthError::corrupt("an array")),
114        }
115    }
116}
117
118/// An object, which crosses the wire as an object.
119#[derive(Debug, Clone, Default, PartialEq)]
120pub struct Std(pub Map<String, Value>);
121
122impl Synth for Std {
123    const KEY: &'static str = "std";
124
125    fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
126        Some((Value::Object(self.0.clone()), with_key(Self::KEY, Map::new())))
127    }
128
129    fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
130        match value {
131            Value::Object(map) => Ok(Self(map.clone())),
132            _ => Err(SynthError::corrupt("an object")),
133        }
134    }
135}
136
137/// A string.
138#[derive(Debug, Clone, Default, PartialEq, Eq)]
139pub struct Str(pub String);
140
141impl Synth for Str {
142    const KEY: &'static str = "str";
143
144    fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
145        None
146    }
147
148    fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
149        value
150            .as_str()
151            .map(|text| Self(text.to_owned()))
152            .ok_or_else(|| SynthError::corrupt("a string"))
153    }
154}
155
156/// An integer.
157#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
158pub struct Int(pub i64);
159
160impl Synth for Int {
161    const KEY: &'static str = "int";
162
163    fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
164        None
165    }
166
167    fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
168        value
169            .as_i64()
170            .map(Self)
171            .ok_or_else(|| SynthError::corrupt("an integer"))
172    }
173}
174
175/// A floating point number.
176#[derive(Debug, Clone, Copy, Default, PartialEq)]
177pub struct Float(pub f64);
178
179impl Synth for Float {
180    const KEY: &'static str = "float";
181
182    fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
183        None
184    }
185
186    fn hydrate(value: &Value, _meta: Option<&Map<String, Value>>) -> Result<Self> {
187        value.as_f64().map(Self).ok_or_else(|| SynthError::corrupt("a number"))
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    #[test]
196    fn a_synthesized_value_carries_its_key_in_the_metadata() {
197        let (value, meta) = Arr(vec![Value::from(1)]).dehydrate().expect("a tuple");
198
199        assert_eq!(value, serde_json::json!([1]));
200        assert_eq!(meta[SYNTH_KEY], serde_json::json!("arr"));
201    }
202
203    #[test]
204    fn a_plain_value_has_no_tuple() {
205        assert_eq!(Str("hello".to_owned()).dehydrate(), None);
206        assert_eq!(Int(3).dehydrate(), None);
207    }
208
209    #[test]
210    fn only_a_tuple_with_a_key_is_split() {
211        let tuple = serde_json::json!(["value", {"s": "arr"}]);
212        let (value, meta) = split_tuple(&tuple);
213        assert_eq!(value, serde_json::json!("value"));
214        assert_eq!(meta.expect("metadata")[SYNTH_KEY], serde_json::json!("arr"));
215
216        let plain = serde_json::json!(["a", "b"]);
217        assert_eq!(split_tuple(&plain), (plain.clone(), None));
218
219        let no_key = serde_json::json!([1, {"x": 1}]);
220        assert_eq!(split_tuple(&no_key), (no_key.clone(), None));
221    }
222
223    #[test]
224    fn a_mismatched_value_is_corrupt_not_a_panic() {
225        assert_eq!(
226            Arr::hydrate(&serde_json::json!("nope"), None),
227            Err(SynthError::corrupt("an array"))
228        );
229        assert_eq!(
230            Int::hydrate(&serde_json::json!(1.5), None),
231            Err(SynthError::corrupt("an integer"))
232        );
233        assert!(Str::hydrate(&serde_json::json!(1), None).is_err());
234    }
235
236    #[test]
237    fn a_value_round_trips_through_its_synthesizer() {
238        let original = Std(Map::from_iter([("a".to_owned(), Value::from(1))]));
239        let (value, meta) = original.dehydrate().expect("a tuple");
240
241        assert_eq!(Std::hydrate(&value, Some(&meta)).expect("hydrates"), original);
242    }
243}