Skip to main content

smgw_cls/
engine.rs

1//! A caller-clocked lifecycle for one outgoing CLS connection.
2//!
3//! Supply elapsed monotonic time. Whenever [`Session::deadline`] changes, arm a
4//! timer and call [`Session::tick`] on expiry, including while the peer is idle.
5//! The driver owns sockets and must close the generation named by [`Action::Close`].
6
7use crate::reconnect_delay;
8use core::time::Duration;
9
10/// Timing and retry limits for one call to [`Session::start`].
11#[derive(Clone, Copy, Debug)]
12pub struct Policy {
13    /// Maximum time allowed for a connection attempt.
14    pub connect_timeout: Duration,
15    /// Maximum lifetime after authentication succeeds.
16    pub session_lifetime: Duration,
17    /// Delay before the first retry.
18    pub initial_delay: Duration,
19    /// Upper bound on any retry delay.
20    pub maximum_delay: Duration,
21    /// Additional attempts allowed across this lifecycle.
22    pub retries: u32,
23}
24
25impl Default for Policy {
26    fn default() -> Self {
27        Self {
28            connect_timeout: Duration::from_secs(5),
29            session_lifetime: Duration::from_secs(60),
30            initial_delay: Duration::from_secs(1),
31            maximum_delay: Duration::from_secs(10),
32            retries: 3,
33        }
34    }
35}
36
37/// An instruction referring to exactly one transport attempt.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum Action {
40    /// Start establishing and authenticating the connection.
41    Connect { generation: u64 },
42    /// Deliver payloads on the authenticated stream.
43    Ready { generation: u64 },
44    /// Release all transport resources for this attempt.
45    Close { generation: u64 },
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49enum State {
50    Idle,
51    Connecting,
52    Active,
53    Backoff,
54}
55
56/// Lifecycle of a single connection. It owns no buffers or operating-system resources.
57#[derive(Debug)]
58pub struct Session {
59    policy: Policy,
60    state: State,
61    generation: u64,
62    retries_used: u32,
63    deadline: Option<Duration>,
64}
65
66impl Session {
67    /// Create an idle engine with a fixed retry policy.
68    pub fn new(policy: Policy) -> Self {
69        Self {
70            policy,
71            state: State::Idle,
72            generation: 0,
73            retries_used: 0,
74            deadline: None,
75        }
76    }
77
78    /// The next absolute deadline on the caller's monotonic clock.
79    pub fn deadline(&self) -> Option<Duration> {
80        self.deadline
81    }
82
83    /// Start an idle lifecycle with a fresh retry budget.
84    pub fn start(&mut self, now: Duration) -> Option<Action> {
85        if self.state != State::Idle {
86            return None;
87        }
88        self.retries_used = 0;
89        self.connect(now)
90    }
91
92    fn connect(&mut self, now: Duration) -> Option<Action> {
93        // Exhaustion leaves the session idle and prevents generation reuse.
94        self.reset();
95        self.generation = self.generation.checked_add(1)?;
96        self.state = State::Connecting;
97        self.deadline = Some(now.saturating_add(self.policy.connect_timeout));
98        Some(Action::Connect {
99            generation: self.generation,
100        })
101    }
102
103    /// Report a verified, authorized handshake. A callback at the deadline is late.
104    pub fn connected(&mut self, generation: u64, now: Duration) -> Option<Action> {
105        if generation != self.generation || self.state != State::Connecting {
106            return None;
107        }
108        if self.deadline.is_some_and(|at| now >= at) {
109            return self.tick(now);
110        }
111        self.state = State::Active;
112        self.deadline = Some(now.saturating_add(self.policy.session_lifetime));
113        Some(Action::Ready { generation })
114    }
115
116    /// Report a failure. Only transient failures consume a retry.
117    pub fn failed(&mut self, generation: u64, now: Duration, retryable: bool) -> Option<Action> {
118        if generation != self.generation || !matches!(self.state, State::Active | State::Connecting)
119        {
120            return None;
121        }
122        self.reset();
123        if retryable && self.retries_used < self.policy.retries {
124            self.deadline = Some(now.saturating_add(reconnect_delay(
125                self.policy.initial_delay,
126                self.policy.maximum_delay,
127                self.retries_used,
128            )));
129            self.retries_used += 1;
130            self.state = State::Backoff;
131        }
132        Some(Action::Close { generation })
133    }
134
135    /// Process an expired timer. Early calls and obsolete timer wakeups are harmless.
136    pub fn tick(&mut self, now: Duration) -> Option<Action> {
137        if self.deadline.is_none_or(|at| now < at) {
138            return None;
139        }
140        match self.state {
141            State::Backoff => self.connect(now),
142            State::Connecting | State::Active => self.failed(self.generation, now, true),
143            State::Idle => None,
144        }
145    }
146
147    /// Stop the lifecycle, cancel timers and close any current transport.
148    pub fn cancel(&mut self) -> Option<Action> {
149        let close = matches!(self.state, State::Active | State::Connecting);
150        self.reset();
151        close.then_some(Action::Close {
152            generation: self.generation,
153        })
154    }
155
156    fn reset(&mut self) {
157        self.state = State::Idle;
158        self.deadline = None;
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    fn at(seconds: u64) -> Duration {
166        Duration::from_secs(seconds)
167    }
168
169    #[test]
170    fn stale_handshake_after_cancel_is_ignored() {
171        let mut s = Session::new(Policy::default());
172        assert_eq!(s.start(at(0)), Some(Action::Connect { generation: 1 }));
173        assert_eq!(s.cancel(), Some(Action::Close { generation: 1 }));
174        assert_eq!(s.connected(1, at(1)), None);
175        assert_eq!(s.deadline(), None);
176        assert_eq!(s.start(at(2)), Some(Action::Connect { generation: 2 }));
177        assert_eq!(s.failed(1, at(3), true), None);
178        assert_eq!(s.connected(1, at(3)), None);
179        assert_eq!(s.connected(2, at(3)), Some(Action::Ready { generation: 2 }));
180    }
181
182    #[test]
183    fn deadlines_and_retries_are_bounded() {
184        let mut s = Session::new(Policy {
185            retries: 1,
186            ..Policy::default()
187        });
188        s.start(at(0));
189        assert_eq!(s.start(at(1)), None);
190        assert_eq!(s.tick(at(4)), None);
191        assert_eq!(s.connected(1, at(5)), Some(Action::Close { generation: 1 }));
192        assert_eq!(s.deadline(), Some(at(6)));
193        assert_eq!(s.tick(at(6)), Some(Action::Connect { generation: 2 }));
194        s.connected(2, at(7));
195        assert_eq!(s.tick(at(67)), Some(Action::Close { generation: 2 }));
196        assert_eq!(s.deadline(), None);
197    }
198
199    #[test]
200    fn permanent_failure_and_cancelled_backoff_stop_retries() {
201        let mut s = Session::new(Policy::default());
202        s.start(at(0));
203        s.failed(1, at(1), false);
204        assert_eq!(s.deadline(), None);
205        s.start(at(2));
206        s.failed(2, at(3), true);
207        assert_eq!(s.cancel(), None);
208        assert_eq!(s.tick(Duration::MAX), None);
209    }
210}