//! A swarm holding a store (`docs/store.md`, On Automerge): where its document holds the //! store, and its genesis change, built byte for byte from the store's root, so that one //! root makes one swarm. //! //! The genesis change writes, in this order and nothing else: the policy at its place //! (`access::policy`), naming the fold; the swarm's ID, the root's, at `_continuum/swarm`; //! and the root at its ID, as bytes; each making the maps on its way //! (`store::write_path`). Its writer is the first 16 bytes of the root's ID, its time 0, //! and it has no message. #![allow(dead_code)] use automerge::legacy::OpType; use automerge::transaction::CommitOptions; use automerge::{ObjId, ObjType, ScalarValue, Value}; use serde_json::Value as JsonValue; use super::typed::{TimestampFormat, Val}; use super::{ActorId, Change, Document, ReadDoc, meta, store}; use crate::federation::store::Id; /// Where the event `id` is. pub(crate) fn event(id: &Id) -> Vec { meta::path(&[meta::EVENTS, &id.to_string()]) } /// The map holding the events, if `doc` holds one. fn events_map(doc: &impl ReadDoc) -> Option { let map = |parent: &ObjId, key: &str| match doc.get(parent, key) { Ok(Some((Value::Object(ObjType::Map), id))) => Some(id), _ => None, }; map(&map(&automerge::ROOT, meta::ROOT)?, meta::EVENTS) } /// The IDs of the events `doc` holds. pub(crate) fn ids(doc: &impl ReadDoc) -> Vec { events_map(doc).map_or_else(Vec::new, |events| { doc.keys(&events) .filter_map(|key| Id::from_hex(&key)) .collect() }) } /// The bytes `doc` holds at the event `id`. pub(crate) fn bytes(doc: &impl ReadDoc, id: &Id) -> Option> { match doc.get(&events_map(doc)?, id.to_string()) { Ok(Some((Value::Scalar(value), _))) => match value.as_ref() { ScalarValue::Bytes(bytes) => Some(bytes.clone()), _ => None, }, _ => None, } } /// The policy of a swarm holding a store of the fold `fold`. pub(crate) fn policy(fold: &str) -> JsonValue { serde_json::json!({"version": 2, "store": fold}) } /// The writer of the genesis change of the store whose root is `id`. pub(crate) fn genesis_writer(id: &Id) -> ActorId { ActorId::from(&id.0[..16]) } /// The genesis change of a swarm holding a store of the fold `fold` whose root is `root`. pub(crate) fn genesis(fold: &str, root: &[u8]) -> Change { let id = Id::of(root); let mut doc = Document::new().with_actor(genesis_writer(&id)); let mut write = doc.transaction(); let writes = [ store::write_path(&mut write, &crate::access::policy::path(), &policy(fold)), store::write_path( &mut write, &meta::path(&[meta::SWARM]), &JsonValue::String(id.to_string()), ), store::write_val_path( &mut write, &event(&id), &Val::Scalar(ScalarValue::Bytes(root.to_vec())), store::Writing::sticky(TimestampFormat::default()), ) .map(|_| ()), ]; for written in writes { // Into an empty document, under paths of maps only: nothing to refuse them. written.expect("an empty document takes the genesis change's writes"); } write.commit_with(CommitOptions::default().with_time(0)); doc.get_changes(&[]) .pop() .expect("the genesis change was just made") } /// A document holding the genesis change of a swarm holding a store of the fold `fold` /// whose root is `root`, written to under a writer of its own: the genesis change's is /// every node's, and writes nothing else. pub(crate) fn started(fold: &str, root: &[u8]) -> anyhow::Result { let mut doc = Document::new(); doc.apply_changes([genesis(fold, root)])?; Ok(doc.with_actor(ActorId::random())) } /// Whether `change` is the genesis change of the swarm holding a store of the fold `fold` /// whose root's ID is `id`: built again from the root it holds, byte for byte the same. pub(crate) fn is_genesis(change: &Change, fold: &str, id: &Id) -> bool { if !change.deps().is_empty() || *change.actor_id() != genesis_writer(id) { return false; } let root = super::changes::decode(change) .operations .into_iter() .find_map(|op| match op.action { OpType::Put(ScalarValue::Bytes(bytes)) if Id::of(&bytes) == *id => Some(bytes), _ => None, }); root.is_some_and(|root| genesis(fold, &root).hash() == change.hash()) } /// Puts `bytes` at the event `id`, held there or not, as no change of a node puts an /// event: for tests of what a change may write. #[cfg(test)] pub(crate) fn put_held(doc: &mut super::Transaction<'_>, id: &Id, bytes: &[u8]) { use automerge::transaction::Transactable; let events = events_map(doc).expect("the events' map"); doc.put(&events, id.to_string(), ScalarValue::Bytes(bytes.to_vec())) .expect("a put"); } #[cfg(test)] mod tests { use super::*; const ROOT: &[u8] = b"{\"a root\":true}"; #[test] fn one_root_makes_one_genesis_change() { let change = genesis("federation", ROOT); assert_eq!(change.hash(), genesis("federation", ROOT).hash()); assert_eq!(change.timestamp(), 0); assert_eq!(change.message(), None); assert!(change.deps().is_empty()); assert_eq!(*change.actor_id(), genesis_writer(&Id::of(ROOT))); assert_ne!(change.hash(), genesis("test", ROOT).hash()); assert_ne!(change.hash(), genesis("federation", b"another root").hash()); } #[test] fn the_genesis_change_writes_the_policy_the_swarm_and_the_root() { let id = Id::of(ROOT); let doc = started("federation", ROOT).unwrap(); assert_ne!(doc.get_actor(), &genesis_writer(&id)); assert_eq!( store::read_plain(&doc, &crate::access::policy::path()).unwrap(), Some(serde_json::json!({"store": "federation", "version": 2})) ); assert_eq!( store::read_plain(&doc, &meta::path(&[meta::SWARM])).unwrap(), Some(JsonValue::String(id.to_string())) ); assert_eq!(ids(&doc), vec![id]); assert_eq!(bytes(&doc, &id).as_deref(), Some(ROOT)); } #[test] fn a_genesis_change_is_known_by_its_root() { let id = Id::of(ROOT); let change = genesis("federation", ROOT); assert!(is_genesis(&change, "federation", &id)); assert!(!is_genesis(&change, "test", &id)); assert!(!is_genesis(&change, "federation", &Id::of(b"another root"))); // Another time, or more written: not it. let mut doc = Document::new().with_actor(genesis_writer(&id)); let mut write = doc.transaction(); store::write_val_path( &mut write, &event(&id), &Val::Scalar(ScalarValue::Bytes(ROOT.to_vec())), store::Writing::sticky(TimestampFormat::default()), ) .unwrap(); write.commit_with(CommitOptions::default().with_time(0)); let other = doc.get_changes(&[]).pop().unwrap(); assert!(!is_genesis(&other, "federation", &id)); } }