//! 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, 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, 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, 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>, 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 Read for T { fn read_path(&self, path: &[String]) -> Result, StoreError> { store::read_path(self, path) } fn read_plain(&self, path: &[String]) -> Result, StoreError> { store::read_plain(self, path) } fn read_typed(&self, path: &[String]) -> Result, StoreError> { let typed = super::typed::JsonForm { typed: true, ..Default::default() }; store::read_plain_as(self, path, typed) } fn keys_at(&self, path: &[String]) -> Result>, StoreError> { store::keys_at(self, path) } } impl 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, StoreError> { doc.read_path(path) } /// [`Read::read_plain`]. pub(crate) fn read_plain( doc: &(impl Read + ?Sized), path: &[String], ) -> Result, StoreError> { doc.read_plain(path) } /// [`Read::keys_at`]. pub(crate) fn keys_at( doc: &(impl Read + ?Sized), path: &[String], ) -> Result>, 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, Default, 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 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, 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, StoreError> { Ok(self.at(path)?.cloned()) } fn read_plain(&self, path: &[String]) -> Result, StoreError> { self.read_path(path) } fn read_typed(&self, path: &[String]) -> Result, StoreError> { self.read_path(path) } fn keys_at(&self, path: &[String]) -> Result>, 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(()) } } #[cfg(test)] mod tree_tests { use serde_json::json; use super::*; fn path(keys: &[&str]) -> Vec { 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!({}))); } }