aboutsummaryrefslogtreecommitdiffstats
path: root/src/federation/store/passing.rs
blob: 39d78b7c7a1486ca90414df13043d3c62267db7e (plain)
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
//! Passing a set of events on (`docs/document.md`, A set of events, Passing on): what
//! two nodes say to each other of their sets, and what a node makes of what it is told.
//! A node keeps nothing of a peer between messages: each message is answered by what the
//! node holds as it comes.
//!
//! * Where a node stands (`Stamp`), said now and then: its store's checkpoint and
//!   heads, which are the same exactly where two stores hold the same; and the
//!   fingerprint of all its names, events and entries.
//! * Fingerprints differ: the two find what differs by ranges (`document::ranges`),
//!   and each asks for the names it lacks and would have (`Set::wants`).
//! * Fingerprints the same and heads not: either the two refuse differently of their
//!   own and hold the same all the same, or someone made fingerprints collide. A node
//!   says its heads, and the other asks for those it doesn't know.
//! * What is asked for by name is sent, as far as it is held; what comes is offered to
//!   the store, or put as an entry; and for what the store then waits on and doesn't
//!   hold, the node asks in turn, back to what both hold.

use std::time::Instant;

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use super::entry::Entry;
use super::memory::Offered;
use super::set::{Put, Set};
use super::{Fold, Id};
use crate::document::ranges::{self, Name};

/// The most names a message of ranges holds, and the most a node asks for at once.
const NAMES: usize = 4096;

/// The most bytes of events and entries in one message.
const BYTES: usize = 1 << 20;

/// Where a node's set stands.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Stamp {
    /// Of its store's checkpoint and heads.
    heads: [u8; 32],
    /// The fingerprint of all its names.
    names: ranges::Fingerprint,
}

/// An event or an entry, as passed on.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum Unit {
    Event(#[serde(with = "serde_bytes")] Vec<u8>),
    Entry(#[serde(with = "serde_bytes")] Vec<u8>),
}

/// What one node says to another of its set.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum Message {
    /// Where it stands.
    Stamp(Stamp),
    /// Its store's heads.
    Heads(Vec<Name>),
    /// Ranges of its names, and their fingerprints or the names.
    Ranges(ranges::Message),
    /// Names it lacks and would have.
    Wants(Vec<Name>),
    /// Events and entries: asked for, or new.
    Units(Vec<Unit>),
}

/// What a node took of a message.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct Took {
    /// The events its store took, in the order taken.
    pub(crate) events: Vec<Id>,
    /// The members whose entry it took.
    pub(crate) entries: Vec<String>,
}

impl Took {
    pub(crate) fn is_empty(&self) -> bool {
        self.events.is_empty() && self.entries.is_empty()
    }
}

/// Where `set` stands.
pub(crate) fn stamp<F: Fold>(set: &Set<F>) -> Stamp {
    let mut hasher = Sha256::new();
    hasher.update(Id::of(set.store().checkpoint()).0);
    // In one order on every node: a store says its heads as it took them.
    let mut heads = set.store().heads();
    heads.sort();
    for head in heads {
        hasher.update(head.0);
    }
    Stamp {
        heads: hasher.finalize().into(),
        names: ranges::fingerprint(&set.names()),
    }
}

/// The unit named `name`, where `set` holds it.
pub(crate) fn unit<F: Fold>(set: &Set<F>, name: &Name) -> Option<Unit> {
    set.get(&Id(*name))
        .map(|bytes| Unit::Event(bytes.to_vec()))
        .or_else(|| {
            set.entry_named(name)
                .map(|entry| Unit::Entry(entry.encode()))
        })
}

/// What `set` makes of `message`, at `now`: what to say back, and what it took.
pub(crate) fn receive<F: Fold>(
    set: &mut Set<F>,
    message: Message,
    now: Instant,
) -> (Vec<Message>, Took) {
    let mut replies = Vec::new();
    let mut took = Took::default();
    match message {
        Message::Stamp(theirs) => {
            let ours = stamp(set);
            if theirs.names != ours.names {
                replies.push(Message::Ranges(ranges::open(&set.names())));
            } else if theirs.heads != ours.heads {
                replies.push(Message::Heads(
                    set.store().heads().iter().map(|id| id.0).collect(),
                ));
            }
        }
        Message::Heads(heads) => ask(set, heads, &mut replies),
        Message::Ranges(theirs) => {
            let answer = ranges::answer(&set.names(), &theirs, NAMES);
            ask(set, answer.lacking, &mut replies);
            if let Some(reply) = answer.reply {
                replies.push(Message::Ranges(reply));
            }
        }
        Message::Wants(names) => {
            let mut units = Vec::new();
            let mut bytes = 0;
            for name in names.iter().take(NAMES) {
                let Some(unit) = unit(set, name) else {
                    continue;
                };
                let size = match &unit {
                    Unit::Event(bytes) | Unit::Entry(bytes) => bytes.len(),
                };
                // What doesn't fit, the peer asks for again.
                if bytes + size > BYTES && !units.is_empty() {
                    break;
                }
                bytes += size;
                units.push(unit);
            }
            if !units.is_empty() {
                replies.push(Message::Units(units));
            }
        }
        Message::Units(units) => {
            for unit in units {
                match unit {
                    Unit::Event(bytes) => {
                        if let Offered::Taken(ids) = set.offer(bytes, now) {
                            took.events.extend(ids);
                        }
                    }
                    Unit::Entry(bytes) => {
                        if let Some(entry) = Entry::decode(&bytes) {
                            let node = entry.node();
                            if set.put_entry(entry) == Put::Taken {
                                took.entries.push(node);
                            }
                        }
                    }
                }
            }
            // What the store waits on now and doesn't hold: back to what both hold.
            let lacks = set.store().lacks().iter().map(|id| id.0).collect();
            ask(set, lacks, &mut replies);
        }
    }
    (replies, took)
}

