From 111c07f83ac626074ef6efc361e706a87556e248 Mon Sep 17 00:00:00 2001 From: tv Date: Sun, 29 Nov 2026 14:24:28 +0000 Subject: federation: what carries a node's store, a document or a set of events Holding's store is read from a document, as it was, or is a set of events' (held::Carried): what offers to it, drops from it and allows again goes through whichever carries it. Nothing makes one carried by a set yet. --- src/federation/held.rs | 50 +++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 47 insertions(+), 3 deletions(-) (limited to 'src/federation') diff --git a/src/federation/held.rs b/src/federation/held.rs index ec3738f..508b2eb 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -34,6 +34,7 @@ use super::event::{self, Does, Event, Signed}; use super::fold::Federation; use super::revision::Feature; use super::store::memory::{Built, Offered, Store}; +use super::store::set::Set; use super::store::{Fold, Id, Refused}; use super::version::Version; use super::vote::{self, Act, Rules, Seen}; @@ -123,10 +124,51 @@ pub(crate) struct Voter { pub(crate) rules: Rules, } +/// What carries the store: a document it is read from, or a set of events, which is +/// the store's own document (`store::set`). +enum Carried { + Store(Box>), + Set(Box>), +} + +impl std::ops::Deref for Carried { + type Target = Store; + + fn deref(&self) -> &Store { + match self { + Carried::Store(store) => store, + Carried::Set(set) => set.store(), + } + } +} + +impl Carried { + fn offer(&mut self, bytes: Vec) -> Offered { + match self { + Carried::Store(store) => store.offer(bytes), + Carried::Set(set) => set.offer(bytes, Instant::now()), + } + } + + fn drop_taken(&mut self, ids: &[Id]) -> Result, Refused> { + match self { + Carried::Store(store) => store.drop_taken(ids), + Carried::Set(set) => set.drop_taken(ids, Instant::now()), + } + } + + fn allow(&mut self, ids: &[Id]) { + match self { + Carried::Store(store) => store.allow(ids), + Carried::Set(set) => set.allow(ids, Instant::now()), + } + } +} + #[derive(Default)] struct Inner { /// None until a document holding a store holds its root. - store: Option>, + store: Option, /// The document read from (`Replica::epoch_seq`), and its events read. epoch_seq: Option, read: HashSet, @@ -322,7 +364,9 @@ impl Holding { match started { Ok(store) => { info!(store = %id, refused = own.len(), dropped = dropped.len(), "Reading the store from the document"); - inner.store = Some(store.refusing(&own, &dropped, &writes)); + inner.store = Some(Carried::Store(Box::new( + store.refusing(&own, &dropped, &writes), + ))); } Err(why) => { if inner.none.replace(id) != Some(id) { @@ -968,7 +1012,7 @@ impl Holding { /// `f` of the store, where the node holds one. pub(crate) fn with(&self, f: impl FnOnce(&Store) -> T) -> Option { - self.inner.lock_or_recover().store.as_ref().map(f) + self.inner.lock_or_recover().store.as_deref().map(f) } /// What a remake's snapshot holds of the store: as this node reads it anew from -- cgit v1.3.1 From a3af68fafee80b3eef493e8b041e21352e547da2 Mon Sep 17 00:00:00 2001 From: tv Date: Sun, 29 Nov 2026 14:27:24 +0000 Subject: federation: a node's store carried by a set of events Holding::carrying: the node's store is a set's, read from no document. What the API and the node's own voting do with the store, they do with it as before; Holding::kind says which kind of document carries it, and with_set and change_set give the set to what passes it on, the node's members read anew after. No node starts so yet. --- src/federation/held.rs | 90 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) (limited to 'src/federation') diff --git a/src/federation/held.rs b/src/federation/held.rs index 508b2eb..cb130ba 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -1015,6 +1015,46 @@ impl Holding { self.inner.lock_or_recover().store.as_deref().map(f) } + /// Itself, its store carried by `set`: the store's own document, read from no + /// other (`store::set`). + pub(crate) fn carrying(self, set: Set) -> Self { + { + let mut inner = self.inner.lock_or_recover(); + inner.store = Some(Carried::Set(Box::new(set))); + self.settle(&mut inner); + } + self + } + + /// The kind of the document that carries the store: a set of events, or the + /// document the node holds, which the store is read from. + pub(crate) fn kind(&self) -> &'static str { + match self.inner.lock_or_recover().store { + Some(Carried::Set(_)) => super::store::set::KIND, + _ => crate::document::KIND, + } + } + + /// What `f` makes of the set of events carrying the store, where one does. + pub(crate) fn with_set(&self, f: impl FnOnce(&Set) -> T) -> Option { + match &self.inner.lock_or_recover().store { + Some(Carried::Set(set)) => Some(f(set)), + _ => None, + } + } + + /// Has `f` change the set of events carrying the store, where one does, and + /// settles what the node keeps of its store by it: its members, as it reads now. + pub(crate) fn change_set(&self, f: impl FnOnce(&mut Set) -> T) -> Option { + let mut inner = self.inner.lock_or_recover(); + let Some(Carried::Set(set)) = inner.store.as_mut() else { + return None; + }; + let out = f(set); + self.settle(&mut inner); + Some(out) + } + /// What a remake's snapshot holds of the store: as this node reads it anew from /// `base`, the document at the remake's base, by its own refusals and its operator's /// drops, as it reads its document whenever it starts; and what it holds back there, @@ -2730,4 +2770,54 @@ mod tests { LATER, ); } + + #[test] + fn a_store_carried_by_a_set_is_the_nodes_store() { + use crate::federation::store::passing; + + let (tv, lass) = (Party::new("tv", 1), Party::new("lass", 2)); + let first = Spec::first(&[&tv, &lass], &[]); + let root = first.root(); + let set = |root: &[u8]| { + Set::new( + Store::::new(root.to_vec(), Vec::new()).expect("a root"), + Duration::from_secs(60), + ) + }; + let holding = Holding::default().carrying(set(&root)); + assert_eq!(holding.kind(), crate::federation::store::set::KIND); + assert_eq!(Holding::default().kind(), crate::document::KIND); + assert!(holding.tells_members()); + // Offered as to any store; and what another's set holds comes by passing on. + let write = tv.write(&[Id::of(&root)], "home/tv/a", harness::str("1")); + assert!(matches!( + holding.offer(write.clone()), + Some(Offered::Taken(_)) + )); + assert_eq!(holding.with(|store| store.taken().len()), Some(1)); + let other = Holding::default().carrying(set(&root)); + let stamp = holding.with_set(passing::stamp).expect("a set"); + let mut to_other = vec![passing::Message::Stamp(stamp)]; + let mut to_holding = Vec::new(); + for _ in 0..10 { + for message in std::mem::take(&mut to_other) { + let (replies, _) = other + .change_set(|set| passing::receive(set, message, Instant::now())) + .expect("a set"); + to_holding.extend(replies); + } + for message in std::mem::take(&mut to_holding) { + let (replies, _) = holding + .change_set(|set| passing::receive(set, message, Instant::now())) + .expect("a set"); + to_other.extend(replies); + } + } + assert_eq!( + other.with(|store| store.taken().to_vec()), + Some(vec![Id::of(&write)]) + ); + // A store read from a document has no set. + assert!(Holding::default().with_set(|_| ()).is_none()); + } } -- cgit v1.3.1 From 27b0fb294c47fea75359c3abadab56cd74c93b33 Mon Sep 17 00:00:00 2001 From: tv Date: Sun, 29 Nov 2026 15:18:39 +0000 Subject: federation: a set's entries as a document's members Holding::entries: where a set of events carries the store, its members' entries as a tree, each at _continuum/members/, which is where the swarm reads members of a document (swarm::members). --- src/federation/held.rs | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) (limited to 'src/federation') diff --git a/src/federation/held.rs b/src/federation/held.rs index cb130ba..dc0db6f 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -1043,6 +1043,28 @@ impl Holding { } } + /// The members' entries as the node reads them of a document, each at + /// `_continuum/members/`, where a set of events carries the store: the + /// document's place for them, which a set keeps apart. + pub(crate) fn entries(&self) -> Option { + use crate::document::view::{Tree, Write}; + self.with_set(|set| { + let mut tree = Tree::new(); + for entry in set.entries() { + if let Some(value) = entry.value() { + let path = [ + meta::ROOT.to_owned(), + meta::MEMBERS.to_owned(), + entry.node(), + ]; + // Into a tree of maps alone: nothing is in the way. + let _ = tree.write_path(&path, &serde_json::Value::Object(value)); + } + } + tree + }) + } + /// Has `f` change the set of events carrying the store, where one does, and /// settles what the node keeps of its store by it: its members, as it reads now. pub(crate) fn change_set(&self, f: impl FnOnce(&mut Set) -> T) -> Option { @@ -2820,4 +2842,43 @@ mod tests { // A store read from a document has no set. assert!(Holding::default().with_set(|_| ()).is_none()); } + + #[test] + fn a_sets_entries_read_as_a_documents_members() { + use crate::federation::store::entry::Entry; + use crate::identity::NodeKey; + + let key = NodeKey::from_seed([7; 32]); + let tv = Party::new("tv", 1); + let first = Spec::first(&[&tv], &[]); + let root = first.root(); + let listed = tv.nodes(&[Id::of(&root)], &[key.id()]); + let mut set = Set::new( + Store::::new(root.clone(), Vec::new()).expect("a root"), + Duration::from_secs(60), + ); + assert!(matches!( + set.offer(listed, Instant::now()), + Offered::Taken(_) + )); + let entry = Entry::new( + &Id::of(&root), + &key, + 1, + &serde_json::json!({"party": "tv", "addresses": ["a"], "alias": "seven"}), + ); + assert_eq!( + set.put_entry(entry), + crate::federation::store::set::Put::Taken + ); + let holding = Holding::default().carrying(set); + let tree = holding.entries().expect("a set"); + assert_eq!(crate::swarm::members::members(&tree), vec![key.id()]); + assert_eq!( + crate::swarm::members::party(&tree, &key.id()), + Some("tv".to_owned()) + ); + assert!(holding.member(&key.id(), Some("tv")) == Some(true)); + assert!(Holding::default().entries().is_none()); + } } -- cgit v1.3.1 From af9de78d7de36848f6ff115c9710fb90d2468af2 Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 13:58:03 +0000 Subject: swarm: a node says the kind of the document it holds In its handshakes, and checks a peer's against it (AppState::kind): a set of events where one carries its store (Holding::of_a_set), else Automerge's, as it was for every node. --- src/federation/held.rs | 18 ++++++++++++++---- src/state/mod.rs | 10 ++++++++++ src/swarm/peer/handshake.rs | 4 ++-- src/swarm/peer/inbound.rs | 4 ++-- 4 files changed, 28 insertions(+), 8 deletions(-) (limited to 'src/federation') diff --git a/src/federation/held.rs b/src/federation/held.rs index dc0db6f..fec21ab 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -111,6 +111,8 @@ pub(crate) struct Holding { members: RwLock>>, /// What it votes for its party with, if it votes by itself. voter: Option, + /// Whether a set of events carries the store (`carrying`), from the node's start on. + of_a_set: bool, // A std mutex: never held while waiting for the document. inner: Mutex, } @@ -261,6 +263,7 @@ impl Holding { near: Vec::new(), members: RwLock::default(), voter: None, + of_a_set: false, inner: Mutex::new(Inner { kept, ..Inner::default() @@ -1017,7 +1020,8 @@ impl Holding { /// Itself, its store carried by `set`: the store's own document, read from no /// other (`store::set`). - pub(crate) fn carrying(self, set: Set) -> Self { + pub(crate) fn carrying(mut self, set: Set) -> Self { + self.of_a_set = true; { let mut inner = self.inner.lock_or_recover(); inner.store = Some(Carried::Set(Box::new(set))); @@ -1029,12 +1033,18 @@ impl Holding { /// The kind of the document that carries the store: a set of events, or the /// document the node holds, which the store is read from. pub(crate) fn kind(&self) -> &'static str { - match self.inner.lock_or_recover().store { - Some(Carried::Set(_)) => super::store::set::KIND, - _ => crate::document::KIND, + if self.of_a_set { + super::store::set::KIND + } else { + crate::document::KIND } } + /// Whether a set of events carries the store. + pub(crate) fn of_a_set(&self) -> bool { + self.of_a_set + } + /// What `f` makes of the set of events carrying the store, where one does. pub(crate) fn with_set(&self, f: impl FnOnce(&Set) -> T) -> Option { match &self.inner.lock_or_recover().store { diff --git a/src/state/mod.rs b/src/state/mod.rs index 604f6ae..36dab9d 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -377,6 +377,16 @@ impl AppState { *self.closing.borrow() } + /// The kind of this node's document (`document::KIND`, or a set of events where + /// one carries its store). + pub(crate) fn kind(&self) -> &'static str { + #[cfg(feature = "federation")] + if self.holding.of_a_set() { + return self.holding.kind(); + } + crate::document::KIND + } + pub(crate) fn local_id(&self) -> &str { self.transport.local_id() } diff --git a/src/swarm/peer/handshake.rs b/src/swarm/peer/handshake.rs index 2e5a315..fc1bc86 100644 --- a/src/swarm/peer/handshake.rs +++ b/src/swarm/peer/handshake.rs @@ -144,7 +144,7 @@ async fn transmit_hello(state: &AppState, peer: &str) -> Result<()> { .await .map(|root| root.0.to_vec()), party: party(state), - kind: crate::document::KIND.to_owned(), + kind: state.kind().to_owned(), }), ) .await; @@ -255,7 +255,7 @@ pub(super) async fn send_hello_reply( .await .map(|root| root.0.to_vec()), party: party(state), - kind: crate::document::KIND.to_owned(), + kind: state.kind().to_owned(), }; debug!(to = %peer, ready, "Sending HELLO_REPLY"); diff --git a/src/swarm/peer/inbound.rs b/src/swarm/peer/inbound.rs index a558ded..dbf1a2e 100644 --- a/src/swarm/peer/inbound.rs +++ b/src/swarm/peer/inbound.rs @@ -114,11 +114,11 @@ pub(crate) async fn handle_message( ParsedMessage::HelloReply(reply) => Some(&reply.kind), _ => None, }; - if let Some(theirs) = kind.filter(|kind| *kind != crate::document::KIND) { + if let Some(theirs) = kind.filter(|kind| *kind != state.kind()) { anyhow::bail!( "{peer} holds a document of another kind ({theirs}; this node's is {}): they sync \ nothing; a release that knows the kind does", - crate::document::KIND + state.kind() ); } -- cgit v1.3.1 From 8e97bcfa65e92da21df912cc5e19cf18027b82b8 Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 14:33:09 +0000 Subject: swarm: a node whose store a set of events carries Such a node (Holding::carrying) holds an Automerge document with nothing in it, which nothing passes on, and its set is its document: * swarm::set passes the set on. Where it stands goes in the node's STATUSes as another kind's stamp, and a peer's is given to the set; what the set says besides goes as a SYNC's body; what the set took, of a peer or of the node itself, goes on to the node's other neighbours. What compares stamps for an Automerge document's sake is handed the node's own, and finds nothing to do; the Automerge sync isn't begun. * The node writes its own entry (AppState::mutate_set): what writes protocol data through a view writes to the members' entries as a tree, and what the node's own reads as after is put as its next entry, signed and passed on. Anything else is refused, and so is a write to an Automerge document as such. * An event the node writes (held::write) is offered to the set and passed on; a set lacks nothing of its store to put again. * The node's swarm is its store's, said at its start. A simulation: three such nodes of two parties register, and each holds the others' entries; events put on two of them reach all three, and they come to stand alike, the documents they hold beside empty. --- src/federation/held.rs | 15 ++++ src/simtest/holding.rs | 80 ++++++++++++++++++++ src/state/mod.rs | 67 +++++++++++++++++ src/swarm/bootstrap.rs | 8 ++ src/swarm/mod.rs | 2 + src/swarm/peer/inbound.rs | 13 ++++ src/swarm/peer/keepalive.rs | 3 + src/swarm/set.rs | 174 ++++++++++++++++++++++++++++++++++++++++++++ src/swarm/sync.rs | 7 ++ 9 files changed, 369 insertions(+) create mode 100644 src/swarm/set.rs (limited to 'src/federation') diff --git a/src/federation/held.rs b/src/federation/held.rs index fec21ab..cd53727 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -538,6 +538,10 @@ impl Holding { /// what its store's checkpoint keeps, then what it took after it, then what it holds /// back, stopped (`Store::held_back`). pub(crate) fn lacking(&self, doc: &impl ReadDoc) -> Vec<(Id, Vec)> { + // A set of events is the store's own document: it lacks none of it. + if self.of_a_set { + return Vec::new(); + } let mut held: HashSet = events::ids(doc).into_iter().collect(); let mut inner = self.inner.lock_or_recover(); inner.left.retain(|(id, _)| !held.contains(id)); @@ -1344,6 +1348,17 @@ pub(crate) async fn write( bytes: Vec, ) -> Result<(), store::StoreError> { let id = Id::of(&bytes); + // Into a set of events it goes as the store takes it, where it didn't yet; and is + // passed on, as written. + if state.of_a_set() { + let holding = Arc::clone(&state.holding); + let _ = tokio::task::spawn_blocking(move || holding.offer(bytes)).await; + let held = state.holding.with(|store| store.get(&id).is_some()); + if held == Some(true) { + crate::swarm::set::wrote(state, vec![id]).await; + } + return Ok(()); + } state .mutate_doc_for( user, diff --git a/src/simtest/holding.rs b/src/simtest/holding.rs index 16158b1..4a8098b 100644 --- a/src/simtest/holding.rs +++ b/src/simtest/holding.rs @@ -1726,3 +1726,83 @@ async fn store_attack_31() { ) .await; } + +/// A store carried by a set of events on `root`, for a node of `party`. +fn of_a_set(party: &str, root: &[u8]) -> Holding { + use crate::federation::store::set::Set; + holding(party).carrying(Set::new( + Store::::new(root.to_vec(), Vec::new()).expect("a root"), + Duration::from_secs(600), + )) +} + +/// How many members' entries `node`'s set holds. +fn entries(node: &AppState) -> usize { + node.holding + .with_set(|set| set.entries().count()) + .unwrap_or(0) +} + +/// Where `node`'s set stands. +fn stands(node: &AppState) -> Option { + node.holding + .with_set(crate::federation::store::passing::stamp) +} + +/// tv lists a and b, lass lists c: each node's store is carried by a set of events, +/// its own document, and nothing is in the Automerge document it holds. Each registers, +/// and its entry reaches the others; events put on a and on c reach all three; and they +/// come to stand alike. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_swarm_of_sets_passes_entries_and_events_on() { + let sim = Sim::with_identity(91); + let (tv, lass, _) = three(); + let (_, root, id) = federation(&[(&tv, &["a", "b"]), (&lass, &["c"])]); + let nodes: Vec = [("a", "tv"), ("b", "tv"), ("c", "lass")] + .into_iter() + .map(|(name, party)| { + let seeds: Vec<&str> = if name == "a" { Vec::new() } else { vec!["a"] }; + let root = root.clone(); + sim.start_with( + name, + &seeds, + Start::FromDocument(Origin::Root), + move |config| { + config.store = Some(id); + config.holding = of_a_set(party, &root); + }, + ) + }) + .collect(); + let members: Vec<&AppState> = nodes.iter().collect(); + let members = &members; + sim.wait_ready(members, SOON).await; + for node in members.iter() { + assert_eq!(node.kind(), crate::federation::store::set::KIND); + assert!(node.holding.tells_members()); + } + sim.wait_until("each holds the three entries", SOON, move || async move { + members.iter().all(|node| entries(node) == 3) + }) + .await; + + let on_a = tv.write(&[id], "home/tv/x", s("1")); + let on_c = lass.write(&[id], "home/lass/y", s("2")); + let ids = [Id::of(&on_a), Id::of(&on_c)]; + put(members[0], &[&on_a]).await; + put(members[2], &[&on_c]).await; + sim.wait_until("a, b and c hold both events", SOON, move || async move { + members.iter().all(|node| holds(node, &ids)) + }) + .await; + sim.wait_until("they stand alike", SOON, move || async move { + let first = stands(members[0]); + first.is_some() && members.iter().all(|node| stands(node) == first) + }) + .await; + for node in members.iter() { + assert_eq!(read(node, |store| store.state().values().len()), Some(2)); + // Nothing went into the document it holds beside. + assert!(node.doc.read().await.heads().is_empty()); + } +} diff --git a/src/state/mod.rs b/src/state/mod.rs index 5fefe11..d512b2b 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -50,6 +50,10 @@ use crate::swarm::throughput::ThroughputTable; use crate::transport; use crate::transport::firewall::Firewall; +/// Why a write is refused where a set of events carries the node's store. +#[cfg(feature = "federation")] +const NOT_A_SETS: &str = "this node's document is a set of events: what is written to it is events, and of its members' entries the node's own"; + #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum NodeLifecycle { // TODO maybe rename discovered_swarm_id to swarm_id if that doesn't impair readability. @@ -636,6 +640,10 @@ impl AppState { T: Send + 'static, E: From + Send + 'static, { + #[cfg(feature = "federation")] + if self.of_a_set() { + return self.mutate_set(f).await; + } self.mutate_doc_as(None, Sign::Protocol, false, move |write| f(write)) .await .map(|(out, _)| out) @@ -654,6 +662,10 @@ impl AppState { T: Send + 'static, E: From + Send + 'static, { + #[cfg(feature = "federation")] + if self.of_a_set() { + return self.mutate_set(f).await; + } self.mutate_doc_as(user, sign, true, move |write| f(write)) .await .map(|(out, _)| out) @@ -673,9 +685,64 @@ impl AppState { T: Send + 'static, E: From + Send + 'static, { + #[cfg(feature = "federation")] + if self.of_a_set() { + return Err(E::from(StoreError::Refused(NOT_A_SETS.to_owned()))); + } self.mutate_doc_as(user, sign, true, f).await } + /// A write where a set of events carries this node's store (`federation::store:: + /// set`): to the members' entries as a document has them (`Holding::entries`), of + /// which the node writes its own alone. What its own reads as after is put as its + /// next entry, signed, and passed on (`swarm::set`). + #[cfg(feature = "federation")] + async fn mutate_set(&self, f: impl FnOnce(&mut dyn Write) -> Result) -> Result + where + E: From, + { + use crate::document::view::Read; + use crate::federation::store::entry::Entry; + use crate::federation::store::set::Put; + + let refused = || E::from(StoreError::Refused(NOT_A_SETS.to_owned())); + let own = crate::swarm::members::member_path(self.local_id()); + let before = self.holding.entries().unwrap_or_default(); + let mut after = before.clone(); + let out = f(&mut after)?; + let was = before.read_path(&own).map_err(E::from)?; + let is = after.read_path(&own).map_err(E::from)?; + // Nothing but its own entry, which it doesn't take away. + let (mut rest_before, mut rest_after) = (before, after); + let _ = rest_before.delete_path(&own, true); + let _ = rest_after.delete_path(&own, true); + if rest_before != rest_after { + return Err(refused()); + } + let Some(is) = is else { + return if was.is_some() { + Err(refused()) + } else { + Ok(out) + }; + }; + if Some(&is) == was.as_ref() { + return Ok(out); + } + let Some(key) = self.node_key.clone() else { + return Err(refused()); + }; + let node = self.local_id().to_owned(); + let put = self.holding.change_set(|set| { + let count = set.entry(&node).map_or(1, |entry| entry.count() + 1); + set.put_entry(Entry::new(&set.store().id(), &key, count, &is)) + }); + if put == Some(Put::Taken) { + crate::swarm::set::registered(self).await; + } + Ok(out) + } + /// [`mutate_doc_for`](Self::mutate_doc_for); with `registering_first`, after this /// node's registration if the policy needs it first. While writes are held /// (`writes_held`), after they no longer are. diff --git a/src/swarm/bootstrap.rs b/src/swarm/bootstrap.rs index a0e4db7..24da958 100644 --- a/src/swarm/bootstrap.rs +++ b/src/swarm/bootstrap.rs @@ -52,6 +52,14 @@ pub(crate) enum Start { } pub(crate) async fn bootstrap(state: &AppState, seeds: &[String], start: Start) -> Result<()> { + // A set of events is its store's document, and the store's ID its swarm's: it + // starts on what it holds, with nothing in the document the node holds beside. + #[cfg(feature = "federation")] + if state.of_a_set() + && let Some(swarm_id) = state.holding.with(|store| store.id().to_string()) + { + state.set_expected_swarm_id(swarm_id).await?; + } if let Start::FromDocument(origin) = start { let Some(swarm_id) = state.swarm_id().await else { bail!("starting on a document without a swarm ID"); diff --git a/src/swarm/mod.rs b/src/swarm/mod.rs index 6c0a242..1637130 100644 --- a/src/swarm/mod.rs +++ b/src/swarm/mod.rs @@ -19,6 +19,8 @@ pub(crate) mod refusals; pub(crate) mod relay; pub(crate) mod roots; pub(crate) mod rtt; +#[cfg(feature = "federation")] +pub(crate) mod set; pub(crate) mod skew; pub(crate) mod source; pub(crate) mod speaking; diff --git a/src/swarm/peer/inbound.rs b/src/swarm/peer/inbound.rs index dbf1a2e..0354356 100644 --- a/src/swarm/peer/inbound.rs +++ b/src/swarm/peer/inbound.rs @@ -218,6 +218,15 @@ pub(crate) async fn handle_message( .map_err(|error| anyhow!("Failed to notify sync worker: {error}"))?; } transport::ParsedMessage::Sync(envelope) => { + // Of a set of events, where one carries this node's store: its own to + // take (`swarm::set`), and nothing of an Automerge document's. + #[cfg(feature = "federation")] + if state.of_a_set() { + if let transport::SyncBody::Kind(body) = envelope.body { + crate::swarm::set::received(state, &peer, body).await; + } + return Ok(()); + } if reactivated { ensure_handshake(state, &peer).await; } @@ -251,6 +260,8 @@ pub(crate) async fn handle_message( crate::swarm::blob::handle(state, &peer, blob).await; } transport::ParsedMessage::Status(remote) => { + #[cfg(feature = "federation")] + let remote = crate::swarm::set::heard_status(state, &peer, remote); // An announcement is no keepalive; it is answered only if we lack some of the // heads it announced (`relay::lacks`), so the announcer learns what we have // that it lacks while we pull. Having all of them, we are as far or further, @@ -290,6 +301,8 @@ pub(crate) async fn handle_message( } } transport::ParsedMessage::StatusReply(remote) => { + #[cfg(feature = "federation")] + let remote = crate::swarm::set::heard_status(state, &peer, remote); // An answer to our slow round's announcement: a tree missed. let announced = peer_state.lock().await.slow_announced_at.take(); if let Some(at) = announced { diff --git a/src/swarm/peer/keepalive.rs b/src/swarm/peer/keepalive.rs index 72ab033..6ab49d8 100644 --- a/src/swarm/peer/keepalive.rs +++ b/src/swarm/peer/keepalive.rs @@ -186,6 +186,9 @@ pub(crate) async fn local_status(state: &AppState, peer: &str) -> transport::Sta Some(peer_state) => peer_state.lock().await.syncs_on(epoch), None => false, }; + // Where a set of events carries the store, where that stands (`swarm::set`). + #[cfg(feature = "federation")] + let heads = crate::swarm::set::stamp(state).unwrap_or(heads); let (reaches, round_trips) = crate::swarm::reach::published_with_round_trips(state); transport::Status { heads, diff --git a/src/swarm/set.rs b/src/swarm/set.rs new file mode 100644 index 0000000..ec2415e --- /dev/null +++ b/src/swarm/set.rs @@ -0,0 +1,174 @@ +//! Passing a set of events on between nodes (`docs/document.md`, A set of events): the +//! swarm's side of `federation::store::passing`, for a node whose store a set carries +//! (`Holding::carrying`). +//! +//! * Where the node stands goes in its STATUSes, keepalives and their replies, as +//! another kind's stamp (`HeadsSummary::Kind`); a peer's is given to the set, and what +//! the set says back goes to that peer. +//! * Everything else the set says goes as a SYNC's body (`SyncBody::Kind`). +//! * What the set took of a peer, or of this node's own, goes on at once to the node's +//! other neighbours, as units: a neighbour that has them takes them for held. +//! +//! Nothing is kept of a peer between messages, and a message lost is nothing to repair: +//! the next keepalive says where the node stands again. + +use std::time::Instant; + +use tracing::debug; + +use crate::federation::store::Id; +use crate::federation::store::passing::{self, Message, Took, Unit}; +use crate::state::AppState; +use crate::swarm::topology; +use crate::transport::{self, HeadsSummary, ParsedMessage, SyncBody}; + +/// Where this node's set stands, as its STATUSes say it; none, where no set carries its +/// store. +pub(crate) fn stamp(state: &AppState) -> Option { + let stamp = state.holding.with_set(passing::stamp)?; + Some(HeadsSummary::Kind( + rmp_serde::to_vec(&stamp).expect("a stamp encodes"), + )) +} + +/// What a STATUS of `peer` says, where a set carries this node's store: where the +/// peer's set stands is given to this node's, off the caller's task; and the status is +/// handed on saying this node's own stamp, so that what compares stamps for an +/// Automerge document's sake finds nothing to do. +pub(crate) fn heard_status( + state: &AppState, + peer: &str, + mut remote: transport::Status, +) -> transport::Status { + let Some(ours) = stamp(state) else { + return remote; + }; + if let HeadsSummary::Kind(bytes) = std::mem::replace(&mut remote.heads, ours) + && let Ok(stamp) = rmp_serde::from_slice::(&bytes) + { + let (state, peer) = (state.clone(), peer.to_owned()); + tokio::spawn(async move { + handle(&state, &peer, Message::Stamp(stamp)).await; + }); + } + remote +} + +/// What a SYNC of `peer` carries of its set, where a set carries this node's store. +pub(crate) async fn received(state: &AppState, peer: &str, body: Vec) { + match rmp_serde::from_slice::(&body) { + Ok(message) => handle(state, peer, message).await, + Err(error) => { + debug!(peer = %peer, error = %error, "What a peer says of its set doesn't read"); + } + } +} + +/// Gives `message` of `peer` to this node's set, sends the peer what the set says back, +/// and passes on what it took. +async fn handle(state: &AppState, peer: &str, message: Message) { + let holding = std::sync::Arc::clone(&state.holding); + // Taking events judges them: off the tasks that read messages. + let made = tokio::task::spawn_blocking(move || { + holding.change_set(|set| passing::receive(set, message, Instant::now())) + }) + .await; + let Ok(Some((replies, took))) = made else { + return; + }; + for reply in replies { + send(state, peer, &reply).await; + } + pass_on(state, Some(peer), took).await; +} + +/// Sends `peer` what this node's set says. +async fn send(state: &AppState, peer: &str, message: &Message) { + let (epoch, epoch_seq) = state.epoch_stamp(); + let envelope = transport::SyncEnvelope { + epoch: transport::EpochTag::of(epoch), + epoch_seq, + body: SyncBody::Kind(rmp_serde::to_vec(message).expect("a message encodes")), + ready: state.is_ready().await && !state.is_closing(), + writer: None, + delivered: false, + sent: state.clock.now_millis(), + signatures: serde_bytes::ByteBuf::new(), + }; + if let Err(error) = state + .transport + .send_message(peer, &ParsedMessage::Sync(envelope)) + .await + { + debug!(peer = %peer, error = %format!("{error:#}"), "Saying of our set failed"); + } +} + +/// Passes on what this node's set took, of `from` or of the node's own: to its other +/// neighbours, as units; and tells what waits on the store, or on who is a member. +async fn pass_on(state: &AppState, from: Option<&str>, took: Took) { + if took.is_empty() { + return; + } + state.notify_store_changed(); + // Entries are where members are reached, and events may change who is one. + state.topology_changed.notify_one(); + let names = took + .events + .iter() + .map(|id| id.0) + .chain(entry_names(state, &took.entries)); + let units: Vec = state + .holding + .with_set(|set| names.filter_map(|name| passing::unit(set, &name)).collect()) + .unwrap_or_default(); + if units.is_empty() { + return; + } + let message = Message::Units(units); + for peer in state.active_peers_on_local_epoch().await { + if Some(peer.as_str()) != from && topology::is_neighbour(state, &peer) { + send(state, &peer, &message).await; + } + } +} + +/// The names of the entries this node's set holds of `nodes`. +fn entry_names(state: &AppState, nodes: &[String]) -> Vec<[u8; 32]> { + state + .holding + .with_set(|set| { + nodes + .iter() + .filter_map(|node| set.entry(node).map(|entry| entry.name())) + .collect() + }) + .unwrap_or_default() +} + +/// Passes on events this node's set took of the node itself (the API, its own votes): +/// `taken`, by their names. +pub(crate) async fn wrote(state: &AppState, taken: Vec) { + pass_on( + state, + None, + Took { + events: taken, + entries: Vec::new(), + }, + ) + .await; +} + +/// Passes on this node's own entry, which its set just took. +pub(crate) async fn registered(state: &AppState) { + pass_on( + state, + None, + Took { + events: Vec::new(), + entries: vec![state.local_id().to_owned()], + }, + ) + .await; +} diff --git a/src/swarm/sync.rs b/src/swarm/sync.rs index c953752..5e736a1 100644 --- a/src/swarm/sync.rs +++ b/src/swarm/sync.rs @@ -63,6 +63,13 @@ async fn deliver_sync_to_peer(state: &AppState, peer: &str) -> Result<()> { } } + // A set of events is passed on otherwise (`swarm::set`): of the Automerge document + // a node holds beside one, nothing. + #[cfg(feature = "federation")] + if state.of_a_set() { + return Ok(()); + } + let we_ready = state.is_ready().await; let validated_swarm = { -- cgit v1.3.1 From 8017b0e69f0350c2a35629ae71d511ddf7a3aa9c Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 14:55:03 +0000 Subject: A node of a swarm holding a store, on a set of events (--store-document) With store-root or store-id, store-document names the file of the store's own document, a set of events: the node holds its store there and nothing in the Automerge document, syncs with nodes holding a set and no others, and goes on from the file when started again. Without a file yet it begins from the root (StoreStart::set); joining by the ID alone needs a file. What a checkpoint forgot is kept for store-keeps-forgotten (30 days). The file stands for store-file, and no checkpoint is pinned. The set is written to its file where it changed, every five seconds with the store's worker and as the node stops (Holding::save), what a checkpoint forgot longer ago let go of first. Simulations: a node behind catches up; a node goes on from its file. --- src/config/mod.rs | 41 +++++++++++++++++ src/federation/held.rs | 64 +++++++++++++++++++++++++- src/lib.rs | 33 ++++++++++++- src/simtest/holding.rs | 122 +++++++++++++++++++++++++++++++++++++++++++++++++ src/swarm/bootstrap.rs | 91 ++++++++++++++++++++++++++++++++++++ 5 files changed, 348 insertions(+), 3 deletions(-) (limited to 'src/federation') diff --git a/src/config/mod.rs b/src/config/mod.rs index efc190d..9c82673 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -215,6 +215,22 @@ pub(crate) const OPTIONS: &[OptionSpec] = &[ "With store-root or store-id: where the node keeps what is its own of its store across restarts, written whenever it changes: the events it refused by what it took before (of two versions changing one, the second), and those its operator had it drop. It reads its store anew from its document whenever it starts: without the file, it may then take what it refused. A file that doesn't read stops the node from starting.", ), #[cfg(feature = "federation")] + option( + "store-document", + Kind::Text, + "PATH", + None, + "With store-root or store-id: hold the store in a document of its own kind, a set of events (docs/document.md), kept in this file, instead of in the Automerge document a swarm syncs otherwise. The node then syncs with nodes holding such a set, and with no others: a swarm is of one kind. The file holds the store's events, what the node refused of its own and what its operator had it drop, and its members' entries; started again, the node goes on from it. Can't be combined with store-file, which the file stands for, nor with store-checkpoint.", + ), + #[cfg(feature = "federation")] + option( + "store-keeps-forgotten", + Kind::Duration, + "DURATION", + Some("30d"), + "With store-document: for how long the node keeps what a checkpoint its store moved to forgot, for nodes still before that checkpoint, which build it from that. A node behind for longer starts from a checkpoint its operator pins.", + ), + #[cfg(feature = "federation")] option( "store-checkpoint", Kind::Text, @@ -809,6 +825,14 @@ pub(crate) struct Settings { #[cfg(feature = "federation")] pub(crate) store_checkpoint: Option, #[cfg(feature = "federation")] + pub(crate) store_document: Option, + #[cfg(feature = "federation")] + #[serde( + default = "default_store_keeps_forgotten", + with = "crate::units::duration_option" + )] + pub(crate) store_keeps_forgotten: Duration, + #[cfg(feature = "federation")] pub(crate) store_party: Option, #[cfg(feature = "federation")] #[serde(default)] @@ -1070,6 +1094,10 @@ fn default_neighbours() -> usize { fn default_electorate_window() -> Duration { Duration::from_secs(7 * 24 * 3600) } +#[cfg(feature = "federation")] +fn default_store_keeps_forgotten() -> Duration { + Duration::from_secs(30 * 24 * 3600) +} fn default_clock_skew_warn() -> Duration { Duration::from_secs(2) } @@ -1332,6 +1360,7 @@ impl Settings { let of_a_store = [ ("store-file", self.store_file.is_some()), ("store-checkpoint", self.store_checkpoint.is_some()), + ("store-document", self.store_document.is_some()), ("store-party", self.store_party.is_some()), ("store-readers", !self.store_readers.is_empty()), ( @@ -1355,6 +1384,16 @@ impl Settings { return Ok(()); } }; + if self.store_document.is_some() { + if self.store_file.is_some() { + bail!("store-document holds what store-file would: unset store-file"); + } + if self.store_checkpoint.is_some() { + bail!( + "store-document: a set of events starts from its root or from its file, from no pinned checkpoint: unset store-checkpoint" + ); + } + } match &self.store_party { None => bail!( "{store}: set store-party, the party this node is of: in a swarm holding a store, nodes sync with the nodes its parties list, each as its party's" @@ -1482,6 +1521,8 @@ impl Settings { #[cfg(feature = "federation")] ("store-checkpoint", self.store_checkpoint.is_some()), #[cfg(feature = "federation")] + ("store-document", self.store_document.is_some()), + #[cfg(feature = "federation")] ("store-party", self.store_party.is_some()), #[cfg(feature = "federation")] ("store-readers", !self.store_readers.is_empty()), diff --git a/src/federation/held.rs b/src/federation/held.rs index cd53727..fd43062 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -111,6 +111,10 @@ pub(crate) struct Holding { members: RwLock>>, /// What it votes for its party with, if it votes by itself. voter: Option, + /// Where the set of events carrying the store is kept (`--store-document`), if it + /// is; and how it stood as it was last written there. + document: Option<(PathBuf, Arc)>, + written: Mutex>, /// Whether a set of events carries the store (`carrying`), from the node's start on. of_a_set: bool, // A std mutex: never held while waiting for the document. @@ -264,6 +268,8 @@ impl Holding { members: RwLock::default(), voter: None, of_a_set: false, + document: None, + written: Mutex::default(), inner: Mutex::new(Inner { kept, ..Inner::default() @@ -1034,6 +1040,51 @@ impl Holding { self } + /// Itself, its store carried by `set` and kept in the file at `path`, where the node + /// is given a set. + pub(crate) fn carrying_if( + self, + set: Option>, + path: Option, + files: Arc, + ) -> Self { + match (set, path) { + (Some(set), Some(path)) => self.carrying(set).kept_in(path, files), + (Some(set), None) => self.carrying(set), + (None, _) => self, + } + } + + /// Itself, keeping the set of events that carries its store in the file at `path`. + pub(crate) fn kept_in(mut self, path: PathBuf, files: Arc) -> Self { + self.document = Some((path, files)); + self + } + + /// Lets go of what a checkpoint forgot longer ago than the set keeps it, and + /// writes the set to its file where it changed since it was last written. + /// Whether it wrote. + pub(crate) fn save(&self) -> std::io::Result { + let Some((path, files)) = &self.document else { + return Ok(false); + }; + let now = Instant::now(); + self.change_set(|set| set.expire(now)); + let mut written = self.written.lock_or_recover(); + let Some((stands, bytes)) = self + .with_set(|set| { + let stands = super::store::passing::stamp(set); + (Some(stands) != *written).then(|| (stands, set.save(now))) + }) + .flatten() + else { + return Ok(false); + }; + files.write_atomic(FileKind::Store, path, &bytes)?; + *written = Some(stands); + Ok(true) + } + /// The kind of the document that carries the store: a set of events, or the /// document the node holds, which the store is read from. pub(crate) fn kind(&self) -> &'static str { @@ -1314,7 +1365,18 @@ pub(crate) async fn run_worker(state: crate::state::AppState) { } } } - _ = looks.tick() => look = true, + _ = looks.tick() => { + look = true; + // A set of events to its file, where it changed (`Holding::save`). + if state.of_a_set() { + let holding = Arc::clone(&state.holding); + if let Ok(Err(error)) = + tokio::task::spawn_blocking(move || holding.save()).await + { + error!(error = %error, "Couldn't write the store's document: a restart goes on from what the file holds"); + } + } + } } } } diff --git a/src/lib.rs b/src/lib.rs index da106b9..8b56399 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -221,11 +221,29 @@ pub async fn run() -> Result<()> { #[cfg(feature = "federation")] let store = bootstrap::StoreStart::of(args.store_root.as_deref(), args.store_id.as_deref(), &files)?; + // Its store's own document, a set of events (`--store-document`): from its file, + // or from the root. + #[cfg(feature = "federation")] + let set = match (&store, &args.store_document) { + (Some(store), Some(path)) => Some(store.set(path, &files, args.store_keeps_forgotten)?), + _ => None, + }; #[cfg(feature = "federation")] let starting = match &store { - Some(store) => { + Some(store) if set.is_none() => { store.starting(starting, remembered.as_ref().map(|r| r.swarm_id.as_str()))? } + // A set is the store's document: the one a swarm syncs otherwise stays empty. + Some(store) => { + let swarm_id = store.swarm_id(); + if let Some(remembered) = remembered.as_ref().filter(|r| r.swarm_id != swarm_id) { + anyhow::bail!( + "The state file remembers swarm {}, not the store's ({swarm_id}): give the store's state file, or another", + remembered.swarm_id + ); + } + None + } None => starting, }; let ( @@ -372,7 +390,8 @@ pub async fn run() -> Result<()> { args.store_party.clone(), )? .near(args.store_neighbour_parties.clone()) - .voting(voter(args)?), + .voting(voter(args)?) + .carrying_if(set, args.store_document.clone(), Arc::clone(&files)), strict_keys: args .strict_keys .iter() @@ -394,7 +413,13 @@ pub async fn run() -> Result<()> { // Join the remembered swarm and no other; HELLOs claim it. A document to start on // names its swarm itself (checked against the remembered one above). + #[cfg(feature = "federation")] + let of_a_set = state.of_a_set(); + #[cfg(not(feature = "federation"))] + let of_a_set = false; let start = match starting_swarm { + // A set of events is what the node starts on: its store's swarm (`bootstrap`). + _ if of_a_set => bootstrap::Start::FromDocument(bootstrap::Origin::Root), Some((swarm_id, origin)) => { state.set_expected_swarm_id(swarm_id).await?; bootstrap::Start::FromDocument(origin) @@ -486,6 +511,10 @@ pub async fn run() -> Result<()> { swarm::state_file::update(&state, true).await; swarm::document_file::flush(&state).await; swarm::document_file::close(&state).await; + #[cfg(feature = "federation")] + if let Err(error) = state.holding.save() { + tracing::error!(error = %error, "Couldn't write the store's document as the node stops"); + } Ok(()) } diff --git a/src/simtest/holding.rs b/src/simtest/holding.rs index 4a8098b..6da7a90 100644 --- a/src/simtest/holding.rs +++ b/src/simtest/holding.rs @@ -1806,3 +1806,125 @@ async fn a_swarm_of_sets_passes_entries_and_events_on() { assert!(node.doc.read().await.heads().is_empty()); } } + +/// Starts `name`, of `party`, on a set of events `set`, kept in the file at `path` where +/// given: the first of them with no seed, the others seeded by `a`. +fn start_on_a_set( + sim: &Sim, + name: &str, + party: &str, + id: Id, + set: crate::federation::store::set::Set, + path: Option, + restart: bool, +) -> AppState { + let seeds: Vec<&str> = if name == "a" { Vec::new() } else { vec!["a"] }; + let party = party.to_owned(); + let adjust = move |config: &mut NodeConfig| { + config.store = Some(id); + config.holding = holding(&party).carrying_if(Some(set), path, Arc::new(Files::default())); + }; + if restart { + sim.restart_with(name, &seeds, Start::FromDocument(Origin::Root), adjust) + } else { + sim.start_with(name, &seeds, Start::FromDocument(Origin::Root), adjust) + } +} + +/// A set of events begun from `root`. +fn a_set(root: &[u8]) -> crate::federation::store::set::Set { + crate::federation::store::set::Set::new( + Store::::new(root.to_vec(), Vec::new()).expect("a root"), + Duration::from_secs(600), + ) +} + +/// a and b hold events; c, of another party, starts later from the root alone, and +/// catches up: it comes to hold what they hold, and to stand as they do. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_node_of_a_set_that_is_behind_catches_up() { + let sim = Sim::with_identity(92); + let (tv, lass, _) = three(); + let (_, root, id) = federation(&[(&tv, &["a", "b"]), (&lass, &["c"])]); + let a = start_on_a_set(&sim, "a", "tv", id, a_set(&root), None, false); + let b = start_on_a_set(&sim, "b", "tv", id, a_set(&root), None, false); + sim.wait_ready(&[&a, &b], SOON).await; + // A chain of writes, each on the one before. + let mut on = id; + let mut ids = Vec::new(); + for n in 0..30 { + let write = tv.write(&[on], "home/tv/x", s(&n.to_string())); + on = Id::of(&write); + ids.push(on); + put(&a, &[&write]).await; + } + let (first, ids) = (&[&a, &b], &ids); + sim.wait_until("a and b hold the writes", SOON, move || async move { + first.iter().all(|node| holds(node, ids)) + }) + .await; + + let c = start_on_a_set(&sim, "c", "lass", id, a_set(&root), None, false); + let all = &[&a, &b, &c]; + sim.wait_until("c holds them too", SOON, move || async move { + holds(all[2], ids) + }) + .await; + sim.wait_until("all stand alike", SOON, move || async move { + let first = stands(all[0]); + first.is_some() && all.iter().all(|node| stands(node) == first) && entries(all[2]) == 3 + }) + .await; +} + +/// A node keeps its set in a file, written as the set changes; started again on what +/// the file holds, it holds what it held, the others' entries among it, before it hears +/// of anyone. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_node_of_a_set_goes_on_from_its_file() { + let sim = Sim::with_identity(93); + let (tv, _, _) = three(); + let (_, root, id) = federation(&[(&tv, &["a", "b"])]); + let dir = crate::files::scratch_dir("set-file"); + let path = dir.join("b.events"); + let a = start_on_a_set(&sim, "a", "tv", id, a_set(&root), None, false); + let b = start_on_a_set(&sim, "b", "tv", id, a_set(&root), Some(path.clone()), false); + sim.wait_ready(&[&a, &b], SOON).await; + let write = tv.write(&[id], "home/tv/x", s("1")); + let ids = [Id::of(&write)]; + put(&a, &[&write]).await; + let (nodes, ids) = (&[&a, &b], &ids); + sim.wait_until( + "both hold the write and both entries", + SOON, + move || async move { + nodes + .iter() + .all(|node| holds(node, ids) && entries(node) == 2) + }, + ) + .await; + assert!(b.holding.save().expect("written") || path.exists()); + + let bytes = std::fs::read(&path).expect("the set's file"); + let set = crate::federation::store::set::Set::::load( + &bytes, + Duration::from_secs(600), + std::time::Instant::now(), + ) + .expect("a set"); + let b = start_on_a_set(&sim, "b", "tv", id, set, Some(path), true); + // What the file held, at once. + assert!(holds(&b, ids)); + assert_eq!(entries(&b), 2); + // And it goes on: a write put on it reaches a. + sim.wait_ready(&[&b], SOON).await; + let next = tv.write(&[ids[0]], "home/tv/x", s("2")); + let next_id = [Id::of(&next)]; + put(&b, &[&next]).await; + let (a, next_id) = (&a, &next_id); + sim.wait_until("a holds what b wrote after", SOON, move || async move { + holds(a, next_id) + }) + .await; +} diff --git a/src/swarm/bootstrap.rs b/src/swarm/bootstrap.rs index 24da958..9d29c5b 100644 --- a/src/swarm/bootstrap.rs +++ b/src/swarm/bootstrap.rs @@ -322,6 +322,53 @@ impl StoreStart { })) } + /// The store's own document, a set of events (`--store-document`), kept in the file + /// at `path`: as the file has it, where there is one, which must be this store's; + /// else begun from the root, which the node must be given then. What a checkpoint + /// forgot is kept for `keeps`. + pub(crate) fn set( + &self, + path: &Path, + files: &Files, + keeps: std::time::Duration, + ) -> Result> { + use crate::federation::fold::Federation; + use crate::federation::store::{memory::Store, set::Set}; + let now = std::time::Instant::now(); + let held = files + .read(FileKind::Store, path) + .with_context(|| format!("Reading the store's document {}", path.display()))?; + if let Some(bytes) = held { + let set = Set::::load(&bytes, keeps, now).map_err(|refused| { + anyhow::anyhow!( + "The store's document {} doesn't read ({}): move it away only knowing the node then starts from the root, and may take what it refused", + path.display(), + refused.0 + ) + })?; + if set.store().id() != self.id { + bail!( + "The store's document {} is of store {}, not {}", + path.display(), + set.store().id(), + self.id + ); + } + info!(swarm_id = %self.id, path = %path.display(), "Going on with the store's document"); + return Ok(set); + } + let Some((root, kept)) = &self.root else { + bail!( + "store-document {} doesn't exist, and store-id names no root to begin it from: give the store's root (store-root)", + path.display() + ); + }; + let store = Store::::new(root.clone(), kept.clone()) + .map_err(|refused| anyhow::anyhow!("The store's root is none: {}", refused.0))?; + info!(swarm_id = %self.id, "Starting the swarm holding the store from its root, as a set of events (--store-document)"); + Ok(Set::new(store, keeps)) + } + /// The swarm's ID: the root's, in hex. pub(crate) fn swarm_id(&self) -> String { self.id.to_string() @@ -651,6 +698,50 @@ mod tests { assert!(joining.starting(None, None).unwrap().is_none()); } + #[cfg(feature = "federation")] + #[test] + fn a_stores_document_is_begun_from_the_root_or_gone_on_with() { + use crate::federation::harness::{self, Party, Spec}; + use crate::federation::store::memory::Offered; + use std::time::{Duration, Instant}; + + let tv = Party::new("tv", 1); + let root = Spec::first(&[&tv], &[]).root(); + let id = Id::of(&root); + let store = StoreStart { + id, + root: Some((root.clone(), Vec::new())), + }; + let joining = StoreStart { id, root: None }; + let dir = crate::files::scratch_dir("store-document"); + let path = dir.join("store.events"); + let files = Files::default(); + let keeps = Duration::from_secs(60); + // No file: from the root, which joining by the ID alone doesn't give. + assert!(joining.set(&path, &files, keeps).is_err()); + let mut set = store.set(&path, &files, keeps).unwrap(); + let write = tv.write(&[id], "home/tv/a", harness::str("1")); + assert!(matches!( + set.offer(write.clone(), Instant::now()), + Offered::Taken(_) + )); + std::fs::write(&path, set.save(Instant::now())).unwrap(); + // A file: gone on with, the root given or not. + for start in [&store, &joining] { + let read = start.set(&path, &files, keeps).unwrap(); + assert_eq!(read.store().taken(), &[Id::of(&write)]); + } + // Of another store, or no document: refused. + let other_root = Spec::first(&[&Party::new("lass", 2)], &[]).root(); + let other = StoreStart { + id: Id::of(&other_root), + root: Some((other_root, Vec::new())), + }; + assert!(other.set(&path, &files, keeps).is_err()); + std::fs::write(&path, b"something else").unwrap(); + assert!(store.set(&path, &files, keeps).is_err()); + } + /// A fork's root, and the event it keeps on a line of its own: the swarm starts from /// the changes founding it. Without that event: no store's root. #[test] -- cgit v1.3.1 From bb860d2cf0adad80016edb7a7baed4df291b828c Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 14:59:37 +0000 Subject: federation: what a set hands the node to read is as a store's document Beside its members' entries, the policy of a swarm holding a store and the swarm's ID (Holding::entries): what reads a document for them reads the same of a node on a set. Tokens are checked against it (api::login): their issuer's entry is there, and a node takes none another issued, as the policy says; read of the empty Automerge document beside, every token was refused. --- src/api/login.rs | 26 ++++++++++++++------------ src/federation/held.rs | 27 +++++++++++++++++++++++---- src/state/mod.rs | 3 ++- 3 files changed, 39 insertions(+), 17 deletions(-) (limited to 'src/federation') diff --git a/src/api/login.rs b/src/api/login.rs index e442ea2..a5bfde5 100644 --- a/src/api/login.rs +++ b/src/api/login.rs @@ -115,10 +115,12 @@ pub(crate) async fn bearer( let now = state.clock.now_millis().as_u64(); let verified = { let replica = state.doc.read().await; - let verified = token::verify(&replica.doc, &text, &swarm, now); + let entries = state.entries(); + let listed = crate::document::view::members_of(&entries, &replica.doc); + let verified = token::verify(listed, &text, &swarm, now); #[cfg(feature = "federation")] let verified = - verified.and_then(|claims| token::issued_here(&replica.doc, state.local_id(), claims)); + verified.and_then(|claims| token::issued_here(listed, state.local_id(), claims)); verified } .and_then(|claims| { @@ -559,17 +561,17 @@ async fn credentials_end( /// sessions. async fn refused_now(state: &AppState, who: &Credentials) -> Option { let replica = state.doc.read().await; + let entries = state.entries(); + let listed = crate::document::view::members_of(&entries, &replica.doc); match who { - Credentials::Token(claims) => { - token::still_taken(&replica.doc, claims).err().or_else(|| { - state - .ended_sessions - .lock_or_recover() - .contains_key(&claims.session) - .then_some(token::Refused::Ended) - }) - } - Credentials::User(user) => token::user_taken(&replica.doc, user).err(), + Credentials::Token(claims) => token::still_taken(listed, claims).err().or_else(|| { + state + .ended_sessions + .lock_or_recover() + .contains_key(&claims.session) + .then_some(token::Refused::Ended) + }), + Credentials::User(user) => token::user_taken(listed, user).err(), } } diff --git a/src/federation/held.rs b/src/federation/held.rs index fd43062..bb34407 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -1108,13 +1108,23 @@ impl Holding { } } - /// The members' entries as the node reads them of a document, each at - /// `_continuum/members/`, where a set of events carries the store: the - /// document's place for them, which a set keeps apart. + /// What the node reads of its document at paths, where a set of events carries the + /// store: what a document holding a store has there. The members' entries, each at + /// `_continuum/members/`, which a set keeps apart; the policy of a swarm + /// holding a store; and the swarm's ID, the store's. pub(crate) fn entries(&self) -> Option { use crate::document::view::{Tree, Write}; self.with_set(|set| { let mut tree = Tree::new(); + // Into a tree of maps alone: nothing is in the way of any of it. + let _ = tree.write_path( + &crate::access::policy::path(), + &events::policy(Federation::NAME), + ); + let _ = tree.write_path( + &meta::path(&[meta::SWARM]), + &serde_json::Value::String(set.store().id().to_string()), + ); for entry in set.entries() { if let Some(value) = entry.value() { let path = [ @@ -1122,7 +1132,6 @@ impl Holding { meta::MEMBERS.to_owned(), entry.node(), ]; - // Into a tree of maps alone: nothing is in the way. let _ = tree.write_path(&path, &serde_json::Value::Object(value)); } } @@ -2966,6 +2975,16 @@ mod tests { Some("tv".to_owned()) ); assert!(holding.member(&key.id(), Some("tv")) == Some(true)); + // And the rest a document holding a store has for the node to read: the + // policy, by which a node takes no token another issued, and the swarm's ID. + assert!(matches!( + crate::access::policy::of(&tree), + crate::access::policy::Policy::Store(_) + )); + assert_eq!( + crate::document::view::read_path(&tree, &meta::path(&[meta::SWARM])).unwrap(), + Some(serde_json::Value::String(Id::of(&root).to_string())) + ); assert!(Holding::default().entries().is_none()); } } diff --git a/src/state/mod.rs b/src/state/mod.rs index d512b2b..21478de 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -404,7 +404,8 @@ impl AppState { } } - /// The members' entries as a document has them, where this node's document keeps + /// What the node reads of a document at paths (its members, the policy, the swarm's + /// ID), where this node's document keeps /// them apart (a set of events, `Holding::entries`): none, where they are in the /// document it holds. pub(crate) fn entries(&self) -> Option { -- cgit v1.3.1 From 5e92406ba1da8a58455420a10a9dd5ca963fa8f3 Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 15:12:04 +0000 Subject: A node joins a swarm of sets with nothing but the store's ID Given store-id and store-document, no file yet and no root, or a checkpoint pinned (store-checkpoint), a node starts with nothing of its store (held::Begun::Start, passing::Start): it asks the members whose handshake it took for the checkpoint named by the store's ID, its root, or by the pin, then for the events that one keeps, each taken only as what its name says; begins its set from them; and is ready, catching up as any node behind. A set gives the checkpoint its store holds by its name (passing::Unit::Checkpoint). A simulation: a node given the ID alone joins two that hold a write. --- src/config/mod.rs | 13 +-- src/federation/held.rs | 71 ++++++++++++++-- src/federation/store/passing.rs | 179 +++++++++++++++++++++++++++++++++++++++- src/lib.rs | 11 ++- src/simtest/holding.rs | 57 ++++++++++++- src/swarm/bootstrap.rs | 81 ++++++++++++------ src/swarm/set.rs | 59 +++++++++++-- 7 files changed, 416 insertions(+), 55 deletions(-) (limited to 'src/federation') diff --git a/src/config/mod.rs b/src/config/mod.rs index 9c82673..5a723c7 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -220,7 +220,7 @@ pub(crate) const OPTIONS: &[OptionSpec] = &[ Kind::Text, "PATH", None, - "With store-root or store-id: hold the store in a document of its own kind, a set of events (docs/document.md), kept in this file, instead of in the Automerge document a swarm syncs otherwise. The node then syncs with nodes holding such a set, and with no others: a swarm is of one kind. The file holds the store's events, what the node refused of its own and what its operator had it drop, and its members' entries; started again, the node goes on from it. Can't be combined with store-file, which the file stands for, nor with store-checkpoint.", + "With store-root or store-id: hold the store in a document of its own kind, a set of events (docs/document.md), kept in this file, instead of in the Automerge document a swarm syncs otherwise. The node then syncs with nodes holding such a set, and with no others: a swarm is of one kind. The file holds the store's events, what the node refused of its own and what its operator had it drop, and its members' entries; started again, the node goes on from it. Without the file yet, the node begins it from the root where it is given one (store-root) and pins no checkpoint; else it joins with nothing, and gathers of the members it reaches what its set begins from, by name: the root, or the checkpoint store-checkpoint names. Can't be combined with store-file, which the file stands for.", ), #[cfg(feature = "federation")] option( @@ -1384,15 +1384,8 @@ impl Settings { return Ok(()); } }; - if self.store_document.is_some() { - if self.store_file.is_some() { - bail!("store-document holds what store-file would: unset store-file"); - } - if self.store_checkpoint.is_some() { - bail!( - "store-document: a set of events starts from its root or from its file, from no pinned checkpoint: unset store-checkpoint" - ); - } + if self.store_document.is_some() && self.store_file.is_some() { + bail!("store-document holds what store-file would: unset store-file"); } match &self.store_party { None => bail!( diff --git a/src/federation/held.rs b/src/federation/held.rs index bb34407..51d8ef0 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -130,6 +130,13 @@ pub(crate) struct Voter { pub(crate) rules: Rules, } +/// A set of events as a node starts with it: held, from its file or begun from the +/// root; or still to be gathered of its peers, where the node was given neither. +pub(crate) enum Begun { + Set(Box>), + Start(super::store::passing::Start), +} + /// What carries the store: a document it is read from, or a set of events, which is /// the store's own document (`store::set`). enum Carried { @@ -175,6 +182,9 @@ impl Carried { struct Inner { /// None until a document holding a store holds its root. store: Option, + /// A set of events to be, where the node started with nothing of its store and + /// gathers what its set begins from of its peers (`store::passing::Start`). + starting: Option>, /// The document read from (`Replica::epoch_seq`), and its events read. epoch_seq: Option, read: HashSet, @@ -1040,18 +1050,65 @@ impl Holding { self } - /// Itself, its store carried by `set` and kept in the file at `path`, where the node - /// is given a set. + /// Itself, its store to be carried by a set of events it has nothing of yet: what + /// `start` gathers of its peers (`swarm::set`). + pub(crate) fn awaiting(mut self, start: super::store::passing::Start) -> Self { + self.of_a_set = true; + self.inner.lock_or_recover().starting = Some(start); + self + } + + /// The names a node that started with nothing asks a peer for, to begin its set + /// from; none, once it holds one. + pub(crate) fn start_wants(&self) -> Vec { + self.inner + .lock_or_recover() + .starting + .as_ref() + .map(|start| start.wants()) + .unwrap_or_default() + } + + /// Takes what a peer sent a node that started with nothing. Whether it holds its + /// set by it. + pub(crate) fn start_take(&self, units: Vec) -> bool { + let mut inner = self.inner.lock_or_recover(); + let Some(set) = inner.starting.as_mut().and_then(|start| start.take(units)) else { + return false; + }; + info!(store = %set.store().id(), "Begun the store's set from what peers gave by name"); + inner.starting = None; + inner.store = Some(Carried::Set(Box::new(set))); + self.settle(&mut inner); + true + } + + /// The store the node holds, or is to hold once it has gathered its set: by its ID. + pub(crate) fn store_id(&self) -> Option { + let inner = self.inner.lock_or_recover(); + inner + .store + .as_ref() + .map(|store| store.id()) + .or_else(|| inner.starting.as_ref().map(|start| start.store())) + } + + /// Itself, its store carried by the set `begun`, held or to be, and kept in the + /// file at `path`; itself, where the node is given no set. pub(crate) fn carrying_if( self, - set: Option>, + begun: Option, path: Option, files: Arc, ) -> Self { - match (set, path) { - (Some(set), Some(path)) => self.carrying(set).kept_in(path, files), - (Some(set), None) => self.carrying(set), - (None, _) => self, + let holding = match begun { + Some(Begun::Set(set)) => self.carrying(*set), + Some(Begun::Start(start)) => self.awaiting(start), + None => return self, + }; + match path { + Some(path) => holding.kept_in(path, files), + None => holding, } } diff --git a/src/federation/store/passing.rs b/src/federation/store/passing.rs index 5a6e2af..88e66a4 100644 --- a/src/federation/store/passing.rs +++ b/src/federation/store/passing.rs @@ -15,12 +15,15 @@ //! the store, or put as an entry; and for what the store then waits on and doesn't //! hold, the node asks in turn, back to what both hold. -use std::time::Instant; +use std::collections::BTreeMap; +use std::time::{Duration, Instant}; use serde::{Deserialize, Serialize}; use super::entry::Entry; +use super::Refused; +use super::memory::Store; use super::set::{Put, Set}; use super::{Fold, Id}; use crate::document::ranges::{self, Name}; @@ -45,6 +48,9 @@ pub(crate) struct Stamp { pub(crate) enum Unit { Event(#[serde(with = "serde_bytes")] Vec), Entry(#[serde(with = "serde_bytes")] Vec), + /// The checkpoint the sender's store holds, a root among them: for a node that + /// starts with nothing but its name (`Start`). + Checkpoint(#[serde(with = "serde_bytes")] Vec), } /// What one node says to another of its set. @@ -62,6 +68,100 @@ pub(crate) enum Message { Units(Vec), } +/// A set to be: what a node that starts with nothing gathers of its peers, to begin +/// its store's set from (`docs/document.md`, A set of events, Passing on). It knows its +/// store by its ID, and where it starts by a name: the store's root, which is the +/// store's ID, or a checkpoint its operator pins. It asks for the checkpoint of that +/// name, then for the events that one keeps; each is what its name says, or not +/// taken. +pub(crate) struct Start { + store: Id, + at: Id, + keeps_forgotten: Duration, + /// The checkpoint named `at`, once it came, and the events it keeps, by name. + checkpoint: Option<(Vec, Vec)>, + kept: BTreeMap>, + fold: std::marker::PhantomData, +} + +impl Start { + /// A set of the store `store` to be, starting at the checkpoint named `at`. + pub(crate) fn new(store: Id, at: Id, keeps_forgotten: Duration) -> Self { + Self { + store, + at, + keeps_forgotten, + checkpoint: None, + kept: BTreeMap::new(), + fold: std::marker::PhantomData, + } + } + + /// The store it is to hold. + pub(crate) fn store(&self) -> Id { + self.store + } + + /// The names it asks a peer for now. + pub(crate) fn wants(&self) -> Vec { + match &self.checkpoint { + None => vec![self.at.0], + Some((_, keeps)) => keeps + .iter() + .filter(|id| !self.kept.contains_key(id)) + .map(|id| id.0) + .take(NAMES) + .collect(), + } + } + + /// Takes what a peer sent of what it asked for. The set, once it has all it + /// begins from; a checkpoint that is none of the fold's, or that the store doesn't + /// begin from, is let go of, to be asked for again. + pub(crate) fn take(&mut self, units: Vec) -> Option> { + for unit in units { + match unit { + Unit::Checkpoint(bytes) + if self.checkpoint.is_none() && Id::of(&bytes) == self.at => + { + if let Some((_, keeps)) = F::parts(&bytes) { + self.checkpoint = Some((bytes, keeps)); + } + } + Unit::Event(bytes) if bytes.len() <= F::LARGEST => { + let id = Id::of(&bytes); + let kept = self + .checkpoint + .as_ref() + .is_some_and(|(_, keeps)| keeps.contains(&id)); + if kept { + self.kept.insert(id, bytes); + } + } + _ => {} + } + } + let (checkpoint, keeps) = self.checkpoint.as_ref()?; + if keeps.iter().any(|id| !self.kept.contains_key(id)) { + return None; + } + let kept: Vec> = self.kept.values().cloned().collect(); + let store: Result, Refused> = if self.at == self.store { + Store::new(checkpoint.clone(), kept) + } else { + Store::pinned(self.store, checkpoint.clone(), kept) + }; + match store { + Ok(store) => Some(Set::new(store, self.keeps_forgotten)), + Err(_) => { + self.checkpoint = None; + self.kept.clear(); + None + } + } + } +} + /// What a node took of a message. #[derive(Debug, Default, PartialEq, Eq)] pub(crate) struct Took { @@ -85,8 +185,13 @@ pub(crate) fn stamp(set: &Set) -> Stamp { } } -/// The unit named `name`, where `set` holds it. +/// The unit named `name`, where `set` holds it: an event, an entry, or the checkpoint +/// its store holds. pub(crate) fn unit(set: &Set, name: &Name) -> Option { + let checkpoint = set.store().checkpoint(); + if Id::of(checkpoint).0 == *name { + return Some(Unit::Checkpoint(checkpoint.to_vec())); + } set.get(&Id(*name)) .map(|bytes| Unit::Event(bytes.to_vec())) .or_else(|| { @@ -130,7 +235,9 @@ pub(crate) fn receive( continue; }; let size = match &unit { - Unit::Event(bytes) | Unit::Entry(bytes) => bytes.len(), + Unit::Event(bytes) | Unit::Entry(bytes) | Unit::Checkpoint(bytes) => { + bytes.len() + } }; // What doesn't fit, the peer asks for again. if bytes + size > BYTES && !units.is_empty() { @@ -152,6 +259,8 @@ pub(crate) fn receive( match unit { Unit::Event(bytes) => events.push(bytes), Unit::Entry(bytes) => entries.push(bytes), + // A node holding a set built its checkpoint itself. + Unit::Checkpoint(_) => {} } } took.events = set.offer_all(events, now); @@ -375,7 +484,7 @@ mod tests { let sizes: Vec = units .iter() .map(|unit| match unit { - Unit::Event(bytes) | Unit::Entry(bytes) => bytes.len(), + Unit::Event(bytes) | Unit::Entry(bytes) | Unit::Checkpoint(bytes) => bytes.len(), }) .collect(); assert!(sizes.iter().sum::() <= BYTES); @@ -430,4 +539,66 @@ mod tests { ); } } + + #[test] + fn a_node_with_nothing_begins_its_set_from_what_peers_give_by_name() { + // A store that moved to a checkpoint, which keeps an event. + let mut ahead = set(); + let now = Instant::now(); + let root = ahead.store().id(); + let first = testfold::put(&[root], "a", "1"); + let first_id = Id::of(&first); + let second = testfold::put(&[first_id], "a", "2"); + let second_id = Id::of(&second); + let lock = testfold::lock(&[second_id], "b"); + let lock_id = Id::of(&lock); + let cut = testfold::cut(&[lock_id], 1, &[lock_id]); + for event in [first, second, lock, cut.clone()] { + assert!(matches!(ahead.offer(event, now), Offered::Taken(_))); + } + let pinned = Id::of(ahead.store().checkpoint()); + assert_ne!(pinned, root); + + // From the root: the checkpoint named by the store's ID, were it still held. + let mut from_root = Start::::new(root, root, KEEPS); + assert_eq!(from_root.wants(), vec![root.0]); + assert_eq!(unit(&ahead, &root.0), None); + let fresh = set(); + let Some(Unit::Checkpoint(bytes)) = unit(&fresh, &root.0) else { + panic!("no root"); + }; + let begun = from_root + .take(vec![Unit::Checkpoint(bytes)]) + .expect("a set, the root keeping nothing"); + assert_eq!(begun.store().id(), root); + + // From a checkpoint its operator pins: that, then what it keeps. + let mut start = Start::::new(root, pinned, KEEPS); + assert_eq!(start.wants(), vec![pinned.0]); + // What isn't what its name says isn't taken. + assert!( + start + .take(vec![Unit::Checkpoint(b"another".to_vec())]) + .is_none() + ); + assert_eq!(start.wants(), vec![pinned.0]); + let checkpoint = unit(&ahead, &pinned.0).expect("its checkpoint"); + assert!(matches!(checkpoint, Unit::Checkpoint(_))); + assert!(start.take(vec![checkpoint]).is_none()); + let wanted = start.wants(); + assert!(!wanted.is_empty() && !wanted.contains(&pinned.0)); + let kept: Vec = wanted + .iter() + .map(|name| unit(&ahead, name).expect("kept")) + .collect(); + let begun = start.take(kept).expect("a set"); + assert_eq!(begun.store().id(), root); + assert_eq!(begun.store().checkpoint(), ahead.store().checkpoint()); + // And it goes on as any set: what the other holds after the checkpoint comes. + let mut sets = [ahead, begun]; + let mut rng = Rng::new(9); + settle(&mut sets, &mut rng, now); + assert!(sets[1].store().get(&Id::of(&cut)).is_some()); + assert_eq!(sets[1].store().taken(), sets[0].store().taken()); + } } diff --git a/src/lib.rs b/src/lib.rs index 8b56399..d4989ab 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -225,7 +225,16 @@ pub async fn run() -> Result<()> { // or from the root. #[cfg(feature = "federation")] let set = match (&store, &args.store_document) { - (Some(store), Some(path)) => Some(store.set(path, &files, args.store_keeps_forgotten)?), + (Some(store), Some(path)) => Some( + store.set( + path, + &files, + args.store_checkpoint + .as_deref() + .and_then(federation::store::Id::from_hex), + args.store_keeps_forgotten, + )?, + ), _ => None, }; #[cfg(feature = "federation")] diff --git a/src/simtest/holding.rs b/src/simtest/holding.rs index 6da7a90..66d5d15 100644 --- a/src/simtest/holding.rs +++ b/src/simtest/holding.rs @@ -1822,7 +1822,11 @@ fn start_on_a_set( let party = party.to_owned(); let adjust = move |config: &mut NodeConfig| { config.store = Some(id); - config.holding = holding(&party).carrying_if(Some(set), path, Arc::new(Files::default())); + config.holding = holding(&party).carrying_if( + Some(held::Begun::Set(Box::new(set))), + path, + Arc::new(Files::default()), + ); }; if restart { sim.restart_with(name, &seeds, Start::FromDocument(Origin::Root), adjust) @@ -1928,3 +1932,54 @@ async fn a_node_of_a_set_goes_on_from_its_file() { }) .await; } + +/// a and b hold the store and a write; c is given the store's ID alone, and nothing of +/// the store: it asks the members it reaches for the root by its name, begins its set +/// from it, and catches up as any node behind. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_node_of_a_set_joins_with_nothing_but_the_stores_id() { + use crate::federation::store::passing; + + let sim = Sim::with_identity(94); + let (tv, lass, _) = three(); + let (_, root, id) = federation(&[(&tv, &["a", "b"]), (&lass, &["c"])]); + let a = start_on_a_set(&sim, "a", "tv", id, a_set(&root), None, false); + let b = start_on_a_set(&sim, "b", "tv", id, a_set(&root), None, false); + sim.wait_ready(&[&a, &b], SOON).await; + let write = tv.write(&[id], "home/tv/x", s("1")); + let ids = [Id::of(&write)]; + put(&a, &[&write]).await; + + let c = sim.start_with( + "c", + &["a"], + Start::FromDocument(Origin::Root), + move |config| { + config.store = Some(id); + config.holding = holding("lass").carrying_if( + Some(held::Begun::Start(passing::Start::new( + id, + id, + Duration::from_secs(600), + ))), + None, + Arc::new(Files::default()), + ); + }, + ); + assert_eq!(c.kind(), crate::federation::store::set::KIND); + assert!(read(&c, |_| ()).is_none()); + sim.wait_ready(&[&c], SOON).await; + let (all, ids) = (&[&a, &b, &c], &ids); + sim.wait_until( + "c holds the store, the write and the entries", + SOON, + move || async move { holds(all[2], ids) && all.iter().all(|node| entries(node) == 3) }, + ) + .await; + sim.wait_until("all stand alike", SOON, move || async move { + let first = stands(all[0]); + first.is_some() && all.iter().all(|node| stands(node) == first) + }) + .await; +} diff --git a/src/swarm/bootstrap.rs b/src/swarm/bootstrap.rs index 9d29c5b..bc27239 100644 --- a/src/swarm/bootstrap.rs +++ b/src/swarm/bootstrap.rs @@ -54,11 +54,24 @@ pub(crate) enum Start { pub(crate) async fn bootstrap(state: &AppState, seeds: &[String], start: Start) -> Result<()> { // A set of events is its store's document, and the store's ID its swarm's: it // starts on what it holds, with nothing in the document the node holds beside. + // Holding nothing of it yet, it first gathers what the set begins from of the + // members it reaches through its seeds (`swarm::set::ask_to_start`). #[cfg(feature = "federation")] - if state.of_a_set() - && let Some(swarm_id) = state.holding.with(|store| store.id().to_string()) - { - state.set_expected_swarm_id(swarm_id).await?; + if state.of_a_set() { + if let Some(store) = state.holding.store_id() { + state.set_expected_swarm_id(store.to_string()).await?; + } + if state.holding.with(|_| ()).is_none() { + reach_seeds(state, seeds).await; + let mut closing = state.closing.subscribe(); + while state.holding.with(|_| ()).is_none() { + crate::swarm::set::ask_to_start(state).await; + tokio::select! { + () = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} + _ = closing.wait_for(|closing| *closing) => return Ok(()), + } + } + } } if let Start::FromDocument(origin) = start { let Some(swarm_id) = state.swarm_id().await else { @@ -324,16 +337,19 @@ impl StoreStart { /// The store's own document, a set of events (`--store-document`), kept in the file /// at `path`: as the file has it, where there is one, which must be this store's; - /// else begun from the root, which the node must be given then. What a checkpoint - /// forgot is kept for `keeps`. + /// else begun from the root, where the node is given it and pins no checkpoint; else + /// to be gathered of its peers, from the checkpoint `pin` names, or the root, by its + /// name. What a checkpoint forgot is kept for `keeps`. pub(crate) fn set( &self, path: &Path, files: &Files, + pin: Option, keeps: std::time::Duration, - ) -> Result> { + ) -> Result { use crate::federation::fold::Federation; - use crate::federation::store::{memory::Store, set::Set}; + use crate::federation::held::Begun; + use crate::federation::store::{memory::Store, passing::Start, set::Set}; let now = std::time::Instant::now(); let held = files .read(FileKind::Store, path) @@ -341,7 +357,7 @@ impl StoreStart { if let Some(bytes) = held { let set = Set::::load(&bytes, keeps, now).map_err(|refused| { anyhow::anyhow!( - "The store's document {} doesn't read ({}): move it away only knowing the node then starts from the root, and may take what it refused", + "The store's document {} doesn't read ({}): move it away only knowing the node then starts anew, and may take what it refused", path.display(), refused.0 ) @@ -355,18 +371,23 @@ impl StoreStart { ); } info!(swarm_id = %self.id, path = %path.display(), "Going on with the store's document"); - return Ok(set); + return Ok(Begun::Set(Box::new(set))); + } + match (&self.root, pin) { + (Some((root, kept)), None) => { + let store = + Store::::new(root.clone(), kept.clone()).map_err(|refused| { + anyhow::anyhow!("The store's root is none: {}", refused.0) + })?; + info!(swarm_id = %self.id, "Starting the swarm holding the store from its root, as a set of events (--store-document)"); + Ok(Begun::Set(Box::new(Set::new(store, keeps)))) + } + (_, pin) => { + let at = pin.unwrap_or(self.id); + info!(swarm_id = %self.id, from = %at, "Joining the swarm holding the store with nothing of it: its set begins from what members give by that name"); + Ok(Begun::Start(Start::new(self.id, at, keeps))) + } } - let Some((root, kept)) = &self.root else { - bail!( - "store-document {} doesn't exist, and store-id names no root to begin it from: give the store's root (store-root)", - path.display() - ); - }; - let store = Store::::new(root.clone(), kept.clone()) - .map_err(|refused| anyhow::anyhow!("The store's root is none: {}", refused.0))?; - info!(swarm_id = %self.id, "Starting the swarm holding the store from its root, as a set of events (--store-document)"); - Ok(Set::new(store, keeps)) } /// The swarm's ID: the root's, in hex. @@ -717,9 +738,17 @@ mod tests { let path = dir.join("store.events"); let files = Files::default(); let keeps = Duration::from_secs(60); - // No file: from the root, which joining by the ID alone doesn't give. - assert!(joining.set(&path, &files, keeps).is_err()); - let mut set = store.set(&path, &files, keeps).unwrap(); + use crate::federation::held::Begun; + let set_of = |start: &StoreStart, pin| match start.set(&path, &files, pin, keeps) { + Ok(Begun::Set(set)) => Some(*set), + Ok(Begun::Start(_)) => None, + Err(error) => panic!("{error:#}"), + }; + // No file: from the root, where given and no checkpoint is pinned; else to be + // gathered of peers. + assert!(set_of(&joining, None).is_none()); + assert!(set_of(&store, Some(Id::of(b"a checkpoint"))).is_none()); + let mut set = set_of(&store, None).expect("from the root"); let write = tv.write(&[id], "home/tv/a", harness::str("1")); assert!(matches!( set.offer(write.clone(), Instant::now()), @@ -728,7 +757,7 @@ mod tests { std::fs::write(&path, set.save(Instant::now())).unwrap(); // A file: gone on with, the root given or not. for start in [&store, &joining] { - let read = start.set(&path, &files, keeps).unwrap(); + let read = set_of(start, None).expect("from the file"); assert_eq!(read.store().taken(), &[Id::of(&write)]); } // Of another store, or no document: refused. @@ -737,9 +766,9 @@ mod tests { id: Id::of(&other_root), root: Some((other_root, Vec::new())), }; - assert!(other.set(&path, &files, keeps).is_err()); + assert!(other.set(&path, &files, None, keeps).is_err()); std::fs::write(&path, b"something else").unwrap(); - assert!(store.set(&path, &files, keeps).is_err()); + assert!(store.set(&path, &files, None, keeps).is_err()); } /// A fork's root, and the event it keeps on a line of its own: the swarm starts from diff --git a/src/swarm/set.rs b/src/swarm/set.rs index ec2415e..6df78ba 100644 --- a/src/swarm/set.rs +++ b/src/swarm/set.rs @@ -25,10 +25,15 @@ use crate::transport::{self, HeadsSummary, ParsedMessage, SyncBody}; /// Where this node's set stands, as its STATUSes say it; none, where no set carries its /// store. pub(crate) fn stamp(state: &AppState) -> Option { - let stamp = state.holding.with_set(passing::stamp)?; - Some(HeadsSummary::Kind( - rmp_serde::to_vec(&stamp).expect("a stamp encodes"), - )) + if !state.holding.of_a_set() { + return None; + } + // A node still gathering what its set begins from stands nowhere yet. + let stamp = state + .holding + .with_set(|set| rmp_serde::to_vec(&passing::stamp(set)).expect("a stamp encodes")) + .unwrap_or_default(); + Some(HeadsSummary::Kind(stamp)) } /// What a STATUS of `peer` says, where a set carries this node's store: where the @@ -56,10 +61,52 @@ pub(crate) fn heard_status( /// What a SYNC of `peer` carries of its set, where a set carries this node's store. pub(crate) async fn received(state: &AppState, peer: &str, body: Vec) { - match rmp_serde::from_slice::(&body) { - Ok(message) => handle(state, peer, message).await, + let message = match rmp_serde::from_slice::(&body) { + Ok(message) => message, Err(error) => { debug!(peer = %peer, error = %error, "What a peer says of its set doesn't read"); + return; + } + }; + // Started with nothing: what was asked for, to begin the set from (`ask_to_start`). + if !state.holding.start_wants().is_empty() { + if let Message::Units(units) = message { + let holding = std::sync::Arc::clone(&state.holding); + let begun = tokio::task::spawn_blocking(move || holding.start_take(units)) + .await + .unwrap_or(false); + if begun { + state.notify_store_changed(); + state.topology_changed.notify_one(); + } else { + ask(state, peer).await; + } + } + return; + } + handle(state, peer, message).await; +} + +/// Asks `peer` for what this node's set begins from, where the node started with +/// nothing and still gathers it. +async fn ask(state: &AppState, peer: &str) { + let wants = state.holding.start_wants(); + if !wants.is_empty() { + send(state, peer, &Message::Wants(wants)).await; + } +} + +/// Asks every peer whose handshake this node took for what its set begins from, where +/// the node started with nothing and still gathers it. +pub(crate) async fn ask_to_start(state: &AppState) { + if state.holding.start_wants().is_empty() { + return; + } + for (peer, peer_state) in state.peers_snapshot().await { + let established = + peer_state.lock().await.hello_state == crate::state::HelloState::Established; + if established { + ask(state, &peer).await; } } } -- cgit v1.3.1 From 93defc68f9b99da921f4746e91e5cee9e6e3f1b9 Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 17:39:23 +0000 Subject: swarm: a node says to each peer the kind that peer holds, of those it holds A node holds one kind of document, or, to come, its store in both (Holding::kinds, of_both). The kind a peer's handshakes say is kept with the peer, where the node holds it too, and is what the node says to it in turn; to a peer that said none yet, a node of more than one kind says each in turn, HELLO by HELLO, until one is answered. A node of one kind says and takes that one, as before. --- src/federation/held.rs | 33 +++++++++++++++++++++++++++------ src/simtest/holding.rs | 4 ++-- src/state/mod.rs | 15 +++++++++------ src/state/peer.rs | 4 ++++ src/swarm/peer/handshake.rs | 18 ++++++++++++++++-- src/swarm/peer/inbound.rs | 22 ++++++++++++++++------ 6 files changed, 74 insertions(+), 22 deletions(-) (limited to 'src/federation') diff --git a/src/federation/held.rs b/src/federation/held.rs index 51d8ef0..154544f 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -117,6 +117,9 @@ pub(crate) struct Holding { written: Mutex>, /// Whether a set of events carries the store (`carrying`), from the node's start on. of_a_set: bool, + /// Whether the node holds the store in the document a swarm syncs otherwise too + /// (`of_both`): a node of both kinds, by which a running swarm moves to sets. + both: bool, // A std mutex: never held while waiting for the document. inner: Mutex, } @@ -278,6 +281,7 @@ impl Holding { members: RwLock::default(), voter: None, of_a_set: false, + both: false, document: None, written: Mutex::default(), inner: Mutex::new(Inner { @@ -1145,18 +1149,35 @@ impl Holding { /// The kind of the document that carries the store: a set of events, or the /// document the node holds, which the store is read from. pub(crate) fn kind(&self) -> &'static str { - if self.of_a_set { - super::store::set::KIND - } else { - crate::document::KIND - } + self.kinds()[0] } - /// Whether a set of events carries the store. + /// Whether a set of events carries the store, and nothing else does. pub(crate) fn of_a_set(&self) -> bool { + self.of_a_set && !self.both + } + + /// Whether the node holds a set of events, alone or beside the Automerge document. + pub(crate) fn has_a_set(&self) -> bool { self.of_a_set } + /// Itself, holding its store in the Automerge document too, beside the set. + pub(crate) fn of_both(mut self) -> Self { + self.both = true; + self + } + + /// The kinds of document the node holds its store in, which it says in + /// handshakes: the one it says first, first. + pub(crate) fn kinds(&self) -> &'static [&'static str] { + match (self.of_a_set, self.both) { + (true, true) => &[crate::document::KIND, super::store::set::KIND], + (true, false) => &[super::store::set::KIND], + (false, _) => &[crate::document::KIND], + } + } + /// What `f` makes of the set of events carrying the store, where one does. pub(crate) fn with_set(&self, f: impl FnOnce(&Set) -> T) -> Option { match &self.inner.lock_or_recover().store { diff --git a/src/simtest/holding.rs b/src/simtest/holding.rs index ebc7528..0841a75 100644 --- a/src/simtest/holding.rs +++ b/src/simtest/holding.rs @@ -1778,7 +1778,7 @@ async fn a_swarm_of_sets_passes_entries_and_events_on() { let members = &members; sim.wait_ready(members, SOON).await; for node in members.iter() { - assert_eq!(node.kind(), crate::federation::store::set::KIND); + assert_eq!(node.kinds(), [crate::federation::store::set::KIND]); assert!(node.holding.tells_members()); } sim.wait_until("each holds the three entries", SOON, move || async move { @@ -1967,7 +1967,7 @@ async fn a_node_of_a_set_joins_with_nothing_but_the_stores_id() { ); }, ); - assert_eq!(c.kind(), crate::federation::store::set::KIND); + assert_eq!(c.kinds(), [crate::federation::store::set::KIND]); assert!(read(&c, |_| ()).is_none()); sim.wait_ready(&[&c], SOON).await; let (all, ids) = (&[&a, &b, &c], &ids); diff --git a/src/state/mod.rs b/src/state/mod.rs index 21478de..0ffa91e 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -381,14 +381,17 @@ impl AppState { *self.closing.borrow() } - /// The kind of this node's document (`document::KIND`, or a set of events where - /// one carries its store). - pub(crate) fn kind(&self) -> &'static str { + /// The kinds of document this node holds, which it says in handshakes: more than + /// one where it holds its store in both (`Holding::kinds`). + pub(crate) fn kinds(&self) -> &'static [&'static str] { #[cfg(feature = "federation")] - if self.holding.of_a_set() { - return self.holding.kind(); + { + self.holding.kinds() + } + #[cfg(not(feature = "federation"))] + { + &[crate::document::KIND] } - crate::document::KIND } /// Whether this node's document is a set of events (`federation::store::set`): diff --git a/src/state/peer.rs b/src/state/peer.rs index 721a754..356736a 100644 --- a/src/state/peer.rs +++ b/src/state/peer.rs @@ -92,6 +92,9 @@ pub(crate) struct PeerState { /// The party its handshakes name, in a swarm holding a store (`swarm::peer::members`). #[cfg(feature = "federation")] pub(crate) party: Option, + /// The kind of document its handshakes say it holds, of those this node holds: what + /// this node says to it in turn, and passes on to it (`swarm::peer::inbound`). + pub(crate) kind: Option<&'static str>, pub(crate) hello_state: HelloState, /// Wait between unanswered HELLOs; reset whenever a new handshake starts. pub(crate) hello_backoff: Backoff, @@ -339,6 +342,7 @@ impl PeerState { tree_writer: None, left: false, hello_attempts: 0, + kind: None, last_hello_at: None, unreachable_since: None, incidents: Incidents::default(), diff --git a/src/swarm/peer/handshake.rs b/src/swarm/peer/handshake.rs index fc1bc86..fc0a31b 100644 --- a/src/swarm/peer/handshake.rs +++ b/src/swarm/peer/handshake.rs @@ -144,7 +144,7 @@ async fn transmit_hello(state: &AppState, peer: &str) -> Result<()> { .await .map(|root| root.0.to_vec()), party: party(state), - kind: state.kind().to_owned(), + kind: kind_to(state, peer).await.to_owned(), }), ) .await; @@ -180,6 +180,20 @@ async fn say_what_we_speak(state: &AppState, peer: &str) { } } +/// The kind of document this node says to `peer` it holds: the one the peer's +/// handshakes said, of those this node holds; where the peer said none yet, and this +/// node holds more than one, each in turn, HELLO by HELLO, until one is answered. +async fn kind_to(state: &AppState, peer: &str) -> &'static str { + let kinds = state.kinds(); + let Some(peer_state) = state.get_peer_state(peer).await else { + return kinds[0]; + }; + let peer_state = peer_state.lock().await; + peer_state + .kind + .unwrap_or(kinds[peer_state.hello_attempts as usize % kinds.len()]) +} + pub(super) async fn ensure_handshake(state: &AppState, peer: &str) { if let Err(error) = send_hello_once(state, peer).await { warn!(peer = %peer, error = %format!("{error:#}"), "HELLO failed; will retry"); @@ -255,7 +269,7 @@ pub(super) async fn send_hello_reply( .await .map(|root| root.0.to_vec()), party: party(state), - kind: state.kind().to_owned(), + kind: kind_to(state, peer).await.to_owned(), }; debug!(to = %peer, ready, "Sending HELLO_REPLY"); diff --git a/src/swarm/peer/inbound.rs b/src/swarm/peer/inbound.rs index 0354356..35d67c8 100644 --- a/src/swarm/peer/inbound.rs +++ b/src/swarm/peer/inbound.rs @@ -114,12 +114,22 @@ pub(crate) async fn handle_message( ParsedMessage::HelloReply(reply) => Some(&reply.kind), _ => None, }; - if let Some(theirs) = kind.filter(|kind| *kind != state.kind()) { - anyhow::bail!( - "{peer} holds a document of another kind ({theirs}; this node's is {}): they sync \ - nothing; a release that knows the kind does", - state.kind() - ); + if let Some(theirs) = kind { + let Some(held) = state.kinds().iter().find(|held| *held == theirs) else { + anyhow::bail!( + "{peer} holds a document of another kind ({theirs}; this node's is {}): they \ + sync nothing; a release that knows the kind does", + state.kinds().join(" and ") + ); + }; + // Of the kinds this node holds, the one the peer holds: what it is told in + // turn, and passed on. + state + .get_or_create_peer_state(&peer) + .await + .lock() + .await + .kind = Some(held); } // The root its document starts from: another than ours, of our epoch, is another -- cgit v1.3.1 From 08ec65219991c7413c8cdef4ce77434f2a121331 Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 17:57:55 +0000 Subject: A node of both kinds, for a swarm to move to sets by (--store-both) With store-document, store-both has the node hold its store in the Automerge document too, and sync with nodes of either kind: * it says to each peer the kind that peer holds, and passes its set on to those that hold sets (swarm::set::holds_a_set), the Automerge document to the others; * what its set takes of the document goes on to the peers on sets (Holding::unpassed), and what its set takes of them is put into the document, as events it lacks are (Holding::lacking); * its entry in the document is put as its entry in the set (swarm::set::mirror_entry), and it reads the members of both; * without the set's file yet, its set is made of the store as it reads it of its document, with what store-file kept of its own. A simulation: two nodes on the Automerge document, one on a set, one of both between them; an event put on either side reaches all four. --- src/config/mod.rs | 21 +++++++++++- src/federation/held.rs | 78 +++++++++++++++++++++++++++++++++++++-------- src/lib.rs | 22 ++++++------- src/simtest/holding.rs | 74 ++++++++++++++++++++++++++++++++++++++++++ src/swarm/bootstrap.rs | 35 ++++++++++++++------ src/swarm/peer/inbound.rs | 11 ++++--- src/swarm/peer/keepalive.rs | 18 ++++++++--- src/swarm/set.rs | 69 +++++++++++++++++++++++++++++++++++---- src/swarm/sync.rs | 6 ++-- 9 files changed, 280 insertions(+), 54 deletions(-) (limited to 'src/federation') diff --git a/src/config/mod.rs b/src/config/mod.rs index 5a723c7..7b17f5d 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -223,6 +223,14 @@ pub(crate) const OPTIONS: &[OptionSpec] = &[ "With store-root or store-id: hold the store in a document of its own kind, a set of events (docs/document.md), kept in this file, instead of in the Automerge document a swarm syncs otherwise. The node then syncs with nodes holding such a set, and with no others: a swarm is of one kind. The file holds the store's events, what the node refused of its own and what its operator had it drop, and its members' entries; started again, the node goes on from it. Without the file yet, the node begins it from the root where it is given one (store-root) and pins no checkpoint; else it joins with nothing, and gathers of the members it reaches what its set begins from, by name: the root, or the checkpoint store-checkpoint names. Can't be combined with store-file, which the file stands for.", ), #[cfg(feature = "federation")] + option( + "store-both", + Kind::Flag, + "BOOL", + Some("false"), + "With store-document: hold the store in the Automerge document too, and sync with nodes of either kind, taking into each what the other holds: an event that comes by one goes on by the other, and the node's entry is in both. For moving a running swarm to sets of events node by node (docs/document.md, From an Automerge document to this): a node is started with it, on the document it has, and without it once no node it reaches holds the Automerge document alone. Without the set's file yet, the set begins from the store as the node reads it of its document.", + ), + #[cfg(feature = "federation")] option( "store-keeps-forgotten", Kind::Duration, @@ -827,6 +835,9 @@ pub(crate) struct Settings { #[cfg(feature = "federation")] pub(crate) store_document: Option, #[cfg(feature = "federation")] + #[serde(default)] + pub(crate) store_both: bool, + #[cfg(feature = "federation")] #[serde( default = "default_store_keeps_forgotten", with = "crate::units::duration_option" @@ -1361,6 +1372,7 @@ impl Settings { ("store-file", self.store_file.is_some()), ("store-checkpoint", self.store_checkpoint.is_some()), ("store-document", self.store_document.is_some()), + ("store-both", self.store_both), ("store-party", self.store_party.is_some()), ("store-readers", !self.store_readers.is_empty()), ( @@ -1384,9 +1396,14 @@ impl Settings { return Ok(()); } }; - if self.store_document.is_some() && self.store_file.is_some() { + if self.store_document.is_some() && self.store_file.is_some() && !self.store_both { bail!("store-document holds what store-file would: unset store-file"); } + if self.store_both && self.store_document.is_none() { + bail!( + "store-both: set store-document, the file of the set of events the node holds beside its Automerge document" + ); + } match &self.store_party { None => bail!( "{store}: set store-party, the party this node is of: in a swarm holding a store, nodes sync with the nodes its parties list, each as its party's" @@ -1516,6 +1533,8 @@ impl Settings { #[cfg(feature = "federation")] ("store-document", self.store_document.is_some()), #[cfg(feature = "federation")] + ("store-both", self.store_both), + #[cfg(feature = "federation")] ("store-party", self.store_party.is_some()), #[cfg(feature = "federation")] ("store-readers", !self.store_readers.is_empty()), diff --git a/src/federation/held.rs b/src/federation/held.rs index 154544f..c5527cb 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -120,6 +120,9 @@ pub(crate) struct Holding { /// Whether the node holds the store in the document a swarm syncs otherwise too /// (`of_both`): a node of both kinds, by which a running swarm moves to sets. both: bool, + /// For how long a set made of the store read from the document keeps what a + /// checkpoint forgot (`of_both`). + keeps_forgotten: Duration, // A std mutex: never held while waiting for the document. inner: Mutex, } @@ -188,6 +191,9 @@ struct Inner { /// A set of events to be, where the node started with nothing of its store and /// gathers what its set begins from of its peers (`store::passing::Start`). starting: Option>, + /// What the set took of the document, to be passed on to the peers that hold sets + /// (`unpassed`): a node of both kinds takes into each what the other holds. + unpassed: Vec, /// The document read from (`Replica::epoch_seq`), and its events read. epoch_seq: Option, read: HashSet, @@ -282,6 +288,7 @@ impl Holding { voter: None, of_a_set: false, both: false, + keeps_forgotten: Duration::ZERO, document: None, written: Mutex::default(), inner: Mutex::new(Inner { @@ -387,9 +394,13 @@ impl Holding { match started { Ok(store) => { info!(store = %id, refused = own.len(), dropped = dropped.len(), "Reading the store from the document"); - inner.store = Some(Carried::Store(Box::new( - store.refusing(&own, &dropped, &writes), - ))); + let store = store.refusing(&own, &dropped, &writes); + // A node of both kinds: the store in a set too, from here on. + inner.store = Some(if self.of_a_set { + Carried::Set(Box::new(Set::new(store, self.keeps_forgotten))) + } else { + Carried::Store(Box::new(store)) + }); } Err(why) => { if inner.none.replace(id) != Some(id) { @@ -404,7 +415,13 @@ impl Holding { for (id, bytes) in unread.events { inner.read.insert(id); match store.offer(bytes) { - Offered::Taken(ids) => taken += ids.len(), + Offered::Taken(ids) => { + taken += ids.len(); + // To pass on, where a set carries the store too (`unpassed`). + if self.of_a_set { + inner.unpassed.extend(ids); + } + } Offered::Refused(why) => { refused += 1; info!(event = %id, why = ?why, "The store refuses an event the document holds"); @@ -558,8 +575,8 @@ impl Holding { /// what its store's checkpoint keeps, then what it took after it, then what it holds /// back, stopped (`Store::held_back`). pub(crate) fn lacking(&self, doc: &impl ReadDoc) -> Vec<(Id, Vec)> { - // A set of events is the store's own document: it lacks none of it. - if self.of_a_set { + // A set of events alone is the store's own document: it lacks none of it. + if self.of_a_set && !self.both { return Vec::new(); } let mut held: HashSet = events::ids(doc).into_iter().collect(); @@ -1062,6 +1079,11 @@ impl Holding { self } + /// What the set took of the document since last asked, in the order taken. + pub(crate) fn unpassed(&self) -> Vec { + std::mem::take(&mut self.inner.lock_or_recover().unpassed) + } + /// The names a node that started with nothing asks a peer for, to begin its set /// from; none, once it holds one. pub(crate) fn start_wants(&self) -> Vec { @@ -1098,7 +1120,7 @@ impl Holding { } /// Itself, its store carried by the set `begun`, held or to be, and kept in the - /// file at `path`; itself, where the node is given no set. + /// file at `path`; itself, where the node is given no set and holds none. pub(crate) fn carrying_if( self, begun: Option, @@ -1108,11 +1130,13 @@ impl Holding { let holding = match begun { Some(Begun::Set(set)) => self.carrying(*set), Some(Begun::Start(start)) => self.awaiting(start), - None => return self, + None => self, }; match path { - Some(path) => holding.kept_in(path, files), - None => holding, + // A set held, to be gathered, or to be made of the store read from the + // document (`of_both`). + Some(path) if holding.of_a_set => holding.kept_in(path, files), + _ => holding, } } @@ -1162,9 +1186,18 @@ impl Holding { self.of_a_set } - /// Itself, holding its store in the Automerge document too, beside the set. - pub(crate) fn of_both(mut self) -> Self { + /// [`of_both`](Self::of_both), where `both`. + pub(crate) fn of_both_if(self, both: bool, keeps: Duration) -> Self { + if both { self.of_both(keeps) } else { self } + } + + /// Itself, holding its store in the Automerge document and in a set of events: the + /// set it is given (`carrying`), or, given none, one made of the store as it is + /// first read from the document, keeping what a checkpoint forgot for `keeps`. + pub(crate) fn of_both(mut self, keeps: Duration) -> Self { self.both = true; + self.of_a_set = true; + self.keeps_forgotten = keeps; self } @@ -1369,6 +1402,16 @@ pub(crate) async fn run_worker(state: crate::state::AppState) { error!(error = %error, "Reading the store from the document failed"); (false, false, false, Vec::new(), Vec::new()) }); + // What the set took of the document goes on to the peers that hold sets, and + // the node's entry in the document is its entry in the set: a node of both + // kinds takes into each what the other holds. + if state.holding.has_a_set() && !state.of_a_set() { + let unpassed = state.holding.unpassed(); + if !unpassed.is_empty() { + crate::swarm::set::wrote(&state, unpassed).await; + } + crate::swarm::set::mirror_entry(&state).await; + } for bytes in signed { if let Err(error) = write(&state, None, bytes).await { warn!(error = %error, "Couldn't put what it signed for its party: put again later"); @@ -1455,7 +1498,7 @@ pub(crate) async fn run_worker(state: crate::state::AppState) { _ = looks.tick() => { look = true; // A set of events to its file, where it changed (`Holding::save`). - if state.of_a_set() { + if state.holding.has_a_set() { let holding = Arc::clone(&state.holding); if let Ok(Err(error)) = tokio::task::spawn_blocking(move || holding.save()).await @@ -1525,7 +1568,14 @@ pub(crate) async fn write( }, ) .await - .map(|_| ()) + .map(|_| ())?; + // A node of both kinds: on to the peers that hold sets, too (`swarm::set`). + if state.holding.has_a_set() + && state.holding.with(|store| store.get(&id).is_some()) == Some(true) + { + crate::swarm::set::wrote(state, vec![id]).await; + } + Ok(()) } async fn put_again(state: &crate::state::AppState) { diff --git a/src/lib.rs b/src/lib.rs index d4989ab..b57f6a5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -225,21 +225,20 @@ pub async fn run() -> Result<()> { // or from the root. #[cfg(feature = "federation")] let set = match (&store, &args.store_document) { - (Some(store), Some(path)) => Some( - store.set( - path, - &files, - args.store_checkpoint - .as_deref() - .and_then(federation::store::Id::from_hex), - args.store_keeps_forgotten, - )?, - ), + (Some(store), Some(path)) => store.set( + path, + &files, + args.store_checkpoint + .as_deref() + .and_then(federation::store::Id::from_hex), + args.store_keeps_forgotten, + args.store_both, + )?, _ => None, }; #[cfg(feature = "federation")] let starting = match &store { - Some(store) if set.is_none() => { + Some(store) if set.is_none() || args.store_both => { store.starting(starting, remembered.as_ref().map(|r| r.swarm_id.as_str()))? } // A set is the store's document: the one a swarm syncs otherwise stays empty. @@ -400,6 +399,7 @@ pub async fn run() -> Result<()> { )? .near(args.store_neighbour_parties.clone()) .voting(voter(args)?) + .of_both_if(args.store_both, args.store_keeps_forgotten) .carrying_if(set, args.store_document.clone(), Arc::clone(&files)), strict_keys: args .strict_keys diff --git a/src/simtest/holding.rs b/src/simtest/holding.rs index 0841a75..120c6da 100644 --- a/src/simtest/holding.rs +++ b/src/simtest/holding.rs @@ -2123,3 +2123,77 @@ async fn a_node_of_a_set_away_across_a_move_builds_the_checkpoint_itself() { .await; assert_eq!(counts(d), counts(&a)); } + +/// A swarm on its way from Automerge documents to sets of events: a and b hold the +/// store in the Automerge document, e in a set, and m in both. a and e take none of +/// each other's handshakes; m takes both, saying to each the kind it holds. An event +/// put on a reaches e through m, and one put on e reaches a and b: m takes into each +/// what the other holds. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_node_of_both_kinds_carries_events_between_them() { + let sim = Sim::with_identity(97); + let (tv, lass, makefu) = three(); + let (_, root, id) = federation(&[(&tv, &["a", "b"]), (&lass, &["m"]), (&makefu, &["e"])]); + let start = |name: &'static str, seeds: &'static [&'static str], holding: Holding| { + let root = root.clone(); + sim.start_with( + name, + seeds, + Start::FromDocument(Origin::Root), + move |config| { + of_the_store(config, id, Some(&root), holding); + }, + ) + }; + let a = start("a", &[], holding("tv")); + let b = start("b", &["a"], holding("tv")); + let m = start( + "m", + &["a"], + holding("lass").of_both(Duration::from_secs(600)), + ); + assert_eq!(m.kinds().len(), 2); + let e = { + let seeds = ["m"]; + let root = root.clone(); + sim.start_with( + "e", + &seeds, + Start::FromDocument(Origin::Root), + move |config| { + config.store = Some(id); + config.holding = holding("makefu").carrying_if( + Some(held::Begun::Set(Box::new(a_set(&root)))), + None, + Arc::new(Files::default()), + ); + }, + ) + }; + let all = &[&a, &b, &m, &e]; + sim.wait_ready(all, SOON).await; + sim.wait_until( + "m holds a set, and its entry and e's in it", + LONG, + move || async move { entries(all[2]) == 2 && entries(all[3]) == 2 }, + ) + .await; + + let on_a = tv.write(&[id], "home/tv/x", s("1")); + let on_e = makefu.write(&[id], "home/makefu/y", s("2")); + let ids = [Id::of(&on_a), Id::of(&on_e)]; + put(&a, &[&on_a]).await; + put(&e, &[&on_e]).await; + let ids = &ids; + sim.wait_until("all four hold both events", LONG, move || async move { + all.iter().all(|node| holds(node, ids)) + }) + .await; + for node in all.iter() { + assert_eq!(read(node, |store| store.state().values().len()), Some(2)); + } + // e's event is in the Automerge document, which m put it in; a's isn't in e's, which + // holds nothing. + assert!(events::ids(&a.doc.read().await.doc).contains(&ids[1])); + assert!(e.doc.read().await.heads().is_empty()); +} diff --git a/src/swarm/bootstrap.rs b/src/swarm/bootstrap.rs index b21b579..45c86e6 100644 --- a/src/swarm/bootstrap.rs +++ b/src/swarm/bootstrap.rs @@ -344,14 +344,16 @@ impl StoreStart { /// at `path`: as the file has it, where there is one, which must be this store's; /// else begun from the root, where the node is given it and pins no checkpoint; else /// to be gathered of its peers, from the checkpoint `pin` names, or the root, by its - /// name. What a checkpoint forgot is kept for `keeps`. + /// name; of `both` kinds, none without a file. What a checkpoint forgot is kept for + /// `keeps`. pub(crate) fn set( &self, path: &Path, files: &Files, pin: Option, keeps: std::time::Duration, - ) -> Result { + both: bool, + ) -> Result> { use crate::federation::fold::Federation; use crate::federation::held::Begun; use crate::federation::store::{memory::Store, passing::Start, set::Set}; @@ -376,7 +378,12 @@ impl StoreStart { ); } info!(swarm_id = %self.id, path = %path.display(), "Going on with the store's document"); - return Ok(Begun::Set(Box::new(set))); + return Ok(Some(Begun::Set(Box::new(set)))); + } + // A node of both kinds makes its set of the store as it reads it of its + // document (`Holding::of_both`). + if both { + return Ok(None); } match (&self.root, pin) { (Some((root, kept)), None) => { @@ -385,12 +392,12 @@ impl StoreStart { anyhow::anyhow!("The store's root is none: {}", refused.0) })?; info!(swarm_id = %self.id, "Starting the swarm holding the store from its root, as a set of events (--store-document)"); - Ok(Begun::Set(Box::new(Set::new(store, keeps)))) + Ok(Some(Begun::Set(Box::new(Set::new(store, keeps))))) } (_, pin) => { let at = pin.unwrap_or(self.id); info!(swarm_id = %self.id, from = %at, "Joining the swarm holding the store with nothing of it: its set begins from what members give by that name"); - Ok(Begun::Start(Start::new(self.id, at, keeps))) + Ok(Some(Begun::Start(Start::new(self.id, at, keeps)))) } } } @@ -753,9 +760,9 @@ mod tests { let files = Files::default(); let keeps = Duration::from_secs(60); use crate::federation::held::Begun; - let set_of = |start: &StoreStart, pin| match start.set(&path, &files, pin, keeps) { - Ok(Begun::Set(set)) => Some(*set), - Ok(Begun::Start(_)) => None, + let set_of = |start: &StoreStart, pin| match start.set(&path, &files, pin, keeps, false) { + Ok(Some(Begun::Set(set))) => Some(*set), + Ok(Some(Begun::Start(_)) | None) => None, Err(error) => panic!("{error:#}"), }; // No file: from the root, where given and no checkpoint is pinned; else to be @@ -780,9 +787,17 @@ mod tests { id: Id::of(&other_root), root: Some((other_root, Vec::new())), }; - assert!(other.set(&path, &files, None, keeps).is_err()); + assert!(other.set(&path, &files, None, keeps, false).is_err()); std::fs::write(&path, b"something else").unwrap(); - assert!(store.set(&path, &files, None, keeps).is_err()); + assert!(store.set(&path, &files, None, keeps, false).is_err()); + // A node of both kinds: the file, where there is one; else none here. + std::fs::remove_file(&path).unwrap(); + assert!( + store + .set(&path, &files, None, keeps, true) + .unwrap() + .is_none() + ); } /// A fork's root, and the event it keeps on a line of its own: the swarm starts from diff --git a/src/swarm/peer/inbound.rs b/src/swarm/peer/inbound.rs index 35d67c8..b6c486d 100644 --- a/src/swarm/peer/inbound.rs +++ b/src/swarm/peer/inbound.rs @@ -228,11 +228,14 @@ pub(crate) async fn handle_message( .map_err(|error| anyhow!("Failed to notify sync worker: {error}"))?; } transport::ParsedMessage::Sync(envelope) => { - // Of a set of events, where one carries this node's store: its own to - // take (`swarm::set`), and nothing of an Automerge document's. + // Of a set of events: this node's set's to take, where it holds one + // (`swarm::set`); and of an Automerge document nothing, where it holds a set + // alone. #[cfg(feature = "federation")] - if state.of_a_set() { - if let transport::SyncBody::Kind(body) = envelope.body { + if state.of_a_set() || matches!(envelope.body, transport::SyncBody::Kind(_)) { + if let transport::SyncBody::Kind(body) = envelope.body + && state.holding.has_a_set() + { crate::swarm::set::received(state, &peer, body).await; } return Ok(()); diff --git a/src/swarm/peer/keepalive.rs b/src/swarm/peer/keepalive.rs index 6ab49d8..bbcc6e3 100644 --- a/src/swarm/peer/keepalive.rs +++ b/src/swarm/peer/keepalive.rs @@ -182,13 +182,21 @@ pub(crate) async fn local_status(state: &AppState, peer: &str) -> transport::Sta let stamp = state.stamp.borrow(); (stamp.summary(), stamp.epoch, stamp.epoch_seq) }; - let syncs_with_you = match state.get_peer_state(peer).await { - Some(peer_state) => peer_state.lock().await.syncs_on(epoch), - None => false, + let (syncs_with_you, _of_a_set) = match state.get_peer_state(peer).await { + Some(peer_state) => { + let peer_state = peer_state.lock().await; + ( + peer_state.syncs_on(epoch), + peer_state + .kind + .is_some_and(|kind| kind != crate::document::KIND), + ) + } + None => (false, false), }; - // Where a set of events carries the store, where that stands (`swarm::set`). + // To a peer that holds a set of events, where this node's stands (`swarm::set`). #[cfg(feature = "federation")] - let heads = crate::swarm::set::stamp(state).unwrap_or(heads); + let heads = crate::swarm::set::stamp(state, _of_a_set).unwrap_or(heads); let (reaches, round_trips) = crate::swarm::reach::published_with_round_trips(state); transport::Status { heads, diff --git a/src/swarm/set.rs b/src/swarm/set.rs index 6df78ba..54a48fe 100644 --- a/src/swarm/set.rs +++ b/src/swarm/set.rs @@ -22,10 +22,22 @@ use crate::state::AppState; use crate::swarm::topology; use crate::transport::{self, HeadsSummary, ParsedMessage, SyncBody}; -/// Where this node's set stands, as its STATUSes say it; none, where no set carries its -/// store. -pub(crate) fn stamp(state: &AppState) -> Option { - if !state.holding.of_a_set() { +/// Whether `peer` holds a set of events, as its handshakes said: what a node of both +/// kinds passes its set on to. A node that holds a set alone takes handshakes of no +/// other. +pub(crate) async fn holds_a_set(state: &AppState, peer: &str) -> bool { + match state.get_peer_state(peer).await { + Some(peer_state) => { + peer_state.lock().await.kind == Some(crate::federation::store::set::KIND) + } + None => false, + } +} + +/// Where this node's set stands, as its STATUSes say it to a peer that holds one +/// (`to_a_set`); none, where the node holds no set, or the peer doesn't. +pub(crate) fn stamp(state: &AppState, to_a_set: bool) -> Option { + if !state.holding.has_a_set() || !(to_a_set || state.holding.of_a_set()) { return None; } // A node still gathering what its set begins from stands nowhere yet. @@ -45,9 +57,14 @@ pub(crate) fn heard_status( peer: &str, mut remote: transport::Status, ) -> transport::Status { - let Some(ours) = stamp(state) else { + // A peer that says where a set stands holds one. + let of_a_set = matches!(remote.heads, HeadsSummary::Kind(_)); + let Some(ours) = stamp(state, of_a_set) else { return remote; }; + if !of_a_set && !state.holding.of_a_set() { + return remote; + } if let HeadsSummary::Kind(bytes) = std::mem::replace(&mut remote.heads, ours) && let Ok(stamp) = rmp_serde::from_slice::(&bytes) { @@ -174,7 +191,10 @@ async fn pass_on(state: &AppState, from: Option<&str>, took: Took) { } let message = Message::Units(units); for peer in state.active_peers_on_local_epoch().await { - if Some(peer.as_str()) != from && topology::is_neighbour(state, &peer) { + if Some(peer.as_str()) != from + && topology::is_neighbour(state, &peer) + && holds_a_set(state, &peer).await + { send(state, &peer, &message).await; } } @@ -219,3 +239,40 @@ pub(crate) async fn registered(state: &AppState) { ) .await; } + +/// On a node of both kinds, puts its entry as the document it holds has it as its entry +/// in the set, where the two differ, and passes it on: what the node says of itself, +/// it says to the peers of either kind. +pub(crate) async fn mirror_entry(state: &AppState) { + use crate::federation::store::entry::Entry; + use crate::federation::store::set::Put; + + if !state.holding.has_a_set() || state.holding.of_a_set() { + return; + } + let Some(key) = state.node_key.clone() else { + return; + }; + let node = state.local_id().to_owned(); + let own = crate::swarm::members::member_path(&node); + let written = crate::document::view::read_path(&state.doc.read().await.doc, &own); + let Ok(Some(serde_json::Value::Object(written))) = written else { + return; + }; + let put = state.holding.change_set(|set| { + let held = set.entry(&node); + if held.and_then(|entry| entry.value()).as_ref() == Some(&written) { + return None; + } + let count = held.map_or(1, |entry| entry.count() + 1); + Some(set.put_entry(Entry::new( + &set.store().id(), + &key, + count, + &serde_json::Value::Object(written), + ))) + }); + if put.flatten() == Some(Put::Taken) { + registered(state).await; + } +} diff --git a/src/swarm/sync.rs b/src/swarm/sync.rs index 5e736a1..3939377 100644 --- a/src/swarm/sync.rs +++ b/src/swarm/sync.rs @@ -63,10 +63,10 @@ async fn deliver_sync_to_peer(state: &AppState, peer: &str) -> Result<()> { } } - // A set of events is passed on otherwise (`swarm::set`): of the Automerge document - // a node holds beside one, nothing. + // A set of events is passed on otherwise (`swarm::set`): with a peer that holds + // one, and of the Automerge document a node holds beside one alone, no sync. #[cfg(feature = "federation")] - if state.of_a_set() { + if state.of_a_set() || crate::swarm::set::holds_a_set(state, peer).await { return Ok(()); } -- cgit v1.3.1 From 6a06bc4a955cdf2b5a183c9ff21e25c79a4e5d9f Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 19:36:56 +0000 Subject: federation: a stopped node on a set passes on what it holds back A store that stopped at an event it can't judge holds back what comes after, and its set gave none of it to others: what was put through such a node reached nobody, and a restart lost it. The set now names what its store holds back among what it gives, passes it on at once as it does what it took, and keeps it in its file; once the store takes again, it gives of it what the store took, or refused of its own. --- docs/document.md | 4 +- docs/guides/federation/when-things-go-wrong.md | 10 +- src/federation/held.rs | 3 +- src/federation/store/memory.rs | 8 ++ src/federation/store/set.rs | 122 ++++++++++++++++++++++--- src/simtest/holding.rs | 72 +++++++++++++++ 6 files changed, 200 insertions(+), 19 deletions(-) (limited to 'src/federation') diff --git a/docs/document.md b/docs/document.md index 07f25b0..07d3420 100644 --- a/docs/document.md +++ b/docs/document.md @@ -667,7 +667,9 @@ held; and where the fold takes it at its history, which every node judges alike. the fold refuses there is held by nobody. One whose history takes it and that the node itself refuses or doesn't read (a node's own: what it took before, its operator's drops, where it stopped) is held and passed on all the same, as the document holds it -today: so that what one node doesn't read still reaches the nodes that do. +today: so that what one node doesn't read still reaches the nodes that do. A node that +stopped holds back what comes after, as it can't tell which of it will be taken, and +passes that on alike, until it takes again: then it holds of it what it took. What builds on such an event, the node can't judge: it holds no history to judge it at. Where nodes took different ones of two versions that changed the same, or an diff --git a/docs/guides/federation/when-things-go-wrong.md b/docs/guides/federation/when-things-go-wrong.md index 13df07d..5bd7f62 100644 --- a/docs/guides/federation/when-things-go-wrong.md +++ b/docs/guides/federation/when-things-go-wrong.md @@ -76,7 +76,7 @@ record. A node stops at a version event writing a version that passed on the version it reads, which its continuum doesn't read: of a later federation, using what a later continuum takes, or none at all. It takes nothing and refuses nothing from then on, and votes -nothing by itself or by hand; what is put through it, it holds back +nothing by itself or by hand; what is put through it, it holds back and passes on (`stopped` when put). Its log says so (`The store stopped at an event this continuum can't judge`), and `GET /events` names the event, why, and how many it holds back: @@ -103,10 +103,10 @@ curl -u tv:secret -X POST -H 'Content-Type: application/json' \ # {"dropped":["9a1e…"]} ``` -Allowed again (`/admin/events/allow`), it stops there once more. A node that stopped -keeps none of it in its set's file: restarted, it stops there again. What it holds back, -it passes on to nobody, and what was put through it since it stopped, no other node has: -put it through another node. A node keeping its store in the Automerge document puts +Allowed again (`/admin/events/allow`), it stops there once more. What a node holds back, +it leaves out of nothing, as it can't tell which will be taken: it passes it on to the +other nodes, which take it where they read that version, and keeps it in its set's file; +restarted, it stops there again. A node keeping its store in the Automerge document puts what it holds back again where its document lacks it, and a remake keeps it, so a remake while nodes are stopped loses none of what was put since. diff --git a/src/federation/held.rs b/src/federation/held.rs index c5527cb..39d6102 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -1545,7 +1545,8 @@ pub(crate) async fn write( if state.of_a_set() { let holding = Arc::clone(&state.holding); let _ = tokio::task::spawn_blocking(move || holding.offer(bytes)).await; - let held = state.holding.with(|store| store.get(&id).is_some()); + // What the set gives: taken, or held back by a store that stopped. + let held = state.holding.with_set(|set| set.get(&id).is_some()); if held == Some(true) { crate::swarm::set::wrote(state, vec![id]).await; } diff --git a/src/federation/store/memory.rs b/src/federation/store/memory.rs index 8f099be..6f4ee5d 100644 --- a/src/federation/store/memory.rs +++ b/src/federation/store/memory.rs @@ -332,6 +332,14 @@ impl Store { .map(|(id, why)| (id, why.as_str(), self.held_back.len())) } + /// The events the store holds back, stopped, in the order offered: the one it stopped + /// at, and those offered since. None while it isn't stopped. + pub(crate) fn holds_back(&self) -> impl ExactSizeIterator { + self.held_back + .iter() + .map(|(id, event)| (*id, event.bytes.as_slice())) + } + /// What the store holds back, stopped (`Fold::stops`): the events offered since, and /// those waiting for events it doesn't hold, as it can't tell which will be taken; each /// after those of its dependencies among them, by ID otherwise. Nothing while it isn't diff --git a/src/federation/store/set.rs b/src/federation/store/set.rs index b033927..d0dbe18 100644 --- a/src/federation/store/set.rs +++ b/src/federation/store/set.rs @@ -9,6 +9,8 @@ //! oldest going first: whoever mints events can mint these; //! * what a move to a checkpoint forgot, for as long as the node's operator says: a node //! still before the checkpoint builds it from them. +//! * what the store holds back, stopped at an event it can't judge (`Fold::stops`): the +//! node can't tell which of it will be taken, and a node that judges it takes it. //! //! And each member's entry (`entry`): its node's newest, and none of a node the store //! doesn't name a member as it reads now. @@ -123,6 +125,9 @@ pub(crate) struct Set { /// The unjudged among them, the oldest first, and their bytes in all. unjudged: VecDeque, unjudged_bytes: usize, + /// What the store holds back, stopped, by ID: where among what it holds back + /// (`Store::holds_back`). + held_back: BTreeMap, /// For how long what a checkpoint forgot is kept. keeps_forgotten: Duration, /// Who carries the store, as it reads now (`Fold::members`). @@ -157,6 +162,7 @@ impl Set { beside: BTreeMap::new(), unjudged: VecDeque::new(), unjudged_bytes: 0, + held_back: BTreeMap::new(), keeps_forgotten, members, entries: BTreeMap::new(), @@ -245,12 +251,13 @@ impl Set { /// document keeps as far as it gives it to others. pub(crate) fn offer(&mut self, bytes: Vec, now: Instant) -> Offered { let offered = self.store.offer(bytes); - self.settle(now); + let _ = self.settle(now); offered } /// Offers events to the store, at `now`, as `offer` does each: those the store took - /// by them, in the order taken. + /// by them, in the order taken, and those it holds back since, stopped: what the + /// document gives to others by them. pub(crate) fn offer_all( &mut self, events: impl IntoIterator>, @@ -262,7 +269,7 @@ impl Set { taken.extend(ids); } } - self.settle(now); + taken.extend(self.settle(now)); taken } @@ -289,7 +296,7 @@ impl Set { /// holds them on, for others. pub(crate) fn drop_taken(&mut self, ids: &[Id], now: Instant) -> Result, Refused> { let dropped = self.store.drop_taken(ids); - self.settle(now); + let _ = self.settle(now); dropped } @@ -317,11 +324,12 @@ impl Set { self.store.offer(bytes); } } - self.settle(now); + let _ = self.settle(now); } - /// Takes in what the store let go of. - fn settle(&mut self, now: Instant) { + /// Takes in what the store let go of, and what it holds back, stopped: the events it + /// holds back since last asked, in the order offered. + fn settle(&mut self, now: Instant) -> Vec { let took = self.store.took(); let gone = self.store.let_go(); // Who is a member is the fold's to say of the store's state, and costs what @@ -376,8 +384,42 @@ impl Set { } !held }); + let held_back = self.hold_back(); #[cfg(test)] self.check(); + held_back + } + + /// Follows what the store holds back, stopped: its names among those the document + /// gives, and those held back since last asked, in the order offered. + fn hold_back(&mut self) -> Vec { + let holds = self.store.holds_back().len(); + // The store holds back more, after what it held back: the common case. + let more = holds >= self.held_back.len() + && self.held_back.len().checked_sub(1).is_none_or(|last| { + self.store + .holds_back() + .nth(last) + .is_some_and(|(id, _)| self.held_back.get(&id) == Some(&last)) + }); + let from = if more { self.held_back.len() } else { 0 }; + if !more { + // It takes again, and may have stopped anew: what it held back, it took, + // refused, or holds back again. + for id in std::mem::take(&mut self.held_back).into_keys() { + if self.store.get(&id).is_none() && !self.beside.contains_key(&id) { + self.names.remove(&id.0); + } + } + } + let mut since = Vec::new(); + for (at, (id, _)) in self.store.holds_back().enumerate().skip(from) { + self.held_back.insert(id, at); + if self.names.insert(id.0) { + since.push(id); + } + } + since } /// Whether the store refuses `id` as the node's own, or for building on such: what @@ -423,12 +465,16 @@ impl Set { self.beside.len() != before } - /// The bytes of an event the document gives to others: one its store holds, or one - /// held beside it. + /// The bytes of an event the document gives to others: one its store holds, one + /// held beside it, or one the store holds back. pub(crate) fn get(&self, id: &Id) -> Option<&[u8]> { self.store .get(id) .or_else(|| self.beside.get(id).map(|(bytes, _)| bytes.as_slice())) + .or_else(|| { + let at = *self.held_back.get(id)?; + self.store.holds_back().nth(at).map(|(_, bytes)| bytes) + }) } /// Why the document holds `id` beside its store, where it does. @@ -436,7 +482,8 @@ impl Set { self.beside.get(id).map(|(_, why)| *why) } - /// The document as bytes, at `now`: what its file holds. All it holds but what waits + /// The document as bytes, at `now`: what its file holds, what its store holds back + /// among it. All it holds but what waits /// for what it builds on, which comes again; and what its node refuses of its own, /// which a store read anew is told before anything is offered to it. pub(crate) fn save(&self, now: Instant) -> Vec { @@ -451,6 +498,12 @@ impl Set { .iter() .filter_map(|id| self.store.get(id)) .map(|bytes| bytes.to_vec().into()) + // What the store holds back, after: offered again, it stops there again. + .chain( + self.store + .holds_back() + .map(|(_, bytes)| bytes.to_vec().into()), + ) .collect(), own: own.iter().map(|id| id.0).collect(), dropped: dropped.iter().map(|id| id.0).collect(), @@ -521,7 +574,7 @@ impl Set { for event in saved.taken { set.store.offer(event.into_vec()); } - set.settle(now); + let _ = set.settle(now); for (bytes, why) in saved.beside { let bytes = bytes.into_vec(); let id = Id::of(&bytes); @@ -543,7 +596,7 @@ impl Set { set.names.insert(id.0); set.beside.insert(id, (bytes, why)); } - set.settle(now); + let _ = set.settle(now); set.expire(now); for entry in saved.entries { if let Some(entry) = Entry::decode(&entry) { @@ -595,6 +648,7 @@ impl Set { .map(|id| id.0) .chain(self.store.kept().iter().map(|bytes| Id::of(bytes).0)) .chain(self.beside.keys().map(|id| id.0)) + .chain(self.held_back.keys().map(|id| id.0)) .chain(self.entries.values().map(Entry::name)) .collect() } @@ -998,4 +1052,48 @@ mod tests { assert!(!set.wants(&waiting[WAITS + 4].0)); assert_eq!(set.store().lacks().len(), WAITS); } + + /// What a store that stopped holds back, the document gives to others, as the node + /// can't tell which of it will be taken; its file keeps it; and once the store takes + /// again, the document gives what the store took of it and no more. + #[test] + fn what_a_stopped_store_holds_back_is_given_to_others() { + let mut set = set(); + let now = Instant::now(); + let root = set.store().id(); + let mark = taken(set.offer(testfold::put(&[root], "mark", "1"), now)); + let new = testfold::era(&[mark], 1, "new"); + let at = Id::of(&new); + let later = testfold::put(&[mark], "b", "1"); + let junk = testfold::junk(&[mark]); + let (later_id, junk_id) = (Id::of(&later), Id::of(&junk)); + // Held back, and given: by name, to catch up by, and as what was taken by them. + assert_eq!( + set.offer_all([new.clone(), later.clone(), junk.clone()], now), + vec![at, later_id, junk_id] + ); + assert!(set.store().stopped().is_some()); + for (id, bytes) in [(at, &new), (later_id, &later), (junk_id, &junk)] { + assert_eq!(set.get(&id), Some(bytes.as_slice())); + assert!(set.names().contains(&id.0)); + assert!(!set.wants(&id.0)); + } + // Offered again, nothing is given anew. + assert!(set.offer_all([later.clone()], now).is_empty()); + // Its file keeps what it holds back: read, the store stops there again. + let mut read = Set::::load(&set.save(now), KEEPS, now).expect("it reads"); + assert_eq!(read.store().stopped().map(|(id, _, _)| *id), Some(at)); + assert_eq!(read.named(), set.named()); + assert_eq!(read.get(&later_id), Some(later.as_slice())); + // Its operator has it drop the event it stopped at: what it held back is taken, + // or refused, and what is refused at its history is given no more. + read.drop_taken(&[at], now).expect("dropped"); + assert!(read.store().stopped().is_none()); + assert_eq!(read.store().taken(), &[mark, later_id]); + assert_eq!(read.get(&junk_id), None); + assert!(!read.names().contains(&junk_id.0)); + // What it dropped is the node's own, which others may take. + assert_eq!(read.beside(&at), Some(Beside::Own)); + assert!(read.names().contains(&at.0)); + } } diff --git a/src/simtest/holding.rs b/src/simtest/holding.rs index 8091cfc..8f601dd 100644 --- a/src/simtest/holding.rs +++ b/src/simtest/holding.rs @@ -1807,6 +1807,78 @@ async fn a_swarm_of_sets_passes_entries_and_events_on() { } } +/// On sets of events, a version of a federation this continuum doesn't know passes, and +/// a version event writes it: every node stops there. What is put through one of them +/// meanwhile, it holds back and passes on, as it can't tell what will be taken: the +/// others hold it back too. Their operators have them drop that event: they take again, +/// all alike. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_stopped_node_of_a_set_passes_on_what_it_holds_back() { + let sim = Sim::with_identity(99); + let (tv, lass, makefu) = three(); + let (first, root, id) = federation(&[(&tv, &["a"]), (&lass, &["b"]), (&makefu, &["c"])]); + let nodes: Vec = [("a", "tv"), ("b", "lass"), ("c", "makefu")] + .into_iter() + .map(|(name, party)| { + let seeds: Vec<&str> = if name == "a" { Vec::new() } else { vec!["a"] }; + let root = root.clone(); + sim.start_with( + name, + &seeds, + Start::FromDocument(Origin::Root), + move |config| { + config.store = Some(id); + config.holding = of_a_set(party, &root); + }, + ) + }) + .collect(); + let members: Vec<&AppState> = nodes.iter().collect(); + let all = &members; + sim.wait_ready(all, SOON).await; + sim.wait_until("each holds the three entries", SOON, move || async move { + all.iter().all(|node| entries(node) == 3) + }) + .await; + + let on = first.hash(); + let text = String::from_utf8(first.after(on).json().bytes()) + .expect("UTF-8") + .replace(r#""federation":1"#, r#""federation":2"#); + let unknown = crate::federation::jcs::read(text.as_bytes()).expect("JCS"); + let hash = Id::of(&unknown.bytes()); + let proposal = tv.propose(&[id], &unknown); + let votes = [&tv, &lass].map(|party| party.vote(&[Id::of(&proposal)], on, hash, true)); + let written = harness::version_event(&[Id::of(&votes[0]), Id::of(&votes[1])], hash); + let at = Id::of(&written); + put(all[0], &[&proposal, &votes[0], &votes[1], &written]).await; + sim.wait_until("every node stopped there", LONG, move || async move { + all.iter().all(|node| stopped(node) == Some(at)) + }) + .await; + + let meanwhile = tv.write(&[id], "home/tv/a", s("1")); + put(all[0], &[&meanwhile]).await; + let meanwhile = Id::of(&meanwhile); + sim.wait_until("every node holds it back", LONG, move || async move { + all.iter() + .all(|node| holds_back(node, &[at, meanwhile], false)) + }) + .await; + + for node in all.iter() { + let dropped = node.holding.drop_taken(&[at]).expect("a store"); + assert_eq!(dropped, Ok(vec![at])); + } + sim.wait_until("every node takes again", LONG, move || async move { + all.iter() + .all(|node| stopped(node).is_none() && holds(node, &[meanwhile])) + }) + .await; + let read: Vec> = all.iter().map(|node| counts(node)).collect(); + assert!(read.iter().all(|counts| counts == &read[0]), "{read:?}"); +} + /// Starts `name`, of `party`, on a set of events `set`, kept in the file at `path` where /// given: the first of them with no seed, the others seeded by `a`. fn start_on_a_set( -- cgit v1.3.1