memberlist-core 0.2.0-alpha.2

A highly customable, adaptable, async runtime agnostic Gossip protocol which helps manage cluster membership and member failure detection.
Documentation
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
546
547
548
549
550
551
552
553
554
use std::{
  collections::HashSet,
  sync::{
    atomic::{AtomicU32, Ordering},
    Arc,
  },
  time::{Duration, Instant},
};

use super::{delegate::Delegate, transport::Transport, types::Epoch, *};
use agnostic_lite::{AfterHandle, AsyncAfterSpawner, RuntimeLite};
use memberlist_types::{Dead, State};
use nodecraft::resolver::AddressResolver;

#[inline]
fn remaining_suspicion_time(
  n: u32,
  k: u32,
  elapsed: Duration,
  min: Duration,
  max: Duration,
) -> Duration {
  let frac = (n as f64 + 1.0).ln() / (k as f64 + 1.0).ln();
  let raw = max.as_secs_f64() - frac * (max.as_secs_f64() - min.as_secs_f64());
  let timeout = (raw * 1000.0).floor();
  if timeout < min.as_millis() as f64 {
    min.saturating_sub(elapsed)
  } else {
    Duration::from_millis(timeout as u64).saturating_sub(elapsed)
  }
}

pub(crate) struct Suspicioner<T, D>
where
  T: Transport,
  D: Delegate<Id = T::Id, Address = <T::Resolver as AddressResolver>::ResolvedAddress>,
{
  memberlist: Memberlist<T, D>,
  node: T::Id,
  change_time: Epoch,
  incarnation: u32,
  #[cfg(feature = "metrics")]
  k: isize,
}

impl<T, D> Suspicioner<T, D>
where
  T: Transport,
  D: Delegate<Id = T::Id, Address = <T::Resolver as AddressResolver>::ResolvedAddress>,
{
  pub(crate) fn new(
    memberlist: Memberlist<T, D>,
    node: T::Id,
    change_time: Epoch,
    incarnation: u32,
    #[cfg(feature = "metrics")] k: isize,
  ) -> Self {
    Suspicioner {
      memberlist,
      node,
      change_time,
      incarnation,
      #[cfg(feature = "metrics")]
      k,
    }
  }

  async fn suspicion(&self, num_confirmations: u32) {
    let Self {
      memberlist: t,
      node: n,
      change_time,
      incarnation,
      #[cfg(feature = "metrics")]
      k,
    } = self;
    let timeout = {
      let members = t.inner.nodes.read().await;

      members.node_map.get(n).and_then(|&idx| {
        let state = &members.nodes[idx];
        let timeout =
          state.state.state == State::Suspect && state.state.state_change == *change_time;
        if timeout {
          Some(Dead::new(
            *incarnation,
            state.id().cheap_clone(),
            t.local_id().cheap_clone(),
          ))
        } else {
          None
        }
      })
    };

    if let Some(dead) = timeout {
      #[cfg(feature = "metrics")]
      {
        if *k > 0 && *k > num_confirmations as isize {
          metrics::counter!(
            "memberlist.degraded.timeout",
            t.inner.opts.metric_labels.iter()
          )
          .increment(1);
        }
      }

      tracing::info!(
        "memberlist.state: marking {} as failed, suspect timeout reached ({} peer confirmations)",
        dead.node(),
        num_confirmations
      );
      let mut memberlist = t.inner.nodes.write().await;
      let dead_node = dead.node().cheap_clone();
      if let Err(e) = t.dead_node(&mut memberlist, dead).await {
        tracing::error!(err=%e, "memberlist.state: failed to mark {dead_node} as failed");
      }
    }
  }
}

pub(crate) struct Suspicion<T, D>
where
  T: Transport,
  D: Delegate<Id = T::Id, Address = <T::Resolver as AddressResolver>::ResolvedAddress>,
{
  n: Arc<AtomicU32>,
  k: u32,
  min: Duration,
  max: Duration,
  start: Instant,
  handle: Option<<<T::Runtime as RuntimeLite>::AfterSpawner as AsyncAfterSpawner>::JoinHandle<()>>,
  suspicioner: Arc<Suspicioner<T, D>>,
  confirmations: HashSet<T::Id>,
}

