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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! Defines the [`Cluster`] utility which trivializes implementing
//! [`State::cluster_at`][crate::State::cluster_at] and
//! [`State::concurrency`][crate::State::concurrency].

use std::collections::VecDeque;
use std::num::NonZeroUsize;

/// Reflects wheter a log entry affects the cluster.
pub trait ClusterLogEntry<N> {
    /// Returns the target concurrency level, if this log entry sets it.
    fn concurrency(&self) -> Option<NonZeroUsize>;

    /// Return the nodes that this log entry adds to the cluster.
    fn added_nodes(&self) -> Vec<N>;

    /// Return the nodes that this log entry removes from the cluster.
    fn removed_nodes(&self) -> Vec<N>;
}

/// Utility to ease the implementation of changes in cluster membership, i.e.
/// joining and parting of nodes, and concurrency.
///
/// This utility is most useful to implementors of the [State](crate::State)
/// trait. Whenever a log entry is [applied](crate::State::apply) it should also
/// be [applied](Cluster::apply) to this `Cluster`. If done consistently,
/// [`concurrency_at_offset_one`](Cluster::concurrency_at_offset_one) and
/// [`nodes_at`](Cluster::nodes_at) can be used to trivially implement the
/// methods [`concurrency`](crate::State::concurrency) and
/// [`cluster_at`](crate::State::cluster_at).
///
/// # Membership Changes
///
/// No limits are placed on membership changes. Practically speaking, however,
/// it is wise not to make significant changes quickly. Nodes should not become
/// voting members of a cluster until they can be certain they won't break an
/// earlier commitment.
///
/// # Concurrency Increases
///
/// The implementation is "optimal" in that it takes advantage of concurrency
/// increases the moment they become known.
///
/// | Round                 | r | r + 1 | r + 2 | … |
/// |-----------------------|---|-------|-------|---|
/// | Log Entry             |   | c ≔ 5 |       |   |
/// | Target Concurrency    | 2 |     5 |     5 | … |
/// | Effective Concurrency | 2 |     5 |     5 | … |
///
/// # Concurrency Decreases
///
/// When concurrency is decreased, it cannot be assumed that everyone knows of
/// this reduction until the the previous concurrency window is exhausted.
/// Consider that the concurrency level is `5` in round `r` and is then reduced
/// by a log entry in round `r + 1`. Any node that does not see that log entry
/// in time may think the concurrency level is unchanged, at least until it
/// exhausts the concurrency of `5` in round `r + 5`. Any further append to the
/// log is only allowed while taking the reduction into account. That means that
/// in effect the concurrency level slowly reduces from `5` to `2`, as if the
/// `5` throws a shadow along the axis of concurrency.
///
/// | Round                 | r | r + 1 | r + 2 | r + 3 | r + 4 | r + 5 | … |
/// |-----------------------|---|-------|-------|-------|-------|-------|---|
/// | Log Entry             |   | c ≔ 2 |       |       |       |       |   |
/// | Target Concurrency    | 5 |     2 |     2 |     2 |     2 |     2 | … |
/// | Effective Concurrency | 5 |     5 |     4 |     3 |     2 |     2 | … |
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct Cluster<N> {
    /// Effective node set for the next round and up to `concurrency_at_offset
    /// -1` previous rounds.
    nodes_at_offset: Vec<N>,
    /// Concurrency level for the next round and up to `concurrency_at_offset
    /// -1` previous rounds.
    concurrency_at_offset: NonZeroUsize,
    /// Concurrency at the end of a potential concurrency reduction shadow.
    ///
    /// The target concurrency is always lower than or equal to all other levels
    /// of concurrency, those in `log_entries` and `concurrency_at_offset`.
    target_concurrency: NonZeroUsize,
    /// Buffer of up to `concurrency_at_offset - 1` "log entries" that affect
    /// either the effective node set or the concurrency level.
    ///
    /// This buffering is used to implement concurrency reduction shadows, i.e.
    /// the concurrency is monotonically decreasing (non-strictly) in these
    /// entries.
    log_entries: VecDeque<(NonZeroUsize, Vec<N>, Vec<N>)>,
}

