Skip to main content

agentmux_srv_core/backend/
message_flow.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! "A sent B a message at T": the `message-flow` event and the short list of recent ones, for the message pulses
5//! of the Atlas agent map.
6//!
7//! It carries ids and times only: the message id, the two agent ids, the host of each end when this srv knows
8//! it, how the message travelled and what happened to it here. There is no field for the text, the subject, a
9//! file name or a size, so none can leak through it. Each srv reports what it handled: a send to another
10//! computer shows on both srvs (the sender's as `lan` or `queued`, the receiver's as `delivered`), and a reader
11//! joins the two by `msg_id`.
12//!
13//! The recent list lives in memory only (`RECENT_MAX` entries, newest last) and is read with
14//! `GET /api/v1/message-flow`.
15
16use std::collections::VecDeque;
17use std::sync::{Arc, Mutex, OnceLock};
18
19use serde::Serialize;
20
21use super::mps::Broker;
22use super::mps_events::MessageFlow;
23
24/// How many recent messages are kept.
25pub const RECENT_MAX: usize = 200;
26
27/// One end of a message: the agent's id (its slug) and the host it runs on, when this srv knows it.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
29#[ts(export, export_to = "../../../frontend/types/rpc/")]
30pub struct MessageFlowEnd {
31    pub agent: String,
32    #[serde(skip_serializing_if = "Option::is_none")]
33    #[ts(optional)]
34    pub host: Option<String>,
35}
36
37/// How the message travelled to or from this srv.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ts_rs::TS)]
39#[ts(export, export_to = "../../../frontend/types/rpc/")]
40#[serde(rename_all = "lowercase")]
41pub enum MessageFlowVia {
42    /// Between two agents of this srv.
43    Host,
44    /// To or from another srv on this computer.
45    Channel,
46    /// To or from another computer on the LAN.
47    Lan,
48    /// Through the cloud relay.
49    Wan,
50}
51
52/// What became of the message here.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ts_rs::TS)]
54#[ts(export, export_to = "../../../frontend/types/rpc/")]
55#[serde(rename_all = "lowercase")]
56pub enum MessageFlowOutcome {
57    /// The receiving agent took it, here or on the peer this srv handed it to.
58    Delivered,
59    /// Kept for an agent that cannot take it now; it is delivered later.
60    Held,
61    /// Given to the cloud relay for the receiver's srv to collect.
62    Queued,
63    /// Not taken: the sender is told why.
64    Refused,
65}
66
67/// The `message-flow` event's payload (`mps_events::MessageFlow`).
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
69#[ts(export, export_to = "../../../frontend/types/rpc/")]
70pub struct MessageFlowEvent {
71    pub msg_id: String,
72    /// When this srv handled it, in milliseconds since 1970.
73    #[ts(type = "number")]
74    pub at_ms: u64,
75    pub from: MessageFlowEnd,
76    pub to: MessageFlowEnd,
77    pub via: MessageFlowVia,
78    pub outcome: MessageFlowOutcome,
79}
80
81/// What a call site knows of a message: ids and the two outcomes, never its content.
82pub struct Seen<'a> {
83    pub msg_id: &'a str,
84    pub from: &'a str,
85    pub from_host: Option<&'a str>,
86    pub to: &'a str,
87    pub to_host: Option<&'a str>,
88    pub via: MessageFlowVia,
89    pub outcome: MessageFlowOutcome,
90}
91
92struct Flow {
93    broker: Arc<Broker>,
94    recent: Mutex<VecDeque<MessageFlowEvent>>,
95}
96
97static FLOW: OnceLock<Flow> = OnceLock::new();
98
99/// Start publishing on `broker` for the rest of the process. The first call wins.
100pub fn install(broker: Arc<Broker>) {
101    let _ = FLOW.set(Flow { broker, recent: Mutex::new(VecDeque::with_capacity(RECENT_MAX)) });
102}
103
104/// The event for `seen`, as handled at `at_ms`. A message with no sender (a cron job, a bridge) or no id has no
105/// line to draw, so there is none.
106fn event_of(seen: &Seen<'_>, at_ms: u64) -> Option<MessageFlowEvent> {
107    let (msg_id, from, to) = (seen.msg_id.trim(), seen.from.trim(), seen.to.trim());
108    if msg_id.is_empty() || from.is_empty() || to.is_empty() {
109        return None;
110    }
111    let end = |agent: &str, host: Option<&str>| MessageFlowEnd {
112        agent: agent.to_string(),
113        host: host.map(str::trim).filter(|h| !h.is_empty()).map(str::to_string),
114    };
115    Some(MessageFlowEvent {
116        msg_id: msg_id.to_string(),
117        at_ms,
118        from: end(from, seen.from_host),
119        to: end(to, seen.to_host),
120        via: seen.via,
121        outcome: seen.outcome,
122    })
123}
124
125/// Adds `event` to `recent`, dropping the oldest once there are `RECENT_MAX`.
126fn remember(recent: &mut VecDeque<MessageFlowEvent>, event: MessageFlowEvent) {
127    if recent.len() >= RECENT_MAX {
128        recent.pop_front();
129    }
130    recent.push_back(event);
131}
132
133/// Records that `seen` happened: published as the `message-flow` event, and kept in the recent list. Does
134/// nothing before [`install`].
135pub fn note(seen: &Seen<'_>) {
136    if let Some(flow) = FLOW.get() {
137        flow.record(seen, agentmux_common::time::now_ms() as u64);
138    }
139}
140
141impl Flow {
142    /// Keeps and publishes the event for `seen`, handled at `at_ms`.
143    fn record(&self, seen: &Seen<'_>, at_ms: u64) {
144        let Some(event) = event_of(seen, at_ms) else { return };
145        remember(&mut self.recent.lock().unwrap_or_else(|e| e.into_inner()), event.clone());
146        self.broker.publish_event::<MessageFlow>(&event, vec![], 0);
147    }
148}
149
150/// The recent messages, oldest first.
151pub fn recent() -> Vec<MessageFlowEvent> {
152    FLOW.get().map(|f| f.recent.lock().unwrap_or_else(|e| e.into_inner()).iter().cloned().collect()).unwrap_or_default()
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    fn seen<'a>(msg_id: &'a str, from: &'a str, to: &'a str) -> Seen<'a> {
160        Seen { msg_id, from, from_host: Some("charlie"), to, to_host: None, via: MessageFlowVia::Lan, outcome: MessageFlowOutcome::Delivered }
161    }
162
163    #[test]
164    fn an_event_has_the_ids_the_hosts_and_the_outcome_and_nothing_else() {
165        let e = event_of(&seen("m-1", "maricon-2", "lazo"), 7).unwrap();
166        assert_eq!(
167            serde_json::to_value(&e).unwrap(),
168            serde_json::json!({
169                "msg_id": "m-1", "at_ms": 7,
170                "from": { "agent": "maricon-2", "host": "charlie" },
171                "to": { "agent": "lazo" },
172                "via": "lan", "outcome": "delivered",
173            })
174        );
175    }
176
177    #[test]
178    fn a_message_with_no_id_or_no_sender_has_no_event() {
179        assert!(event_of(&seen("", "a", "b"), 1).is_none());
180        assert!(event_of(&seen("m", "  ", "b"), 1).is_none());
181        assert!(event_of(&seen("m", "a", ""), 1).is_none());
182    }
183
184    #[test]
185    fn a_blank_host_is_no_host() {
186        let mut s = seen("m", "a", "b");
187        s.from_host = Some(" ");
188        assert_eq!(event_of(&s, 1).unwrap().from.host, None);
189    }
190
191    #[test]
192    fn every_outcome_and_route_has_its_own_name() {
193        let names = |s: &Seen<'_>| {
194            let v = serde_json::to_value(event_of(s, 1).unwrap()).unwrap();
195            (v["via"].as_str().unwrap().to_string(), v["outcome"].as_str().unwrap().to_string())
196        };
197        for (via, outcome, want) in [
198            (MessageFlowVia::Host, MessageFlowOutcome::Held, ("host", "held")),
199            (MessageFlowVia::Channel, MessageFlowOutcome::Refused, ("channel", "refused")),
200            (MessageFlowVia::Wan, MessageFlowOutcome::Queued, ("wan", "queued")),
201        ] {
202            let mut s = seen("m", "a", "b");
203            (s.via, s.outcome) = (via, outcome);
204            assert_eq!(names(&s), (want.0.to_string(), want.1.to_string()));
205        }
206    }
207
208    #[test]
209    fn a_message_is_published_as_the_event_and_kept_in_the_recent_list() {
210        let broker = Arc::new(Broker::new());
211        let published = Arc::new(Mutex::new(Vec::new()));
212        let sink = Arc::clone(&published);
213        broker.add_observer(Arc::new(move |e: &crate::backend::mps::MuxEvent| sink.lock().unwrap().push((e.event.clone(), e.data.clone()))));
214        let flow = Flow { broker, recent: Mutex::new(VecDeque::new()) };
215        flow.record(&seen("m-1", "maricon-2", "lazo"), 9);
216        flow.record(&seen("", "maricon-2", "lazo"), 10);
217        let published = published.lock().unwrap();
218        assert_eq!(published.len(), 1, "a message with no id says nothing");
219        assert_eq!(published[0].0, "message-flow");
220        assert_eq!(published[0].1.as_ref().unwrap()["msg_id"], "m-1");
221        assert_eq!(flow.recent.lock().unwrap().iter().map(|e| e.at_ms).collect::<Vec<_>>(), vec![9]);
222    }
223
224    #[test]
225    fn the_recent_list_keeps_the_newest_and_is_bounded() {
226        let mut recent = VecDeque::new();
227        for n in 0..RECENT_MAX + 5 {
228            remember(&mut recent, event_of(&seen(&format!("m-{n}"), "a", "b"), n as u64).unwrap());
229        }
230        assert_eq!(recent.len(), RECENT_MAX);
231        assert_eq!(recent.front().unwrap().msg_id, "m-5");
232        assert_eq!(recent.back().unwrap().msg_id, format!("m-{}", RECENT_MAX + 4));
233    }
234}