impl<T, D> Suspicion<T, D>
where
  T: Transport,
  D: Delegate<Id = T::Id, Address = <T::Resolver as AddressResolver>::ResolvedAddress>,
{
  /// Returns a after_func started with the max time, and that will drive
  /// to the min time after seeing k or more confirmations. The from node will be
  /// excluded from confirmations since we might get our own suspicion message
  /// gossiped back to us. The minimum time will be used if no confirmations are
  /// called for (k = 0).
  pub(crate) fn new(
    from: T::Id,
    k: isize,
    min: Duration,
    max: Duration,
    suspicioner: Suspicioner<T, D>,
  ) -> Self {
    #[allow(clippy::mutable_key_type)]
    let confirmations = [from].into_iter().collect();
    let n = Arc::new(AtomicU32::new(0));
    let timeout = if (k as u32) < 1 { min } else { max };
    let suspicioner = Arc::new(suspicioner);
    let n1 = n.clone();
    let s1 = suspicioner.clone();
    let handle = <T::Runtime as RuntimeLite>::spawn_after(timeout, async move {
      s1.suspicion(n1.load(Ordering::SeqCst)).await;
    });

    Suspicion {
      n,
      k: k as u32,
      min,
      max,
      start: Instant::now(),
      suspicioner,
      handle: Some(handle),
      confirmations,
    }
  }
}

impl<T, D> Suspicion<T, D>
where
  T: Transport,
  D: Delegate<Id = T::Id, Address = <T::Resolver as AddressResolver>::ResolvedAddress>,
{
  /// Confirm registers that a possibly new peer has also determined the given
  /// node is suspect. This returns true if this was new information, and false
  /// if it was a duplicate confirmation, or if we've got enough confirmations to
  /// hit the minimum.
  pub(crate) async fn confirm(&mut self, from: &T::Id) -> bool {
    if self.n.load(Ordering::Relaxed) >= self.k {
      return false;
    }

    if self.confirmations.contains(from) {
      return false;
    }

    self.confirmations.insert(from.cheap_clone());

    if let Some(h) = self.handle.take() {
      if !h.is_expired() {
        // Compute the new timeout given the current number of confirmations and
        // adjust the after_func. If the timeout becomes negative *and* we can cleanly
        // stop the after_func then we will call the timeout function directly from
        // here.
        let n = self.n.fetch_add(1, Ordering::SeqCst) + 1;
        let elapsed = self.start.elapsed();
        let remaining = remaining_suspicion_time(n, self.k, elapsed, self.min, self.max);

        h.abort();
        if remaining > Duration::ZERO {
          let n = self.n.clone();
          let suspicioner = self.suspicioner.clone();
          self.handle = Some(<T::Runtime as RuntimeLite>::spawn_after_at(
            Instant::now() + remaining,
            async move {
              suspicioner.suspicion(n.load(Ordering::SeqCst)).await;
            },
          ));
        } else {
          let n = self.n.clone();
          let suspicioner = self.suspicioner.clone();
          <T::Runtime as RuntimeLite>::spawn_detach(async move {
            suspicioner.suspicion(n.load(Ordering::SeqCst)).await;
          });
        }
      }
    }

    true
  }
}