impl<N, I> Cluster<N>
where
    N: crate::NodeInfo<Id = I> + Clone,
    I: crate::Identifier + Ord,
{
    /// Returns a new cluster with the given initial state.
    pub fn new(nodes: Vec<N>, concurrency: NonZeroUsize) -> Self {
        Cluster {
            nodes_at_offset: nodes,
            concurrency_at_offset: concurrency,
            target_concurrency: concurrency,
            log_entries: VecDeque::new(),
        }
    }

    /// Applies the given log entry, making the appropiate updates.
    pub fn apply<E: ClusterLogEntry<N>>(&mut self, log_entry: &E) {
        let new_concurrency = log_entry.concurrency();
        let mut added_nodes = log_entry.added_nodes();
        let mut removed_nodes = log_entry.removed_nodes();

        if !added_nodes.is_empty() && !removed_nodes.is_empty() {
            added_nodes.sort_by_key(|n| n.id());
            added_nodes.dedup_by_key(|n| n.id());

            removed_nodes.sort_by_key(|n| n.id());
            removed_nodes.dedup_by_key(|n| n.id());

            let any_node_added_and_removed = added_nodes.iter().any(|a| {
                removed_nodes
                    .binary_search_by_key(&a.id(), |n| n.id())
                    .is_ok()
            });

            assert!(
                !any_node_added_and_removed,
                "Simultaneously adding and removing a node is undefined."
            );
        }

        let prev = self
            .log_entries
            .back()
            .map(|(c, _, _)| *c)
            .unwrap_or(self.concurrency_at_offset);

        if self.target_concurrency < prev {
            // Compact node changes, which is necessary for when concurrency is
            // decreased and then increased again. Since we do it consistently,
            // we only have to compact the changes with one other entry.

            let mut compactable = self
                .log_entries
                .iter_mut()
                .rev()
                .enumerate()
                .take_while(|(i, (c, _, _))| usize::from(prev) + i == usize::from(*c))
                .last()
                .map(|(_, (_, a, r))| (a, r));

            if let Some((ref mut a, ref mut r)) = compactable {
                if !removed_nodes.is_empty() {
                    a.retain(|n| {
                        removed_nodes
                            .binary_search_by_key(&n.id(), |n| n.id())
                            .is_err()
                    });
                }

                let mut added = Vec::new();
                std::mem::swap(&mut added, &mut added_nodes);
                if !added.is_empty() {
                    a.append(&mut added);
                    a.sort_by_key(|n| n.id());
                    a.dedup_by_key(|n| n.id());
                }

                let mut removed = Vec::new();
                std::mem::swap(&mut removed, &mut removed_nodes);
                if !removed.is_empty() {
                    r.append(&mut removed);
                    r.sort_by_key(|n| n.id());
                    r.dedup_by_key(|n| n.id());
                }
            }
        }

        if let Some(new_concurrency) = new_concurrency {
            if new_concurrency > self.target_concurrency {
                self.log_entries
                    .iter_mut()
                    .rev()
                    .enumerate()
                    .take_while(|(i, (c, _, _))| usize::from(*c) > i + 1)
                    .for_each(|(_, (c, _, _))| *c = new_concurrency);
            }

            self.target_concurrency = new_concurrency;
        }

        let next = NonZeroUsize::new(std::cmp::max::<usize>(
            self.target_concurrency.into(),
            usize::from(prev) - 1,
        ))
        .unwrap();

        self.log_entries
            .push_back((next, added_nodes, removed_nodes));

        while self.log_entries.len() >= self.concurrency_at_offset.into() {
            let (c, added, removed) = self.log_entries.pop_front().unwrap();

            self.concurrency_at_offset = c;

            if !added.is_empty() {
                self.nodes_at_offset.extend(added);
                self.nodes_at_offset.sort_by_key(|n| n.id());
                self.nodes_at_offset.dedup_by_key(|n| n.id());
            }

            self.nodes_at_offset
                .retain(|n| removed.binary_search_by_key(&n.id(), |n| n.id()).is_err());
        }
    }

    /// Returns the concurrency at offset one.
    pub fn concurrency_at_offset_one(&self) -> NonZeroUsize {
        self.log_entries
            .back()
            .map(|(c, _, _)| *c)
            .unwrap_or(self.concurrency_at_offset)
    }

    /// Equivalent to `c.nodes_at(NonZeroUsize::new(1).unwrap()).unwrap()`.
    pub fn nodes_at_offset_one(&self) -> Vec<N> {
        self.nodes_at(NonZeroUsize::new(1).unwrap()).unwrap()
    }

    /// Returns effective set of nodes of the cluster for the given round number
    /// or `None` when the level of concurrency does not allow the node set to
    /// be determined yet.
    pub fn nodes_at(&self, round_offset: NonZeroUsize) -> Option<Vec<N>> {
        if round_offset > self.concurrency_at_offset_one() {
            return None;
        }

        // If `round_offset == 1` the result must be `nodes_at_offset`. If it is greater
        // than `1`, we have to take up to `round_offset - 1` log entries into account.
        // "Up to" because fewer may have accumulated as yet.
        let round_offset: usize = round_offset.into();
        let concurrency: usize = self.concurrency_at_offset.into();
        let take = round_offset - 1;
        // Initially or after concurrency increases `log_entries` may contain less than
        // `concurrency - 1` entries. These need to be accounted for.
        let take = take - std::cmp::min(take, concurrency - self.log_entries.len() - 1);
        let take = std::cmp::min(take, self.log_entries.len());

        let mut nodes = self.log_entries.iter().take(take).fold(
            self.nodes_at_offset.clone(),
            |mut aggregate, (_m, added, removed)| {
                aggregate.extend(added.iter().cloned());
                aggregate.retain(|n| removed.binary_search_by_key(&n.id(), |n| n.id()).is_err());
                aggregate
            },
        );

        nodes.sort_by_key(|n| n.id());
        nodes.dedup_by_key(|n| n.id());

        Some(nodes)
    }
}

