Skip to main content

tilo_resource/
value.rs

1//! JSON values stored as the document's own maps, lists and scalars.
2//!
3//! A [`serde_json::Value`] field holds JSON another party shapes: an account
4//! type's connection settings, a binding's literal value, a parameter's JSON
5//! Schema. It is stored as what it is: an object is a map, an array a list,
6//! a string, a number, a boolean and `null` are scalars. So two people
7//! changing different keys of one object both keep their change, and
8//! history sees the key that changed, never a rewritten string.
9//!
10//! The mapping is [`tilo_automerge::json`]'s, which stores a settings section,
11//! a page's JSON and a bot's view of an item the same way.
12//!
13//! [`value_model!`](crate::value_model) stores a serde type the same way, as
14//! its JSON form: for a type `#[derive(Model)]` cannot describe, because it
15//! is defined below this crate or holds itself (a condition of conditions).
16
17use automerge::{ObjId, Prop, ReadDoc, Value};
18
19use crate::model::{Doc, Model, ModelError, Slot};
20use crate::path::Settable;
21
22/// The document's own error, or the shape a JSON value could not hold,
23/// as [`ModelError`] reports it.
24impl From<tilo_automerge::json::JsonError> for ModelError {
25    fn from(error: tilo_automerge::json::JsonError) -> Self {
26        match error {
27            tilo_automerge::json::JsonError::Shape { path, expected } => {
28                Self::Shape { path, expected }
29            }
30            tilo_automerge::json::JsonError::Automerge(error) => Self::Automerge(error),
31        }
32    }
33}
34
35/// The slot as the document names it: a key, or an index a list inserts at
36/// when it is the list's end.
37fn prop(slot: Slot<'_>) -> (&ObjId, Prop) {
38    match slot {
39        Slot::Key(obj, key) => (obj, Prop::Map(key.to_owned())),
40        Slot::Index(obj, index) | Slot::Insert(obj, index) => (obj, Prop::Seq(index)),
41    }
42}
43
44/// Write a JSON value into `slot`, changing only what differs.
45fn store_json(doc: &mut Doc, slot: Slot<'_>, value: &serde_json::Value) -> Result<(), ModelError> {
46    let (obj, prop) = prop(slot);
47    Ok(tilo_automerge::json::write(doc, obj, prop, value)?)
48}
49
50/// The JSON value the document held at `value` (the object `id`) as of
51/// `heads`: [`load_json`] of a past version, read in place rather than on a
52/// fork of the document.
53pub(crate) fn read_value_at(
54    doc: &impl ReadDoc,
55    value: &Value<'_>,
56    id: &ObjId,
57    heads: &[automerge::ChangeHash],
58) -> Result<serde_json::Value, ModelError> {
59    Ok(match value {
60        Value::Scalar(scalar) => tilo_automerge::json::scalar_json(scalar)?,
61        Value::Object(_) => tilo_automerge::json::read_at(doc, id, heads, None)?,
62    })
63}
64
65/// The JSON value the document holds at `value` (the object `id`).
66fn load_json(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<serde_json::Value, ModelError> {
67    Ok(tilo_automerge::json::read_value(doc, value, id)?)
68}
69
70/// Any JSON value, stored as the document's maps, lists and scalars; see
71/// the module docs. An absent slot reads as `null`.
72impl Settable for serde_json::Value {}
73impl Model for serde_json::Value {
74    crate::__own_table!(serde_json::Value);
75    crate::model::leaf_paths!();
76    const NULLABLE: bool = true;
77    #[inline(never)]
78    fn to_json(&self) -> serde_json::Value {
79        self.clone()
80    }
81    #[inline(never)]
82    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
83        Ok(value.clone())
84    }
85    #[inline(never)]
86    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
87        load_json(doc, value, id)
88    }
89    fn missing() -> Result<Self, ModelError> {
90        Ok(Self::Null)
91    }
92    #[inline(never)]
93    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
94        store_json(doc, slot, self)
95    }
96    /// Made with the map as the maps, lists and scalars [`Self::store`]
97    /// writes.
98    fn fresh(&self, _: automerge::TextEncoding) -> crate::model::Fresh {
99        tilo_automerge::json::hydrate(self)
100            .map_or(crate::model::Fresh::Store, crate::model::Fresh::Value)
101    }
102    #[inline(never)]
103    fn stores_as(&self, before: &Self) -> bool {
104        self == before
105    }
106}
107
108/// A JSON object, stored as a map: [`serde_json::Value`]'s object.
109impl Settable for serde_json::Map<String, serde_json::Value> {}
110impl Model for serde_json::Map<String, serde_json::Value> {
111    crate::__own_table!(serde_json::Map<String, serde_json::Value>);
112    crate::model::leaf_paths!();
113    fn value_schema() -> serde_json::Value {
114        serde_json::json!({"type": "object"})
115    }
116    #[inline(never)]
117    fn to_json(&self) -> serde_json::Value {
118        serde_json::Value::Object(self.clone())
119    }
120    #[inline(never)]
121    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
122        match value {
123            serde_json::Value::Object(fields) => Ok(fields.clone()),
124            serde_json::Value::Null => Ok(Self::new()),
125            _ => Err(ModelError::shape("an object")),
126        }
127    }
128    #[inline(never)]
129    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
130        Self::from_json(&load_json(doc, value, id)?)
131    }
132    fn missing() -> Result<Self, ModelError> {
133        Ok(Self::new())
134    }
135    #[inline(never)]
136    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
137        let (obj, prop) = prop(slot);
138        Ok(tilo_automerge::json::write_object(doc, obj, prop, self)?)
139    }
140    #[inline(never)]
141    fn stores_as(&self, before: &Self) -> bool {
142        self == before
143    }
144}
145
146/// Implements [`Model`] (and [`Settable`](crate::Settable)) for serde types
147/// stored as their JSON form, the way a [`serde_json::Value`] is: an object
148/// as a map, an array as a list, everything else as a scalar. For a type
149/// `#[derive(Model)]` cannot describe: one defined in a crate below this
150/// one (an [`ActionKey`](tilo_actions::ActionKey)), or one that holds
151/// itself (a condition made of conditions). A type the app shapes derives
152/// `Model` instead, so its fields have paths and edits of their own.
153///
154/// The types need `Serialize`, `Deserialize` and a `PartialEq` holding only
155/// between values of equal JSON forms, as a derived one does. An absent slot
156/// has no value: hold one in an `Option`, a `Vec` or a map, or name the
157/// types after `default:` to read an absent slot as their `Default`.
158#[macro_export]
159macro_rules! value_model {
160    (default: $($ty:ty),* $(,)?) => {$(
161        impl $crate::Settable for $ty {}
162        impl $crate::Model for $ty {
163            $crate::leaf_paths!();
164            const TABLE: &'static $crate::table::ModelTable =
165                &$crate::table::ModelTable::of_json(&$crate::table::ValueOf::<$ty>::DEFAULTED);
166            $crate::__table_functions!();
167            fn missing() -> ::core::result::Result<Self, $crate::ModelError> {
168                ::core::result::Result::Ok(<Self as ::core::default::Default>::default())
169            }
170        }
171    )*};
172    ($($ty:ty),* $(,)?) => {$(
173        impl $crate::Settable for $ty {}
174        impl $crate::Model for $ty {
175            $crate::leaf_paths!();
176            const TABLE: &'static $crate::table::ModelTable =
177                &$crate::table::ModelTable::of_json(&$crate::table::ValueOf::<$ty>::DESC);
178            $crate::__table_functions!();
179            fn missing() -> ::core::result::Result<Self, $crate::ModelError> {
180                ::core::result::Result::Err($crate::ModelError::Missing {
181                    path: ::std::string::String::new(),
182                })
183            }
184        }
185    )*};
186}
187
188// The action addresses and parameter declarations other apps publish, as a
189// Shortcut step stores them, and who acted, as a change keeps it: types of the
190// action protocol, below this crate.
191value_model!(
192    tilo_actions::ActionKey,
193    tilo_actions::ActionParam,
194    tilo_actions::Acting
195);
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200    use crate::model::{read_key, write_key};
201    use automerge::transaction::Transactable;
202    use automerge::{ObjType, ROOT, ReadDoc};
203    use serde_json::json;
204    use tilo_automerge::ApplyIncoming;
205
206    tilo_test_env::scenario! {
207        fn a_json_value_is_stored_and_merged_as_maps_lists_and_scalars;
208
209        phase it_reads_back_as_written;
210        {
211            let value = json!({
212                "host": "imap.example",
213                "port": 993,
214                "big": u64::MAX,
215                "ratio": 0.5,
216                "tls": true,
217                "folders": ["INBOX", {"name": "Sent", "sync": false}],
218                "proxy": null,
219            });
220            let mut doc = Doc::new();
221            write_key(&mut doc, &ROOT, "config", &value).unwrap();
222            assert_eq!(
223                read_key::<serde_json::Value>(&doc, &ROOT, "config").unwrap(),
224                value
225            );
226            let Some((Value::Object(ObjType::Map), map)) = doc.get(&ROOT, "config").unwrap() else {
227                panic!("an object is a map");
228            };
229            assert!(matches!(
230                doc.get(&map, "folders").unwrap(),
231                Some((Value::Object(ObjType::List), _))
232            ));
233            assert_eq!(
234                read_key::<serde_json::Value>(&doc, &ROOT, "absent").unwrap(),
235                serde_json::Value::Null
236            );
237        }
238
239        phase an_unchanged_write_makes_no_operation;
240        {
241            let value = json!({"a": [1, 2, {"b": "c"}], "d": "e"});
242            let mut doc = Doc::new();
243            write_key(&mut doc, &ROOT, "v", &value).unwrap();
244            doc.commit();
245            write_key(&mut doc, &ROOT, "v", &value).unwrap();
246            assert_eq!(doc.pending_ops(), 0);
247        }
248
249        phase removed_keys_and_elements_are_removed;
250        {
251            let mut doc = Doc::new();
252            write_key(&mut doc, &ROOT, "v", &json!({"a": 1, "b": [1, 2, 3]})).unwrap();
253            write_key(&mut doc, &ROOT, "v", &json!({"b": [1]})).unwrap();
254            assert_eq!(
255                read_key::<serde_json::Value>(&doc, &ROOT, "v").unwrap(),
256                json!({"b": [1]})
257            );
258            write_key(&mut doc, &ROOT, "v", &json!("whole")).unwrap();
259            assert_eq!(
260                read_key::<serde_json::Value>(&doc, &ROOT, "v").unwrap(),
261                json!("whole")
262            );
263        }
264
265        phase concurrent_changes_to_different_keys_both_survive;
266        {
267            let mut base = Doc::new();
268            write_key(&mut base, &ROOT, "config", &json!({"host": "a", "port": 1})).unwrap();
269            base.commit();
270            let mut left = base.fork();
271            let mut right = base.fork();
272            write_key(&mut left, &ROOT, "config", &json!({"host": "b", "port": 1})).unwrap();
273            write_key(
274                &mut right,
275                &ROOT,
276                "config",
277                &json!({"host": "a", "port": 2}),
278            )
279            .unwrap();
280            left.merge_incoming(&mut right).unwrap();
281            assert_eq!(
282                read_key::<serde_json::Value>(&left, &ROOT, "config").unwrap(),
283                json!({"host": "b", "port": 2})
284            );
285        }
286
287        phase a_value_model_type_is_stored_as_its_json_form;
288        {
289            let key = tilo_actions::ActionKey::new("so.tilo.notes", "notes.page", "rename");
290            let mut doc = Doc::new();
291            write_key(&mut doc, &ROOT, "action", &Some(key.clone())).unwrap();
292            assert!(matches!(
293                doc.get(&ROOT, "action").unwrap(),
294                Some((Value::Object(ObjType::Map), _))
295            ));
296            assert_eq!(
297                read_key::<Option<tilo_actions::ActionKey>>(&doc, &ROOT, "action").unwrap(),
298                Some(key)
299            );
300            assert_eq!(
301                read_key::<Option<tilo_actions::ActionKey>>(&doc, &ROOT, "absent").unwrap(),
302                None
303            );
304            assert!(read_key::<tilo_actions::ActionKey>(&doc, &ROOT, "absent").is_err());
305            let param = tilo_actions::ActionParam::required(
306                "title",
307                tilo_actions::ParamType::Text,
308                "The page's title",
309            );
310            write_key(&mut doc, &ROOT, "params", &vec![param.clone()]).unwrap();
311            assert_eq!(
312                read_key::<Vec<tilo_actions::ActionParam>>(&doc, &ROOT, "params").unwrap(),
313                vec![param]
314            );
315        }
316    }
317}