isb-apps 1.6.11

isb's apps over stacks: deployments, builds, jobs, backups, templates and notifications. Use the `isb` crate.
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
//! A monitor's state machine: failure and recovery thresholds (hysteresis),
//! one notification per change (de-duplication) and flap damping. No I/O,
//! so every rule is tested on its own.
//!
//! - `failure_threshold` failed checks in a row take a monitor down;
//!   `recovery_threshold` successful ones bring it back up. A new monitor's
//!   first success makes it up at once.
//! - A new monitor is `pending` until its first success. Failures before
//!   that are *pending* checks, not downtime: no threshold, no incident, no
//!   `down`. If it has only failed for [`NEVER_UP_MS`], channels hear once
//!   that it *never came up* (a `down`), and the monitor stays pending
//!   (flagged `never_up`) until a check succeeds, which then sends an `up`.
//! - Channels hear `down` once per incident and `up` once after it, always
//!   alternating: an up is only sent after a down was.
//! - A monitor that went down [`FLAP_DOWNS`] times within [`FLAP_WINDOW_MS`]
//!   is *flapping*: the change that makes it so is still sent (saying so),
//!   then nothing more until it has held one state for [`FLAP_WINDOW_MS`];
//!   then the state it settled in is sent if channels last heard otherwise.

use serde::{Deserialize, Serialize};

/// How long a monitor must hold one state to stop flapping, and the window
/// downs are counted in.
pub const FLAP_WINDOW_MS: u64 = 30 * 60 * 1000;
/// Downs within the window that make a monitor flapping.
pub const FLAP_DOWNS: usize = 3;
/// How long a new monitor may only fail before it is called "never came up".
pub const NEVER_UP_MS: u64 = 30 * 60 * 1000;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
    /// Not checked yet (or channels were never told anything).
    #[default]
    Pending,
    Up,
    Down,
}

impl Status {
    pub fn as_str(self) -> &'static str {
        match self {
            Status::Pending => "pending",
            Status::Up => "up",
            Status::Down => "down",
        }
    }
}

/// How many checks in a row change the status.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Thresholds {
    pub failures: u32,
    pub recoveries: u32,
}

/// A monitor's state, kept across daemon restarts so a restart never sends
/// a down (or an up) twice.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct State {
    pub status: Status,
    /// Unix milliseconds the status began.
    pub since: u64,
    /// Failed checks in a row.
    pub fails: u32,
    /// Successful checks in a row.
    pub oks: u32,
    /// When the current run of failures began.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failing_since: Option<u64>,
    /// What channels were last told.
    pub notified: Status,
    /// When the incident channels were told about began.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub down_since: Option<u64>,
    /// Unix milliseconds of recent downs, for flap damping.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub downs: Vec<u64>,
    pub flapping: bool,
    /// The certificate (by its expiry, unix seconds) already warned about.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cert_warned: Option<u64>,
    /// When the first check of a pending monitor ran.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub first_check: Option<u64>,
    /// Pending for [`NEVER_UP_MS`] with only failures.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub never_up: bool,
}

/// What a check changed, and what to tell channels.
#[derive(Debug, Clone, PartialEq)]
pub struct Step {
    /// The new status, when it changed.
    pub changed: Option<Status>,
    pub notify: Notify,
    /// The check failed while the monitor was waiting for its first
    /// success: kept as pending, not as a failure.
    pub pending: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Notify {
    None,
    /// Down since `since` (the first failed check of the incident).
    Down {
        since: u64,
        flapping: bool,
    },
    /// Still no success `NEVER_UP_MS` after the first check (`since`).
    NeverUp {
        since: u64,
    },
    /// Up again; it was down from `down_since`.
    Up {
        down_since: u64,
        downtime_ms: u64,
    },
}

impl State {
    /// Take one check's result at `now` (unix milliseconds).
    pub fn observe(&mut self, ok: bool, now: u64, t: Thresholds) -> Step {
        if self.status == Status::Pending && !ok {
            return self.observe_pending(now);
        }
        let changed = self.count(ok, now, t);
        if let Some(s) = changed {
            self.status = s;
            self.since = now;
            if s == Status::Down {
                self.downs.push(now);
            }
        }
        self.downs
            .retain(|d| now.saturating_sub(*d) < FLAP_WINDOW_MS);
        let was = self.flapping;
        if changed == Some(Status::Down) && self.downs.len() >= FLAP_DOWNS {
            self.flapping = true;
        } else if self.flapping && now.saturating_sub(self.since) >= FLAP_WINDOW_MS {
            self.flapping = false;
        }
        let notify = self.decide(now, was);
        Step {
            changed,
            notify,
            pending: false,
        }
    }