/// Asks for those of `names` that `set` would have.
fn ask<F: Fold>(set: &Set<F>, names: Vec<Name>, replies: &mut Vec<Message>) {
    let wanted: Vec<Name> = names
        .into_iter()
        .filter(|name| set.wants(name))
        .take(NAMES)
        .collect();
    if !wanted.is_empty() {
        replies.push(Message::Wants(wanted));
    }
}

#[cfg(test)]
mod tests {
    use std::collections::VecDeque;
    use std::time::Duration;

    use super::super::memory::Store;
    use super::super::testfold::{self, TestFold};
    use super::*;
    use crate::testrand::{Rng, for_seeds};

    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 key(seed: u8) -> crate::identity::NodeKey {
        crate::identity::NodeKey::from_seed([seed; 32])
    }

    /// Has every node tell every other where it stands, and all that follows from it
    /// delivered, in an order `rng` chooses, losing none; the messages that went.
    fn settle(sets: &mut [Set<TestFold>], rng: &mut Rng, now: Instant) -> usize {
        let mut queue: VecDeque<(usize, usize, Message)> = VecDeque::new();
        for from in 0..sets.len() {
            for to in 0..sets.len() {
                if from != to {
                    queue.push_back((from, to, Message::Stamp(stamp(&sets[from]))));
                }
            }
        }
        let mut messages = 0;
        while !queue.is_empty() {
            let at = rng.below(queue.len());
            let (from, to, message) = queue.remove(at).expect("one queued");
            messages += 1;
            assert!(messages < 100_000, "passing on doesn't end");
            let (replies, _) = receive(&mut sets[to], message, now);
            for reply in replies {
                queue.push_back((to, from, reply));
            }
        }
        messages
    }

    /// Rounds of `settle` until a round changes nothing; how many it took.
    fn settled(sets: &mut [Set<TestFold>], rng: &mut Rng, now: Instant) -> usize {
        for round in 1..=20 {
            let before: Vec<_> = sets.iter().map(|set| set.names()).collect();
            settle(sets, rng, now);
            if sets.iter().map(|set| set.names()).collect::<Vec<_>>() == before {
                return round;
            }
        }
        panic!("the sets don't settle");
    }

    #[test]
    fn two_that_stand_alike_say_nothing_more() {
        let mut sets = [set(), set()];
        let now = Instant::now();
        let root = sets[0].store().id();
        for set in &mut sets {
            set.offer(testfold::put(&[root], "a", "1"), now);
        }
        assert_eq!(stamp(&sets[0]), stamp(&sets[1]));
        let mut rng = Rng::new(1);
        assert_eq!(settle(&mut sets, &mut rng, now), 2);
    }

    #[test]
    fn one_behind_catches_up() {
        let mut sets = [set(), set()];
        let now = Instant::now();
        let root = sets[0].store().id();
        let mut on = root;
        for n in 0..200 {
            let put = testfold::put(&[on], "a", &n.to_string());
            on = Id::of(&put);
            sets[0].offer(put, now);
        }
        let mut rng = Rng::new(2);
        settle(&mut sets, &mut rng, now);
        assert_eq!(sets[1].store().taken(), sets[0].store().taken());
        assert_eq!(stamp(&sets[0]), stamp(&sets[1]));
    }

    #[test]
    fn nodes_that_wrote_apart_come_to_hold_the_same() {
        for_seeds(30, |rng| {
            let now = Instant::now();
            let count = rng.between(2, 5);
            let mut sets: Vec<Set<TestFold>> = (0..count).map(|_| set()).collect();
            let root = sets[0].store().id();
            // The members, known to all; then each writes on what it holds, apart.
            let mut on = root;
            for node in 0..count {
                let member = testfold::put(&[on], &format!("node:{}", key(node as u8).id()), "a");
                on = Id::of(&member);
                for set in &mut sets {
                    set.offer(member.clone(), now);
                }
            }
            for (node, set) in sets.iter_mut().enumerate() {
                let mut on = on;
                for n in 0..rng.between(0, 40) {
                    let put = testfold::put(&[on], &format!("k{}", rng.below(5)), &n.to_string());
                    on = Id::of(&put);
                    set.offer(put, now);
                }
                let entry = Entry::new(
                    &root,
                    &key(node as u8),
                    rng.between(1, 3) as u64,
                    &serde_json::json!({ "alias": node }),
                );
                assert_eq!(set.put_entry(entry), Put::Taken);
            }
            settled(&mut sets, rng, now);
            let first = &sets[0];
            for set in &sets[1..] {
                assert_eq!(stamp(set), stamp(first));
                assert_eq!(set.names(), first.names());
                assert_eq!(set.store().state().counts(), first.store().state().counts());
                assert_eq!(set.entries().count(), count);
            }
        });
    }

