aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-29 15:18:39 +0000
committertv <tv@krebsco.de>2026-11-29 15:18:39 +0000
commit6849e72e09199534026de63fa79ae09ecb903297 (patch)
tree177f00a040ed4ba6cce51f38057788293b100e2e /src
parent8cdde74fcdcf31414da0d22222d2cc338df20fa1 (diff)
document: a tree of JSON, read and written as any document
view::Tree: maps of maps down to values, behind Read and Write. For a kind that keeps what the node reads at paths otherwise, and hands it over so.
Diffstat (limited to 'src')
-rw-r--r--src/document/view.rs179
1 files changed, 179 insertions, 0 deletions
diff --git a/src/document/view.rs b/src/document/view.rs
index 018e8c0..d8819d2 100644
--- a/src/document/view.rs
+++ b/src/document/view.rs
@@ -116,3 +116,182 @@ pub(crate) fn delete_path(
) -> 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<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(())
+ }
+}
+
+#[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!({})));
+ }
+}