    /// A failed check before the first success: counted, never a down.
    fn observe_pending(&mut self, now: u64) -> Step {
        let first = *self.first_check.get_or_insert(now);
        self.fails = self.fails.saturating_add(1);
        self.oks = 0;
        self.failing_since.get_or_insert(now);
        let mut notify = Notify::None;
        if !self.never_up && now.saturating_sub(first) >= NEVER_UP_MS {
            self.never_up = true;
            self.notified = Status::Down;
            self.down_since = Some(first);
            notify = Notify::NeverUp { since: first };
        }
        Step {
            changed: None,
            notify,
            pending: true,
        }
    }

    /// Count the check; the status it now calls for, when that is a change.
    fn count(&mut self, ok: bool, now: u64, t: Thresholds) -> Option<Status> {
        if ok {
            self.oks = self.oks.saturating_add(1);
            self.fails = 0;
            self.failing_since = None;
            let enough = self.status == Status::Pending || self.oks >= t.recoveries.max(1);
            if enough {
                self.never_up = false;
                self.first_check = None;
            }
            (self.status != Status::Up && enough).then_some(Status::Up)
        } else {
            self.fails = self.fails.saturating_add(1);
            self.oks = 0;
            self.failing_since.get_or_insert(now);
            (self.status != Status::Down && self.fails >= t.failures.max(1)).then_some(Status::Down)
        }
    }

    fn decide(&mut self, now: u64, was_flapping: bool) -> Notify {
        // Held while flapping; the change that started it still goes out.
        if self.flapping && was_flapping {
            return Notify::None;
        }
        match (self.status, self.notified) {
            (Status::Down, n) if n != Status::Down => {
                let since = self.failing_since.unwrap_or(now).min(now);
                self.notified = Status::Down;
                self.down_since = Some(since);
                Notify::Down {
                    since,
                    flapping: self.flapping,
                }
            }
            (Status::Up, Status::Down) => {
                let down_since = self.down_since.take().unwrap_or(now);
                self.notified = Status::Up;
                Notify::Up {
                    down_since,
                    downtime_ms: now.saturating_sub(down_since),
                }
            }
            (Status::Up, Status::Pending) => {
                // The first up is not news.
                self.notified = Status::Up;
                Notify::None
            }
            _ => Notify::None,
        }
    }

    /// Start counting afresh (a resumed or edited monitor), keeping what
    /// channels were told.
    pub fn reset_counts(&mut self) {
        self.fails = 0;
        self.oks = 0;
        self.failing_since = None;
        if self.status == Status::Pending {
            self.first_check = None;
        }
    }
}

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

    const T: Thresholds = Thresholds {
        failures: 2,
        recoveries: 2,
    };

    fn run(s: &mut State, checks: &[(bool, u64)]) -> Vec<Notify> {
        checks
            .iter()
            .map(|(ok, at)| s.observe(*ok, *at, T).notify)
            .filter(|n| *n != Notify::None)
            .collect()
    }

