aboutsummaryrefslogtreecommitdiffstats
path: root/src/document
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-12-01 02:45:46 +0100
committertv <tv@krebsco.de>2026-12-01 02:45:46 +0100
commit34bfcb661ed74bf40809576bbb388362cb7ffaa1 (patch)
tree8422db7db396dd4ae83403837cd954a94f882a7a /src/document
parent34434f7fd5a6bab1884a63c96679f48045f4bffd (diff)
parent6a06bc4a955cdf2b5a183c9ff21e25c79a4e5d9f (diff)
Merge remote-tracking branch 'events'HEADmaster
Diffstat (limited to 'src/document')
-rw-r--r--src/document/passing.rs1
-rw-r--r--src/document/view.rs343
2 files changed, 344 insertions, 0 deletions
diff --git a/src/document/passing.rs b/src/document/passing.rs
index 0b9a3dd..dc116e3 100644
--- a/src/document/passing.rs
+++ b/src/document/passing.rs
@@ -194,6 +194,7 @@ pub(crate) fn carried_bytes(body: &SyncBody) -> Option<usize> {
SyncBody::Message(payload) | SyncBody::Deflated(payload) => Some(payload.0.len()),
SyncBody::Changes { changes, .. } => Some(changes.iter().map(|change| change.len()).sum()),
SyncBody::Delta(_) => None,
+ SyncBody::Kind(bytes) => Some(bytes.len()),
}
}
diff --git a/src/document/view.rs b/src/document/view.rs
index 018e8c0..8df88b3 100644
--- a/src/document/view.rs
+++ b/src/document/view.rs
@@ -116,3 +116,346 @@ 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, 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, the policy and the swarm's ID: of what its
+/// document keeps apart and hands over as a tree (`AppState::entries`), where it does,
+/// over the document it holds. A node holding its store in a set of events alone reads
+/// the tree, the document beside being empty; one holding it in both reads the members
+/// of both.
+pub(crate) fn members_of<'a>(entries: &'a Option<Tree>, doc: &'a dyn Read) -> Listed<'a> {
+ Listed {
+ over: entries.as_ref(),
+ under: doc,
+ }
+}
+
+/// A tree over a document (`members_of`): at a path, what the tree holds there, else
+/// what the document does; where both hold maps, the two as one, the tree's values over
+/// the document's.
+pub(crate) struct Listed<'a> {
+ over: Option<&'a Tree>,
+ under: &'a dyn Read,
+}
+
+/// `over` on `under`: maps as one, key by key; anything else, `over`.
+fn laid(over: JsonValue, under: JsonValue) -> JsonValue {
+ match (over, under) {
+ (JsonValue::Object(mut over), JsonValue::Object(under)) => {
+ for (key, below) in under {
+ let merged = match over.remove(&key) {
+ Some(above) => laid(above, below),
+ None => below,
+ };
+ over.insert(key, merged);
+ }
+ JsonValue::Object(over)
+ }
+ (over, _) => over,
+ }
+}
+
+impl Listed<'_> {
+ fn read(
+ &self,
+ path: &[String],
+ under: impl FnOnce(&dyn Read) -> Result<Option<JsonValue>, StoreError>,
+ ) -> Result<Option<JsonValue>, StoreError> {
+ let Some(over) = self.over else {
+ return under(self.under);
+ };
+ // The tree first: where it holds a value that is no map, the document isn't
+ // asked, nor is what it holds on the way in the way.
+ match over.read_path(path) {
+ Ok(Some(above)) if !above.is_object() => Ok(Some(above)),
+ Ok(above) => match (above, under(self.under)) {
+ (Some(above), Ok(Some(below))) => Ok(Some(laid(above, below))),
+ (Some(above), _) => Ok(Some(above)),
+ (None, below) => below,
+ },
+ Err(_) => under(self.under),
+ }
+ }
+}
+
+impl Read for Listed<'_> {
+ fn read_path(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> {
+ self.read(path, |doc| doc.read_path(path))
+ }
+
+ fn read_plain(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> {
+ self.read(path, |doc| doc.read_plain(path))
+ }
+
+ fn read_typed(&self, path: &[String]) -> Result<Option<JsonValue>, StoreError> {
+ self.read(path, |doc| doc.read_typed(path))
+ }
+
+ fn keys_at(&self, path: &[String]) -> Result<Option<Vec<String>>, StoreError> {
+ let below = self.under.keys_at(path);
+ let Some(over) = self.over else {
+ return below;
+ };
+ match (over.keys_at(path)?, below) {
+ (Some(mut above), Ok(Some(below))) => {
+ for key in below {
+ if !above.contains(&key) {
+ above.push(key);
+ }
+ }
+ Ok(Some(above))
+ }
+ (Some(above), _) => Ok(Some(above)),
+ (None, below) => below,
+ }
+ }
+}
+
+#[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!({})));
+ }
+
+ #[test]
+ fn a_tree_over_a_document_reads_as_both() {
+ let mut under = Tree::new();
+ under
+ .write_path(&path(&["m", "a"]), &json!({"alias": "a", "tier": 1}))
+ .unwrap();
+ under
+ .write_path(&path(&["m", "b"]), &json!({"alias": "b"}))
+ .unwrap();
+ under
+ .write_path(&path(&["only", "under"]), &json!(1))
+ .unwrap();
+ let mut over = Tree::new();
+ over.write_path(&path(&["m", "a"]), &json!({"alias": "A"}))
+ .unwrap();
+ over.write_path(&path(&["m", "c"]), &json!({"alias": "c"}))
+ .unwrap();
+ over.write_path(&path(&["policy"]), &json!("p")).unwrap();
+ let entries = Some(over);
+ let listed = members_of(&entries, &under);
+ // Keys of both; a map of both as one, the tree's values over the document's.
+ let mut keys = listed.keys_at(&path(&["m"])).unwrap().expect("a map");
+ keys.sort();
+ assert_eq!(keys, path(&["a", "b", "c"]));
+ assert_eq!(
+ listed.read_path(&path(&["m", "a"])).unwrap(),
+ Some(json!({"alias": "A", "tier": 1}))
+ );
+ assert_eq!(
+ listed.read_path(&path(&["m", "a", "alias"])).unwrap(),
+ Some(json!("A"))
+ );
+ assert_eq!(
+ listed.read_path(&path(&["m", "b", "alias"])).unwrap(),
+ Some(json!("b"))
+ );
+ assert_eq!(
+ listed.read_plain(&path(&["m", "c", "alias"])).unwrap(),
+ Some(json!("c"))
+ );
+ assert_eq!(
+ listed.read_typed(&path(&["policy"])).unwrap(),
+ Some(json!("p"))
+ );
+ assert_eq!(
+ listed.read_path(&path(&["only", "under"])).unwrap(),
+ Some(json!(1))
+ );
+ assert_eq!(listed.read_path(&path(&["nowhere"])).unwrap(), None);
+ // No tree: the document as it is.
+ let none = None;
+ let listed = members_of(&none, &under);
+ assert_eq!(
+ listed.read_path(&path(&["m", "a", "alias"])).unwrap(),
+ Some(json!("a"))
+ );
+ assert_eq!(
+ listed
+ .keys_at(&path(&["m"]))
+ .unwrap()
+ .map(|keys| keys.len()),
+ Some(2)
+ );
+ }
+}