Skip to main content

zaun_community_protocol/client/session/
timers.rs

1//! Time-driven work: retries and give-ups (§7.3), fragment expiry (§5.2), acks (§10.5).
2
3use super::{Session, SessionState};
4use crate::client::outbound::{envelope_text, frame};
5use crate::client::pending::Origin;
6use crate::client::{ClientError, ClientEvent, ProtocolError};
7use crate::command::Body;
8use crate::command::sync::Ack;
9use crate::envelope::ErrorBody;
10use crate::error_code::ErrorCode;
11use crate::ids::RequestId;
12
13/// How many recent ack ids to remember.
14const ACK_IDS: usize = 16;
15
16impl Session {
17    /// Drives timers at `now_ms`: discards stale fragment reassemblies, resends due requests
18    /// with the same text (commands only once the welcome is verified), abandons requests
19    /// after the give-up time, and queues a `sync.ack` when 30 s passed with unacked frames or
20    /// when a refused ack's retry time has come.
21    pub fn poll_timeouts(&mut self, now_ms: u64) -> Vec<ClientEvent> {
22        let mut out = Vec::new();
23        self.reassembler.expire(now_ms);
24        let ready = self.state == SessionState::Ready;
25        let due = self
26            .pending
27            .due(now_ms, &self.config.retry, ready, self.heard_ms);
28        for (request_id, pending) in due.expired {
29            if pending.origin == Origin::Resume {
30                self.resumes_in_flight = self.resumes_in_flight.saturating_sub(1);
31            }
32            out.push(ClientEvent::GaveUp {
33                request_id,
34                kind: pending.kind,
35            });
36        }
37        for id in due.resend {
38            if let Err(e) = self.resend(&id, now_ms) {
39                out.push(ClientEvent::ProtocolError(ProtocolError::AutoSend(e)));
40            }
41        }
42        self.after_input(now_ms, &mut out);
43        out
44    }
45
46    /// Re-frames a pending request's stored text (fresh fragment id) and reschedules it.
47    pub(super) fn resend(&mut self, id: &RequestId, now_ms: u64) -> Result<(), ClientError> {
48        let budget = self.config.text_budget;
49        let retry = self.config.retry;
50        let Some(p) = self.pending.get_mut(id) else {
51            return Ok(());
52        };
53        let messages = frame(&p.text, budget)?;
54        p.attempt = p.attempt.saturating_add(1);
55        p.next_ms = retry.next_at(now_ms, p.attempt, None);
56        p.refused = false;
57        self.transmit.extend(messages);
58        Ok(())
59    }
60
61    /// Sends `sync.ack` with the current cursors (§10.5). Acks are not tracked for retries
62    /// with the same text: a refused one is replaced by a new one (`ack_refused`).
63    pub(super) fn send_acks(&mut self) -> Result<(), ClientError> {
64        let community = self.community_id();
65        for body in self.cursors.ack_bodies() {
66            let id = RequestId::random()?;
67            let text = envelope_text(&body, Some(id), community, None)?;
68            self.transmit.extend(frame(&text, self.config.text_budget)?);
69            if self.ack_ids.len() == ACK_IDS {
70                self.ack_ids.pop_front();
71            }
72            let channels = body.channels.iter().map(|c| c.channel_id).collect();
73            self.ack_ids.push_back((id, channels));
74        }
75        self.ack.reset();
76        self.ack_ripe_ms = None;
77        self.ack_retry_ms = None;
78        Ok(())
79    }
80
81    /// Whether a `sync.ack` is due at `now_ms`: a refused ack's retry time has come, or, with
82    /// no retry pending, the 8-frame / 30 s cadence (§10.5). A pending retry holds back the
83    /// cadence, so nothing is acked before the host's `retry_after_ms`.
84    pub(super) fn ack_due(&self, now_ms: u64) -> bool {
85        self.ack_retry_ms
86            .map_or_else(|| self.ack.due(now_ms), |at| now_ms >= at)
87    }
88
89    /// The host refused the ack at `ack_ids[index]` (§10.5). `RATE_LIMITED` marks its
90    /// channels for the next ack and schedules one new ack, built from the cursors as they
91    /// are then, `retry_after_ms` later (the retry policy's first delay without a hint); it
92    /// is reported as [`ClientEvent::Retrying`]. Other refusals are dropped as before.
93    pub(super) fn ack_refused(
94        &mut self,
95        index: usize,
96        error: ErrorBody,
97        now_ms: u64,
98        out: &mut Vec<ClientEvent>,
99    ) {
100        if error.code != ErrorCode::RateLimited {
101            return;
102        }
103        let Some((request_id, channels)) = self.ack_ids.get_mut(index) else {
104            return;
105        };
106        let request_id = *request_id;
107        let channels = std::mem::take(channels);
108        self.cursors.mark_unacked(&channels);
109        let wait = error
110            .extras
111            .retry_after_ms
112            .unwrap_or_else(|| self.config.retry.refused_delay(1));
113        let at = now_ms.saturating_add(wait);
114        let at = self.ack_retry_ms.map_or(at, |pending| pending.max(at));
115        self.ack_retry_ms = Some(at);
116        out.push(ClientEvent::Retrying {
117            request_id,
118            kind: Ack::NAME,
119            error,
120            retry_at_ms: at,
121        });
122    }
123}