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