Diffinery

homeflare/celldpublic

celld/crates/logic/alarm.rs
44 lines · 1.7 KBRaw History
1//! Alarm retry policy, reified sans-IO. After a handler fails, `celld` persists
2//! a backoff in SQLite (`storage.rs`) and abandons the alarm once a bounded
3//! number of limit-counting failures accrue. That schedule is a pure function
4//! of the row's retry counters; storage is its executor.
5//!
6//! NOTE: `lifecycle::on_event` models a SEPARATE in-memory attempt backoff. The
7//! two converge when `on_event` is wired into production (the
8//! `ensure_cell → on_event` slice).
9
10use crate::Ms;
11
12/// Failures that count toward the ceiling before the alarm is abandoned.
13const RETRY_CEILING: i64 = 6;
14/// Backoff base; the nth retry waits `BACKOFF_BASE_MS << min(retry, MAX_SHIFT)`.
15const BACKOFF_BASE_MS: Ms = 2_000;
16const MAX_BACKOFF_SHIFT: i64 = 6;
17
18/// What to do with an alarm whose handler just failed.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum AlarmRetry {
21 /// The ceiling is reached; abandon the alarm.
22 GiveUp,
23 /// Reschedule for `at_ms`; the executor also bumps the retry counters.
24 Retry { at_ms: Ms },
25}
26
27/// `retry` is the total failure count (drives the exponential backoff);
28/// `counted_retry` is how many counted against the limit. `counts_against_limit`
29/// is false for failures the caller excuses (e.g. a shed under pressure) — those
30/// back off but never reach the ceiling.
31pub fn alarm_retry(
32 now_ms: Ms,
33 retry: i64,
34 counted_retry: i64,
35 counts_against_limit: bool,
36) -> AlarmRetry {
37 if counts_against_limit && counted_retry >= RETRY_CEILING {
38 AlarmRetry::GiveUp
39 } else {
40 let shift = retry.clamp(0, MAX_BACKOFF_SHIFT) as u32;
41 let at_ms = now_ms.saturating_add(BACKOFF_BASE_MS * (1_i64 << shift));
42 AlarmRetry::Retry { at_ms }
43 }
44}