//! 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::time::Instant; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use super::entry::Entry; use super::memory::Offered; 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), } /// 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), } /// 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 { let mut hasher = Sha256::new(); hasher.update(Id::of(set.store().checkpoint()).0); // In one order on every node: a store says its heads as it took them. let mut heads = set.store().heads(); heads.sort(); for head in heads { hasher.update(head.0); } Stamp { heads: hasher.finalize().into(), names: ranges::fingerprint(&set.names()), } } /// The unit named `name`, where `set` holds it. pub(crate) fn unit(set: &Set, name: &Name) -> Option { 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); 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) => 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) => { for unit in units { match unit { Unit::Event(bytes) => { if let Offered::Taken(ids) = set.offer(bytes, now) { took.events.extend(ids); } } Unit::Entry(bytes) => { 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) } /// 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::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.names()).collect(); settle(sets, rng, now); if sets.iter().map(|set| set.names()).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.names(), first.names()); 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.names(), b.names()); 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) => 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 ); } } }