#[cfg(test)]
mod tests {
    use std::num::NonZeroUsize;

    use super::Cluster;

    fn n(n: usize) -> NonZeroUsize {
        NonZeroUsize::new(n).unwrap()
    }

    impl<N: Clone> super::ClusterLogEntry<N> for (Option<Vec<N>>, Option<Vec<N>>, Option<usize>) {
        fn concurrency(&self) -> Option<NonZeroUsize> {
            self.2.map(NonZeroUsize::new).map(Option::unwrap)
        }

        fn added_nodes(&self) -> Vec<N> {
            self.0.clone().unwrap_or_default()
        }

        fn removed_nodes(&self) -> Vec<N> {
            self.1.clone().unwrap_or_default()
        }
    }

    impl crate::NodeInfo for usize {
        type Id = usize;

        fn id(&self) -> Self::Id {
            *self
        }
    }

    #[test]
    fn test_initial_cluster() {
        let n1 = 1;
        let n2 = 2;

        let cluster = Cluster::new(vec![n1, n2], n(1));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1, n2]));
        assert_eq!(cluster.nodes_at(n(2)), None);
    }

    #[test]
    fn test_add_node_non_concurrently() {
        let n1 = 1;
        let n2 = 2;

        let mut cluster = Cluster::new(vec![n1], n(1));
        cluster.apply(&(Some(vec![n2]), None, None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1, n2]));
    }

    #[test]
    fn test_add_node_concurrently() {
        let n1 = 1;
        let n2 = 2;

        let mut cluster = Cluster::new(vec![n1], n(2));
        cluster.apply(&(Some(vec![n2]), None, None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1, n2]));
        assert_eq!(cluster.nodes_at(n(3)), None);

        cluster.apply(&(None, None, None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1, n2]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1, n2]));
        assert_eq!(cluster.nodes_at(n(3)), None);
    }

    #[test]
    fn test_remove_node_non_concurrently() {
        let n1 = 1;
        let n2 = 2;

        let mut cluster = Cluster::new(vec![n1, n2], n(1));
        cluster.apply(&(None, Some(vec![n2]), None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
    }

    #[test]
    fn test_remove_node_concurrently() {
        let n1 = 1;
        let n2 = 2;

        let mut cluster = Cluster::new(vec![n1, n2], n(2));
        cluster.apply(&(None, Some(vec![n2]), None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1, n2]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(3)), None);

        cluster.apply(&(None, None, None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(3)), None);
    }

    #[test]
    fn test_concurrency() {
        let n1 = 1;
        let n2 = 2;

        let mut cluster = Cluster::new(vec![n1], n(5));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(3)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(4)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(5)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(6)), None);

        cluster.apply(&(Some(vec![n2]), None, None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(3)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(4)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(5)), Some(vec![n1, n2]));
        assert_eq!(cluster.nodes_at(n(6)), None);
    }

    #[test]
    fn test_increase_concurrency() {
        let n1 = 1;
        let n2 = 2;

        let mut cluster = Cluster::new(vec![n1], n(3));

        cluster.apply(&(Some(vec![n2]), None, None));
        cluster.apply(&(None, None, Some(5)));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1, n2]));
        assert_eq!(cluster.nodes_at(n(3)), Some(vec![n1, n2]));
        assert_eq!(cluster.nodes_at(n(4)), Some(vec![n1, n2]));
        assert_eq!(cluster.nodes_at(n(5)), Some(vec![n1, n2]));
        assert_eq!(cluster.nodes_at(n(6)), None);

        cluster.apply(&(None, Some(vec![n1]), None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1, n2]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1, n2]));
        assert_eq!(cluster.nodes_at(n(3)), Some(vec![n1, n2]));
        assert_eq!(cluster.nodes_at(n(4)), Some(vec![n1, n2]));
        assert_eq!(cluster.nodes_at(n(5)), Some(vec![n2]));
        assert_eq!(cluster.nodes_at(n(6)), None);
    }

    #[test]
    fn test_decrease_concurrency_once() {
        let n1 = 1;
        let n2 = 2;
        let n3 = 3;

        let mut cluster = Cluster::new(vec![n1], n(5));

        cluster.apply(&(None, None, Some(1)));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(3)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(4)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(5)), None);

        cluster.apply(&(Some(vec![n2]), None, None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(3)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(4)), None);

        cluster.apply(&(Some(vec![n3]), None, None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(3)), None);

        cluster.apply(&(None, Some(vec![n1]), None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), None);

        cluster.apply(&(None, None, None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n2, n3]));
        assert_eq!(cluster.nodes_at(n(2)), None);
    }

    #[test]
    fn test_decrease_concurrency_twice() {
        let n1 = 1;
        let n2 = 2;
        let n3 = 3;

        let mut cluster = Cluster::new(vec![n1], n(5));

        cluster.apply(&(None, None, Some(3)));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(3)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(4)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(5)), None);

        cluster.apply(&(Some(vec![n2]), None, Some(1)));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(3)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(4)), None);

        cluster.apply(&(Some(vec![n3]), None, None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(3)), None);

        cluster.apply(&(None, Some(vec![n1]), None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), None);

        cluster.apply(&(None, None, None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n2, n3]));
        assert_eq!(cluster.nodes_at(n(2)), None);
    }

    #[test]
    fn test_decrease_concurrency_then_increase_again() {
        let n1 = 1;
        let n2 = 2;
        let n3 = 3;

        let mut cluster = Cluster::new(vec![n1], n(5));

        cluster.apply(&(None, None, Some(1)));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(3)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(4)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(5)), None);

        cluster.apply(&(Some(vec![n2]), None, None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(3)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(4)), None);

        cluster.apply(&(Some(vec![n3]), None, Some(5)));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(3)), Some(vec![n1, n2, n3]));
        assert_eq!(cluster.nodes_at(n(4)), Some(vec![n1, n2, n3]));
        assert_eq!(cluster.nodes_at(n(5)), Some(vec![n1, n2, n3]));
        assert_eq!(cluster.nodes_at(n(6)), None);

        cluster.apply(&(None, Some(vec![n1]), None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1, n2, n3]));
        assert_eq!(cluster.nodes_at(n(3)), Some(vec![n1, n2, n3]));
        assert_eq!(cluster.nodes_at(n(4)), Some(vec![n1, n2, n3]));
        assert_eq!(cluster.nodes_at(n(5)), Some(vec![n2, n3]));
        assert_eq!(cluster.nodes_at(n(6)), None);

        cluster.apply(&(None, None, None));

        assert_eq!(cluster.nodes_at(n(1)), Some(vec![n1, n2, n3]));
        assert_eq!(cluster.nodes_at(n(2)), Some(vec![n1, n2, n3]));
        assert_eq!(cluster.nodes_at(n(3)), Some(vec![n1, n2, n3]));
        assert_eq!(cluster.nodes_at(n(4)), Some(vec![n2, n3]));
        assert_eq!(cluster.nodes_at(n(5)), Some(vec![n2, n3]));
        assert_eq!(cluster.nodes_at(n(6)), None);
    }
}