//! Passing a set of events on (`docs/document.md`, A set of events, Passing on): what //! two nodes say to each other of their sets, and what a node makes of what it is told. //! A node keeps nothing of a peer between messages: each message is answered by what the //! node holds as it comes. //! //! * Where a node stands (`Stamp`), said now and then: its store's checkpoint and //! heads, which are the same exactly where two stores hold the same; and the //! fingerprint of all its names, events and entries. //! * Fingerprints differ: the two find what differs by ranges (`document::ranges`), //! and each asks for the names it lacks and would have (`Set::wants`). //! * Fingerprints the same and heads not: either the two refuse differently of their //! own and hold the same all the same, or someone made fingerprints collide. A node //! says its heads, and the other asks for those it doesn't know. //! * What is asked for by name is sent, as far as it is held; what comes is offered to //! 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::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}; /// The most names a message of ranges holds, and the most a node asks for at once. const NAMES: usize = 4096; /// The most bytes of events and entries in one message. const BYTES: usize = 1 << 20; /// Where a node's set stands. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub(crate) struct Stamp { /// Of its store's checkpoint and heads. heads: [u8; 32], /// The fingerprint of all its names. names: ranges::Fingerprint, } /// An event or an entry, as passed on. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 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. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub(crate) enum Message { /// Where it stands. Stamp(Stamp), /// Its store's heads. Heads(Vec), /// Ranges of its names, and their fingerprints or the names. Ranges(ranges::Message), /// Names it lacks and would have. Wants(Vec), /// Events and entries: asked for, or new. 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 { /// The events its store took, in the order taken. pub(crate) events: Vec, /// The members whose entry it took. pub(crate) entries: Vec, } impl Took { pub(crate) fn is_empty(&self) -> bool { self.events.is_empty() && self.entries.is_empty() } } /// Where `set` stands. pub(crate) fn stamp(set: &Set) -> Stamp { Stamp { heads: set.stands(), names: set.names().fingerprint(), } } /// 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(|| { set.entry_named(name) .map(|entry| Unit::Entry(entry.encode())) }) } /// What `set` makes of `message`, at `now`: what to say back, and what it took. pub(crate) fn receive( set: &mut Set, message: Message, now: Instant, ) -> (Vec, Took) { let mut replies = Vec::new(); let mut took = Took::default(); match message { Message::Stamp(theirs) => { let ours = stamp(set); if theirs.names != ours.names { replies.push(Message::Ranges(ranges::open(set.names()))); } else if theirs.heads != ours.heads { replies.push(Message::Heads( set.store().heads().iter().map(|id| id.0).collect(), )); } } Message::Heads(heads) => ask(set, heads, &mut replies), Message::Ranges(theirs) => { let answer = ranges::answer(set.names(), &theirs, NAMES, salt()); ask(set, answer.lacking, &mut replies); if let Some(reply) = answer.reply { replies.push(Message::Ranges(reply)); } } Message::Wants(names) => { let mut units = Vec::new(); let mut bytes = 0; for name in names.iter().take(NAMES) { let Some(unit) = unit(set, name) else { continue; }; let size = match &unit { 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() { break; } bytes += size; units.push(unit); } if !units.is_empty() { replies.push(Message::Units(units)); } } Message::Units(units) => { // The events at once, then the entries: who is a member may be among the // events. let mut events = Vec::new(); let mut entries = Vec::new(); for unit in units { 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); for bytes in entries { if let Some(entry) = Entry::decode(&bytes) { let node = entry.node(); if set.put_entry(entry) == Put::Taken { took.entries.push(node); } } } // What the store waits on now and doesn't hold: back to what both hold. let lacks = set.store().lacks().iter().map(|id| id.0).collect(); ask(set, lacks, &mut replies); } } (replies, took) } /// A number nobody knows beforehand, to split ranges by (`ranges::answer`). fn salt() -> u64 { let mut bytes = [0; 8]; // Without randomness, the same each time: ranges are compared all the same. let _ = getrandom::fill(&mut bytes); u64::from_le_bytes(bytes) } /// Asks for those of `names` that `set` would have. fn ask(set: &Set, names: Vec, replies: &mut Vec) { let wanted: Vec = names .into_iter() .filter(|name| set.wants(name)) .take(NAMES) .collect(); if !wanted.is_empty() { replies.push(Message::Wants(wanted)); } } #[cfg(test)] mod tests { use std::collections::VecDeque; use std::time::Duration; use super::super::memory::{Offered, Store}; use super::super::testfold::{self, TestFold}; use super::*; use crate::testrand::{Rng, for_seeds}; const KEEPS: Duration = Duration::from_secs(60); fn set() -> Set { Set::new( Store::new(testfold::root("tests"), Vec::new()).expect("a root"), KEEPS, ) } fn key(seed: u8) -> crate::identity::NodeKey { crate::identity::NodeKey::from_seed([seed; 32]) } /// Has every node tell every other where it stands, and all that follows from it /// delivered, in an order `rng` chooses, losing none; the messages that went. fn settle(sets: &mut [Set], rng: &mut Rng, now: Instant) -> usize { let mut queue: VecDeque<(usize, usize, Message)> = VecDeque::new(); for from in 0..sets.len() { for to in 0..sets.len() { if from != to { queue.push_back((from, to, Message::Stamp(stamp(&sets[from])))); } } } let mut messages = 0; while !queue.is_empty() { let at = rng.below(queue.len()); let (from, to, message) = queue.remove(at).expect("one queued"); messages += 1; assert!(messages < 100_000, "passing on doesn't end"); let (replies, _) = receive(&mut sets[to], message, now); for reply in replies { queue.push_back((to, from, reply)); } } messages } /// Rounds of `settle` until a round changes nothing; how many it took. fn settled(sets: &mut [Set], rng: &mut Rng, now: Instant) -> usize { for round in 1..=20 { let before: Vec<_> = sets.iter().map(|set| set.named()).collect(); settle(sets, rng, now); if sets.iter().map(|set| set.named()).collect::>() == before { return round; } } panic!("the sets don't settle"); } #[test] fn two_that_stand_alike_say_nothing_more() { let mut sets = [set(), set()]; let now = Instant::now(); let root = sets[0].store().id(); for set in &mut sets { set.offer(testfold::put(&[root], "a", "1"), now); } assert_eq!(stamp(&sets[0]), stamp(&sets[1])); let mut rng = Rng::new(1); assert_eq!(settle(&mut sets, &mut rng, now), 2); } #[test] fn one_behind_catches_up() { let mut sets = [set(), set()]; let now = Instant::now(); let root = sets[0].store().id(); let mut on = root; for n in 0..200 { let put = testfold::put(&[on], "a", &n.to_string()); on = Id::of(&put); sets[0].offer(put, now); } let mut rng = Rng::new(2); settle(&mut sets, &mut rng, now); assert_eq!(sets[1].store().taken(), sets[0].store().taken()); assert_eq!(stamp(&sets[0]), stamp(&sets[1])); } #[test] fn nodes_that_wrote_apart_come_to_hold_the_same() { for_seeds(30, |rng| { let now = Instant::now(); let count = rng.between(2, 5); let mut sets: Vec> = (0..count).map(|_| set()).collect(); let root = sets[0].store().id(); // The members, known to all; then each writes on what it holds, apart. let mut on = root; for node in 0..count { let member = testfold::put(&[on], &format!("node:{}", key(node as u8).id()), "a"); on = Id::of(&member); for set in &mut sets { set.offer(member.clone(), now); } } for (node, set) in sets.iter_mut().enumerate() { let mut on = on; for n in 0..rng.between(0, 40) { let put = testfold::put(&[on], &format!("k{}", rng.below(5)), &n.to_string()); on = Id::of(&put); set.offer(put, now); } let entry = Entry::new( &root, &key(node as u8), rng.between(1, 3) as u64, &serde_json::json!({ "alias": node }), ); assert_eq!(set.put_entry(entry), Put::Taken); } settled(&mut sets, rng, now); let first = &sets[0]; for set in &sets[1..] { assert_eq!(stamp(set), stamp(first)); assert_eq!(set.named(), first.named()); assert_eq!(set.store().state().counts(), first.store().state().counts()); assert_eq!(set.entries().count(), count); } }); } #[test] fn what_one_refuses_of_its_own_still_reaches_the_others_through_it() { // b took the other era, and stands between a, which wrote on the one, and c. let (mut a, mut b, c) = (set(), set(), set()); let now = Instant::now(); let root = a.store().id(); let other = testfold::era(&[root], 1, "other"); b.offer(other, now); let one = testfold::era(&[root], 1, "one"); let one_id = Id::of(&one); a.offer(one, now); let on = testfold::put(&[one_id], "a", "1"); let on_id = Id::of(&on); a.offer(on, now); let mut rng = Rng::new(3); // a and b; then b and c: never a and c. let mut pair = [a, b]; settled(&mut pair, &mut rng, now); let [a, b] = pair; assert!(b.store().get(&one_id).is_none()); assert!(b.get(&one_id).is_some()); assert!(b.get(&on_id).is_some()); let mut pair = [b, c]; settled(&mut pair, &mut rng, now); let [b, c] = pair; // c takes whichever era came first of b: both reached it. assert!(c.get(&one_id).is_some()); assert!(c.get(&on_id).is_some()); assert_eq!(c.named(), b.named()); assert_eq!(a.names().len(), 3); } #[test] fn what_is_asked_for_and_held_is_sent_within_the_bound() { let mut set = set(); let now = Instant::now(); let root = set.store().id(); let large = "x".repeat(40_000); let mut names = vec![[9; 32]]; for n in 0..40 { let put = testfold::put(&[root], &format!("k{n}"), &large); names.push(Id::of(&put).0); assert!(matches!(set.offer(put, now), Offered::Taken(_))); } let (replies, took) = receive(&mut set, Message::Wants(names.clone()), now); assert!(took.is_empty()); let [Message::Units(units)] = replies.as_slice() else { panic!("no units: {replies:?}"); }; let sizes: Vec = units .iter() .map(|unit| match unit { Unit::Event(bytes) | Unit::Entry(bytes) | Unit::Checkpoint(bytes) => bytes.len(), }) .collect(); assert!(sizes.iter().sum::() <= BYTES); assert!( units.len() > 20 && units.len() < 40, "{} units", units.len() ); // Those asked for first, as far as held. assert_eq!(units[0], unit(&set, &names[1]).expect("held")); } #[test] fn a_node_asks_back_for_what_an_event_builds_on() { // Told a head alone, a node asks for it, and then for what it builds on. let mut ahead = set(); let mut behind = 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); ahead.offer(first, now); ahead.offer(second, now); let (replies, _) = receive(&mut behind, Message::Heads(vec![second_id.0]), now); assert_eq!(replies, vec![Message::Wants(vec![second_id.0])]); let (units, _) = receive(&mut ahead, replies[0].clone(), now); let (replies, took) = receive(&mut behind, units[0].clone(), now); assert!(took.is_empty()); assert_eq!(replies, vec![Message::Wants(vec![first_id.0])]); let (units, _) = receive(&mut ahead, replies[0].clone(), now); let (replies, took) = receive(&mut behind, units[0].clone(), now); assert!(replies.is_empty()); assert_eq!(took.events, vec![first_id, second_id]); } #[test] fn messages_read_back_from_their_bytes() { let set = set(); for message in [ Message::Stamp(stamp(&set)), Message::Heads(vec![[1; 32]]), Message::Ranges(ranges::open(set.names())), Message::Wants(vec![[2; 32]]), Message::Units(vec![Unit::Event(vec![1, 2]), Unit::Entry(vec![3])]), ] { let bytes = rmp_serde::to_vec(&message).expect("a message encodes"); assert_eq!( rmp_serde::from_slice::(&bytes).expect("a message"), message ); } } #[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()); } }