aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-16 19:33:58 +0000
committertv <tv@krebsco.de>2026-11-16 21:24:48 +0100
commit969767fa5270f90fb3b289177d83d6baab1cbdc2 (patch)
treefe15d0496b2fa213b87685e4dcc3c58abf23a414 /src
parent7f31a5bca06dccdd4edaed6699bc6e6f479a2b27 (diff)
document: a store swarm's genesis change, built byte for byte from its root
A swarm holding a store starts from its genesis change, which every node builds from the store's root alike, so that one root makes one swarm (`docs/store.md`, What the document holds). `document::events` builds it: it writes the policy naming the fold, the swarm's ID (the root's) and the root at its ID, as bytes, each making the maps on its way, under the writer made of the root ID's first 16 bytes, at time 0, without a message. `is_genesis` tells such a change by building it again from the root it holds; `started` is a document holding it, written to under a writer of its own; `ids` and `bytes` read the events a document holds at `_continuum/events`. All of it behind the `federation` feature.
Diffstat (limited to 'src')
-rw-r--r--src/document/events.rs176
-rw-r--r--src/document/meta.rs3
-rw-r--r--src/document/mod.rs2
3 files changed, 181 insertions, 0 deletions
diff --git a/src/document/events.rs b/src/document/events.rs
new file mode 100644
index 0000000..873d3e3
--- /dev/null
+++ b/src/document/events.rs
@@ -0,0 +1,176 @@
+//! 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::transaction::CommitOptions;
+use automerge::legacy::OpType;
+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<String> {
+ meta::path(&[meta::EVENTS, &id.to_string()])
+}
+
+/// The map holding the events, if `doc` holds one.
+fn events_map(doc: &impl ReadDoc) -> Option<ObjId> {
+ 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<Id> {
+ 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<Vec<u8>> {
+ 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<Document> {
+ 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())
+}
+
+#[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));
+ }
+}
diff --git a/src/document/meta.rs b/src/document/meta.rs
index 3b693cf..7a9a489 100644
--- a/src/document/meta.rs
+++ b/src/document/meta.rs
@@ -23,6 +23,7 @@
//! * `logouts/<name>`: when a user's tokens were last revoked (`access::registry`).
//! * `sessions/<name>/<session>`: a session of the user ended (logged out of), until
//! when it would have lasted: its tokens aren't taken (`access::registry`).
+//! * `events/<ID>`: in a swarm holding a store, its events (`document::events`).
//! * `local/<pk>/<name>`: never stored, and never writable: what a node holds alone
//! (its log filter, its configuration, its debug endpoints), named for capabilities
//! (`api::access::needed`).
@@ -45,6 +46,8 @@ pub(crate) const BANNED: &str = "banned";
pub(crate) const LOGOUTS: &str = "logouts";
pub(crate) const SESSIONS: &str = "sessions";
pub(crate) const LOCAL: &str = "local";
+#[cfg(feature = "federation")]
+pub(crate) const EVENTS: &str = "events";
/// The store path `_continuum/<parts…>`.
pub(crate) fn path(parts: &[&str]) -> Vec<String> {
diff --git a/src/document/mod.rs b/src/document/mod.rs
index 76349ad..e548d01 100644
--- a/src/document/mod.rs
+++ b/src/document/mod.rs
@@ -51,6 +51,8 @@ pub(crate) mod at;
#[cfg(test)]
pub(crate) mod bench;
pub(crate) mod changes;
+#[cfg(feature = "federation")]
+pub(crate) mod events;
pub(crate) mod file;
pub(crate) mod inspect;
pub(crate) mod lock;