diff options
| author | tv <tv@krebsco.de> | 2026-11-29 13:24:34 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-29 13:24:34 +0000 |
| commit | 61fb06c420d5e481badc8a9d3252b90cf9013746 (patch) | |
| tree | d90578948fc7b581594621a13dae9be0cd3ad2f8 | |
| parent | 2d31675f5c2c3b3475be89558c55a8a6e604df49 (diff) | |
federation: passing a set of events on
What two nodes say to each other of their sets (store::passing), with
nothing kept of a peer between messages: where a node stands, its
store's checkpoint and heads and the fingerprint of all its names;
ranges (document::ranges, whose messages serialize), where fingerprints
differ; its heads, where they differ and the fingerprints don't; the
names it lacks and would have; events and entries, no more than 1 MiB a
message. What comes is offered to the store or put as an entry, and for
what the store then waits on and doesn't hold (Store::lacks) the node
asks in turn.
Sets that wrote apart come to hold the same, over seeds; what a node
refuses of its own reaches others through it.
Used by nothing yet: no node carries a set.
| -rw-r--r-- | src/document/ranges.rs | 7 | ||||
| -rw-r--r-- | src/federation/store/memory.rs | 12 | ||||
| -rw-r--r-- | src/federation/store/mod.rs | 1 | ||||
| -rw-r--r-- | src/federation/store/passing.rs | 432 |
4 files changed, 449 insertions, 3 deletions
diff --git a/src/document/ranges.rs b/src/document/ranges.rs index 8ae71e9..b142f90 100644 --- a/src/document/ranges.rs +++ b/src/document/ranges.rs @@ -23,6 +23,7 @@ use std::collections::BTreeSet; use std::ops::Bound; +use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; /// What is reconciled: 32 bytes, in the order of their bytes. @@ -36,7 +37,7 @@ const FEW: usize = 2 * PARTS; /// What stands for the names of a range: the same for the same names, and, but for /// names made to collide, for no others. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)] pub(crate) struct Fingerprint(pub(crate) [u8; 16]); /// The names of a range added up, and how many. @@ -82,7 +83,7 @@ pub(crate) type Upper = Option<Name>; /// What a message says of one range, which begins where the part before ended (the /// first, before every name) and ends at `upper`. -#[derive(Clone, PartialEq, Eq, Debug)] +#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub(crate) enum Part { /// Nothing to say of it: it is done, or left for another message. Skip { upper: Upper }, @@ -111,7 +112,7 @@ impl Part { } /// Parts in order, the last ending after every name. -#[derive(Clone, PartialEq, Eq, Debug, Default)] +#[derive(Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)] pub(crate) struct Message(pub(crate) Vec<Part>); /// What a node makes of a message. diff --git a/src/federation/store/memory.rs b/src/federation/store/memory.rs index 781ba01..0243d03 100644 --- a/src/federation/store/memory.rs +++ b/src/federation/store/memory.rs @@ -256,6 +256,18 @@ impl<F: Fold> Store<F> { || self.holding_back.contains(id) } + /// What events that wait build on and the store doesn't hold, nor has wait. + pub(crate) fn lacks(&self) -> Vec<Id> { + let mut lacks: Vec<Id> = self + .waits_for + .iter() + .filter(|(id, waiting)| !waiting.is_empty() && !self.waiting.contains_key(id)) + .map(|(id, _)| *id) + .collect(); + lacks.sort(); + lacks + } + /// Whether an event waits for dependencies the store doesn't hold. pub(crate) fn is_waiting(&self, id: &Id) -> bool { self.waiting.contains_key(id) diff --git a/src/federation/store/mod.rs b/src/federation/store/mod.rs index c3fa106..4527e2f 100644 --- a/src/federation/store/mod.rs +++ b/src/federation/store/mod.rs @@ -10,6 +10,7 @@ use crate::transport::Hex; pub(crate) mod entry; pub(crate) mod memory; +pub(crate) mod passing; #[cfg(test)] mod properties; pub(crate) mod set; diff --git a/src/federation/store/passing.rs b/src/federation/store/passing.rs new file mode 100644 index 0000000..39d78b7 --- /dev/null +++ b/src/federation/store/passing.rs @@ -0,0 +1,432 @@ +//! 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<u8>), + Entry(#[serde(with = "serde_bytes")] Vec<u8>), +} + +/// 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<Name>), + /// Ranges of its names, and their fingerprints or the names. + Ranges(ranges::Message), + /// Names it lacks and would have. + Wants(Vec<Name>), + /// Events and entries: asked for, or new. + Units(Vec<Unit>), +} + +/// 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<Id>, + /// The members whose entry it took. + pub(crate) entries: Vec<String>, +} + +impl Took { + pub(crate) fn is_empty(&self) -> bool { + self.events.is_empty() && self.entries.is_empty() + } +} + +/// Where `set` stands. +pub(crate) fn stamp<F: Fold>(set: &Set<F>) -> 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<F: Fold>(set: &Set<F>, name: &Name) -> Option<Unit> { + 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<F: Fold>( + set: &mut Set<F>, + message: Message, + now: Instant, +) -> (Vec<Message>, 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<F: Fold>(set: &Set<F>, names: Vec<Name>, replies: &mut Vec<Message>) { + let wanted: Vec<Name> = 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<TestFold> { + 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<TestFold>], 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<TestFold>], 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::<Vec<_>>() == 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<Set<TestFold>> = (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<usize> = units + .iter() + .map(|unit| match unit { + Unit::Event(bytes) | Unit::Entry(bytes) => bytes.len(), + }) + .collect(); + assert!(sizes.iter().sum::<usize>() <= 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::<Message>(&bytes).expect("a message"), + message + ); + } + } +} |