    #[test]
    fn what_one_refuses_of_its_own_still_reaches_the_others_through_it() {
        // b took the other era, and stands between a, which wrote on the one, and c.
        let (mut a, mut b, c) = (set(), set(), set());
        let now = Instant::now();
        let root = a.store().id();
        let other = testfold::era(&[root], 1, "other");
        b.offer(other, now);
        let one = testfold::era(&[root], 1, "one");
        let one_id = Id::of(&one);
        a.offer(one, now);
        let on = testfold::put(&[one_id], "a", "1");
        let on_id = Id::of(&on);
        a.offer(on, now);
        let mut rng = Rng::new(3);
        // a and b; then b and c: never a and c.
        let mut pair = [a, b];
        settled(&mut pair, &mut rng, now);
        let [a, b] = pair;
        assert!(b.store().get(&one_id).is_none());
        assert!(b.get(&one_id).is_some());
        assert!(b.get(&on_id).is_some());
        let mut pair = [b, c];
        settled(&mut pair, &mut rng, now);
        let [b, c] = pair;
        // c takes whichever era came first of b: both reached it.
        assert!(c.get(&one_id).is_some());
        assert!(c.get(&on_id).is_some());
        assert_eq!(c.names(), b.names());
        assert_eq!(a.names().len(), 3);
    }

    #[test]
    fn what_is_asked_for_and_held_is_sent_within_the_bound() {
        let mut set = set();
        let now = Instant::now();
        let root = set.store().id();
        let large = "x".repeat(40_000);
        let mut names = vec![[9; 32]];
        for n in 0..40 {
            let put = testfold::put(&[root], &format!("k{n}"), &large);
            names.push(Id::of(&put).0);
            assert!(matches!(set.offer(put, now), Offered::Taken(_)));
        }
        let (replies, took) = receive(&mut set, Message::Wants(names.clone()), now);
        assert!(took.is_empty());
        let [Message::Units(units)] = replies.as_slice() else {
            panic!("no units: {replies:?}");
        };
        let sizes: Vec<usize> = units
            .iter()
            .map(|unit| match unit {
                Unit::Event(bytes) | Unit::Entry(bytes) => bytes.len(),
            })
            .collect();
        assert!(sizes.iter().sum::<usize>() <= BYTES);
        assert!(
            units.len() > 20 && units.len() < 40,
            "{} units",
            units.len()
        );
        // Those asked for first, as far as held.
        assert_eq!(units[0], unit(&set, &names[1]).expect("held"));
    }

    #[test]
    fn a_node_asks_back_for_what_an_event_builds_on() {
        // Told a head alone, a node asks for it, and then for what it builds on.
        let mut ahead = set();
        let mut behind = set();
        let now = Instant::now();
        let root = ahead.store().id();
        let first = testfold::put(&[root], "a", "1");
        let first_id = Id::of(&first);
        let second = testfold::put(&[first_id], "a", "2");
        let second_id = Id::of(&second);
        ahead.offer(first, now);
        ahead.offer(second, now);
        let (replies, _) = receive(&mut behind, Message::Heads(vec![second_id.0]), now);
        assert_eq!(replies, vec![Message::Wants(vec![second_id.0])]);
        let (units, _) = receive(&mut ahead, replies[0].clone(), now);
        let (replies, took) = receive(&mut behind, units[0].clone(), now);
        assert!(took.is_empty());
        assert_eq!(replies, vec![Message::Wants(vec![first_id.0])]);
        let (units, _) = receive(&mut ahead, replies[0].clone(), now);
        let (replies, took) = receive(&mut behind, units[0].clone(), now);
        assert!(replies.is_empty());
        assert_eq!(took.events, vec![first_id, second_id]);
    }

    #[test]
    fn messages_read_back_from_their_bytes() {
        let set = set();
        for message in [
            Message::Stamp(stamp(&set)),
            Message::Heads(vec![[1; 32]]),
            Message::Ranges(ranges::open(&set.names())),
            Message::Wants(vec![[2; 32]]),
            Message::Units(vec![Unit::Event(vec![1, 2]), Unit::Entry(vec![3])]),
        ] {
            let bytes = rmp_serde::to_vec(&message).expect("a message encodes");
            assert_eq!(
                rmp_serde::from_slice::<Message>(&bytes).expect("a message"),
                message
            );
        }
    }
}