//! A set of events: the store's own document (`docs/document.md`, A set of events), the //! kind `events`. A store (`memory`), and beside it what the store itself lets go of //! and its node still gives to others: //! //! * events whose history takes them and the node doesn't, by what it took before or as //! its operator had it drop them: other nodes take them; //! * events that build on such: the node can't judge them, as it holds no history to //! judge them at, and others may take them. No more than `UNJUDGED` of them, the //! 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. //! //! What the fold refuses at its history, and what isn't one of its events, is held by //! nobody. use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::time::{Duration, Instant}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use super::entry::Entry; use super::memory::{Gone, Offered, Refusal, Store}; use super::{Fold, Id, Refused}; use crate::document::ranges::{Name, Names}; /// The kind, as nodes name it where they meet. pub(crate) const KIND: &str = "events"; /// The most events held unjudged, and the most bytes of them. const UNJUDGED: usize = 1024; const UNJUDGED_BYTES: usize = 16 << 20; /// Why the document holds an event its store doesn't. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Beside { /// Its history takes it, and the node doesn't. Own, /// It builds on one the node doesn't take, and wasn't judged. Unjudged, /// A move to a checkpoint forgot it, then. Forgotten(Instant), } /// The most events the store has wait for what they build on. const WAITS: usize = 1024; /// The most names of strangers' entries remembered. const STRANGERS: usize = 1024; /// What became of an entry put. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Put { /// It is its node's entry now. Taken, /// It is its node's entry already. Held, /// The document holds a newer one of its node. Older, /// Its node is no member, as the store reads now. Stranger, /// It is no entry of this store, and why. Refused(&'static str), } /// The nodes that carry `store`, as it reads now. fn members_of(store: &Store) -> BTreeSet { F::members(store.state()) .into_iter() .map(|(node, _)| node) .collect() } /// What a document's file begins with. const FILE: &[u8] = b"continuum-events/1\n"; /// A document as its file holds it (`Set::save`). #[derive(Serialize, Deserialize)] struct Saved { store: [u8; 32], #[serde(with = "serde_bytes")] checkpoint: Vec, kept: Vec, taken: Vec, own: Vec<[u8; 32]>, dropped: Vec<[u8; 32]>, writes: Vec<([u8; 32], [u8; 32])>, beside: Vec<(serde_bytes::ByteBuf, SavedBeside)>, entries: Vec, /// The checkpoint the node's operator pinned, which the document began from, if /// any: none in a file written before it was kept. #[serde(default)] pinned: Option<[u8; 32]>, } /// Why a document holds an event beside its store, as its file says it: what a /// checkpoint forgot, with how many seconds ago. #[derive(Serialize, Deserialize)] enum SavedBeside { Own, Unjudged, Forgotten(u64), } /// Where `store` stands: of its checkpoint and its heads, the same on every node /// whose store holds the same. fn stands_of(store: &Store) -> [u8; 32] { let mut hasher = Sha256::new(); hasher.update(Id::of(store.checkpoint()).0); // In one order on every node: a store says its heads as it took them. let mut heads = store.heads(); heads.sort(); for head in heads { hasher.update(head.0); } hasher.finalize().into() } /// A set of events, of a fold `F`. pub(crate) struct Set { store: Store, /// What is held beside the store, by ID. beside: BTreeMap, Beside)>, /// The unjudged among them, the oldest first, and their bytes in all. unjudged: VecDeque, unjudged_bytes: usize, /// What the store holds back, stopped, by ID: where among what it holds back /// (`Store::holds_back`). held_back: BTreeMap, /// For how long what a checkpoint forgot is kept. keeps_forgotten: Duration, /// Who carries the store, as it reads now (`Fold::members`). members: BTreeSet, /// Each member's entry, by its node. entries: BTreeMap, /// Entries of nodes that are no members, by name: not asked for again until who is /// one changes. No more than `STRANGERS`. strangers: BTreeSet, /// The names of all the document gives to others, kept as it changes. names: Names, /// The entries' names, each with its node. entry_names: BTreeMap, /// Where the store stands: of its checkpoint and its heads, read anew where it /// changed. stands: [u8; 32], /// The checkpoint the node's operator pinned, which the document began from, if /// any. pinned: Option, } impl Set { /// The document of `store`, keeping what a checkpoint forgot for `keeps_forgotten`. pub(crate) fn new(store: Store, keeps_forgotten: Duration) -> Self { let members = members_of::(&store); let stands = stands_of(&store); let names = store .taken() .iter() .map(|id| id.0) .chain(store.kept().iter().map(|bytes| Id::of(bytes).0)) .collect(); Self { store: store.telling().waiting_no_more_than(WAITS), beside: BTreeMap::new(), unjudged: VecDeque::new(), unjudged_bytes: 0, held_back: BTreeMap::new(), keeps_forgotten, members, entries: BTreeMap::new(), strangers: BTreeSet::new(), names, entry_names: BTreeMap::new(), stands, pinned: None, } } /// Itself, begun from the checkpoint `pin` that its node's operator pinned, if any. pub(crate) fn pinned_at(mut self, pin: Option) -> Self { self.pinned = pin; self } /// The checkpoint the node's operator pinned, which the document began from, if /// any: with another pinned, the node begins anew from that one. pub(crate) fn pinned(&self) -> Option { self.pinned } /// Takes a member's entry, where it is its node's newest: of a higher count than the /// one held, or of the same and a lower name. pub(crate) fn put_entry(&mut self, entry: Entry) -> Put { if let Err(why) = entry.checks(&self.store.id()) { return Put::Refused(why); } let node = entry.node(); if !self.members.contains(&node) { if self.strangers.len() < STRANGERS { self.strangers.insert(entry.name()); } return Put::Stranger; } match self.entries.get(&node) { Some(held) if *held == entry => Put::Held, Some(held) if held.count() > entry.count() || (held.count() == entry.count() && held.name() < entry.name()) => { Put::Older } _ => { let name = entry.name(); self.names.insert(name); self.entry_names.insert(name, node.clone()); if let Some(older) = self.entries.insert(node, entry) { let older = older.name(); self.names.remove(&older); self.entry_names.remove(&older); } #[cfg(test)] self.check(); Put::Taken } } } /// The entry of the member `node`, where the document holds one. pub(crate) fn entry(&self, node: &str) -> Option<&Entry> { self.entries.get(node) } /// The members' entries, in the order of their nodes. pub(crate) fn entries(&self) -> impl Iterator { self.entries.values() } /// The entry named `name`, where the document holds it. pub(crate) fn entry_named(&self, name: &Name) -> Option<&Entry> { self.entry_names .get(name) .and_then(|node| self.entries.get(node)) } /// Whether the document would have what is named `name`, which a peer holds: not /// what it holds, what its store refused, waits for or let go of, nor an entry of a /// node that is no member. pub(crate) fn wants(&self, name: &Name) -> bool { !self.store.knows(&Id(*name)) && !self.beside.contains_key(&Id(*name)) && !self.strangers.contains(name) && self.entry_named(name).is_none() } /// Where the store stands (`stands_of`). pub(crate) fn stands(&self) -> [u8; 32] { self.stands } /// The store: what the node reads. pub(crate) fn store(&self) -> &Store { &self.store } /// Offers an event to the store, at `now`; what the store lets go of by it, the /// document keeps as far as it gives it to others. pub(crate) fn offer(&mut self, bytes: Vec, now: Instant) -> Offered { let offered = self.store.offer(bytes); 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, 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>, now: Instant, ) -> Vec { let mut taken = Vec::new(); for bytes in events { if let Offered::Taken(ids) = self.store.offer(bytes) { taken.extend(ids); } } taken.extend(self.settle(now)); taken } /// Reads anew who is a member, and lets go of the entries of those who aren't. fn members_anew(&mut self) { let members = members_of::(&self.store); if members != self.members { let (names, entry_names) = (&mut self.names, &mut self.entry_names); self.entries.retain(|node, entry| { let member = members.contains(node); if !member { let name = entry.name(); names.remove(&name); entry_names.remove(&name); } member }); self.strangers.clear(); self.members = members; } } /// Has the store drop events it took (`Store::drop_taken`), at `now`: the document /// holds them on, for others. pub(crate) fn drop_taken(&mut self, ids: &[Id], now: Instant) -> Result, Refused> { let dropped = self.store.drop_taken(ids); let _ = self.settle(now); dropped } /// Has the store take back what the node refused of its own (`Store::allow`), and /// offers it what the document held of that, at `now`. pub(crate) fn allow(&mut self, ids: &[Id], now: Instant) { self.store.allow(ids); let again: Vec = self .beside .iter() .filter(|(id, (_, why))| { matches!(why, Beside::Own | Beside::Unjudged) && self.store.refusal(id).is_none() }) .map(|(id, _)| *id) .collect(); // Each after what it builds on, as far as that is among them: offered in any // order, the store has what comes early wait. for id in again { if let Some((bytes, why)) = self.beside.remove(&id) { self.names.remove(&id.0); if why == Beside::Unjudged { self.unjudged.retain(|other| *other != id); self.unjudged_bytes -= bytes.len(); } self.store.offer(bytes); } } let _ = self.settle(now); } /// 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 { 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 // reading that costs: asked only where the store changed. if !took.is_empty() || !gone.is_empty() { self.members_anew(); self.stands = stands_of(&self.store); } for id in took { self.names.insert(id.0); } for (id, bytes, gone) in gone { let why = match gone { Gone::Forgotten => Beside::Forgotten(now), Gone::Own => Beside::Own, Gone::NotAbove => { self.names.remove(&id.0); continue; } Gone::BuiltOn(on) => { if !self.own(&on) { self.names.remove(&id.0); continue; } Beside::Unjudged } }; if why == Beside::Unjudged { self.unjudged.push_back(id); self.unjudged_bytes += bytes.len(); } self.names.insert(id.0); self.beside.insert(id, (bytes, why)); } while self.unjudged.len() > UNJUDGED || self.unjudged_bytes > UNJUDGED_BYTES { let Some(oldest) = self.unjudged.pop_front() else { break; }; if let Some((bytes, _)) = self.beside.remove(&oldest) { self.names.remove(&oldest.0); self.unjudged_bytes -= bytes.len(); } } // What the store holds again, it holds: taken after all, or kept by a checkpoint. let store = &self.store; let (unjudged, unjudged_bytes) = (&mut self.unjudged, &mut self.unjudged_bytes); self.beside.retain(|id, (bytes, why)| { let held = store.get(id).is_some(); if held && *why == Beside::Unjudged { unjudged.retain(|other| other != id); *unjudged_bytes -= bytes.len(); } !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 { 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 /// builds on it, others may take. fn own(&self, id: &Id) -> bool { let mut id = *id; // A chain of refusals ends: each names one refused before it. for _ in 0..=UNJUDGED { match self.store.refusal(&id) { Some(Refusal::Own | Refusal::Dropped) => return true, Some(Refusal::BuiltOn(on)) => { // One held unjudged builds on the node's own; one not held was let // go as building on what every node refuses, or fell out. if self.beside.contains_key(&id) { return true; } id = *on; } _ => return false, } } false } /// Lets go of what a checkpoint forgot longer ago than the document keeps it, at /// `now`. Whether it let go of anything. pub(crate) fn expire(&mut self, now: Instant) -> bool { let keeps = self.keeps_forgotten; let before = self.beside.len(); let names = &mut self.names; self.beside.retain(|id, (_, why)| { let keep = match why { Beside::Forgotten(since) => now.saturating_duration_since(*since) < keeps, _ => true, }; if !keep { names.remove(&id.0); } keep }); #[cfg(test)] self.check(); self.beside.len() != before } /// How long, at `now`, until the document lets go of something a checkpoint forgot /// (`expire`), if it keeps any. pub(crate) fn next_expiry(&self, now: Instant) -> Option { self.beside .values() .filter_map(|(_, why)| match why { Beside::Forgotten(since) => Some( (*since + self.keeps_forgotten).saturating_duration_since(now) + Duration::from_millis(1), ), _ => None, }) .min() } /// 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. pub(crate) fn beside(&self, id: &Id) -> Option { self.beside.get(id).map(|(_, why)| *why) } /// 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 { let (own, dropped) = self.store.own(); let saved = Saved { store: self.store.id().0, checkpoint: self.store.checkpoint().to_vec(), kept: self.store.kept().into_iter().map(Into::into).collect(), taken: self .store .taken() .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(), writes: self .store .dropped_writes() .iter() .map(|(id, writes)| (id.0, writes.0)) .collect(), beside: self .beside .values() .map(|(bytes, why)| { let why = match why { Beside::Own => SavedBeside::Own, Beside::Unjudged => SavedBeside::Unjudged, Beside::Forgotten(since) => { SavedBeside::Forgotten(now.saturating_duration_since(*since).as_secs()) } }; (bytes.clone().into(), why) }) .collect(), entries: self .entries .values() .map(|entry| entry.encode().into()) .collect(), pinned: self.pinned.map(|id| id.0), }; let mut out = FILE.to_vec(); rmp_serde::encode::write(&mut out, &saved).expect("a document encodes"); out } /// The document from the bytes of its file (`save`), at `now`, keeping what a /// checkpoint forgot for `keeps_forgotten`. Every event is offered to a store anew, /// and every entry checked: what the bytes hold that the store wouldn't take, it /// doesn't. pub(crate) fn load( bytes: &[u8], keeps_forgotten: Duration, now: Instant, ) -> Result { let body = bytes .strip_prefix(FILE) .ok_or_else(|| Refused::new("no document of a set of events"))?; let saved: Saved = rmp_serde::from_slice(body).map_err(|error| Refused::new(error.to_string()))?; let id = Id(saved.store); let kept: Vec> = saved .kept .into_iter() .map(|bytes| bytes.into_vec()) .collect(); let store = if Id::of(&saved.checkpoint) == id { Store::new(saved.checkpoint, kept)? } else { Store::pinned(id, saved.checkpoint, kept)? }; let ids = |ids: &[[u8; 32]]| ids.iter().map(|id| Id(*id)).collect::>(); let writes: Vec<(Id, Id)> = saved .writes .iter() .map(|(id, writes)| (Id(*id), Id(*writes))) .collect(); let store = store.refusing(&ids(&saved.own), &ids(&saved.dropped), &writes); let mut set = Self::new(store, keeps_forgotten).pinned_at(saved.pinned.map(Id)); for event in saved.taken { set.store.offer(event.into_vec()); } let _ = set.settle(now); for (bytes, why) in saved.beside { let bytes = bytes.into_vec(); let id = Id::of(&bytes); if bytes.len() > F::LARGEST || set.store.get(&id).is_some() { continue; } let why = match why { SavedBeside::Own => Beside::Own, SavedBeside::Unjudged => { set.unjudged.push_back(id); set.unjudged_bytes += bytes.len(); Beside::Unjudged } // As long ago as the file says, as far as this clock goes back. SavedBeside::Forgotten(ago) => { Beside::Forgotten(now.checked_sub(Duration::from_secs(ago)).unwrap_or(now)) } }; set.names.insert(id.0); set.beside.insert(id, (bytes, why)); } let _ = set.settle(now); set.expire(now); for entry in saved.entries { if let Some(entry) = Entry::decode(&entry) { set.put_entry(entry); } } Ok(set) } /// That the names kept are those of what the document holds: looked at each time /// while they are few, and now and then when many. #[cfg(test)] fn check(&self) { assert_eq!( self.stands, stands_of(&self.store), "where the store stands" ); assert!( self.entries.len() == self.entry_names.len() && self .entries .iter() .all(|(node, entry)| self.entry_names.get(&entry.name()) == Some(node)), "the entries' names" ); if self.names.len() > 256 && !self.names.len().is_multiple_of(61) { return; } assert!( self.names.iter().eq(self.named().iter()), "the names kept aren't what the document holds" ); } /// The names of all the document gives to others, to catch up by /// (`document::ranges`): what its store took and what its checkpoint keeps, and what /// it holds beside. pub(crate) fn names(&self) -> &Names { &self.names } /// The names anew, from what the document holds: what `names` keeps. #[cfg(test)] pub(crate) fn named(&self) -> BTreeSet { self.store .taken() .iter() .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() } } #[cfg(test)] mod tests { use super::super::testfold::{self, TestFold}; use super::*; const KEEPS: Duration = Duration::from_secs(60); fn set() -> Set { Set::new( Store::new(testfold::root("tests"), Vec::new()).expect("a root"), KEEPS, ) } fn taken(offered: Offered) -> Id { match offered { Offered::Taken(ids) => ids[0], other => panic!("not taken: {other:?}"), } } #[test] fn what_the_store_takes_is_the_stores() { let mut set = set(); let now = Instant::now(); let root = set.store().id(); let put = testfold::put(&[root], "a", "1"); let id = taken(set.offer(put.clone(), now)); assert_eq!(set.get(&id), Some(put.as_slice())); assert_eq!(set.beside(&id), None); assert_eq!(set.named(), BTreeSet::from([id.0])); } #[test] fn what_the_fold_refuses_is_held_by_nobody() { let mut set = set(); let now = Instant::now(); let root = set.store().id(); let junk = testfold::junk(&[root]); let id = Id::of(&junk); assert!(matches!( set.offer(junk, now), Offered::Refused(Refusal::Judged(_)) )); // Nor what builds on it, nor what is no event. let on = testfold::put(&[id], "a", "1"); let on_id = Id::of(&on); assert_eq!(set.offer(on, now), Offered::Refused(Refusal::BuiltOn(id))); assert_eq!( set.offer(b"no event".to_vec(), now), Offered::Refused(Refusal::None) ); assert_eq!(set.get(&id), None); assert_eq!(set.get(&on_id), None); assert!(set.names().is_empty()); } #[test] fn what_the_node_refuses_of_its_own_it_gives_to_others() { let mut set = set(); let now = Instant::now(); let root = set.store().id(); taken(set.offer(testfold::era(&[root], 1, "one"), now)); let other = testfold::era(&[root], 1, "other"); let other_id = Id::of(&other); assert_eq!( set.offer(other.clone(), now), Offered::Refused(Refusal::Own) ); assert_eq!(set.get(&other_id), Some(other.as_slice())); assert_eq!(set.beside(&other_id), Some(Beside::Own)); // And what builds on it, unjudged; and on that. let on = testfold::put(&[other_id], "a", "1"); let on_id = Id::of(&on); assert_eq!( set.offer(on.clone(), now), Offered::Refused(Refusal::BuiltOn(other_id)) ); assert_eq!(set.beside(&on_id), Some(Beside::Unjudged)); let further = testfold::put(&[on_id], "a", "2"); let further_id = Id::of(&further); set.offer(further, now); assert_eq!(set.beside(&further_id), Some(Beside::Unjudged)); assert!(set.names().contains(&other_id.0)); assert!(set.names().contains(&further_id.0)); // Offered again, it is as it was. assert_eq!(set.offer(other, now), Offered::Refused(Refusal::Own)); assert_eq!(set.beside(&other_id), Some(Beside::Own)); } #[test] fn what_waited_on_the_nodes_own_is_held_unjudged() { let mut set = set(); let now = Instant::now(); let root = set.store().id(); taken(set.offer(testfold::era(&[root], 1, "one"), now)); let other = testfold::era(&[root], 1, "other"); let other_id = Id::of(&other); // What builds on it comes first, and waits. let on = testfold::put(&[other_id], "a", "1"); let on_id = Id::of(&on); assert_eq!(set.offer(on, now), Offered::Waiting); assert_eq!(set.beside(&on_id), None); set.offer(other, now); assert_eq!(set.beside(&on_id), Some(Beside::Unjudged)); } #[test] fn no_more_is_held_unjudged_than_the_bound() { let mut set = set(); let now = Instant::now(); let root = set.store().id(); taken(set.offer(testfold::era(&[root], 1, "one"), now)); let other = testfold::era(&[root], 1, "other"); let other_id = Id::of(&other); set.offer(other, now); let mut ids = Vec::new(); for n in 0..UNJUDGED + 10 { let on = testfold::put(&[other_id], "a", &n.to_string()); ids.push(Id::of(&on)); set.offer(on, now); } // The oldest went; the node's own stays. assert_eq!(set.beside(&ids[0]), None); assert_eq!(set.beside(&ids[9]), None); assert_eq!(set.beside(&ids[10]), Some(Beside::Unjudged)); assert_eq!( set.beside(ids.last().expect("some")), Some(Beside::Unjudged) ); assert_eq!(set.beside(&other_id), Some(Beside::Own)); assert_eq!(set.unjudged.len(), UNJUDGED); } #[test] fn what_an_operator_drops_is_given_to_others_and_taken_when_allowed() { let mut set = set(); let now = Instant::now(); let root = set.store().id(); let one = testfold::era(&[root], 1, "one"); let one_id = taken(set.offer(one.clone(), now)); let on = testfold::put(&[one_id], "a", "1"); let on_id = taken(set.offer(on, now)); assert_eq!(set.drop_taken(&[one_id], now), Ok(vec![one_id, on_id])); assert_eq!(set.beside(&one_id), Some(Beside::Own)); assert_eq!(set.beside(&on_id), Some(Beside::Unjudged)); assert_eq!(set.get(&one_id), Some(one.as_slice())); assert!(set.store().taken().is_empty()); // Allowed again, the store takes both, and the document holds neither beside. set.allow(&[one_id], now); assert_eq!(set.beside(&one_id), None); assert_eq!(set.beside(&on_id), None); assert_eq!(set.store().taken().len(), 2); assert!(set.unjudged.is_empty()); assert_eq!(set.unjudged_bytes, 0); } #[test] fn what_a_checkpoint_forgot_is_kept_for_a_while() { let mut set = set(); let now = Instant::now(); let root = set.store().id(); let first = testfold::put(&[root], "a", "1"); let first_id = taken(set.offer(first.clone(), now)); let second = taken(set.offer(testfold::put(&[first_id], "a", "2"), now)); let lock = taken(set.offer(testfold::lock(&[second], "b"), now)); let before = set.named(); taken(set.offer(testfold::cut(&[lock], 1, &[lock]), now)); // The store moved, and forgot the first put; the document didn't. assert_eq!(set.store().get(&first_id), None); assert_eq!(set.get(&first_id), Some(first.as_slice())); assert_eq!(set.beside(&first_id), Some(Beside::Forgotten(now))); assert!(set.named().is_superset(&before)); // Until its time is up. assert!(!set.expire(now + KEEPS - Duration::from_secs(1))); assert_eq!(set.get(&first_id), Some(first.as_slice())); assert!(set.expire(now + KEEPS)); assert_eq!(set.get(&first_id), None); assert!(!set.names().contains(&first_id.0)); } fn key(seed: u8) -> crate::identity::NodeKey { crate::identity::NodeKey::from_seed([seed; 32]) } /// Makes the node of `key` a member of group `group` (none: no member), on `on`. fn member(set: &mut Set, on: Id, key: u8, group: &str) -> Id { let node = self::key(key).id(); taken(set.offer( testfold::put(&[on], &format!("node:{node}"), group), Instant::now(), )) } fn entry(set: &Set, key: u8, count: u64, alias: &str) -> Entry { Entry::new( &set.store().id(), &self::key(key), count, &serde_json::json!({ "alias": alias }), ) } #[test] fn a_members_newest_entry_is_its_entry() { let mut set = set(); let root = set.store().id(); member(&mut set, root, 1, "a"); let node = key(1).id(); let first = entry(&set, 1, 1, "one"); assert_eq!(set.put_entry(first.clone()), Put::Taken); assert_eq!(set.put_entry(first.clone()), Put::Held); assert_eq!(set.entry(&node), Some(&first)); assert!(set.names().contains(&first.name())); assert!(!set.wants(&first.name())); let second = entry(&set, 1, 2, "two"); assert!(set.wants(&second.name())); assert_eq!(set.put_entry(second.clone()), Put::Taken); assert_eq!(set.put_entry(first.clone()), Put::Older); assert_eq!(set.entry(&node), Some(&second)); assert!(!set.names().contains(&first.name())); assert_eq!(set.entry_named(&second.name()), Some(&second)); assert_eq!(set.entries().count(), 1); } #[test] fn of_two_entries_of_one_count_the_lower_name_is_kept() { let mut set = set(); let root = set.store().id(); member(&mut set, root, 1, "a"); let (one, other) = (entry(&set, 1, 1, "one"), entry(&set, 1, 1, "other")); let (low, high) = if one.name() < other.name() { (one, other) } else { (other, one) }; // Whichever comes first. assert_eq!(set.put_entry(high.clone()), Put::Taken); assert_eq!(set.put_entry(low.clone()), Put::Taken); assert_eq!(set.put_entry(high), Put::Older); assert_eq!(set.entry(&key(1).id()), Some(&low)); } #[test] fn an_entry_of_no_member_is_held_by_nobody() { let mut set = set(); let root = set.store().id(); let stranger = entry(&set, 2, 1, "stranger"); assert_eq!(set.put_entry(stranger.clone()), Put::Stranger); assert_eq!(set.entry(&key(2).id()), None); // Not asked for again, until who is a member changes. assert!(!set.wants(&stranger.name())); let made = member(&mut set, root, 2, "a"); assert!(set.wants(&stranger.name())); assert_eq!(set.put_entry(stranger.clone()), Put::Taken); // And gone with its node. member(&mut set, made, 2, ""); assert_eq!(set.entry(&key(2).id()), None); assert!(!set.names().contains(&stranger.name())); } #[test] fn an_entry_of_another_store_or_changed_is_refused() { let mut set = set(); let root = set.store().id(); member(&mut set, root, 1, "a"); let other = Entry::new( &Id::of(b"another store"), &key(1), 1, &serde_json::json!({}), ); assert!(matches!(set.put_entry(other), Put::Refused(_))); assert_eq!(set.entries().count(), 0); } #[test] fn what_the_store_has_seen_isnt_wanted() { let mut set = set(); let now = Instant::now(); let root = set.store().id(); let put = testfold::put(&[root], "a", "1"); let junk = testfold::junk(&[root]); let waits = testfold::put(&[Id::of(b"nowhere")], "a", "1"); for bytes in [&put, &junk, &waits] { assert!(set.wants(&Id::of(bytes).0)); set.offer(bytes.clone(), now); assert!(!set.wants(&Id::of(bytes).0)); } assert!(!set.wants(&root.0)); } #[test] fn a_document_reads_back_from_its_file() { let mut set = set(); let now = Instant::now(); let root = set.store().id(); // A member and its entry; an era, and one the node refuses of its own, with what // builds on it; puts, a lock, and a cut that forgets the first of them. let made = member(&mut set, root, 1, "a"); let entry = entry(&set, 1, 1, "one"); set.put_entry(entry.clone()); let era = taken(set.offer(testfold::era(&[made], 1, "one"), now)); let other = testfold::era(&[made], 1, "other"); let other_id = Id::of(&other); set.offer(other, now); let on = testfold::put(&[other_id], "x", "1"); let on_id = Id::of(&on); set.offer(on, now); let first = taken(set.offer(testfold::put(&[era], "a", "1"), now)); let second = taken(set.offer(testfold::put(&[first], "a", "2"), now)); let lock = taken(set.offer(testfold::lock(&[second], "b"), now)); taken(set.offer(testfold::cut(&[lock], 1, &[lock]), now)); let after = taken(set.offer(testfold::put(&set.store().heads(), "c", "1"), now)); assert!(matches!(set.beside(&first), Some(Beside::Forgotten(_)))); let later = now + Duration::from_secs(10); let read = Set::::load(&set.save(later), KEEPS, later).expect("a document"); assert_eq!(read.named(), set.named()); assert_eq!(read.store().id(), set.store().id()); assert_eq!(read.store().checkpoint(), set.store().checkpoint()); assert_eq!(read.store().taken(), set.store().taken()); assert_eq!(read.store().state().counts(), set.store().state().counts()); assert!(read.store().get(&after).is_some()); assert_eq!(read.beside(&other_id), Some(Beside::Own)); assert_eq!(read.beside(&on_id), Some(Beside::Unjudged)); assert_eq!(read.entry(&key(1).id()), Some(&entry)); assert_eq!(read.unjudged_bytes, set.unjudged_bytes); // The node refuses its own as before, offered again. let mut read = read; assert_eq!( read.offer(testfold::era(&[made], 1, "other"), later), Offered::Refused(Refusal::Own) ); // What the checkpoint forgot is kept for what is left of its time. assert!(read.get(&first).is_some()); assert!(!read.expire(later + KEEPS - Duration::from_secs(11))); assert!(read.expire(later + KEEPS - Duration::from_secs(10))); assert!(read.get(&first).is_none()); } #[test] fn a_file_past_its_time_holds_nothing_forgotten() { let mut set = set(); let now = Instant::now(); let root = set.store().id(); let first = taken(set.offer(testfold::put(&[root], "a", "1"), now)); let second = taken(set.offer(testfold::put(&[first], "a", "2"), now)); let lock = taken(set.offer(testfold::lock(&[second], "b"), now)); taken(set.offer(testfold::cut(&[lock], 1, &[lock]), now)); let later = now + KEEPS; let read = Set::::load(&set.save(later), KEEPS, later).expect("a document"); assert!(read.get(&first).is_none()); assert_eq!(read.store().taken(), set.store().taken()); } #[test] fn what_is_no_document_isnt_read() { assert!(Set::::load(b"something else", KEEPS, Instant::now()).is_err()); let mut cut = set().save(Instant::now()); cut.truncate(cut.len() - 3); assert!(Set::::load(&cut, KEEPS, Instant::now()).is_err()); } #[test] fn what_a_move_leaves_beside_the_heads_is_held_no_more() { let mut set = set(); let now = Instant::now(); let root = set.store().id(); let first = taken(set.offer(testfold::put(&[root], "a", "1"), now)); let lock = taken(set.offer(testfold::lock(&[first], "b"), now)); // Written beside the lock, on the first put: not above the heads to come. let beside = taken(set.offer(testfold::put(&[first], "c", "1"), now)); assert!(set.names().contains(&beside.0)); taken(set.offer(testfold::cut(&[lock], 1, &[lock]), now)); assert_eq!(set.get(&beside), None); assert!(!set.names().contains(&beside.0)); assert!(!set.wants(&beside.0)); } #[test] fn no_more_wait_than_the_bound() { let mut set = set(); let now = Instant::now(); let mut waiting = Vec::new(); for n in 0..WAITS + 5 { let on = Id::of(format!("nowhere {n}").as_bytes()); let put = testfold::put(&[on], "a", "1"); waiting.push(Id::of(&put)); assert_eq!(set.offer(put, now), Offered::Waiting); } // The ones waiting longest went, as if they had never come: wanted again. assert!(set.wants(&waiting[0].0)); assert!(set.wants(&waiting[4].0)); assert!(!set.wants(&waiting[5].0)); 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::::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)); } /// A file written before it said which checkpoint was pinned: read, with none. #[test] fn a_file_that_says_no_pinned_checkpoint_reads() { use serde_bytes::ByteBuf; type Before = ( [u8; 32], ByteBuf, Vec, Vec, Vec<[u8; 32]>, Vec<[u8; 32]>, Vec<([u8; 32], [u8; 32])>, Vec<(ByteBuf, SavedBeside)>, Vec, ); let mut set = set(); let now = Instant::now(); let root = set.store().id(); let id = taken(set.offer(testfold::put(&[root], "a", "1"), now)); let saved = set.pinned_at(Some(root)).save(now); let body = saved.strip_prefix(FILE).expect("a file"); let (a, b, c, d, e, f, g, h, i, pinned): (_, _, _, _, _, _, _, _, _, Option<[u8; 32]>) = rmp_serde::from_slice(body).expect("as written"); assert_eq!(pinned, Some(root.0)); let before: Before = (a, b, c, d, e, f, g, h, i); let mut file = FILE.to_vec(); rmp_serde::encode::write(&mut file, &before).expect("it encodes"); let read = Set::::load(&file, KEEPS, now).expect("it reads"); assert_eq!(read.pinned(), None); assert_eq!(read.store().taken(), &[id]); } }