//! 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 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 super::memory::{Gone, Offered, Refusal, Store}; use super::{Fold, Id, Refused}; use crate::document::ranges::Name; /// 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), } /// 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, /// For how long what a checkpoint forgot is kept. keeps_forgotten: Duration, } impl Set { /// The document of `store`, keeping what a checkpoint forgot for `keeps_forgotten`. pub(crate) fn new(store: Store, keeps_forgotten: Duration) -> Self { Self { store: store.telling(), beside: BTreeMap::new(), unjudged: VecDeque::new(), unjudged_bytes: 0, keeps_forgotten, } } /// 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); self.settle(now); offered } /// 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); 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) { if why == Beside::Unjudged { self.unjudged.retain(|other| *other != id); self.unjudged_bytes -= bytes.len(); } self.store.offer(bytes); } } self.settle(now); } /// Takes in what the store let go of. fn settle(&mut self, now: Instant) { for (id, bytes, gone) in self.store.let_go() { let why = match gone { Gone::Forgotten => Beside::Forgotten(now), Gone::Own => Beside::Own, Gone::BuiltOn(on) => { if !self.own(&on) { continue; } Beside::Unjudged } }; if why == Beside::Unjudged { self.unjudged.push_back(id); self.unjudged_bytes += bytes.len(); } 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.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 }); } /// 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(); self.beside.retain(|_, (_, why)| match why { Beside::Forgotten(since) => now.saturating_duration_since(*since) < keeps, _ => true, }); self.beside.len() != before } /// The bytes of an event the document gives to others: one its store holds, or one /// held beside it. pub(crate) fn get(&self, id: &Id) -> Option<&[u8]> { self.store .get(id) .or_else(|| self.beside.get(id).map(|(bytes, _)| bytes.as_slice())) } /// 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 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) -> 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)) .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.names(), 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.names(); 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.names().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)); } }