    #[test]
    fn thresholds_and_one_notification_per_incident() {
        let mut s = State::default();
        // The first success makes a new monitor up, quietly.
        assert_eq!(run(&mut s, &[(true, 1000)]), vec![]);
        assert_eq!(s.status, Status::Up);
        // One failure is not enough.
        assert_eq!(run(&mut s, &[(false, 2000), (true, 3000)]), vec![]);
        assert_eq!(s.status, Status::Up);
        // Two are; the incident starts at the first.
        let n = run(&mut s, &[(false, 4000), (false, 5000)]);
        assert_eq!(
            n,
            vec![Notify::Down {
                since: 4000,
                flapping: false
            }]
        );
        assert_eq!(s.status, Status::Down);
        // More failures say nothing more.
        assert_eq!(run(&mut s, &[(false, 6000), (false, 7000)]), vec![]);
        // One success does not recover it (hysteresis); a failure resets it.
        assert_eq!(
            run(&mut s, &[(true, 8000), (false, 9000), (true, 10_000)]),
            vec![]
        );
        assert_eq!(s.status, Status::Down);
        // Two in a row do, with the downtime from the first failure.
        let n = run(&mut s, &[(true, 11_000)]);
        assert_eq!(
            n,
            vec![Notify::Up {
                down_since: 4000,
                downtime_ms: 7000
            }]
        );
        assert_eq!(s.status, Status::Up);
        assert_eq!(s.notified, Status::Up);
    }

    #[test]
    fn a_new_monitor_waits_for_its_first_success() {
        let mut s = State::default();
        // Failures before the first success are pending, never down.
        for at in [10, 20, 30, 40] {
            let st = s.observe(false, at, T);
            assert!(st.pending);
            assert_eq!((st.changed, st.notify), (None, Notify::None));
        }
        assert_eq!(s.status, Status::Pending);
        assert!(s.downs.is_empty());
        // The first success is up, quietly, and clears the waiting.
        let st = s.observe(true, 50, T);
        assert!(!st.pending);
        assert_eq!((st.changed, st.notify), (Some(Status::Up), Notify::None));
        assert_eq!((s.first_check, s.never_up, s.fails), (None, false, 0));
        assert_eq!(s.notified, Status::Up);
    }

    #[test]
    fn pending_failures_do_not_count_toward_the_threshold() {
        let mut s = State::default();
        run(&mut s, &[(false, 10), (false, 20), (false, 30)]);
        // Up on the first success; one failure then is still below 2.
        assert_eq!(run(&mut s, &[(true, 40), (false, 50)]), vec![]);
        assert_eq!(s.status, Status::Up);
        assert_eq!(s.fails, 1);
    }

    #[test]
    fn real_downtime_after_up_still_pages() {
        let mut s = State::default();
        run(&mut s, &[(false, 10), (true, 20)]);
        let n = run(&mut s, &[(false, 30), (false, 40)]);
        assert_eq!(
            n,
            vec![Notify::Down {
                since: 30,
                flapping: false
            }]
        );
        assert_eq!(s.status, Status::Down);
        assert!(!s.observe(false, 50, T).pending);
    }

    #[test]
    fn a_monitor_that_never_comes_up_says_so_once() {
        let mut s = State::default();
        assert_eq!(run(&mut s, &[(false, 1000)]), vec![]);
        // Just short of the window: nothing.
        assert_eq!(run(&mut s, &[(false, 1000 + NEVER_UP_MS - 1)]), vec![]);
        let n = run(
            &mut s,
            &[(false, 1000 + NEVER_UP_MS), (false, 2000 + NEVER_UP_MS)],
        );
        assert_eq!(n, vec![Notify::NeverUp { since: 1000 }]);
        // Still pending, flagged; no second message.
        assert_eq!((s.status, s.never_up), (Status::Pending, true));
        assert_eq!(run(&mut s, &[(false, 3000 + NEVER_UP_MS)]), vec![]);
        // When it finally answers, channels hear it is up.
        let at = 4000 + NEVER_UP_MS;
        let n = run(&mut s, &[(true, at)]);
        assert_eq!(
            n,
            vec![Notify::Up {
                down_since: 1000,
                downtime_ms: at - 1000
            }]
        );
        assert_eq!((s.status, s.never_up), (Status::Up, false));
    }

