aboutsummaryrefslogtreecommitdiffstats
path: root/src/federation
diff options
context:
space:
mode:
Diffstat (limited to 'src/federation')
-rw-r--r--src/federation/store/set.rs217
1 files changed, 217 insertions, 0 deletions
diff --git a/src/federation/store/set.rs b/src/federation/store/set.rs
index 88dfa73..cb55136 100644
--- a/src/federation/store/set.rs
+++ b/src/federation/store/set.rs
@@ -19,6 +19,8 @@
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::time::{Duration, Instant};
+use serde::{Deserialize, Serialize};
+
use super::entry::Entry;
use super::memory::{Gone, Offered, Refusal, Store};
use super::{Fold, Id, Refused};
@@ -68,6 +70,33 @@ fn members_of<F: Fold>(store: &Store<F>) -> BTreeSet<String> {
.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<u8>,
+ kept: Vec<serde_bytes::ByteBuf>,
+ taken: Vec<serde_bytes::ByteBuf>,
+ own: Vec<[u8; 32]>,
+ dropped: Vec<[u8; 32]>,
+ writes: Vec<([u8; 32], [u8; 32])>,
+ beside: Vec<(serde_bytes::ByteBuf, SavedBeside)>,
+ entries: Vec<serde_bytes::ByteBuf>,
+}
+
+/// 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),
+}
+
/// A set of events, of a fold `F`.
pub(crate) struct Set<F: Fold> {
store: Store<F>,
@@ -296,6 +325,122 @@ impl<F: Fold> Set<F> {
self.beside.get(id).map(|(_, why)| *why)
}
+ /// The document as bytes, at `now`: what its file holds. 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<u8> {
+ 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())
+ .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(),
+ };
+ 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<Self, Refused> {
+ 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<Vec<u8>> = 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::<Vec<Id>>();
+ 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);
+ for event in saved.taken {
+ set.store.offer(event.into_vec());
+ }
+ 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.beside.insert(id, (bytes, why));
+ }
+ set.settle(now);
+ set.expire(now);
+ for entry in saved.entries {
+ if let Some(entry) = Entry::decode(&entry) {
+ set.put_entry(entry);
+ }
+ }
+ Ok(set)
+ }
+
/// 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.
@@ -602,4 +747,76 @@ mod tests {
}
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::<TestFold>::load(&set.save(later), KEEPS, later).expect("a document");
+ assert_eq!(read.names(), set.names());
+ 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::<TestFold>::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::<TestFold>::load(b"something else", KEEPS, Instant::now()).is_err());
+ let mut cut = set().save(Instant::now());
+ cut.truncate(cut.len() - 3);
+ assert!(Set::<TestFold>::load(&cut, KEEPS, Instant::now()).is_err());
+ }
}