Skip to main content

agentmux_srv_core/backend/lan/
seen_agents.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The agents a LAN peer has listed, kept after the peer goes quiet.
5//!
6//! A peer that stops answering is dropped from `LanDiscoveryController::get_instances`, and its agents
7//! with it, so a message to one of them looks like a message to a name nobody knows. This remembers the
8//! name and the host that listed it, so `server::reactive::peer_hold` can tell "an agent of a machine that is
9//! down" from "a name that does not exist". Kept in `lan-seen-agents.json` beside the databases, written
10//! only when a name appears or moves host (or its record is a day old), so a poll every few seconds
11//! costs no writes.
12
13use std::collections::HashMap;
14use std::path::{Path, PathBuf};
15use std::sync::{Mutex, OnceLock};
16
17use serde::{Deserialize, Serialize};
18
19/// Names kept; the oldest listing is dropped past this, so a peer listing endless names cannot grow it.
20const MAX_SEEN: usize = 1024;
21/// A name not listed for this long is forgotten: the agent was deleted or its machine retired.
22const FORGET_AFTER_SECS: u64 = 30 * 24 * 3600;
23/// A listing that changes nothing is written again only when the stored one is this old.
24const REFRESH_AFTER_SECS: u64 = 24 * 3600;
25
26/// Where a name was last listed.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct SeenAgent {
29    pub hostname: String,
30    pub seen_secs: u64,
31}
32
33#[derive(Default)]
34struct Seen {
35    agents: HashMap<String, SeenAgent>,
36    loaded: bool,
37}
38
39impl Seen {
40    /// Note that `hostname` listed `names` at `now_secs`; whether the record on disk is now out of date.
41    fn remember(&mut self, names: &[String], hostname: &str, now_secs: u64) -> bool {
42        let mut stale = false;
43        for name in names {
44            let key = name.trim().to_lowercase();
45            if key.is_empty() {
46                continue;
47            }
48            let old = self.agents.get(&key);
49            if old.is_none_or(|o| o.hostname != hostname || now_secs.saturating_sub(o.seen_secs) >= REFRESH_AFTER_SECS) {
50                stale = true;
51                self.agents.insert(key, SeenAgent { hostname: hostname.to_string(), seen_secs: now_secs });
52            }
53        }
54        while self.agents.len() > MAX_SEEN {
55            let Some(oldest) = self.agents.iter().min_by_key(|(_, v)| v.seen_secs).map(|(k, _)| k.clone()) else { break };
56            self.agents.remove(&oldest);
57        }
58        stale
59    }
60
61    fn lookup(&self, name: &str, now_secs: u64) -> Option<SeenAgent> {
62        let seen = self.agents.get(&name.trim().to_lowercase())?;
63        (now_secs.saturating_sub(seen.seen_secs) < FORGET_AFTER_SECS).then(|| seen.clone())
64    }
65}
66
67fn read(path: &Path) -> HashMap<String, SeenAgent> {
68    std::fs::read(path).ok().and_then(|bytes| serde_json::from_slice(&bytes).ok()).unwrap_or_default()
69}
70
71/// Write through a temp file and a rename, so a crash leaves the old record whole.
72fn write(path: &Path, agents: &HashMap<String, SeenAgent>) {
73    let Ok(json) = serde_json::to_vec(agents) else { return };
74    let tmp = path.with_extension("json.tmp");
75    if std::fs::write(&tmp, json).is_ok() && std::fs::rename(&tmp, path).is_err() {
76        let _ = std::fs::remove_file(&tmp);
77    }
78}
79
80/// Where the record lives; none under test, so a test never reads or writes the real one.
81fn record_path() -> Option<PathBuf> {
82    #[cfg(any(test, feature = "test-support"))]
83    {
84        None
85    }
86    #[cfg(not(any(test, feature = "test-support")))]
87    {
88        Some(crate::backend::base::get_mux_data_dir().join("lan-seen-agents.json"))
89    }
90}
91
92fn seen() -> &'static Mutex<Seen> {
93    static SEEN: OnceLock<Mutex<Seen>> = OnceLock::new();
94    SEEN.get_or_init(Default::default)
95}
96
97fn load_once(seen: &mut Seen) {
98    if !seen.loaded {
99        seen.loaded = true;
100        if let Some(path) = record_path() {
101            seen.agents = read(&path);
102        }
103    }
104}
105
106/// Note that `hostname` listed `names` at `now_secs`.
107pub fn remember(names: &[String], hostname: &str, now_secs: u64) {
108    let mut guard = seen().lock().unwrap_or_else(|e| e.into_inner());
109    load_once(&mut guard);
110    if guard.remember(names, hostname, now_secs) {
111        if let Some(path) = record_path() {
112            write(&path, &guard.agents);
113        }
114    }
115}
116
117/// Where `name` was last listed by a LAN peer, if one ever listed it (and not over 30 days ago).
118pub fn lookup(name: &str) -> Option<SeenAgent> {
119    let mut guard = seen().lock().unwrap_or_else(|e| e.into_inner());
120    load_once(&mut guard);
121    guard.lookup(name, agentmux_common::time::now_secs_u64())
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    fn names(n: &[&str]) -> Vec<String> {
129        n.iter().map(|s| s.to_string()).collect()
130    }
131
132    #[test]
133    fn a_listed_name_is_found_by_any_case_with_its_host() {
134        let mut seen = Seen::default();
135        assert!(seen.remember(&names(&["Maricon", " "]), "charlie", 10));
136        assert_eq!(seen.lookup("MARICON", 11), Some(SeenAgent { hostname: "charlie".into(), seen_secs: 10 }));
137        assert_eq!(seen.agents.len(), 1, "a blank name is not kept");
138    }
139
140    #[test]
141    fn only_a_new_name_a_new_host_or_an_old_record_asks_for_a_write() {
142        let mut seen = Seen::default();
143        assert!(seen.remember(&names(&["Opaz"]), "charlie", 10), "new");
144        assert!(!seen.remember(&names(&["Opaz"]), "charlie", 20), "same name, same host: no write");
145        assert_eq!(seen.agents["opaz"].seen_secs, 10, "and the stored time stays");
146        assert!(seen.remember(&names(&["opaz"]), "starpower", 30), "moved host");
147        assert_eq!(seen.lookup("Opaz", 31).map(|s| s.hostname), Some("starpower".to_string()));
148        assert!(seen.remember(&names(&["Opaz"]), "starpower", 30 + REFRESH_AFTER_SECS), "a day old");
149    }
150
151    #[test]
152    fn a_name_not_listed_for_thirty_days_is_forgotten() {
153        let mut seen = Seen::default();
154        seen.remember(&names(&["Gone"]), "charlie", 10);
155        assert!(seen.lookup("gone", 10 + FORGET_AFTER_SECS - 1).is_some());
156        assert!(seen.lookup("gone", 10 + FORGET_AFTER_SECS).is_none());
157    }
158
159    #[test]
160    fn past_the_cap_the_oldest_listing_goes() {
161        let mut seen = Seen::default();
162        for i in 0..MAX_SEEN + 5 {
163            seen.remember(&[format!("agent{i}")], "h", i as u64);
164        }
165        assert_eq!(seen.agents.len(), MAX_SEEN);
166        assert!(!seen.agents.contains_key("agent0") && seen.agents.contains_key(&format!("agent{}", MAX_SEEN + 4)));
167    }
168
169    #[test]
170    fn the_record_survives_a_write_and_a_read_and_a_bad_file_reads_empty() {
171        let dir = std::env::temp_dir().join(format!("seen-agents-{}", uuid::Uuid::new_v4()));
172        std::fs::create_dir_all(&dir).unwrap();
173        let path = dir.join("lan-seen-agents.json");
174        let mut seen = Seen::default();
175        seen.remember(&names(&["Parlo"]), "charlie", 5);
176        write(&path, &seen.agents);
177        assert_eq!(read(&path).get("parlo"), Some(&SeenAgent { hostname: "charlie".into(), seen_secs: 5 }));
178        std::fs::write(&path, b"not json").unwrap();
179        assert!(read(&path).is_empty());
180        assert!(read(&dir.join("missing.json")).is_empty());
181        let _ = std::fs::remove_dir_all(&dir);
182    }
183}