impl<T, D> Drop for Suspicion<T, D>
where
  T: Transport,
  D: Delegate<Id = T::Id, Address = <T::Resolver as AddressResolver>::ResolvedAddress>,
{
  fn drop(&mut self) {
    if let Some(h) = self.handle.take() {
      h.abort();
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn test_suspicion_remaining_suspicion_time() {
    let cases = vec![
      (
        0,
        3,
        Duration::from_secs(0),
        Duration::from_secs(2),
        Duration::from_secs(30),
        Duration::from_secs(30),
      ),
      (
        1,
        3,
        Duration::from_secs(2),
        Duration::from_secs(2),
        Duration::from_secs(30),
        Duration::from_secs(14),
      ),
      (
        2,
        3,
        Duration::from_secs(3),
        Duration::from_secs(2),
        Duration::from_secs(30),
        Duration::from_millis(4810),
      ),
      (
        3,
        3,
        Duration::from_secs(4),
        Duration::from_secs(2),
        Duration::from_secs(30),
        Duration::ZERO,
      ),
      (
        4,
        3,
        Duration::from_secs(5),
        Duration::from_secs(2),
        Duration::from_secs(30),
        Duration::ZERO,
      ),
      (
        5,
        3,
        Duration::from_secs(10),
        Duration::from_secs(2),
        Duration::from_secs(30),
        Duration::ZERO,
      ),
    ];

    for (i, (n, k, elapsed, min, max, expected)) in cases.into_iter().enumerate() {
      let remaining = remaining_suspicion_time(n, k, elapsed, min, max);
      assert_eq!(
        remaining, expected,
        "case {}: remaining {:?} != expected {:?}",
        i, remaining, expected
      );
    }
  }

  // TODO: find a way to test the suspicioner and suspicion structs

  // struct Pair {
  //   from: &'static str,
  //   new_info: bool,
  // }

  // const K: u32 = 3;
  // const MIN: Duration = Duration::from_millis(500);
  // const MAX: Duration = Duration::from_secs(2);

  // fn test_cases() -> Vec<(i32, &'static str, Vec<Pair>, Duration)> {
  //   vec![
  //     (0, "me", vec![], MAX),
  //     (
  //       1,
  //       "me",
  //       vec![
  //         Pair {
  //           from: "me",
  //           new_info: false,
  //         },
  //         Pair {
  //           from: "foo",
  //           new_info: true,
  //         },
  //       ],
  //       Duration::from_millis(1250),
  //     ),
  //     (
  //       1,
  //       "me",
  //       vec![
  //         Pair {
  //           from: "me",
  //           new_info: false,
  //         },
  //         Pair {
  //           from: "foo",
  //           new_info: true,
  //         },
  //         Pair {
  //           from: "foo",
  //           new_info: false,
  //         },
  //         Pair {
  //           from: "foo",
  //           new_info: false,
  //         },
  //       ],
  //       Duration::from_millis(1250),
  //     ),
  //     (
  //       2,
  //       "me",
  //       vec![
  //         Pair {
  //           from: "me",
  //           new_info: false,
  //         },
  //         Pair {
  //           from: "foo",
  //           new_info: true,
  //         },
  //         Pair {
  //           from: "bar",
  //           new_info: true,
  //         },
  //       ],
  //       Duration::from_millis(810),
  //     ),
  //     (
  //       3,
  //       "me",
  //       vec![
  //         Pair {
  //           from: "me",
  //           new_info: false,
  //         },
  //         Pair {
  //           from: "foo",
  //           new_info: true,
  //         },
  //         Pair {
  //           from: "bar",
  //           new_info: true,
  //         },
  //         Pair {
  //           from: "baz",
  //           new_info: true,
  //         },
  //       ],
  //       MIN,
  //     ),
  //     (
  //       3,
  //       "me",
  //       vec![
  //         Pair {
  //           from: "me",
  //           new_info: false,
  //         },
  //         Pair {
  //           from: "foo",
  //           new_info: true,
  //         },
  //         Pair {
  //           from: "bar",
  //           new_info: true,
  //         },
  //         Pair {
  //           from: "baz",
  //           new_info: true,
  //         },
  //         Pair {
  //           from: "zoo",
  //           new_info: false,
  //         },
  //       ],
  //       MIN,
  //     ),
  //   ]
  // }

  // #[tokio::test]
  // async fn test_suspicion_after_func() {
  //   use futures::FutureExt;

  //   for (i, (num_confirmations, from, confirmations, expected)) in
  //     test_cases().into_iter().enumerate()
  //   {
  //     let (tx, rx) = async_channel::unbounded();
  //     let start = Instant::now();
  //     let f = move |nc: u32| {
  //       let tx = tx.clone();
  //       assert_eq!(
  //         nc, num_confirmations as u32,
  //         "case {}: bad {} != {}",
  //         i, nc, num_confirmations
  //       );
  //       async move {
  //         tx.send(Instant::now().duration_since(start)).await.unwrap();
  //       }
  //       .boxed()
  //     };

  //     let mut s = Suspicion::<DummyTransport, VoidDelegate<>>::new(from.into(), K, MIN, MAX, f);
  //     let fudge = Duration::from_millis(25);
  //     for p in confirmations.iter() {
  //       tokio::time::sleep(fudge).await;
  //       assert_eq!(
  //         s.confirm(&p.from.into()).await,
  //         p.new_info,
  //         "case {}: newInfo mismatch for {}",
  //         i,
  //         p.from
  //       );
  //     }

  //     let sleep = expected - fudge * (confirmations.len() as u32) - fudge;
  //     tokio::time::sleep(sleep).await;
  //     match rx.try_recv() {
  //       Ok(d) => panic!("case {}: should not have fired ({:?})", i, d),
  //       Err(TryRecvError::Empty) => (),
  //       Err(TryRecvError::Closed) => panic!("case {}: channel closed", i),
  //     }

  //     // Wait through the timeout and a little after and make sure it
  //     // fires.
  //     tokio::time::sleep(2 * fudge).await;
  //     match rx.recv().await {
  //       Ok(_) => (),
  //       Err(_) => panic!("case {}: should have fired", i),
  //     }

  //     // Confirm after to make sure it handles a negative remaining
  //     // time correctly and doesn't fire again.
  //     s.confirm(&"late".into(), $expr).await;
  //     tokio::time::sleep(expected + 2 * fudge).await;
  //     match rx.try_recv() {
  //       Ok(d) => panic!("case {}: should not have fired ({:?})", i, d),
  //       Err(TryRecvError::Empty) => (),
  //       Err(TryRecvError::Closed) => panic!("case {}: channel closed", i),
  //     }
  //   }
  // }

  // #[tokio::test]
  // async fn test_suspicion_after_func_zero_k() {
  //   use agnostic::tokio::TokioRuntime;
  //   use futures::FutureExt;

  //   let (tx, rx) = async_channel::unbounded();
  //   let f = move |_| {
  //     let tx = tx.clone();
  //     async move {
  //       tx.send(()).await.unwrap();
  //     }
  //     .boxed()
  //   };

  //   let mut s = Suspicion::<DummyTransport, DummyDelegate>::new(
  //     "me".into(),
  //     0,
  //     Duration::from_millis(25),
  //     Duration::from_secs(30),
  //     f,
  //   );

  //   assert!(!s.confirm(&"foo".into(), $expr).await);
  //   let _ = tokio::time::timeout(Duration::from_millis(50), rx.recv())
  //     .await
  //     .unwrap();
  // }

  // #[tokio::test]
  // async fn test_suspicion_after_func_immediate() {
  //   use futures::FutureExt;

  //   let (tx, rx) = async_channel::unbounded();
  //   let f = move |_| {
  //     let tx = tx.clone();
  //     async move {
  //       tx.send(()).await.unwrap();
  //     }
  //     .boxed()
  //   };

  //   let mut s = Suspicion::<DummyTransport, DummyDelegate>::new(
  //     "me".into(),
  //     1,
  //     Duration::from_millis(100),
  //     Duration::from_secs(30),
  //     f,
  //   );

  //   tokio::time::sleep(Duration::from_millis(200)).await;
  //   s.confirm(&"foo".into(), $expr).await;

  //   let _ = tokio::time::timeout(Duration::from_millis(25), rx.recv())
  //     .await
  //     .unwrap();
  // }
}