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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
|
//! A fold made for the store's tests (`docs/federation-tests.md`): smaller than the
//! federation's, but judging by history, refusing by what a node took before, reading by
//! what counts, and moving to checkpoints, as the federation does.
//!
//! * `put`: a value at a key, refused where the key is locked at its history. What a key
//! holds is its latest put, none other having it in its history, then the lowest ID.
//! * `lock`: a key locked for good.
//! * `era`: era `n`, taken only where `n` is one past the era at its history; of two of one
//! number, a node keeps the first it takes (as the federation's versions).
//! * `cut`: cut `n`, naming heads to move the store to, as `era`: above the heads the latest
//! cut of its history names, and holding that cut (or after the checkpoint the state
//! starts from, where it holds none); none of them in another's history. It must be above
//! them.
//! * `junk`: refused wherever it is.
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use super::{Fold, Id, Refused};
#[derive(Serialize, Deserialize)]
struct Event {
deps: Vec<String>,
kind: Kind,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum Kind {
Put { key: String, value: String },
Lock { key: String },
Era { n: u64, tag: String },
Cut { n: u64, heads: Vec<String> },
Junk,
}
/// A checkpoint, a root among them.
#[derive(Serialize, Deserialize)]
struct Checkpoint {
name: String,
at: Vec<String>,
keeps: Vec<String>,
era: u64,
tag: String,
cut: u64,
locks: Vec<String>,
}
/// An event of this fold, built on `deps`.
pub(crate) fn event(deps: &[Id], kind: Kind) -> Vec<u8> {
let mut deps: Vec<String> = deps.iter().map(Id::to_string).collect();
deps.sort();
deps.dedup();
serde_json::to_vec(&Event { deps, kind }).expect("an event encodes")
}
pub(crate) fn put(deps: &[Id], key: &str, value: &str) -> Vec<u8> {
event(
deps,
Kind::Put {
key: key.to_owned(),
value: value.to_owned(),
},
)
}
pub(crate) fn lock(deps: &[Id], key: &str) -> Vec<u8> {
event(
deps,
Kind::Lock {
key: key.to_owned(),
},
)
}
pub(crate) fn era(deps: &[Id], n: u64, tag: &str) -> Vec<u8> {
event(
deps,
Kind::Era {
n,
tag: tag.to_owned(),
},
)
}
pub(crate) fn cut(deps: &[Id], n: u64, heads: &[Id]) -> Vec<u8> {
let mut heads: Vec<String> = heads.iter().map(Id::to_string).collect();
heads.sort();
event(deps, Kind::Cut { n, heads })
}
pub(crate) fn junk(deps: &[Id]) -> Vec<u8> {
event(deps, Kind::Junk)
}
/// A root, named so that tests can tell several apart.
pub(crate) fn root(name: &str) -> Vec<u8> {
serde_json::to_vec(&Checkpoint {
name: name.to_owned(),
at: Vec::new(),
keeps: Vec::new(),
era: 0,
tag: String::new(),
cut: 0,
locks: Vec::new(),
})
.expect("a root encodes")
}
/// What a fork's root takes besides its heads: the era it starts in.
pub(crate) fn fork_spec(era: u64, tag: &str) -> Vec<u8> {
serde_json::to_vec(&(era, tag)).expect("a spec encodes")
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct State {
/// Every event added, by ID, with its dependencies.
graph: BTreeMap<Id, Vec<Id>>,
/// What the checkpoint keeps: in the history of every event after it.
before: BTreeSet<Id>,
/// The heads the checkpoint was built at.
at: BTreeSet<Id>,
puts: BTreeMap<String, BTreeSet<Id>>,
values: BTreeMap<Id, String>,
locks: BTreeSet<String>,
era: u64,
tags: BTreeMap<u64, String>,
cut: u64,
/// The heads each cut names, by its number; and each cut, with its number.
cuts: BTreeMap<u64, Vec<Id>>,
cut_events: BTreeMap<Id, u64>,
}
impl State {
/// Whether `b` is in the history of `a`.
pub(crate) fn built_on(&self, a: &Id, b: &Id) -> bool {
// What the checkpoint keeps is in the history of every event after it. Of the
// checkpoint's heads, the state holds no history: as it tells, none builds on what
// the checkpoint keeps, nor on another head.
if self.before.contains(b) {
return self.graph.contains_key(a) && !self.before.contains(a);
}
let mut seen = BTreeSet::new();
let mut todo: Vec<Id> = self.graph.get(a).cloned().unwrap_or_default();
while let Some(next) = todo.pop() {
if next == *b {
return true;
}
if seen.insert(next) {
todo.extend(self.graph.get(&next).into_iter().flatten().copied());
}
}
false
}
/// What each key holds: its latest put, then the lowest ID.
pub(crate) fn counts(&self) -> BTreeMap<String, String> {
self.counting()
.into_iter()
.map(|(key, id)| (key, self.values[&id].clone()))
.collect()
}
fn counting(&self) -> BTreeMap<String, Id> {
self.puts
.iter()
.filter_map(|(key, puts)| {
puts.iter()
.filter(|p| !puts.iter().any(|q| q != *p && self.built_on(q, p)))
.min()
.map(|id| (key.clone(), *id))
})
.collect()
}
pub(crate) fn locks(&self) -> &BTreeSet<String> {
&self.locks
}
pub(crate) fn era(&self) -> (u64, Option<&String>) {
(self.era, self.tags.get(&self.era))
}
pub(crate) fn cut(&self) -> u64 {
self.cut
}
/// The heads the latest cut names, where it is one of the state's events.
pub(crate) fn named(&self) -> Option<&[Id]> {
self.cuts.get(&self.cut).map(Vec::as_slice)
}
/// The events here above `heads` (`docs/store.md`, Events): each with them all in its
/// history, and each of its dependencies one of them or above them.
fn above(&self, heads: &BTreeSet<Id>) -> BTreeSet<Id> {
let mut above = BTreeSet::new();
loop {
let more: Vec<Id> = self
.graph
.iter()
.filter(|(id, deps)| {
!above.contains(*id)
&& !heads.contains(*id)
&& !deps.is_empty()
&& deps
.iter()
.all(|dep| heads.contains(dep) || above.contains(dep))
&& (deps.iter().any(|dep| above.contains(dep))
|| heads.iter().all(|head| deps.contains(head)))
})
.map(|(id, _)| *id)
.collect();
if more.is_empty() {
return above;
}
above.extend(more);
}
}
/// Whether an event built on `deps`, whose history reads as this state, may name
/// `heads` for a checkpoint: as `cut` says, and the event above them.
fn may_cut(&self, deps: &[Id], heads: &[Id]) -> bool {
if heads.is_empty() || heads.windows(2).any(|pair| pair[0] >= pair[1]) {
return false;
}
if heads
.iter()
.any(|a| heads.iter().any(|b| a != b && self.built_on(a, b)))
{
return false;
}
let after = match self.cuts.get(&self.cut) {
// The latest cut of the history is one of the state's events.
Some(current) => {
let above = self.above(¤t.iter().copied().collect());
heads.iter().all(|head| above.contains(head))
&& self.cut_events.iter().any(|(cut, n)| {
*n == self.cut
&& heads
.iter()
.any(|head| head == cut || self.built_on(head, cut))
})
}
// The latest cut is in the history of the checkpoint the state starts from: the
// heads are after that checkpoint, or its own, which count as after the latest
// cut and holding it, so that a node starting from it judges the cut naming it
// as every node does.
None => {
heads.iter().eq(self.at.iter())
|| heads
.iter()
.all(|head| self.graph.contains_key(head) && !self.before.contains(head))
}
};
let named: BTreeSet<Id> = heads.iter().copied().collect();
let above = self.above(&named);
after
&& deps
.iter()
.all(|dep| named.contains(dep) || above.contains(dep))
&& (deps.iter().any(|dep| above.contains(dep))
|| named.iter().all(|head| deps.contains(head)))
}
}
fn decode(bytes: &[u8]) -> Option<(Vec<Id>, Kind)> {
let event: Event = serde_json::from_slice(bytes).ok()?;
let deps = event
.deps
.iter()
.map(|dep| Id::from_hex(dep))
.collect::<Option<Vec<_>>>()?;
Some((deps, event.kind))
}
fn ids(texts: &[String]) -> Option<Vec<Id>> {
texts.iter().map(|text| Id::from_hex(text)).collect()
}
fn hex(ids: impl IntoIterator<Item = Id>) -> Vec<String> {
let mut texts: Vec<String> = ids.into_iter().map(|id| id.to_string()).collect();
texts.sort();
texts
}
pub(crate) struct TestFold;
impl Fold for TestFold {
type State = State;
const NAME: &'static str = "test";
const LARGEST: usize = 64 * 1024;
fn dependencies(event: &[u8]) -> Option<Vec<Id>> {
decode(event).map(|(deps, _)| deps)
}
fn judge(at: &State, _id: &Id, event: &[u8]) -> Result<(), Refused> {
let (deps, kind) = decode(event).ok_or_else(|| Refused::new("no event"))?;
match kind {
Kind::Put { key, .. } if at.locks.contains(&key) => {
Err(Refused::new(format!("{key} is locked")))
}
Kind::Put { .. } | Kind::Lock { .. } => Ok(()),
Kind::Era { n, .. } if n == at.era + 1 => Ok(()),
Kind::Era { n, .. } => Err(Refused::new(format!("era {n} after {}", at.era))),
Kind::Cut { n, heads } => {
let heads = ids(&heads).ok_or_else(|| Refused::new("heads not IDs"))?;
if n != at.cut + 1 {
Err(Refused::new(format!("cut {n} after {}", at.cut)))
} else if !at.may_cut(&deps, &heads) {
Err(Refused::new("heads it may not name"))
} else {
Ok(())
}
}
Kind::Junk => Err(Refused::new("junk")),
}
}
fn add(state: &mut State, id: &Id, event: &[u8]) {
let Some((deps, kind)) = decode(event) else {
return;
};
state.graph.insert(*id, deps);
match kind {
Kind::Put { key, value } => {
state.puts.entry(key).or_default().insert(*id);
state.values.insert(*id, value);
}
Kind::Lock { key } => {
state.locks.insert(key);
}
Kind::Era { n, tag } => {
state.era = state.era.max(n);
state.tags.insert(n, tag);
}
Kind::Cut { n, heads } => {
state.cut = state.cut.max(n);
state.cuts.insert(n, ids(&heads).unwrap_or_default());
state.cut_events.insert(*id, n);
}
Kind::Junk => {}
}
}
fn keeps(now: &State, _id: &Id, event: &[u8]) -> bool {
match decode(event) {
Some((_, Kind::Era { n, tag })) => {
n == now.era + 1 || now.tags.get(&n).is_some_and(|took| *took == tag)
}
Some((_, Kind::Cut { n, heads })) => {
n == now.cut + 1
|| now
.cuts
.get(&n)
.is_some_and(|took| ids(&heads).is_some_and(|heads| *took == heads))
}
_ => true,
}
}
fn checkpoint(at: &State, heads: &[Id]) -> (Vec<u8>, Vec<Id>) {
let keeps: Vec<Id> = at.counting().into_values().collect();
let checkpoint = Checkpoint {
name: String::new(),
at: hex(heads.iter().copied()),
keeps: hex(keeps.iter().copied()),
era: at.era,
tag: at.tags.get(&at.era).cloned().unwrap_or_default(),
cut: at.cut,
locks: at.locks.iter().cloned().collect(),
};
let bytes = serde_json::to_vec(&checkpoint).expect("a checkpoint encodes");
(bytes, keeps)
}
fn parts(checkpoint: &[u8]) -> Option<(Vec<Id>, Vec<Id>)> {
let checkpoint: Checkpoint = serde_json::from_slice(checkpoint).ok()?;
Some((ids(&checkpoint.at)?, ids(&checkpoint.keeps)?))
}
fn start(checkpoint: &[u8], kept: &[(Id, Vec<u8>)]) -> Result<State, Refused> {
let checkpoint: Checkpoint =
serde_json::from_slice(checkpoint).map_err(|_| Refused::new("no checkpoint"))?;
let mut state = State {
at: ids(&checkpoint.at)
.ok_or_else(|| Refused::new("heads not IDs"))?
.into_iter()
.collect(),
locks: checkpoint.locks.into_iter().collect(),
era: checkpoint.era,
cut: checkpoint.cut,
..State::default()
};
state.tags.insert(checkpoint.era, checkpoint.tag);
for (id, bytes) in kept {
match decode(bytes) {
Some((_, Kind::Put { key, value })) => {
state.graph.insert(*id, Vec::new());
state.before.insert(*id);
state.puts.entry(key).or_default().insert(*id);
state.values.insert(*id, value);
}
_ => return Err(Refused::new("a checkpoint keeps puts only")),
}
}
Ok(state)
}
fn fork(at: &State, heads: &[Id], spec: &[u8]) -> Result<(Vec<u8>, Vec<Id>), Refused> {
let (era, tag): (u64, String) =
serde_json::from_slice(spec).map_err(|_| Refused::new("no spec"))?;
let keeps: Vec<Id> = at.counting().into_values().collect();
let root = Checkpoint {
name: String::new(),
at: hex(heads.iter().copied()),
keeps: hex(keeps.iter().copied()),
era,
tag,
cut: 0,
locks: at.locks.iter().cloned().collect(),
};
let bytes = serde_json::to_vec(&root).expect("a root encodes");
Ok((bytes, keeps))
}
fn moves_to(now: &State) -> Option<Vec<Id>> {
let heads = now.cuts.get(&now.cut)?;
(heads.iter().copied().collect::<BTreeSet<_>>() != now.at).then(|| heads.clone())
}
fn members(_state: &State) -> Vec<(String, String)> {
Vec::new()
}
}
|