Skip to main content

agentmux_srv_core/backend/viewer/
sends.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What each paired device has sent lately: a rate limit, and the
5//! `message_id`s already taken, so a retry after a lost reply is answered
6//! from memory instead of delivered twice (agentmux-mobile's
7//! SPEC_SEND_FROM_THE_PHONE_2026_10_13 §4, §5.2.1). Memory only: a restart
8//! forgets it, which a retry 10 minutes later would too.
9
10use std::collections::{HashMap, VecDeque};
11use std::time::{Duration, Instant};
12
13/// Sends one device may make in [`RATE_WINDOW`].
14pub const RATE_LIMIT: usize = 30;
15pub const RATE_WINDOW: Duration = Duration::from_secs(60);
16/// How long a `message_id` is remembered.
17pub const REMEMBER: Duration = Duration::from_secs(600);
18
19/// How a delivered message reached the agent.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum Sent {
22    /// The agent has it.
23    Delivered,
24    /// Waiting for the agent's process (starting, restarting), which reads
25    /// it when it can.
26    Queued,
27}
28
29impl Sent {
30    pub fn as_str(self) -> &'static str {
31        match self {
32            Self::Delivered => "delivered",
33            Self::Queued => "queued",
34        }
35    }
36}
37
38/// Whether a send may go ahead.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum Admit {
41    /// A new message: deliver it, then [`SendLedger::finish`].
42    New,
43    /// Already delivered: answer as before.
44    Duplicate(Sent),
45    /// The same message is being delivered right now.
46    InFlight,
47    /// Too many sends; try again after this long.
48    RateLimited(Duration),
49}
50
51#[derive(Default)]
52struct DeviceSends {
53    /// When each send in the window was admitted, oldest first.
54    recent: VecDeque<Instant>,
55    /// `message_id` → its outcome (`None` while in flight) and when it came.
56    ids: HashMap<String, (Option<Sent>, Instant)>,
57}
58
59#[derive(Default)]
60pub struct SendLedger {
61    by_device: HashMap<String, DeviceSends>,
62}
63
64impl SendLedger {
65    pub fn admit(&mut self, device_id: &str, message_id: &str, now: Instant) -> Admit {
66        let sends = self.by_device.entry(device_id.to_string()).or_default();
67        sends.ids.retain(|_, (_, at)| now.duration_since(*at) < REMEMBER);
68        while sends.recent.front().is_some_and(|at| now.duration_since(*at) >= RATE_WINDOW) {
69            sends.recent.pop_front();
70        }
71        match sends.ids.get(message_id) {
72            Some((Some(sent), _)) => return Admit::Duplicate(*sent),
73            Some((None, _)) => return Admit::InFlight,
74            None => {}
75        }
76        if sends.recent.len() >= RATE_LIMIT {
77            let oldest = *sends.recent.front().expect("non-empty at the limit");
78            return Admit::RateLimited(RATE_WINDOW.saturating_sub(now.duration_since(oldest)));
79        }
80        sends.recent.push_back(now);
81        sends.ids.insert(message_id.to_string(), (None, now));
82        Admit::New
83    }
84
85    /// Record how an admitted message went. `None`: it failed, and a retry
86    /// may try again.
87    pub fn finish(&mut self, device_id: &str, message_id: &str, outcome: Option<Sent>) {
88        let Some(sends) = self.by_device.get_mut(device_id) else { return };
89        match outcome {
90            Some(sent) => {
91                if let Some(entry) = sends.ids.get_mut(message_id) {
92                    entry.0 = Some(sent);
93                }
94            }
95            None => {
96                sends.ids.remove(message_id);
97            }
98        }
99    }
100
101    /// Forget a revoked device.
102    pub fn forget_device(&mut self, device_id: &str) {
103        self.by_device.remove(device_id);
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    #[test]
112    fn a_message_id_is_delivered_once_and_a_failed_one_can_be_retried() {
113        let mut ledger = SendLedger::default();
114        let t = Instant::now();
115        assert_eq!(ledger.admit("d", "m1", t), Admit::New);
116        assert_eq!(ledger.admit("d", "m1", t), Admit::InFlight, "still being delivered");
117        ledger.finish("d", "m1", Some(Sent::Queued));
118        assert_eq!(ledger.admit("d", "m1", t), Admit::Duplicate(Sent::Queued));
119        assert_eq!(ledger.admit("other", "m1", t), Admit::New, "ids are per device");
120
121        assert_eq!(ledger.admit("d", "m2", t), Admit::New);
122        ledger.finish("d", "m2", None);
123        assert_eq!(ledger.admit("d", "m2", t), Admit::New, "a failed send may be tried again");
124
125        // Remembered for REMEMBER, then a new message as far as srv knows.
126        assert_eq!(ledger.admit("d", "m1", t + REMEMBER), Admit::New);
127    }
128
129    #[test]
130    fn thirty_sends_a_minute_then_wait_for_the_oldest_to_leave_the_window() {
131        let mut ledger = SendLedger::default();
132        let t = Instant::now();
133        for i in 0..RATE_LIMIT {
134            let at = t + Duration::from_secs(i as u64);
135            assert_eq!(ledger.admit("d", &format!("m{i}"), at), Admit::New);
136            ledger.finish("d", &format!("m{i}"), Some(Sent::Delivered));
137        }
138        let at = t + Duration::from_secs(40);
139        assert_eq!(ledger.admit("d", "late", at), Admit::RateLimited(Duration::from_secs(20)));
140        assert_eq!(ledger.admit("d", "m3", at), Admit::Duplicate(Sent::Delivered), "a retry is answered even when limited");
141        assert_eq!(ledger.admit("other", "x", at), Admit::New, "the limit is per device");
142        assert_eq!(ledger.admit("d", "late", t + RATE_WINDOW), Admit::New, "the oldest left the window");
143        ledger.forget_device("d");
144        assert_eq!(ledger.admit("d", "m3", at), Admit::New, "a revoked device's ids are gone");
145    }
146}