diff options
| author | tv <tv@krebsco.de> | 2026-12-01 02:45:46 +0100 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-12-01 02:45:46 +0100 |
| commit | 34bfcb661ed74bf40809576bbb388362cb7ffaa1 (patch) | |
| tree | 8422db7db396dd4ae83403837cd954a94f882a7a /src/federation | |
| parent | 34434f7fd5a6bab1884a63c96679f48045f4bffd (diff) | |
| parent | 6a06bc4a955cdf2b5a183c9ff21e25c79a4e5d9f (diff) | |
Diffstat (limited to 'src/federation')
| -rw-r--r-- | src/federation/held.rs | 442 | ||||
| -rw-r--r-- | src/federation/store/memory.rs | 8 | ||||
| -rw-r--r-- | src/federation/store/passing.rs | 179 | ||||
| -rw-r--r-- | src/federation/store/set.rs | 122 |
4 files changed, 729 insertions, 22 deletions
diff --git a/src/federation/held.rs b/src/federation/held.rs index ec3738f..39d6102 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}; @@ -110,6 +111,18 @@ pub(crate) struct Holding { members: RwLock<Option<BTreeSet<(String, String)>>>, /// What it votes for its party with, if it votes by itself. voter: Option<Voter>, + /// 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<Files>)>, + written: Mutex<Option<super::store::passing::Stamp>>, + /// 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, + /// 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<Inner>, } @@ -123,10 +136,64 @@ 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<Set<Federation>>), + Start(super::store::passing::Start<Federation>), +} + +/// 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<Store<Federation>>), + Set(Box<Set<Federation>>), +} + +impl std::ops::Deref for Carried { + type Target = Store<Federation>; + + fn deref(&self) -> &Store<Federation> { + match self { + Carried::Store(store) => store, + Carried::Set(set) => set.store(), + } + } +} + +impl Carried { + fn offer(&mut self, bytes: Vec<u8>) -> 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<Vec<Id>, 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<Federation>>, + store: Option<Carried>, + /// 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<super::store::passing::Start<Federation>>, + /// 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<Id>, /// The document read from (`Replica::epoch_seq`), and its events read. epoch_seq: Option<u32>, read: HashSet<Id>, @@ -219,6 +286,11 @@ impl Holding { near: Vec::new(), members: RwLock::default(), voter: None, + of_a_set: false, + both: false, + keeps_forgotten: Duration::ZERO, + document: None, + written: Mutex::default(), inner: Mutex::new(Inner { kept, ..Inner::default() @@ -322,7 +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(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) { @@ -337,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"); @@ -491,6 +575,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<u8>)> { + // 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<Id> = events::ids(doc).into_iter().collect(); let mut inner = self.inner.lock_or_recover(); inner.left.retain(|(id, _)| !held.contains(id)); @@ -968,7 +1056,210 @@ impl Holding { /// `f` of the store, where the node holds one. pub(crate) fn with<T>(&self, f: impl FnOnce(&Store<Federation>) -> T) -> Option<T> { - self.inner.lock_or_recover().store.as_ref().map(f) + 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(mut self, set: Set<Federation>) -> Self { + self.of_a_set = true; + { + let mut inner = self.inner.lock_or_recover(); + inner.store = Some(Carried::Set(Box::new(set))); + self.settle(&mut inner); + } + self + } + + /// 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<Federation>) -> Self { + self.of_a_set = true; + self.inner.lock_or_recover().starting = Some(start); + self + } + + /// What the set took of the document since last asked, in the order taken. + pub(crate) fn unpassed(&self) -> Vec<Id> { + 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<crate::document::ranges::Name> { + 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<super::store::passing::Unit>) -> 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<Id> { + 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 and holds none. + pub(crate) fn carrying_if( + self, + begun: Option<Begun>, + path: Option<PathBuf>, + files: Arc<Files>, + ) -> Self { + let holding = match begun { + Some(Begun::Set(set)) => self.carrying(*set), + Some(Begun::Start(start)) => self.awaiting(start), + None => self, + }; + match path { + // 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, + } + } + + /// 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<Files>) -> 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<bool> { + 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 { + self.kinds()[0] + } + + /// 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 + } + + /// [`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 + } + + /// 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<T>(&self, f: impl FnOnce(&Set<Federation>) -> T) -> Option<T> { + match &self.inner.lock_or_recover().store { + Some(Carried::Set(set)) => Some(f(set)), + _ => None, + } + } + + /// 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/<node ID>`, 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<crate::document::view::Tree> { + 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 = [ + meta::ROOT.to_owned(), + meta::MEMBERS.to_owned(), + entry.node(), + ]; + 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<T>(&self, f: impl FnOnce(&mut Set<Federation>) -> T) -> Option<T> { + 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 @@ -1111,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"); @@ -1194,7 +1495,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.holding.has_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"); + } + } + } } } } @@ -1228,6 +1540,18 @@ pub(crate) async fn write( bytes: Vec<u8>, ) -> 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; + // 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; + } + return Ok(()); + } state .mutate_doc_for( user, @@ -1245,7 +1569,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) { @@ -2686,4 +3017,103 @@ 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::<Federation>::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()); + } + + #[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::<Federation>::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)); + // 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/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<F: Fold> Store<F> { .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<Item = (Id, &[u8])> { + 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/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<u8>), Entry(#[serde(with = "serde_bytes")] Vec<u8>), + /// 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<u8>), } /// What one node says to another of its set. @@ -62,6 +68,100 @@ pub(crate) enum Message { Units(Vec<Unit>), } +/// 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<F: Fold> { + store: Id, + at: Id, + keeps_forgotten: Duration, + /// The checkpoint named `at`, once it came, and the events it keeps, by name. + checkpoint: Option<(Vec<u8>, Vec<Id>)>, + kept: BTreeMap<Id, Vec<u8>>, + fold: std::marker::PhantomData<F>, +} + +impl<F: Fold> Start<F> { + /// 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<Name> { + 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<Unit>) -> Option<Set<F>> { + 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<Vec<u8>> = self.kept.values().cloned().collect(); + let store: Result<Store<F>, 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<F: Fold>(set: &Set<F>) -> 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<F: Fold>(set: &Set<F>, name: &Name) -> Option<Unit> { + 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<F: Fold>( 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<F: Fold>( 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<usize> = 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::<usize>() <= 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::<TestFold>::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::<TestFold>::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<Unit> = 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/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<F: Fold> { /// The unjudged among them, the oldest first, and their bytes in all. unjudged: VecDeque<Id>, unjudged_bytes: usize, + /// What the store holds back, stopped, by ID: where among what it holds back + /// (`Store::holds_back`). + held_back: BTreeMap<Id, usize>, /// 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<F: Fold> Set<F> { beside: BTreeMap::new(), unjudged: VecDeque::new(), unjudged_bytes: 0, + held_back: BTreeMap::new(), keeps_forgotten, members, entries: BTreeMap::new(), @@ -245,12 +251,13 @@ impl<F: Fold> Set<F> { /// document keeps as far as it gives it to others. pub(crate) fn offer(&mut self, bytes: Vec<u8>, 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<Item = Vec<u8>>, @@ -262,7 +269,7 @@ impl<F: Fold> Set<F> { taken.extend(ids); } } - self.settle(now); + taken.extend(self.settle(now)); taken } @@ -289,7 +296,7 @@ impl<F: Fold> Set<F> { /// holds them on, for others. pub(crate) fn drop_taken(&mut self, ids: &[Id], now: Instant) -> Result<Vec<Id>, Refused> { let dropped = self.store.drop_taken(ids); - self.settle(now); + let _ = self.settle(now); dropped } @@ -317,11 +324,12 @@ impl<F: Fold> Set<F> { 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<Id> { 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<F: Fold> Set<F> { } !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<Id> { + 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<F: Fold> Set<F> { 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<F: Fold> Set<F> { 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<u8> { @@ -451,6 +498,12 @@ impl<F: Fold> Set<F> { .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<F: Fold> Set<F> { 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<F: Fold> Set<F> { 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<F: Fold> Set<F> { .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::<TestFold>::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)); + } } |
