aboutsummaryrefslogtreecommitdiffstats
path: root/src/document/view.rs
blob: ff93ae6578a9347a64acaff3fa73f86d2189fad9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
//! A document to read and to write, whatever kind it is of: what the node asks of one
//! where it asks no more than values at paths (`docs/document.md`, The seam). The
//! member registry, the users, access control's reads and the rules read through `Read`,
//! and what writes protocol data writes through `Write`; what an Automerge document can
//! do beyond that (`store`) is asked of it as such.
//!
//! Automerge's documents, its writes in progress and a document as it was (`at::At`) are
//! all read so, and its writes in progress written so.

use serde_json::Value as JsonValue;

use super::store::{self, StoreError};
use super::{ReadDoc, Transactable};

/// A document to read: as it is, as a write in progress has it, or as it was.
pub(crate) trait Read {
    /// The value at a path; the empty path is everything.
    fn read_path(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError>;

    /// `read_path` of a value its user may have signed (`access::envelope`): an envelope
    /// read as the value it holds, unchecked (the policy checked it before it went in),
    /// a signed `null` as nothing.
    fn read_plain(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError>;

    /// `read_plain`, telling apart what plain JSON shows alike, where the document's
    /// kind stores them apart: a text, tagged, from a string.
    fn read_typed(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError>;

    /// The keys of the map at `path`; None if there is no map there (nothing, or another
    /// value).
    fn keys_at(&self, path: &[String]) -> Result<Option<Vec<String>>, StoreError>;
}

/// A document being written: what is written is read back at once (`Read`), and goes in
/// or not as a whole.
pub(crate) trait Write: Read {
    /// Writes the value at `path`, making the maps on the way: afterwards it reads as
    /// `value`.
    fn write_path(&mut self, path: &[String], value: &JsonValue) -> Result<(), StoreError>;

    /// Deletes the value at `path`. With `prune`, the maps above it that it leaves empty
    /// go too.
    fn delete_path(&mut self, path: &[String], prune: bool) -> Result<(), StoreError>;
}

impl<T: ReadDoc> Read for T {
    fn read_path(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> {
        store::read_path(self, path)
    }

    fn read_plain(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> {
        store::read_plain(self, path)
    }

    fn read_typed(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> {
        let typed = super::typed::JsonForm {
            typed: true,
            ..Default::default()
        };
        store::read_plain_as(self, path, typed)
    }

    fn keys_at(&self, path: &[String]) -> Result<Option<Vec<String>>, StoreError> {
        store::keys_at(self, path)
    }
}

impl<T: Transactable> Write for T {
    fn write_path(&mut self, path: &[String], value: &JsonValue) -> Result<(), StoreError> {
        store::write_path(self, path, value)
    }

    fn delete_path(&mut self, path: &[String], prune: bool) -> Result<(), StoreError> {
        store::delete_path(self, path, prune)
    }
}

/// [`Read::read_path`].
pub(crate) fn read_path(
    doc: &(impl Read + ?Sized),
    path: &[String],
) -> Result<Option<JsonValue>, StoreError> {
    doc.read_path(path)
}

/// [`Read::read_plain`].
pub(crate) fn read_plain(
    doc: &(impl Read + ?Sized),
    path: &[String],
) -> Result<Option<JsonValue>, StoreError> {
    doc.read_plain(path)
}

/// [`Read::keys_at`].
pub(crate) fn keys_at(
    doc: &(impl Read + ?Sized),
    path: &[String],
) -> Result<Option<Vec<String>>, StoreError> {
    doc.keys_at(path)
}

/// [`Write::write_path`].
pub(crate) fn write_path(
    doc: &mut (impl Write + ?Sized),
    path: &[String],
    value: &JsonValue,
) -> Result<(), StoreError> {
    doc.write_path(path, value)
}

/// [`Write::delete_path`].
pub(crate) fn delete_path(
    doc: &mut (impl Write + ?Sized),
    path: &[String],
    prune: bool,
) -> Result<(), StoreError> {
    doc.delete_path(path, prune)
}

/// A document that is a tree of JSON and nothing else: maps of maps, down to values. For
/// a kind that keeps what the node reads at paths otherwise (a set of events its
/// members' entries), and hands it over so; and for what writes there through `Write`,
/// which then looks at what the tree holds after.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(not(feature = "federation"), allow(dead_code))]
pub(crate) struct Tree(pub(crate) JsonValue);

#[cfg_attr(not(feature = "federation"), allow(dead_code))]
impl Default for Tree {
    fn default() -> Self {
        Self::new()
    }
}

impl Tree {
    /// A tree holding nothing.
    pub(crate) fn new() -> Self {
        Tree(JsonValue::Object(serde_json::Map::new()))
    }

    /// The value at `path`: through maps alone.
    fn at(&self, path: &[String]) -> Result<Option<&JsonValue>, StoreError> {
        let mut value = &self.0;
        for key in path {
            match value {
                JsonValue::Object(map) => match map.get(key) {
                    Some(inner) => value = inner,
                    None => return Ok(None),
                },
                _ => return Err(StoreError::Conflict),
            }
        }
        Ok(Some(value))
    }
}

impl Read for Tree {
    fn read_path(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> {
        Ok(self.at(path)?.cloned())
    }

    fn read_plain(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> {
        self.read_path(path)
    }

    fn read_typed(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> {
        self.read_path(path)
    }

    fn keys_at(&self, path: &[String]) -> Result<Option<Vec<String>>, StoreError> {
        Ok(match self.at(path) {
            Ok(Some(JsonValue::Object(map))) => Some(map.keys().cloned().collect()),
            _ => None,
        })
    }
}

impl Write for Tree {
    fn write_path(&mut self, path: &[String], value: &JsonValue) -> Result<(), StoreError> {
        let mut at = &mut self.0;
        for key in path {
            if at.is_null() {
                *at = JsonValue::Object(serde_json::Map::new());
            }
            let JsonValue::Object(map) = at else {
                return Err(StoreError::Conflict);
            };
            at = map.entry(key.clone()).or_insert(JsonValue::Null);
        }
        *at = value.clone();
        Ok(())
    }

    fn delete_path(&mut self, path: &[String], prune: bool) -> Result<(), StoreError> {
        let Some((last, above)) = path.split_last() else {
            return Err(StoreError::NotFound);
        };
        let mut at = &mut self.0;
        for key in above {
            match at {
                JsonValue::Object(map) => match map.get_mut(key) {
                    Some(inner) => at = inner,
                    None => return Err(StoreError::NotFound),
                },
                _ => return Err(StoreError::Conflict),
            }
        }
        let JsonValue::Object(map) = at else {
            return Err(StoreError::Conflict);
        };
        if map.remove(last).is_none() {
            return Err(StoreError::NotFound);
        }
        // The maps left empty above it, from the deepest up, the root never.
        if prune {
            for depth in (1..path.len()).rev() {
                let Ok(Some(JsonValue::Object(map))) = self.at(&path[..depth]) else {
                    break;
                };
                if !map.is_empty() {
                    break;
                }
                self.delete_path(&path[..depth], false)?;
            }
        }
        Ok(())
    }
}

/// Where the node reads its members: `entries`, where its document keeps them apart
/// and hands them over as a tree (`AppState::entries`); else `doc` itself.
pub(crate) fn members_of<'a>(entries: &'a Option<Tree>, doc: &'a dyn Read) -> &'a dyn Read {
    match entries {
        Some(tree) => tree,
        None => doc,
    }
}

#[cfg(test)]
mod tree_tests {
    use serde_json::json;

    use super::*;

    fn path(keys: &[&str]) -> Vec<String> {
        keys.iter().map(|key| (*key).to_owned()).collect()
    }

    #[test]
    fn a_tree_reads_what_was_written() {
        let mut tree = Tree::new();
        tree.write_path(&path(&["a", "b", "c"]), &json!(1)).unwrap();
        tree.write_path(&path(&["a", "d"]), &json!({"e": [1, 2]}))
            .unwrap();
        assert_eq!(
            tree.read_path(&path(&["a", "b", "c"])).unwrap(),
            Some(json!(1))
        );
        assert_eq!(
            tree.read_plain(&path(&["a", "d", "e"])).unwrap(),
            Some(json!([1, 2]))
        );
        assert_eq!(
            tree.read_typed(&[]).unwrap(),
            Some(json!({"a": {"b": {"c": 1}, "d": {"e": [1, 2]}}}))
        );
        assert_eq!(tree.read_path(&path(&["a", "x"])).unwrap(), None);
        assert_eq!(tree.read_path(&path(&["x", "y"])).unwrap(), None);
        let mut keys = tree.keys_at(&path(&["a"])).unwrap().expect("a map");
        keys.sort();
        assert_eq!(keys, path(&["b", "d"]));
        assert_eq!(tree.keys_at(&path(&["a", "b", "c"])).unwrap(), None);
        assert_eq!(tree.keys_at(&path(&["x"])).unwrap(), None);
        // Through a value that is no map: a conflict, as in any document.
        assert!(matches!(
            tree.read_path(&path(&["a", "b", "c", "z"])),
            Err(StoreError::Conflict)
        ));
        assert!(matches!(
            tree.write_path(&path(&["a", "b", "c", "z"]), &json!(1)),
            Err(StoreError::Conflict)
        ));
        // Written over, it reads as the new value.
        tree.write_path(&path(&["a", "b"]), &json!("v")).unwrap();
        assert_eq!(
            tree.read_path(&path(&["a", "b"])).unwrap(),
            Some(json!("v"))
        );
    }

    #[test]
    fn a_tree_deletes_and_prunes() {
        let mut tree = Tree::new();
        tree.write_path(&path(&["a", "b", "c"]), &json!(1)).unwrap();
        tree.write_path(&path(&["a", "d"]), &json!(2)).unwrap();
        assert!(matches!(
            tree.delete_path(&path(&["a", "x"]), false),
            Err(StoreError::NotFound)
        ));
        tree.delete_path(&path(&["a", "b", "c"]), false).unwrap();
        assert_eq!(tree.read_path(&path(&["a", "b"])).unwrap(), Some(json!({})));
        tree.write_path(&path(&["a", "b", "c"]), &json!(1)).unwrap();
        tree.delete_path(&path(&["a", "b", "c"]), true).unwrap();
        // The map left empty went; the one that holds something stays.
        assert_eq!(
            tree.read_path(&path(&["a"])).unwrap(),
            Some(json!({"d": 2}))
        );
        tree.delete_path(&path(&["a", "d"]), true).unwrap();
        assert_eq!(tree.read_path(&[]).unwrap(), Some(json!({})));
    }
}