aboutsummaryrefslogtreecommitdiffstats
path: root/src/federation/store/passing.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/federation/store/passing.rs')
-rw-r--r--src/federation/store/passing.rs215
1 files changed, 211 insertions, 4 deletions
diff --git a/src/federation/store/passing.rs b/src/federation/store/passing.rs
index 5a6e2af..2e69a96 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,123 @@ 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>>,
+ /// What its node refused of its own, what its operator had it drop, and what the
+ /// dropped write (`Store::refusing`): of a set the node held before.
+ own: Vec<Id>,
+ dropped: Vec<Id>,
+ writes: Vec<(Id, Id)>,
+ 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(),
+ own: Vec::new(),
+ dropped: Vec::new(),
+ writes: Vec::new(),
+ fold: std::marker::PhantomData,
+ }
+ }
+
+ /// Itself, its store to refuse what `held`, a set the node held before, refuses of
+ /// its node's own and as its operator had it drop: a node that begins anew from
+ /// another checkpoint keeps what it refused.
+ pub(crate) fn refusing_as(mut self, held: &Set<F>) -> Self {
+ (self.own, self.dropped) = held.store().own();
+ self.writes = held.store().dropped_writes();
+ self
+ }
+
+ /// 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.refusing(&self.own, &self.dropped, &self.writes),
+ self.keeps_forgotten,
+ )
+ .pinned_at((self.at != self.store).then_some(self.at)),
+ ),
+ 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 +208,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 +258,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 +282,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 +507,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 +562,79 @@ 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);
+ assert_eq!(begun.pinned(), None);
+
+ // From a checkpoint its operator pins: that, then what it keeps; and refusing
+ // what a set the node held before refused as its operator had it drop.
+ let mut held = set();
+ let dropped = match held.offer(testfold::put(&[root], "c", "1"), now) {
+ Offered::Taken(ids) => ids[0],
+ other => panic!("not taken: {other:?}"),
+ };
+ held.drop_taken(&[dropped], now).expect("dropped");
+ let mut start = Start::<TestFold>::new(root, pinned, KEEPS).refusing_as(&held);
+ 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());
+ assert_eq!(begun.store().own(), (Vec::new(), vec![dropped]));
+ // Its file says which checkpoint was pinned.
+ assert_eq!(begun.pinned(), Some(pinned));
+ let read = Set::<TestFold>::load(&begun.save(now), KEEPS, now).expect("it reads");
+ assert_eq!(read.pinned(), Some(pinned));
+ // 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());
+ }
}