    #[test]
    fn thresholds_of_one() {
        let one = Thresholds {
            failures: 1,
            recoveries: 1,
        };
        let mut s = State::default();
        assert_eq!(s.observe(true, 1, one).notify, Notify::None);
        assert!(matches!(
            s.observe(false, 2, one).notify,
            Notify::Down { .. }
        ));
        assert!(matches!(s.observe(true, 3, one).notify, Notify::Up { .. }));
        // Zero is treated as one.
        let zero = Thresholds {
            failures: 0,
            recoveries: 0,
        };
        assert!(matches!(
            s.observe(false, 4, zero).notify,
            Notify::Down { .. }
        ));
    }

    #[test]
    fn flapping_is_damped_and_settles() {
        let one = Thresholds {
            failures: 1,
            recoveries: 1,
        };
        let mut s = State::default();
        let mut sent = Vec::new();
        let mut at = 1_000;
        s.observe(true, at, one);
        // Down and up every minute, ten times.
        for _ in 0..10 {
            for ok in [false, true] {
                at += 60_000;
                let n = s.observe(ok, at, one).notify;
                if n != Notify::None {
                    sent.push(n);
                }
            }
        }
        // down, up, down, up, then the third down (flapping), then quiet.
        assert_eq!(sent.len(), 5, "{sent:?}");
        assert!(matches!(sent[4], Notify::Down { flapping: true, .. }));
        assert!(s.flapping);
        // It stays up: nothing until it has held for the window, then the
        // up channels have not heard yet.
        let mut later = Vec::new();
        for _ in 0..40 {
            at += 60_000;
            let n = s.observe(true, at, one).notify;
            if n != Notify::None {
                later.push(n);
            }
        }
        assert_eq!(later.len(), 1, "{later:?}");
        assert!(matches!(later[0], Notify::Up { .. }));
        assert!(!s.flapping);
        assert_eq!(s.notified, Status::Up);
    }

    #[test]
    fn flapping_that_settles_down_is_not_told_twice() {
        let one = Thresholds {
            failures: 1,
            recoveries: 1,
        };
        let mut s = State::default();
        let mut at = 0;
        let mut sent = Vec::new();
        for ok in [true, false, true, false, true, false, true, false] {
            at += 1000;
            let n = s.observe(ok, at, one).notify;
            if n != Notify::None {
                sent.push(n);
            }
        }
        // The last flap left it down, and channels heard the flapping down.
        assert_eq!(s.notified, Status::Down);
        let n_before = sent.len();
        for _ in 0..40 {
            at += 60_000;
            let n = s.observe(false, at, one).notify;
            if n != Notify::None {
                sent.push(n);
            }
        }
        assert_eq!(sent.len(), n_before, "{sent:?}");
        assert!(!s.flapping);
    }

    #[test]
    fn state_survives_a_restart() {
        let mut s = State::default();
        run(&mut s, &[(true, 1), (false, 2), (false, 3)]);
        assert_eq!(s.status, Status::Down);
        let saved = serde_json::to_string(&s).unwrap();
        let mut back: State = serde_json::from_str(&saved).unwrap();
        assert_eq!(back, s);
        // Still down after the restart: no second down.
        assert_eq!(run(&mut back, &[(false, 4), (false, 5)]), vec![]);
        let n = run(&mut back, &[(true, 6), (true, 7)]);
        assert_eq!(
            n,
            vec![Notify::Up {
                down_since: 2,
                downtime_ms: 5
            }]
        );
        // An old state file without the newer fields still loads.
        let old: State = serde_json::from_str(r#"{"status":"up"}"#).unwrap();
        assert_eq!(old.status, Status::Up);
    }
}