1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
|
//! 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<F: Fold> {
store: Store<F>,
/// What is held beside the store, by ID.
beside: BTreeMap<Id, (Vec<u8>, Beside)>,
/// The unjudged among them, the oldest first, and their bytes in all.
unjudged: VecDeque<Id>,
unjudged_bytes: usize,
/// For how long what a checkpoint forgot is kept.
keeps_forgotten: Duration,
}
impl<F: Fold> Set<F> {
/// The document of `store`, keeping what a checkpoint forgot for `keeps_forgotten`.
pub(crate) fn new(store: Store<F>, 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<F> {
&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<u8>, 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<Vec<Id>, 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<Id> = 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<Beside> {
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<Name> {
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<TestFold> {
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));
}
}
|