Skip to main content

zaun_community_protocol/client/
retry.rs

1//! Retry schedule of unanswered commands (§7.3).
2
3use crate::envelope::ErrorBody;
4use crate::limits::DAY_MS;
5
6/// The first delay after a transient error (§7.3), doubling like the backoff: the host
7/// answered, so there is no answer still on its way to wait for.
8const REFUSED_INITIAL_MS: u64 = 2_000;
9
10/// Exponential backoff: `initial_ms`, then ×`factor`, capped at `cap_ms`; give up once
11/// `give_up_ms` have passed since the first send (§7.3: 5 s, ×2, 60 s, 24 h).
12///
13/// A resend also waits until the host has been silent for `initial_ms` (at most `cap_ms`
14/// longer): while its messages are still arriving, the answer is most likely among them.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct RetryPolicy {
17    /// Delay before the first retry.
18    pub initial_ms: u64,
19    /// Multiplier per attempt.
20    pub factor: u64,
21    /// Largest delay.
22    pub cap_ms: u64,
23    /// Total time after which a request is abandoned.
24    pub give_up_ms: u64,
25}
26
27impl Default for RetryPolicy {
28    fn default() -> Self {
29        Self::SPEC
30    }
31}
32
33impl RetryPolicy {
34    /// The §7.3 schedule.
35    pub const SPEC: Self = Self {
36        initial_ms: 5_000,
37        factor: 2,
38        cap_ms: 60_000,
39        give_up_ms: DAY_MS,
40    };
41
42    /// The delay after send number `attempt` (1 = the first send): 5 s, 10 s, 20 s, 40 s,
43    /// then 60 s.
44    #[must_use]
45    pub fn delay(&self, attempt: u32) -> u64 {
46        let exponent = attempt.saturating_sub(1);
47        let growth = self.factor.checked_pow(exponent).unwrap_or(u64::MAX);
48        self.initial_ms.saturating_mul(growth).min(self.cap_ms)
49    }
50
51    /// The delay after a transient error on send number `attempt`: 2 s, 4 s, 8 s, … 60 s,
52    /// never longer than [`RetryPolicy::delay`].
53    #[must_use]
54    pub fn refused_delay(&self, attempt: u32) -> u64 {
55        let exponent = attempt.saturating_sub(1);
56        let growth = self.factor.checked_pow(exponent).unwrap_or(u64::MAX);
57        REFUSED_INITIAL_MS
58            .saturating_mul(growth)
59            .min(self.cap_ms)
60            .min(self.delay(attempt))
61    }
62
63    /// The next send time after send number `attempt` at `now_ms`: the backoff, or after a
64    /// transient `error` its [`RetryPolicy::refused_delay`] or, if later, its
65    /// `retry_after_ms`.
66    #[must_use]
67    pub fn next_at(&self, now_ms: u64, attempt: u32, error: Option<&ErrorBody>) -> u64 {
68        let wait = match error {
69            None => self.delay(attempt),
70            Some(e) => self
71                .refused_delay(attempt)
72                .max(e.extras.retry_after_ms.unwrap_or(0)),
73        };
74        now_ms.saturating_add(wait)
75    }
76
77    /// Whether a resend due at `due_ms` goes out at `now_ms`, the host last heard at
78    /// `heard_ms`: once the host has been silent for `initial_ms`, or `cap_ms` after it was
79    /// due, whatever the host is sending.
80    #[must_use]
81    pub const fn resend_now(&self, due_ms: u64, heard_ms: Option<u64>, now_ms: u64) -> bool {
82        if now_ms < due_ms {
83            return false;
84        }
85        let quiet = match heard_ms {
86            Some(heard) => now_ms.saturating_sub(heard) >= self.initial_ms,
87            None => true,
88        };
89        quiet || now_ms.saturating_sub(due_ms) >= self.cap_ms
90    }
91
92    /// Whether a request first sent at `first_ms` is abandoned at `now_ms`.
93    #[must_use]
94    pub const fn expired(&self, first_ms: u64, now_ms: u64) -> bool {
95        now_ms.saturating_sub(first_ms) >= self.give_up_ms
96    }
97}
98
99/// Whether an error response is transient: not idempotency-recorded, so the same
100/// `request_id` may be retried (§7.3: `BUSY`, `RATE_LIMITED`, `INTERNAL`,
101/// `SLOWMODE_ACTIVE`).
102#[must_use]
103pub fn is_transient(error: &ErrorBody) -> bool {
104    !error.is_recorded()
105}