diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/access/bans.rs | 7 | ||||
| -rw-r--r-- | src/access/challenge.rs | 12 | ||||
| -rw-r--r-- | src/access/envelope.rs | 27 | ||||
| -rw-r--r-- | src/access/policy.rs | 20 | ||||
| -rw-r--r-- | src/access/registry.rs | 39 | ||||
| -rw-r--r-- | src/access/rules.rs | 58 | ||||
| -rw-r--r-- | src/access/sealed.rs | 31 | ||||
| -rw-r--r-- | src/access/strict.rs | 20 | ||||
| -rw-r--r-- | src/access/token.rs | 41 | ||||
| -rw-r--r-- | src/api/login.rs | 6 | ||||
| -rw-r--r-- | src/api/peers.rs | 4 | ||||
| -rw-r--r-- | src/api/users.rs | 36 | ||||
| -rw-r--r-- | src/document/mod.rs | 1 | ||||
| -rw-r--r-- | src/document/view.rs | 118 | ||||
| -rw-r--r-- | src/swarm/bootstrap.rs | 16 | ||||
| -rw-r--r-- | src/swarm/members.rs | 99 | ||||
| -rw-r--r-- | src/swarm/peer/forget.rs | 9 | ||||
| -rw-r--r-- | src/swarm/topology/mod.rs | 4 |
18 files changed, 338 insertions, 210 deletions
diff --git a/src/access/bans.rs b/src/access/bans.rs index a314f49..999f610 100644 --- a/src/access/bans.rs +++ b/src/access/bans.rs @@ -5,7 +5,8 @@ //! (`access::rules`, judged as the ban stood when they were made), and the tokens it //! issued (`access::token`). Deleting the entry lifts the ban. -use crate::document::{ReadDoc, meta, store}; +use crate::document::meta; +use crate::document::view::{self, Read}; /// Where `node`'s ban is. pub(crate) fn path(node: &str) -> Vec<String> { @@ -13,6 +14,6 @@ pub(crate) fn path(node: &str) -> Vec<String> { } /// Whether `doc` bans `node`. -pub(crate) fn banned(doc: &impl ReadDoc, node: &str) -> bool { - store::read_plain(doc, &path(node)).ok().flatten().is_some() +pub(crate) fn banned(doc: &impl Read, node: &str) -> bool { + view::read_plain(doc, &path(node)).ok().flatten().is_some() } diff --git a/src/access/challenge.rs b/src/access/challenge.rs index 8df0f08..4dd8dfb 100644 --- a/src/access/challenge.rs +++ b/src/access/challenge.rs @@ -16,7 +16,7 @@ use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD as B64URL}; use serde::{Deserialize, Serialize}; use super::{registry, sshsig}; -use crate::document::ReadDoc; +use crate::document::view::Read; use crate::identity::NodeKey; /// What a user's signature over a challenge is for (`sshsig`). @@ -70,7 +70,7 @@ pub(crate) struct Used(HashMap<String, (u64, String)>); /// `per_user` of its own still remembered. Why not, if not. #[allow(clippy::too_many_arguments)] pub(crate) fn take( - doc: &impl ReadDoc, + doc: &impl Read, key: &NodeKey, challenge: &str, signature: &str, @@ -150,8 +150,8 @@ pub(crate) fn take_with( mod tests { use super::*; use crate::document::Document; - use crate::document::store; use crate::document::testing::change; + use crate::document::view; use ed25519_dalek::SigningKey; use serde_json::json; @@ -163,12 +163,12 @@ mod tests { change(&mut doc, |doc| { let mut alice = registry::entry("root", 1, &[]); alice["keys"] = json!({ "laptop": line }); - store::write_path(doc, ®istry::user_path("alice"), &alice).unwrap(); + view::write_path(doc, ®istry::user_path("alice"), &alice).unwrap(); let mut carol = registry::entry("root", 1, &[]); carol["keys"] = json!({ "laptop": line }); carol["disabled"] = json!(true); - store::write_path(doc, ®istry::user_path("carol"), &carol).unwrap(); - store::write_path( + view::write_path(doc, ®istry::user_path("carol"), &carol).unwrap(); + view::write_path( doc, ®istry::user_path("bob"), ®istry::entry("root", 1, &[]), diff --git a/src/access/envelope.rs b/src/access/envelope.rs index f697809..d592bff 100644 --- a/src/access/envelope.rs +++ b/src/access/envelope.rs @@ -25,7 +25,8 @@ use sha2::{Digest, Sha256}; use super::{Right, agree, registry, sshsig}; pub(crate) use crate::document::signed::Payload; -use crate::document::{ReadDoc, meta, signed, store}; +use crate::document::view::{self, Read}; +use crate::document::{meta, signed}; /// What a signature over a payload is for (`sshsig`). pub(crate) const NAMESPACE: &str = "continuum-value"; @@ -38,8 +39,8 @@ pub(crate) fn listed_at() -> Vec<String> { /// The paths `doc` lists as user-signed; an entry that isn't a list of strings is left /// out. -pub(crate) fn listed(doc: &impl ReadDoc) -> Vec<Vec<String>> { - let Ok(Some(JsonValue::Array(entries))) = store::read_plain(doc, &listed_at()) else { +pub(crate) fn listed(doc: &impl Read) -> Vec<Vec<String>> { + let Ok(Some(JsonValue::Array(entries))) = view::read_plain(doc, &listed_at()) else { return Vec::new(); }; entries @@ -66,7 +67,7 @@ fn deciding() -> Vec<Vec<String>> { /// The paths whose values their users sign under a strict policy: what decides who may /// do what (`deciding`), and those `doc` lists (`listed`). -pub(crate) fn signed_paths(doc: &impl ReadDoc) -> Vec<Vec<String>> { +pub(crate) fn signed_paths(doc: &impl Read) -> Vec<Vec<String>> { let mut paths = deciding(); paths.extend(listed(doc)); paths @@ -150,7 +151,7 @@ pub(crate) fn read(envelope: &str) -> Result<Payload, String> { /// its swarm, that path, naming what it replaces and numbered after it, signed by one of /// its user's keys, a user who may write there. pub(crate) fn check( - doc: &impl ReadDoc, + doc: &impl Read, envelope: &str, path: &[String], previous: Option<&str>, @@ -160,7 +161,7 @@ pub(crate) fn check( payload, signature, } = signed::open(envelope)?; - let swarm = store::read_path( + let swarm = view::read_path( doc, &crate::document::meta::path(&[crate::document::meta::SWARM]), ) @@ -206,7 +207,7 @@ pub(crate) fn check( /// with only its keys changed from the one at `path` in `doc`, one left at least: a user /// manages its own keys, whatever else it may do. fn own_keys_only( - doc: &impl ReadDoc, + doc: &impl Read, payload: &Payload, user: ®istry::User, path: &[String], @@ -214,7 +215,7 @@ fn own_keys_only( if user.disabled || path != registry::user_path(&payload.user) { return false; } - let Ok(Some(mut before)) = store::read_plain(doc, path) else { + let Ok(Some(mut before)) = view::read_plain(doc, path) else { return false; }; // One key left at least: a user can't sign, nor log in by key, without one. @@ -256,13 +257,13 @@ mod tests { let line = sshsig::PublicKey(key.verifying_key().to_bytes()).line(); let mut doc = Document::new(); change(&mut doc, |doc| { - store::write_path(doc, &path("_continuum/swarm"), &json!("s")).unwrap(); + view::write_path(doc, &path("_continuum/swarm"), &json!("s")).unwrap(); let mut alice = registry::entry("root", 1, &[(path("config"), &[Right::Write][..])]); alice["keys"] = json!({ "laptop": line }); - store::write_path(doc, ®istry::user_path("alice"), &alice).unwrap(); + view::write_path(doc, ®istry::user_path("alice"), &alice).unwrap(); let mut bob = registry::entry("root", 1, &[]); bob["keys"] = json!({ "laptop": line }); - store::write_path(doc, ®istry::user_path("bob"), &bob).unwrap(); + view::write_path(doc, ®istry::user_path("bob"), &bob).unwrap(); }); doc } @@ -363,7 +364,7 @@ mod tests { fn users_sign_their_own_keys() { let key = SigningKey::from_bytes(&[5; 32]); let doc = registry_with(&key); - let entry = store::read_plain(&doc, ®istry::user_path("alice")) + let entry = view::read_plain(&doc, ®istry::user_path("alice")) .unwrap() .unwrap(); let line = @@ -388,7 +389,7 @@ mod tests { fn listed_paths() { let mut doc = Document::new(); change(&mut doc, |doc| { - store::write_path(doc, &listed_at(), &json!([["config"], ["a", "b"], "junk"])).unwrap(); + view::write_path(doc, &listed_at(), &json!([["config"], ["a", "b"], "junk"])).unwrap(); }); assert_eq!(listed(&doc), vec![path("config"), path("a/b")]); let signed = signed_paths(&doc); diff --git a/src/access/policy.rs b/src/access/policy.rs index 1e28731..e4027b8 100644 --- a/src/access/policy.rs +++ b/src/access/policy.rs @@ -20,7 +20,8 @@ use serde_json::Value as JsonValue; -use crate::document::{ReadDoc, meta, store}; +use crate::document::meta; +use crate::document::view::{self, Read}; /// The policy versions this node knows: rules by path, and a swarm holding a store. pub(crate) const VERSION: u64 = 1; @@ -108,7 +109,7 @@ pub(crate) fn first( pub(crate) fn as_written(value: &JsonValue) -> Result<Policy, String> { let mut doc = crate::document::Document::new(); let mut write = doc.transaction(); - store::write_path(&mut write, &path(), value).map_err(|error| error.to_string())?; + view::write_path(&mut write, &path(), value).map_err(|error| error.to_string())?; let policy = of(&write); write.rollback(); Ok(policy) @@ -118,8 +119,8 @@ pub(crate) fn as_written(value: &JsonValue) -> Result<Policy, String> { /// where its `store` is, as continuum writes them: an Automerge text there, or one holding /// the policy, reads as a string in plain JSON, so a policy that would read so only /// through a text is one nobody knows, never what its characters spell. -pub(crate) fn of(doc: &impl ReadDoc) -> Policy { - match store::read_plain(doc, &path()) { +pub(crate) fn of(doc: &impl Read) -> Policy { + match view::read_plain(doc, &path()) { Ok(Some(value)) => match read(&value) { policy if policy.strict() && !a_string(doc, "values") => { Policy::Unknown("values not a string".to_owned()) @@ -137,13 +138,9 @@ pub(crate) fn of(doc: &impl ReadDoc) -> Policy { /// Whether the policy `doc` holds, read in typed JSON (where a text is tagged, and an /// envelope reads as its payload), has a string for its `key`. -fn a_string(doc: &impl ReadDoc, key: &str) -> bool { - let typed = crate::document::typed::JsonForm { - typed: true, - ..Default::default() - }; +fn a_string(doc: &impl Read, key: &str) -> bool { matches!( - store::read_plain_as(doc, &path(), typed), + doc.read_typed(&path()), Ok(Some(value)) if value.get(key).is_some_and(JsonValue::is_string) ) } @@ -211,13 +208,14 @@ fn store_of(value: &JsonValue) -> Policy { mod tests { use super::*; use crate::document::Document; + use crate::document::store; use crate::document::testing::change; use serde_json::json; fn with(policy: JsonValue) -> Policy { let mut doc = Document::new(); change(&mut doc, |doc| { - store::write_path(doc, &path(), &policy).unwrap(); + view::write_path(doc, &path(), &policy).unwrap(); }); of(&doc) } diff --git a/src/access/registry.rs b/src/access/registry.rs index e806d0c..5a58e1f 100644 --- a/src/access/registry.rs +++ b/src/access/registry.rs @@ -18,7 +18,8 @@ use std::collections::BTreeMap; use serde_json::{Value as JsonValue, json}; use super::{Capability, Caps, Right}; -use crate::document::{ReadDoc, meta, store}; +use crate::document::meta; +use crate::document::view::{self, Read}; /// `_continuum/users`. pub(crate) fn users_dir() -> Vec<String> { @@ -34,13 +35,13 @@ pub(crate) fn user_path(name: &str) -> Vec<String> { /// Whether the swarm has a registry: until it has, every user a node lets in may do /// everything but write protocol data (`docs/access.md`, A swarm without a registry). -pub(crate) fn exists(doc: &impl ReadDoc) -> bool { - matches!(store::keys_at(doc, &users_dir()), Ok(Some(_))) +pub(crate) fn exists(doc: &impl Read) -> bool { + matches!(view::keys_at(doc, &users_dir()), Ok(Some(_))) } /// The registered users' names, sorted. -pub(crate) fn names(doc: &impl ReadDoc) -> Vec<String> { - let mut names = store::keys_at(doc, &users_dir()) +pub(crate) fn names(doc: &impl Read) -> Vec<String> { + let mut names = view::keys_at(doc, &users_dir()) .ok() .flatten() .unwrap_or_default(); @@ -127,11 +128,11 @@ impl User { } /// The entry of user `name`, if it has one. -pub(crate) fn user(doc: &impl ReadDoc, name: &str) -> Option<User> { - let value = store::read_plain(doc, &user_path(name)).ok()??; +pub(crate) fn user(doc: &impl Read, name: &str) -> Option<User> { + let value = view::read_plain(doc, &user_path(name)).ok()??; let mut user = value.is_object().then(|| User::from_json(&value))?; // A damaged one revokes every token. - user.tokens_not_before = match store::read_plain(doc, &logouts_path(name)) { + user.tokens_not_before = match view::read_plain(doc, &logouts_path(name)) { Ok(None) => 0, Ok(Some(at)) => at.as_u64().unwrap_or(u64::MAX), Err(_) => u64::MAX, @@ -155,15 +156,15 @@ pub(crate) fn session_path(name: &str, session: &str) -> Vec<String> { } /// Whether user `name`'s session `session` was ended (`session_path`). -pub(crate) fn session_ended(doc: &impl ReadDoc, name: &str, session: &str) -> bool { - store::read_path(doc, &session_path(name, session)) +pub(crate) fn session_ended(doc: &impl Read, name: &str, session: &str) -> bool { + view::read_path(doc, &session_path(name, session)) .ok() .flatten() .is_some() } /// The users who may manage users: enabled, with `write` on `_continuum/users`. -pub(crate) fn managers(doc: &impl ReadDoc) -> Vec<String> { +pub(crate) fn managers(doc: &impl Read) -> Vec<String> { names(doc) .into_iter() .filter(|name| caps_of(doc, name).allows(Right::Write, &users_dir())) @@ -171,7 +172,7 @@ pub(crate) fn managers(doc: &impl ReadDoc) -> Vec<String> { } /// What user `name` may do: none if it isn't registered (or is disabled). -pub(crate) fn caps_of(doc: &impl ReadDoc, name: &str) -> Caps { +pub(crate) fn caps_of(doc: &impl Read, name: &str) -> Caps { user(doc, name).map(|user| user.caps()).unwrap_or_default() } @@ -289,7 +290,7 @@ mod tests { ], ); change(&mut doc, |tx| { - store::write_path(tx, &user_path("alice"), &entry).unwrap() + view::write_path(tx, &user_path("alice"), &entry).unwrap() }); assert!(exists(&doc)); assert_eq!(super::names(&doc), vec!["alice"]); @@ -308,7 +309,7 @@ mod tests { let mut entry = entry("x", 0, &[(vec![], &[Right::Read])]); entry["disabled"] = json!(true); change(&mut doc, |tx| { - store::write_path(tx, &user_path("carol"), &entry).unwrap() + view::write_path(tx, &user_path("carol"), &entry).unwrap() }); assert!(user(&doc, "carol").is_some()); assert!(caps_of(&doc, "carol").is_empty()); @@ -319,7 +320,7 @@ mod tests { "disabled": "no" }); change(&mut doc, |tx| { - store::write_path(tx, &user_path("dave"), &damaged).unwrap() + view::write_path(tx, &user_path("dave"), &damaged).unwrap() }); let dave = user(&doc, "dave").unwrap(); assert_eq!(dave.caps.len(), 1); @@ -374,14 +375,14 @@ mod tests { for (name, caps) in [("alice", all_caps()), ("bob", vec![(Vec::new(), DATA)])] { let entry = entry("x", 0, &caps); change(&mut doc, |tx| { - store::write_path(tx, &user_path(name), &entry).unwrap() + view::write_path(tx, &user_path(name), &entry).unwrap() }); } assert_eq!(managers(&doc), vec!["alice"]); let mut disabled = user_path("alice"); disabled.push("disabled".to_owned()); change(&mut doc, |tx| { - store::write_path(tx, &disabled, &json!(true)).unwrap() + view::write_path(tx, &disabled, &json!(true)).unwrap() }); assert!(managers(&doc).is_empty()); } @@ -391,14 +392,14 @@ mod tests { let mut ours = Document::new(); let entry = entry("x", 0, &[]); change(&mut ours, |tx| { - store::write_path(tx, &user_path("erin"), &entry).unwrap() + view::write_path(tx, &user_path("erin"), &entry).unwrap() }); let mut theirs = ours.fork(); for (doc, at) in [(&mut ours, "notes"), (&mut theirs, "logs")] { let mut cap_path = user_path("erin"); cap_path.extend(["caps".to_owned(), new_id()]); let cap = capability("x", 0, &path(at), &[Right::Read]); - change(doc, |tx| store::write_path(tx, &cap_path, &cap).unwrap()); + change(doc, |tx| view::write_path(tx, &cap_path, &cap).unwrap()); } ours.merge(&mut theirs).unwrap(); let caps = caps_of(&ours, "erin"); diff --git a/src/access/rules.rs b/src/access/rules.rs index 520ff0f..93cef63 100644 --- a/src/access/rules.rs +++ b/src/access/rules.rs @@ -44,7 +44,8 @@ use crate::document::at::At; use crate::document::inspect::{Action, Op, Path}; use crate::document::meta; use crate::document::replica::Epoch; -use crate::document::{ChangeHash, Document, ReadDoc, store}; +use crate::document::view::{self, Read}; +use crate::document::{ChangeHash, Document, ReadDoc}; /// A change to judge, as its bytes say. #[derive(Debug, Clone)] @@ -195,18 +196,37 @@ pub(crate) fn judge_reading( }; } let at = At::new(doc, change.seen).ok_or(Refusal::Unready)?; - judge_seen(&at, epoch, &change.unit(), reads.at(change.seen)).map_err(Refusal::Rule) + let unit = change.unit(); + // A swarm holding a store is judged by what a change writes of an Automerge document + // (`access::holding`). + let holding = |fold: &str| { + #[cfg(feature = "federation")] + { + super::holding::judge(&at, epoch, &unit, fold) + } + #[cfg(not(feature = "federation"))] + { + let _ = fold; + Ok(()) + } + }; + judge_seen(&at, epoch, &unit, reads.at(change.seen), holding).map_err(Refusal::Rule) } /// Judges `unit` by the rules, reading `at`, the document (of `epoch`) as its writer saw /// it, with what was read of it before (`read`): why they refuse it, where they do. Not /// an epoch's root, which writes what its document starts with and is judged by none. +/// In a swarm holding a store of some fold, as `holding` judges it there, which is its +/// kind of document's to say. pub(crate) fn judge_seen( - at: &impl ReadDoc, + at: &impl Read, epoch: Epoch, unit: &Unit<'_>, read: &mut Seen, + holding: impl FnOnce(&str) -> Result<(), String>, ) -> Result<(), String> { + #[cfg(not(feature = "federation"))] + let _ = &holding; // Written while the document had no policy (or one this node doesn't know): judged // as it was then, by none. History from before the policy stays as it is. let policy = read @@ -223,7 +243,7 @@ pub(crate) fn judge_seen( // its genesis change, or not at all. #[cfg(feature = "federation")] match policy { - Policy::Store(fold) => return super::holding::judge(at, epoch, unit, fold), + Policy::Store(fold) => return holding(fold), _ if super::holding::turns_store(unit.ops) => { return Err("a swarm holds a store from its genesis change only".to_owned()); } @@ -247,7 +267,7 @@ pub(crate) fn judge_seen( let member = *read .member .entry(node.to_owned()) - .or_insert_with(|| store::read_path(at, &own_entry).ok().flatten().is_some()); + .or_insert_with(|| view::read_path(at, &own_entry).ok().flatten().is_some()); let registering = unit .paths .iter() @@ -287,7 +307,7 @@ pub(crate) fn judge_seen( .paths .iter() .any(|other| other.len() > path.len() && other.starts_with(path)) - && store::read_path(at, path).ok().flatten().is_none() + && view::read_path(at, path).ok().flatten().is_none() }) .collect(); // Whether the change only makes a map at `path`, where there is none. @@ -296,7 +316,7 @@ pub(crate) fn judge_seen( .iter() .filter(|op| op.path == *path) .all(|op| op.action == Action::MakeMap) - && store::read_path(at, path).ok().flatten().is_none() + && view::read_path(at, path).ok().flatten().is_none() }; for path in unit.paths { if on_the_way.contains(path) { @@ -371,7 +391,7 @@ pub(crate) fn judge_seen( unit.paths .iter() .any(|other| other == &meta::path(&[meta::REMAKES, id, "proposal"])) - && store::read_path(at, &meta::path(&[meta::REMAKES, id])) + && view::read_path(at, &meta::path(&[meta::REMAKES, id])) .ok() .flatten() .is_none() @@ -383,7 +403,7 @@ pub(crate) fn judge_seen( // one who may write them. None => made(path) || user_may(path), Some("proposal") => { - store::read_path(at, &meta::path(&[meta::REMAKES, id, "proposal"])) + view::read_path(at, &meta::path(&[meta::REMAKES, id, "proposal"])) .ok() .flatten() .is_none() @@ -482,7 +502,7 @@ pub(crate) fn judge_held( /// string put there that is one (or deleting what is there); nothing within one; nothing /// in an object nowhere to be found, which might be one. fn sealed_values( - at: &impl ReadDoc, + at: &impl Read, declared: &[super::sealed::Declared], ops: &[Op], ) -> Result<(), String> { @@ -514,7 +534,7 @@ fn sealed_values( /// as a write replacing it does); nothing within one; above one, /// nothing replacing or deleting what holds one (a map made where there is none yet, /// what is inside a list or text, which holds none). -fn signed_values(at: &impl ReadDoc, ops: &[Op]) -> Result<(), String> { +fn signed_values(at: &impl Read, ops: &[Op]) -> Result<(), String> { let signed = super::envelope::signed_paths(at); for op in ops { let path = &op.path; @@ -533,7 +553,7 @@ fn signed_values(at: &impl ReadDoc, ops: &[Op]) -> Result<(), String> { Action::Delete if replaced() => continue, _ => return Err(format!("{} holds a value its user signs", shown(path))), }; - let previous = match store::read_path(at, path) { + let previous = match view::read_path(at, path) { Ok(Some(serde_json::Value::String(text))) if super::envelope::read(&text).is_ok() => { @@ -569,7 +589,7 @@ fn signed_values(at: &impl ReadDoc, ops: &[Op]) -> Result<(), String> { /// Whether what is at `path` in `at` holds a value at a place for one its user signs, /// of `signed` (`envelope::signed_paths`), signed or from before the policy; one that /// doesn't read, as if it did. -fn holds_signed(at: &impl ReadDoc, path: &[String], signed: &[Vec<String>]) -> bool { +fn holds_signed(at: &impl Read, path: &[String], signed: &[Vec<String>]) -> bool { fn within(value: &serde_json::Value, place: &mut Vec<String>, signed: &[Vec<String>]) -> bool { if super::envelope::is_signed(signed, place) { return true; @@ -586,7 +606,7 @@ fn holds_signed(at: &impl ReadDoc, path: &[String], signed: &[Vec<String>]) -> b _ => false, } } - match store::read_path(at, path) { + match view::read_path(at, path) { Ok(Some(value)) => within(&value, &mut path.to_vec(), signed), Ok(None) => false, Err(_) => true, @@ -608,12 +628,12 @@ fn shown(path: &Path) -> String { /// Whether remake `id`, coordinated by `node`, made `epoch`: as its snapshot's metadata /// says (`remake::snapshot`), at `at`. Never genesis. -pub(super) fn made_the_epoch(at: &impl ReadDoc, epoch: Epoch, id: &str, node: &str) -> bool { +pub(super) fn made_the_epoch(at: &impl Read, epoch: Epoch, id: &str, node: &str) -> bool { if epoch.generation == 0 { return false; } let generation = epoch.generation.to_string(); - let Some(metadata) = store::read_path(at, &meta::path(&[meta::EPOCHS, &generation])) + let Some(metadata) = view::read_path(at, &meta::path(&[meta::EPOCHS, &generation])) .ok() .flatten() else { @@ -627,8 +647,8 @@ pub(super) fn made_the_epoch(at: &impl ReadDoc, epoch: Epoch, id: &str, node: &s } /// The coordinator remake `id`'s proposal names, at `at`. -pub(super) fn coordinator(at: &impl ReadDoc, id: &str) -> Option<String> { - let proposal = store::read_path(at, &meta::path(&[meta::REMAKES, id, "proposal"])) +pub(super) fn coordinator(at: &impl Read, id: &str) -> Option<String> { + let proposal = view::read_path(at, &meta::path(&[meta::REMAKES, id, "proposal"])) .ok() .flatten()?; proposal @@ -659,7 +679,7 @@ mod tests { }; let at = path(at); transact(doc, UnixMillis(1), &writer, |doc| { - store::write_path(doc, &at, &value) + view::write_path(doc, &at, &value) }) .unwrap(); } diff --git a/src/access/sealed.rs b/src/access/sealed.rs index 2b8085a..c30bea7 100644 --- a/src/access/sealed.rs +++ b/src/access/sealed.rs @@ -25,7 +25,8 @@ use serde_json::Value as JsonValue; use sha2::{Digest, Sha256}; use super::{agree, envelope, registry, sshsig}; -use crate::document::{ReadDoc, meta, store}; +use crate::document::meta; +use crate::document::view::{self, Read}; /// What every sealed value starts with. const PREFIX: &str = "cs1."; @@ -47,8 +48,8 @@ pub(crate) struct Declared { } /// What `doc` declares sealed; an entry that doesn't read as one is left out. -pub(crate) fn declared(doc: &impl ReadDoc) -> Vec<Declared> { - let Ok(Some(JsonValue::Array(entries))) = store::read_plain(doc, &declared_at()) else { +pub(crate) fn declared(doc: &impl Read) -> Vec<Declared> { + let Ok(Some(JsonValue::Array(entries))) = view::read_plain(doc, &declared_at()) else { return Vec::new(); }; entries @@ -140,11 +141,7 @@ pub(crate) fn recipients(sealed: &str) -> Result<BTreeSet<String>, String> { /// (as its writer saw it): a sealed value, or, signed by its user (`access::envelope`), /// one holding a sealed value or `null` (deleted); with readers declared, sealed for /// exactly their keys. -pub(crate) fn check( - doc: &impl ReadDoc, - declared: &Declared, - value: &JsonValue, -) -> Result<(), String> { +pub(crate) fn check(doc: &impl Read, declared: &Declared, value: &JsonValue) -> Result<(), String> { let JsonValue::String(text) = value else { return Err("a sealed value is a string (cs1.<age file>)".to_owned()); }; @@ -187,7 +184,7 @@ pub(crate) fn check( /// Checks what is at `path` in `doc` after a write there: nothing within a declared /// place but its value, and every value at one (at `path` or below it) as `check` says. /// Why not, if not. -pub(crate) fn kept(doc: &impl ReadDoc, path: &[String]) -> Result<(), String> { +pub(crate) fn kept(doc: &impl Read, path: &[String]) -> Result<(), String> { let declared = declared(doc); if declared.is_empty() || !reaches(&declared, path) { return Ok(()); @@ -196,7 +193,7 @@ pub(crate) fn kept(doc: &impl ReadDoc, path: &[String]) -> Result<(), String> { return Err(format!("/{} is within a sealed value", path.join("/"))); } fn walk( - doc: &impl ReadDoc, + doc: &impl Read, declared: &[Declared], value: &JsonValue, at: &mut Vec<String>, @@ -215,7 +212,7 @@ pub(crate) fn kept(doc: &impl ReadDoc, path: &[String]) -> Result<(), String> { } Ok(()) } - match store::read_path(doc, path) { + match view::read_path(doc, path) { Ok(Some(value)) => walk(doc, &declared, &value, &mut path.to_vec()), Ok(None) => Ok(()), Err(error) => Err(error.to_string()), @@ -270,11 +267,11 @@ mod tests { change(&mut doc, |doc| { let mut alice = registry::entry("root", 1, &[]); alice["keys"] = json!({ "laptop": key(1).line(), "phone": key(2).line() }); - store::write_path(doc, ®istry::user_path("alice"), &alice).unwrap(); + view::write_path(doc, ®istry::user_path("alice"), &alice).unwrap(); let mut bob = registry::entry("root", 1, &[]); bob["keys"] = json!({ "laptop": key(3).line() }); - store::write_path(doc, ®istry::user_path("bob"), &bob).unwrap(); - store::write_path( + view::write_path(doc, ®istry::user_path("bob"), &bob).unwrap(); + view::write_path( doc, &declared_at(), &json!([ @@ -360,13 +357,13 @@ mod tests { let mut doc = swarm(); let all = sealed_for(&[key(1), key(2), key(3)]); change(&mut doc, |doc| { - store::write_path(doc, &path("secrets"), &json!({"db": all, "other": all})).unwrap(); - store::write_path(doc, &path("elsewhere"), &json!("plain")).unwrap(); + view::write_path(doc, &path("secrets"), &json!({"db": all, "other": all})).unwrap(); + view::write_path(doc, &path("elsewhere"), &json!("plain")).unwrap(); }); assert!(kept(&doc, &path("secrets")).is_ok()); assert!(kept(&doc, &path("elsewhere")).is_ok()); change(&mut doc, |doc| { - store::write_path(doc, &path("secrets/web"), &json!("plain")).unwrap(); + view::write_path(doc, &path("secrets/web"), &json!("plain")).unwrap(); }); assert!(kept(&doc, &path("secrets")).is_err()); assert!(kept(&doc, &path("secrets/web")).is_err()); diff --git a/src/access/strict.rs b/src/access/strict.rs index 0b294f8..9857bed 100644 --- a/src/access/strict.rs +++ b/src/access/strict.rs @@ -16,7 +16,7 @@ use serde_json::Value as JsonValue; use sha2::{Digest, Sha256}; use super::{envelope, sshsig}; -use crate::document::{ReadDoc, store}; +use crate::document::view::{self, Read}; /// What a manifest's signature is for (`sshsig`). pub(crate) const NAMESPACE: &str = "continuum-strict"; @@ -95,21 +95,21 @@ pub(crate) fn digest(value: &JsonValue) -> String { /// The places values are signed in `doc` (`envelope::signed_paths`, `*` as `doc` has /// them) that hold one, with it, as the store reads it. -pub(crate) fn held(doc: &impl ReadDoc) -> Vec<(Vec<String>, JsonValue)> { +pub(crate) fn held(doc: &impl Read) -> Vec<(Vec<String>, JsonValue)> { fn expand( - doc: &impl ReadDoc, + doc: &impl Read, pattern: &[String], at: Vec<String>, out: &mut Vec<(Vec<String>, JsonValue)>, ) { match pattern.split_first() { None => { - if let Ok(Some(value)) = store::read_path(doc, &at) { + if let Ok(Some(value)) = view::read_path(doc, &at) { out.push((at, value)); } } Some((segment, rest)) if segment == "*" => { - for key in store::keys_at(doc, &at).ok().flatten().unwrap_or_default() { + for key in view::keys_at(doc, &at).ok().flatten().unwrap_or_default() { let mut next = at.clone(); next.push(key); expand(doc, rest, next, out); @@ -135,7 +135,7 @@ pub(crate) fn held(doc: &impl ReadDoc) -> Vec<(Vec<String>, JsonValue)> { /// held at a signed place now, the policy `policy`, for `user` to look over and sign at /// `at`. Its exact line. pub(crate) fn manifest_of( - doc: &impl ReadDoc, + doc: &impl Read, swarm: &str, epoch: crate::document::replica::EpochRecord, base: &[crate::document::ChangeHash], @@ -225,15 +225,15 @@ mod tests { fn a_manifest_signed_and_checked() { let mut doc = Document::new(); change(&mut doc, |doc| { - store::write_path(doc, &path("_continuum/users/alice"), &json!({"caps": {}})).unwrap(); - store::write_path( + view::write_path(doc, &path("_continuum/users/alice"), &json!({"caps": {}})).unwrap(); + view::write_path( doc, &path("_continuum/access/userSigned"), &json!([["config"]]), ) .unwrap(); - store::write_path(doc, &path("config"), &json!({"mode": "fast"})).unwrap(); - store::write_path(doc, &path("notes"), &json!(1)).unwrap(); + view::write_path(doc, &path("config"), &json!({"mode": "fast"})).unwrap(); + view::write_path(doc, &path("notes"), &json!(1)).unwrap(); }); let policy = json!({"version": 1, "values": "signed"}); let epoch = diff --git a/src/access/token.rs b/src/access/token.rs index 650a5c4..073d1e4 100644 --- a/src/access/token.rs +++ b/src/access/token.rs @@ -17,7 +17,8 @@ use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD as BASE64URL}; use serde::{Deserialize, Serialize}; use super::{Capability, registry}; -use crate::document::{ReadDoc, meta, store}; +use crate::document::meta; +use crate::document::view::{self, Read}; use crate::identity::{self, NodeKey}; const PREFIX: &str = "ct1."; @@ -117,7 +118,7 @@ pub(crate) enum Refused { /// (`registry::User::tokens_not_before`), of a session not ended /// (`registry::session_ended`). pub(crate) fn verify( - doc: &impl ReadDoc, + doc: &impl Read, token: &str, swarm: &str, now: u64, @@ -161,11 +162,7 @@ pub(crate) fn verify( /// store, only one it issued itself (`docs/store.md`, Members), as a node there is /// whoever its operator lets in, and lets in nobody's but its own. #[cfg(feature = "federation")] -pub(crate) fn issued_here( - doc: &impl ReadDoc, - local: &str, - claims: Claims, -) -> Result<Claims, Refused> { +pub(crate) fn issued_here(doc: &impl Read, local: &str, claims: Claims) -> Result<Claims, Refused> { match super::policy::of(doc) { super::policy::Policy::Store(_) if claims.issuer != local => Err(Refused::ElsewhereIssued), _ => Ok(claims), @@ -176,14 +173,14 @@ pub(crate) fn issued_here( /// its issuer a member and not banned, its user registered, enabled, its tokens not /// revoked since and its session not ended. What a stream opened with it is judged by /// as the document changes (`api::login::streams_end`). -pub(crate) fn still_taken(doc: &impl ReadDoc, claims: &Claims) -> Result<(), Refused> { +pub(crate) fn still_taken(doc: &impl Read, claims: &Claims) -> Result<(), Refused> { issuer_counts(doc, claims)?; user_counts(doc, claims) } /// Its issuer a member of the swarm, not banned. -fn issuer_counts(doc: &impl ReadDoc, claims: &Claims) -> Result<(), Refused> { - let member = store::read_path(doc, &meta::path(&[meta::MEMBERS, &claims.issuer])) +fn issuer_counts(doc: &impl Read, claims: &Claims) -> Result<(), Refused> { + let member = view::read_path(doc, &meta::path(&[meta::MEMBERS, &claims.issuer])) .ok() .flatten() .is_some(); @@ -198,7 +195,7 @@ fn issuer_counts(doc: &impl ReadDoc, claims: &Claims) -> Result<(), Refused> { /// In a swarm with a registry: its user registered, enabled, its tokens not revoked /// since it was issued, its session not ended. -fn user_counts(doc: &impl ReadDoc, claims: &Claims) -> Result<(), Refused> { +fn user_counts(doc: &impl Read, claims: &Claims) -> Result<(), Refused> { user_taken(doc, &claims.user)?; if let Some(user) = registry::user(doc, &claims.user) { if claims.iat < user.tokens_not_before { @@ -214,7 +211,7 @@ fn user_counts(doc: &impl ReadDoc, claims: &Claims) -> Result<(), Refused> { /// In a swarm with a registry: user `name` registered and enabled. What a stream opened /// by password or a proxy's header is judged by as the document changes /// (`api::login::streams_end`), as one opened with a token is by `still_taken`. -pub(crate) fn user_taken(doc: &impl ReadDoc, name: &str) -> Result<(), Refused> { +pub(crate) fn user_taken(doc: &impl Read, name: &str) -> Result<(), Refused> { if registry::exists(doc) { let user = registry::user(doc, name).ok_or(Refused::UnknownUser)?; if user.disabled { @@ -256,7 +253,7 @@ mod tests { fn member(doc: &mut Document, key: &NodeKey) { let path = meta::path(&[meta::MEMBERS, &key.id()]); - change(doc, |tx| store::write_path(tx, &path, &json!({})).unwrap()); + change(doc, |tx| view::write_path(tx, &path, &json!({})).unwrap()); } /// A party's session names the key it logged in with, which a token of a user's @@ -374,7 +371,7 @@ mod tests { let ban = crate::access::bans::path(&key.id()); let mut banned = doc.fork(); change(&mut banned, |tx| { - store::write_path(tx, &ban, &json!({"reason": "lost"})).unwrap() + view::write_path(tx, &ban, &json!({"reason": "lost"})).unwrap() }); assert_eq!( verify(&banned, &token, "s", 1_500), @@ -405,24 +402,24 @@ mod tests { assert!(verify(&doc, &token, "s", 1_500).is_ok()); let bob = registry::entry("x", 0, ®istry::all_caps()); change(&mut doc, |tx| { - store::write_path(tx, ®istry::user_path("bob"), &bob).unwrap() + view::write_path(tx, ®istry::user_path("bob"), &bob).unwrap() }); assert_eq!(verify(&doc, &token, "s", 1_500), Err(Refused::UnknownUser)); let mut alice = registry::entry("x", 0, &[(Vec::new(), &[Right::Read][..])]); change(&mut doc, |tx| { - store::write_path(tx, ®istry::user_path("alice"), &alice).unwrap(); - store::write_path(tx, ®istry::logouts_path("alice"), &json!(1_000)).unwrap() + view::write_path(tx, ®istry::user_path("alice"), &alice).unwrap(); + view::write_path(tx, ®istry::logouts_path("alice"), &json!(1_000)).unwrap() }); assert!(verify(&doc, &token, "s", 1_500).is_ok()); change(&mut doc, |tx| { - store::write_path(tx, ®istry::logouts_path("alice"), &json!(1_001)).unwrap() + view::write_path(tx, ®istry::logouts_path("alice"), &json!(1_001)).unwrap() }); assert_eq!(verify(&doc, &token, "s", 1_500), Err(Refused::Revoked)); // One session ended: its tokens refused, another's taken. let session = claims_of(&token).session; change(&mut doc, |tx| { - store::write_path(tx, ®istry::logouts_path("alice"), &json!(0)).unwrap(); - store::write_path( + view::write_path(tx, ®istry::logouts_path("alice"), &json!(0)).unwrap(); + view::write_path( tx, ®istry::session_path("alice", &session), &json!(10_000), @@ -433,8 +430,8 @@ mod tests { assert!(verify(&doc, &issue(&key, &claims(&key)), "s", 1_500).is_ok()); alice["disabled"] = json!(true); change(&mut doc, |tx| { - store::write_path(tx, ®istry::logouts_path("alice"), &json!(0)).unwrap(); - store::write_path(tx, ®istry::user_path("alice"), &alice).unwrap() + view::write_path(tx, ®istry::logouts_path("alice"), &json!(0)).unwrap(); + view::write_path(tx, ®istry::user_path("alice"), &alice).unwrap() }); assert_eq!(verify(&doc, &token, "s", 1_500), Err(Refused::Disabled)); } diff --git a/src/api/login.rs b/src/api/login.rs index ffcf9b8..02c54a3 100644 --- a/src/api/login.rs +++ b/src/api/login.rs @@ -678,7 +678,7 @@ async fn end(state: &AppState, claims: &Claims, by: &str) -> Result<(), ApiError if !registry::exists(&*doc) { return Ok::<_, ApiError>(false); } - crate::document::store::write_path(doc, &path, &json!(until))?; + crate::document::view::write_path(doc, &path, &json!(until))?; Ok(true) }) .await? @@ -783,10 +783,10 @@ pub(crate) async fn revoke_tokens(state: &AppState, name: &str, by: &str) -> Res ), )); } - if crate::document::store::read_path(&*doc, &entry)?.is_none() { + if crate::document::view::read_path(&*doc, &entry)?.is_none() { return Err(ApiError(StatusCode::NOT_FOUND, None)); } - crate::document::store::write_path(doc, &logouts, &json!(after))?; + crate::document::view::write_path(doc, &logouts, &json!(after))?; Ok(()) }) .await?; diff --git a/src/api/peers.rs b/src/api/peers.rs index 30d1204..fc203f5 100644 --- a/src/api/peers.rs +++ b/src/api/peers.rs @@ -13,7 +13,7 @@ use tracing::warn; use super::store_status; use crate::document::replica::EpochRecord; -use crate::document::store; +use crate::document::view; use crate::locks::MutexExt; use crate::state::{AppState, HelloState, Incidents, Liveness}; use crate::swarm::peer::forgotten_path; @@ -326,7 +326,7 @@ pub(crate) async fn delete_peer( user, crate::document::signatures::Sign::Protocol, move |doc| { - store::write_path(doc, &forgotten_path(&peer_clone), &record)?; + view::write_path(doc, &forgotten_path(&peer_clone), &record)?; crate::swarm::members::unregister(doc, &peer_clone) }, ) diff --git a/src/api/users.rs b/src/api/users.rs index f27eff1..cf28ed1 100644 --- a/src/api/users.rs +++ b/src/api/users.rs @@ -49,7 +49,7 @@ use super::ApiError; use super::access::{Access, Before, registry_kept}; use super::auth::AuthenticatedUser; use crate::access::{Right, envelope, registry}; -use crate::document::store; +use crate::document::view; use crate::state::AppState; /// A capability as a request gives it. @@ -133,7 +133,7 @@ fn may_manage(state: &AppState, user: &str, access: &Access) -> Result<(), ApiEr /// A user's entry as the API shows it: as recorded, with its name. fn shown(doc: &impl crate::document::ReadDoc, name: &str) -> Option<JsonValue> { - let mut entry = store::read_plain(doc, ®istry::user_path(name)).ok()??; + let mut entry = view::read_plain(doc, ®istry::user_path(name)).ok()??; if let Some(object) = entry.as_object_mut() { object.insert("name".to_owned(), json!(name)); } @@ -148,11 +148,11 @@ pub(crate) async fn own_keys( ) -> Result<Json<JsonValue>, ApiError> { let replica = state.doc.read().await; let path = registry::user_path(&user.0); - let entry = store::read_plain(&replica.doc, &path) + let entry = view::read_plain(&replica.doc, &path) .ok() .flatten() .ok_or_else(|| ApiError(StatusCode::NOT_FOUND, Some("no entry of yours".to_owned())))?; - let signed = match store::read_path(&replica.doc, &path) { + let signed = match view::read_path(&replica.doc, &path) { Ok(Some(JsonValue::String(text))) if envelope::read(&text).is_ok() => Some(text), _ => None, }; @@ -218,7 +218,7 @@ async fn own_key( ), )); } - if store::read_path(&*doc, &entry)?.is_none() { + if view::read_path(&*doc, &entry)?.is_none() { return Err(ApiError( StatusCode::NOT_FOUND, Some("no entry of yours".to_owned()), @@ -227,7 +227,7 @@ async fn own_key( if line.is_none() && !password { let mut keys = entry.clone(); keys.push("keys".to_owned()); - let others = store::keys_at(&*doc, &keys)? + let others = view::keys_at(&*doc, &keys)? .unwrap_or_default() .into_iter() .filter(|other| *other != id_kept) @@ -244,8 +244,8 @@ async fn own_key( } } match line { - Some(line) => store::write_path(doc, &path, &json!(line))?, - None => match store::delete_path(doc, &path, false) { + Some(line) => view::write_path(doc, &path, &json!(line))?, + None => match view::delete_path(doc, &path, false) { Ok(()) => {} Err(crate::document::store::StoreError::NotFound) => { return Err(ApiError(StatusCode::NOT_FOUND, None)); @@ -340,7 +340,7 @@ pub(crate) async fn add( &user.0, format!("Added user {name}"), move |doc, by, since| { - if store::read_path(&*doc, &path)?.is_some() { + if view::read_path(&*doc, &path)?.is_some() { return Err(ApiError( StatusCode::CONFLICT, Some("the user exists".to_owned()), @@ -350,7 +350,7 @@ pub(crate) async fn add( .iter() .map(|(path, rights)| (path.clone(), rights.as_slice())) .collect(); - store::write_path(doc, &path, ®istry::entry(by, since, &caps))?; + view::write_path(doc, &path, ®istry::entry(by, since, &caps))?; Ok(()) }, ) @@ -372,7 +372,7 @@ pub(crate) async fn remove( &user.0, format!("Removed user {name}"), move |doc, _, _| { - store::delete_path(doc, &path, false)?; + view::delete_path(doc, &path, false)?; Ok(()) }, ) @@ -395,12 +395,12 @@ pub(crate) async fn set_disabled( if disabled { "Disabled" } else { "Enabled" } ); change(&state, &user.0, what, move |doc, _, _| { - if store::read_path(&*doc, &entry)?.is_none() { + if view::read_path(&*doc, &entry)?.is_none() { return Err(ApiError(StatusCode::NOT_FOUND, None)); } let mut path = entry; path.push("disabled".to_owned()); - store::write_path(doc, &path, &json!(disabled))?; + view::write_path(doc, &path, &json!(disabled))?; Ok(()) }) .await?; @@ -423,10 +423,10 @@ pub(crate) async fn grant( path.extend(["caps".to_owned(), id.clone()]); let what = format!("Granted user {name} {:?} on {:?}", cap.rights, cap.path); change(&state, &user.0, what, move |doc, by, since| { - if store::read_path(&*doc, &entry)?.is_none() { + if view::read_path(&*doc, &entry)?.is_none() { return Err(ApiError(StatusCode::NOT_FOUND, None)); } - store::write_path( + view::write_path( doc, &path, ®istry::capability(by, since, &cap.path, &rights), @@ -452,7 +452,7 @@ pub(crate) async fn revoke( &user.0, format!("Revoked capability {id} of user {name}"), move |doc, _, _| { - store::delete_path(doc, &path, false)?; + view::delete_path(doc, &path, false)?; Ok(()) }, ) @@ -498,7 +498,7 @@ pub(crate) async fn add_several( change(&state, &user.0, what, move |doc, by, since| { for (name, caps) in &users { let path = registry::user_path(name); - if store::read_path(&*doc, &path)?.is_some() { + if view::read_path(&*doc, &path)?.is_some() { return Err(ApiError( StatusCode::CONFLICT, Some(format!("user {name} exists")), @@ -508,7 +508,7 @@ pub(crate) async fn add_several( .iter() .map(|(path, rights)| (path.clone(), rights.as_slice())) .collect(); - store::write_path(doc, &path, ®istry::entry(by, since, &caps))?; + view::write_path(doc, &path, ®istry::entry(by, since, &caps))?; } Ok(()) }) diff --git a/src/document/mod.rs b/src/document/mod.rs index ac35b95..d6505ba 100644 --- a/src/document/mod.rs +++ b/src/document/mod.rs @@ -74,6 +74,7 @@ pub(crate) mod sync; #[cfg(test)] pub(crate) mod testing; pub(crate) mod typed; +pub(crate) mod view; #[cfg(test)] mod tests { diff --git a/src/document/view.rs b/src/document/view.rs new file mode 100644 index 0000000..018e8c0 --- /dev/null +++ b/src/document/view.rs @@ -0,0 +1,118 @@ +//! 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) +} diff --git a/src/swarm/bootstrap.rs b/src/swarm/bootstrap.rs index 53b4af8..27b5e6b 100644 --- a/src/swarm/bootstrap.rs +++ b/src/swarm/bootstrap.rs @@ -26,7 +26,7 @@ use uuid::Uuid; use crate::document; use crate::document::meta::{self, SWARM}; use crate::document::replica::Epoch; -use crate::document::store; +use crate::document::view; use crate::document::{ActorId, Document}; use crate::files::{FileKind, Files}; use crate::force::Force; @@ -115,19 +115,19 @@ pub(crate) async fn bootstrap(state: &AppState, seeds: &[String], start: Start) state .mutate_doc(move |doc| { for (path, entry) in &users { - store::write_path(doc, path, entry)?; + view::write_path(doc, path, entry)?; } if let Some(policy) = &policy { - store::write_path(doc, &crate::access::policy::path(), policy)?; + view::write_path(doc, &crate::access::policy::path(), policy)?; } - store::write_path(doc, &swarm_id_path(), &recorded)?; - store::write_path( + view::write_path(doc, &swarm_id_path(), &recorded)?; + view::write_path( doc, &crate::swarm::topology::neighbours_path(), &JsonValue::from(neighbours), )?; - store::write_path(doc, &crate::swarm::topology::topology_path(), &topology)?; - store::write_path( + view::write_path(doc, &crate::swarm::topology::topology_path(), &topology)?; + view::write_path( doc, &crate::swarm::topology::dissemination_path(), &dissemination, @@ -247,7 +247,7 @@ fn swarm_id_path() -> Vec<String> { /// The swarm ID the document names, if any. fn read_swarm_id(doc: &Document) -> Option<String> { - match store::read_path(doc, &swarm_id_path()) { + match view::read_path(doc, &swarm_id_path()) { Ok(Some(JsonValue::String(id))) if !id.is_empty() => Some(id), _ => None, } diff --git a/src/swarm/members.rs b/src/swarm/members.rs index de33185..4039b2a 100644 --- a/src/swarm/members.rs +++ b/src/swarm/members.rs @@ -24,9 +24,10 @@ use std::time::Duration; use serde_json::{Value as JsonValue, json}; use tracing::{debug, info, warn}; +use crate::document::Document; use crate::document::meta; -use crate::document::store::{self, StoreError}; -use crate::document::{Document, ReadDoc, Transactable}; +use crate::document::store::StoreError; +use crate::document::view::{self, Read, Write}; use crate::state::AppState; pub(crate) fn members_dir() -> Vec<String> { @@ -40,8 +41,8 @@ pub(crate) fn member_path(pk: &str) -> Vec<String> { } /// Public keys of all registered members, sorted. -pub(crate) fn members(doc: &impl ReadDoc) -> Vec<String> { - let mut members = store::keys_at(doc, &members_dir()) +pub(crate) fn members(doc: &impl Read) -> Vec<String> { + let mut members = view::keys_at(doc, &members_dir()) .ok() .flatten() .unwrap_or_default(); @@ -74,18 +75,14 @@ fn tier_path(pk: &str) -> Vec<String> { /// `pk`'s tier; transient unless its entry says stable. pub(crate) fn tier(doc: &Document, pk: &str) -> Tier { - match store::read_path(doc, &tier_path(pk)) { + match view::read_path(doc, &tier_path(pk)) { Ok(Some(JsonValue::String(tier))) if tier == "stable" => Tier::Stable, _ => Tier::Transient, } } -pub(crate) fn set_tier( - doc: &mut impl Transactable, - pk: &str, - tier: Tier, -) -> Result<(), StoreError> { - store::write_path(doc, &tier_path(pk), &json!(tier.as_str())) +pub(crate) fn set_tier(doc: &mut impl Write, pk: &str, tier: Tier) -> Result<(), StoreError> { + view::write_path(doc, &tier_path(pk), &json!(tier.as_str())) } fn alias_path(pk: &str) -> Vec<String> { @@ -103,8 +100,8 @@ fn party_path(pk: &str) -> Vec<String> { /// The party `pk`'s entry names, in a swarm holding a store. #[cfg(feature = "federation")] -pub(crate) fn party(doc: &impl ReadDoc, pk: &str) -> Option<String> { - match store::read_path(doc, &party_path(pk)) { +pub(crate) fn party(doc: &impl Read, pk: &str) -> Option<String> { + match view::read_path(doc, &party_path(pk)) { Ok(Some(JsonValue::String(party))) => Some(party), _ => None, } @@ -112,7 +109,7 @@ pub(crate) fn party(doc: &impl ReadDoc, pk: &str) -> Option<String> { /// `pk`'s alias, if it gave itself one. pub(crate) fn alias(doc: &Document, pk: &str) -> Option<String> { - match store::read_path(doc, &alias_path(pk)) { + match view::read_path(doc, &alias_path(pk)) { Ok(Some(JsonValue::String(alias))) => Some(alias), _ => None, } @@ -126,10 +123,10 @@ pub(crate) fn aliases(doc: &Document) -> HashMap<String, String> { .collect() } -fn set_alias(doc: &mut impl Transactable, pk: &str, alias: Option<&str>) -> Result<(), StoreError> { +fn set_alias(doc: &mut impl Write, pk: &str, alias: Option<&str>) -> Result<(), StoreError> { match alias { - Some(alias) => store::write_path(doc, &alias_path(pk), &json!(alias)), - None => match store::delete_path(doc, &alias_path(pk), false) { + Some(alias) => view::write_path(doc, &alias_path(pk), &json!(alias)), + None => match view::delete_path(doc, &alias_path(pk), false) { Err(StoreError::NotFound) => Ok(()), result => result, }, @@ -144,20 +141,16 @@ fn dashboard_path(pk: &str) -> Vec<String> { /// Where people reach `pk`'s dashboard, if it says. pub(crate) fn dashboard(doc: &Document, pk: &str) -> Option<String> { - match store::read_path(doc, &dashboard_path(pk)) { + match view::read_path(doc, &dashboard_path(pk)) { Ok(Some(JsonValue::String(url))) => Some(url), _ => None, } } -fn set_dashboard( - doc: &mut impl Transactable, - pk: &str, - url: Option<&str>, -) -> Result<(), StoreError> { +fn set_dashboard(doc: &mut impl Write, pk: &str, url: Option<&str>) -> Result<(), StoreError> { match url { - Some(url) => store::write_path(doc, &dashboard_path(pk), &json!(url)), - None => match store::delete_path(doc, &dashboard_path(pk), false) { + Some(url) => view::write_path(doc, &dashboard_path(pk), &json!(url)), + None => match view::delete_path(doc, &dashboard_path(pk), false) { Err(StoreError::NotFound) => Ok(()), result => result, }, @@ -178,7 +171,7 @@ const MAX_ADDRESSES: usize = 16; /// Where `pk` says it can be reached (at most `MAX_ADDRESSES`); none if its entry /// doesn't say. pub(crate) fn addresses(doc: &Document, pk: &str) -> Vec<String> { - match store::read_path(doc, &addresses_path(pk)) { + match view::read_path(doc, &addresses_path(pk)) { Ok(Some(JsonValue::Array(items))) => items .into_iter() .filter_map(|item| match item { @@ -232,7 +225,7 @@ const MAX_RELAYS: usize = 32; /// aren't members, e.g. nodes that only relay. Every member's transport may /// pick them (`Transport::learn_relays`), after the relays it is configured with. pub(crate) fn relays(doc: &Document) -> Vec<String> { - match store::read_path(doc, &meta::path(&[meta::RELAYS])) { + match view::read_path(doc, &meta::path(&[meta::RELAYS])) { Ok(Some(JsonValue::Array(items))) => items .into_iter() .filter_map(|item| match item { @@ -251,15 +244,15 @@ fn alive_path(pk: &str) -> Vec<String> { path } -fn millis_at(doc: &impl ReadDoc, path: &[String]) -> Option<u64> { - match store::read_path(doc, path) { +fn millis_at(doc: &impl Read, path: &[String]) -> Option<u64> { + match view::read_path(doc, path) { Ok(Some(JsonValue::Number(number))) => number.as_u64(), _ => None, } } /// When `pk` last said it is alive (Unix ms): its last renewal, or its registration. -pub(crate) fn alive_at(doc: &impl ReadDoc, pk: &str) -> Option<u64> { +pub(crate) fn alive_at(doc: &impl Read, pk: &str) -> Option<u64> { let mut since = member_path(pk); since.push("since".to_owned()); millis_at(doc, &alive_path(pk)).max(millis_at(doc, &since)) @@ -269,7 +262,7 @@ pub(crate) fn alive_at(doc: &impl ReadDoc, pk: &str) -> Option<u64> { /// electorate of a remake (`remake::coordinator`). A stamp further in the future than a /// renewal interval (`alive_renewal`) doesn't count: its node's clock is that far ahead /// (it warns about it, `swarm::skew`), and the stamp would never age out. -pub(crate) fn electorate(doc: &impl ReadDoc, now_ms: u64, window: Duration) -> Vec<String> { +pub(crate) fn electorate(doc: &impl Read, now_ms: u64, window: Duration) -> Vec<String> { let oldest = now_ms.saturating_sub(window.as_millis() as u64); let newest = now_ms.saturating_add(alive_renewal(window).as_millis() as u64); members(doc) @@ -288,7 +281,7 @@ fn window_path(pk: &str) -> Vec<String> { /// publish in their entries (ms, `window`): every node renews its alive stamp by it /// (`alive_renewal`), so a coordinator with a shorter window than others' still counts /// them all. Below `MIN_ELECTORATE_WINDOW` (which no node accepts) counts as that. -pub(crate) fn shortest_window(doc: &impl ReadDoc, own: Duration) -> Duration { +pub(crate) fn shortest_window(doc: &impl Read, own: Duration) -> Duration { members(doc) .iter() .filter_map(|pk| millis_at(doc, &window_path(pk))) @@ -311,8 +304,8 @@ pub(crate) const MIN_ELECTORATE_WINDOW: Duration = Duration::from_secs(7 * RENEWAL_MOST_OFTEN.as_secs()); /// Whether `node` is registered in `doc`'s member list. -pub(crate) fn registered(doc: &impl ReadDoc, node: &str) -> bool { - store::read_path(doc, &member_path(node)) +pub(crate) fn registered(doc: &impl Read, node: &str) -> bool { + view::read_path(doc, &member_path(node)) .ok() .flatten() .is_some() @@ -382,7 +375,7 @@ pub(crate) async fn ensure_registered(state: &AppState) { if !registered { let entry = entry(state); match state - .mutate_doc_registering(move |doc| store::write_path(doc, &own, &entry)) + .mutate_doc_registering(move |doc| view::write_path(doc, &own, &entry)) .await { Ok(()) => info!( @@ -397,7 +390,7 @@ pub(crate) async fn ensure_registered(state: &AppState) { if recorded_window != Some(window) { let path = window_path(&local); match state - .mutate_doc(move |doc| store::write_path(doc, &path, &json!(window))) + .mutate_doc(move |doc| view::write_path(doc, &path, &json!(window))) .await { Ok(()) => debug!( @@ -412,7 +405,7 @@ pub(crate) async fn ensure_registered(state: &AppState) { if alive.is_none_or(|at| now.saturating_sub(at) >= renewal) { let path = alive_path(&local); match state - .mutate_doc(move |doc| store::write_path(doc, &path, &json!(now))) + .mutate_doc(move |doc| view::write_path(doc, &path, &json!(now))) .await { Ok(()) => debug!("Renewed our alive stamp in the member list"), @@ -424,7 +417,7 @@ pub(crate) async fn ensure_registered(state: &AppState) { let path = addresses_path(&local); let value = json!(own_addresses); match state - .mutate_doc(move |doc| store::write_path(doc, &path, &value)) + .mutate_doc(move |doc| view::write_path(doc, &path, &value)) .await { Ok(()) => info!(addresses = ?own_addresses, "Addresses updated in the member list"), @@ -454,7 +447,7 @@ pub(crate) async fn ensure_registered(state: &AppState) { if recorded.as_deref() != Some(ours) { let (path, value) = (party_path(&local), json!(ours)); match state - .mutate_doc(move |doc| store::write_path(doc, &path, &value)) + .mutate_doc(move |doc| view::write_path(doc, &path, &value)) .await { Ok(()) => info!( @@ -512,8 +505,8 @@ impl RecordedLinks { /// `pk`'s recorded links; none if its entry doesn't say (at most `MAX_RECORDED_LINKS` /// in each set). -pub(crate) fn links(doc: &impl ReadDoc, pk: &str) -> RecordedLinks { - let Ok(Some(JsonValue::Object(links))) = store::read_path(doc, &links_path(pk)) else { +pub(crate) fn links(doc: &impl Read, pk: &str) -> RecordedLinks { + let Ok(Some(JsonValue::Object(links))) = view::read_path(doc, &links_path(pk)) else { return RecordedLinks::default(); }; let set = |name: &str| -> BTreeSet<String> { @@ -535,12 +528,12 @@ pub(crate) fn links(doc: &impl ReadDoc, pk: &str) -> RecordedLinks { /// Records `pk`'s `links` (at most `MAX_RECORDED_LINKS` in each set); none removes them. pub(crate) fn set_links( - doc: &mut impl Transactable, + doc: &mut impl Write, pk: &str, links: &RecordedLinks, ) -> Result<(), StoreError> { if links.is_empty() { - return match store::delete_path(doc, &links_path(pk), false) { + return match view::delete_path(doc, &links_path(pk), false) { Err(StoreError::NotFound) => Ok(()), result => result, }; @@ -552,12 +545,12 @@ pub(crate) fn set_links( "unreached": list(&links.unreached), "reached": list(&links.reached), }); - store::write_path(doc, &links_path(pk), &value) + view::write_path(doc, &links_path(pk), &value) } /// Removes `pk`'s entry (an operator forgot it). Absent is fine. -pub(crate) fn unregister(doc: &mut impl Transactable, pk: &str) -> Result<(), StoreError> { - match store::delete_path(doc, &member_path(pk), false) { +pub(crate) fn unregister(doc: &mut impl Write, pk: &str) -> Result<(), StoreError> { + match view::delete_path(doc, &member_path(pk), false) { Err(StoreError::NotFound) => Ok(()), result => result, } @@ -584,7 +577,7 @@ mod tests { ]; change(&mut doc, |doc| { for (pk, entry) in entries { - store::write_path(doc, &member_path(pk), &entry).unwrap(); + view::write_path(doc, &member_path(pk), &entry).unwrap(); } }); assert_eq!( @@ -599,11 +592,11 @@ mod tests { assert!(relays(&doc).is_empty()); let relay = "libp2p:/ip6/fd00::1/tcp/9661"; change(&mut doc, |doc| { - store::write_path(doc, &meta::path(&[meta::RELAYS]), &json!([relay, 7])).unwrap() + view::write_path(doc, &meta::path(&[meta::RELAYS]), &json!([relay, 7])).unwrap() }); assert_eq!(relays(&doc), [relay]); // Anything but text is ignored. change(&mut doc, |doc| { - store::write_path(doc, &meta::path(&[meta::RELAYS]), &json!(relay)).unwrap() + view::write_path(doc, &meta::path(&[meta::RELAYS]), &json!(relay)).unwrap() }); assert!(relays(&doc).is_empty()); // Not a list. } @@ -614,19 +607,19 @@ mod tests { let mut doc = Document::new(); assert_eq!(shortest_window(&doc, 7 * day), 7 * day); change(&mut doc, |doc| { - store::write_path( + view::write_path( doc, &member_path("a"), &json!({ "window": 30 * 86_400_000_u64 }), ) .unwrap(); - store::write_path(doc, &member_path("b"), &json!({ "window": 86_400_000 })).unwrap(); - store::write_path(doc, &member_path("c"), &json!({ "since": 1 })).unwrap(); + view::write_path(doc, &member_path("b"), &json!({ "window": 86_400_000 })).unwrap(); + view::write_path(doc, &member_path("c"), &json!({ "since": 1 })).unwrap(); }); assert_eq!(shortest_window(&doc, 7 * day), day); // Below what any node accepts: as the shortest it accepts. change(&mut doc, |doc| { - store::write_path(doc, &window_path("c"), &json!(1)).unwrap(); + view::write_path(doc, &window_path("c"), &json!(1)).unwrap(); }); assert_eq!(shortest_window(&doc, 7 * day), MIN_ELECTORATE_WINDOW); } diff --git a/src/swarm/peer/forget.rs b/src/swarm/peer/forget.rs index a1676b5..8616ae9 100644 --- a/src/swarm/peer/forget.rs +++ b/src/swarm/peer/forget.rs @@ -11,7 +11,8 @@ use tracing::{info, warn}; use crate::document::Document; use crate::document::meta; -use crate::document::store::{self, StoreError}; +use crate::document::store::StoreError; +use crate::document::view; use crate::state::{AppState, Standing}; fn forgotten_dir() -> Vec<String> { @@ -32,7 +33,7 @@ pub(crate) fn affects_forget_records(path: &[String]) -> bool { } fn forgotten_peers(doc: &Document) -> Vec<String> { - store::keys_at(doc, &forgotten_dir()) + view::keys_at(doc, &forgotten_dir()) .ok() .flatten() .unwrap_or_default() @@ -56,7 +57,7 @@ pub(super) async fn apply_forget_records(state: &AppState, applied: &mut Applied forgotten_peers(&replica.doc) .into_iter() .filter_map(|pk| { - let record = store::read_path(&replica.doc, &forgotten_path(&pk)).ok()??; + let record = view::read_path(&replica.doc, &forgotten_path(&pk)).ok()??; Some((pk, record)) }) .collect() @@ -99,7 +100,7 @@ pub(super) async fn apply_forget_records(state: &AppState, applied: &mut Applied let local_id = state.local_id().to_owned(); let _ = state .mutate_doc(move |doc| { - match store::delete_path(&mut *doc, &forgotten_path(&local_id), false) { + match view::delete_path(&mut *doc, &forgotten_path(&local_id), false) { Ok(()) => { info!("We were forgotten swarm-wide but are alive; cancelling the record") } diff --git a/src/swarm/topology/mod.rs b/src/swarm/topology/mod.rs index f2538cc..df9a27e 100644 --- a/src/swarm/topology/mod.rs +++ b/src/swarm/topology/mod.rs @@ -161,7 +161,7 @@ pub(crate) fn swarm_ways( what: &str, own: T, ) -> T { - match crate::document::store::read_path(doc, path) { + match crate::document::view::read_path(doc, path) { Ok(Some(value)) => match serde_json::from_value(value.clone()) { Ok(recorded) => recorded, Err(_) => { @@ -686,7 +686,7 @@ pub(crate) fn neighbours_path() -> Vec<String> { /// document has none (a swarm from before it was recorded), or one that isn't a number /// from 2 to `MAX_NEIGHBOURS`, this node's own (`own`). pub(crate) fn swarm_neighbours(doc: &crate::document::Document, own: usize) -> usize { - match crate::document::store::read_path(doc, &neighbours_path()) { + match crate::document::view::read_path(doc, &neighbours_path()) { Ok(Some(value)) => match value.as_u64() { Some(k) if (2..=MAX_NEIGHBOURS).contains(&k) => k as usize, _ => { |
