Covers phases 1-2 of the build order in the architecture spec: the IMAP sync engine (IDLE + UIDVALIDITY tracking + jittered reconnect, headers first with lazy body fetch), the full data model, and a minimal REST API for auth, accounts, folders, messages and delta polling. Credentials are encrypted at rest with ChaCha20-Poly1305 rather than libsodium secretbox, to avoid a system dependency for the same construction. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
37 lines
1004 B
Rust
37 lines
1004 B
Rust
//! Jittered exponential backoff for reconnecting to flaky IMAP servers
|
|
//! (server-architecture-spec.md §3.1).
|
|
|
|
use rand::Rng;
|
|
use std::time::Duration;
|
|
|
|
pub struct Backoff {
|
|
attempt: u32,
|
|
base: Duration,
|
|
max: Duration,
|
|
}
|
|
|
|
impl Backoff {
|
|
pub fn new() -> Self {
|
|
Self {
|
|
attempt: 0,
|
|
base: Duration::from_secs(1),
|
|
max: Duration::from_secs(300),
|
|
}
|
|
}
|
|
|
|
pub fn reset(&mut self) {
|
|
self.attempt = 0;
|
|
}
|
|
|
|
/// Next delay, doubling each call up to `max`, plus up to 30% jitter so
|
|
/// many accounts reconnecting at once don't hammer the server in lockstep.
|
|
pub fn next_delay(&mut self) -> Duration {
|
|
let exp = self.base.as_secs_f64() * 2f64.powi(self.attempt as i32);
|
|
let capped = exp.min(self.max.as_secs_f64());
|
|
self.attempt = self.attempt.saturating_add(1);
|
|
|
|
let jitter_factor = rand::thread_rng().gen_range(1.0..1.3);
|
|
Duration::from_secs_f64(capped * jitter_factor)
|
|
}
|
|
}
|