Skip to main content

agentmux_srv_core/backend/
fleet_source.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What this install says about itself beyond agent names, on the LAN fleet
5//! feed, the UDP and mDNS records and the cloud presence record
6//! (agentmux-mobile's SPEC_FLEET_HOST_TAGS_AND_CLOUD_HOSTS_2026_10_06 §5–6):
7//! each agent's kind, how many channels this machine is running, and this
8//! install's id. Also each agent's state and since when
9//! (`backend::agent_state`, agentmux-mobile's
10//! SPEC_AGENT_STATUS_AND_LIVE_PANE_FEED_2026_10_07 §3).
11//!
12//! The fleet feed's change detection calls [`FleetSource::observe`] once a
13//! second. The LAN replies, which have no fleet feed in hand, read the
14//! channel count it last saw ([`latest_channels_running`]) and
15//! [`install_id`].
16
17use std::collections::{BTreeMap, HashMap};
18use std::sync::atomic::{AtomicU32, Ordering};
19use std::sync::{Arc, OnceLock};
20use std::time::{Duration, Instant};
21
22use crate::backend::agent_state::{AgentState, SinceTracker};
23use crate::backend::fleet_feed::{AgentKind, FleetObservation};
24use crate::backend::reactive::registry::AgentEntry;
25use crate::backend::storage::store::Store;
26
27/// The upper bound of `channels_running` on every wire.
28pub const MAX_CHANNELS_RUNNING: u32 = 99;
29
30/// How long a channel count is reused before the shared registry is read
31/// again. The registry's own heartbeat is 20 s; reading its directory every
32/// second would buy nothing.
33const CHANNELS_REREAD: Duration = Duration::from_secs(5);
34
35/// The count [`FleetSource::observe`] last saw; 0 before the first look.
36static LATEST_CHANNELS_RUNNING: AtomicU32 = AtomicU32::new(0);
37
38static INSTALL_ID: OnceLock<String> = OnceLock::new();
39
40/// This install's WAN instance id (26 chars of lowercase base32, a hash of
41/// the instance public key; not a secret), or `None` when this process has
42/// no WAN identity store. The instance is minted once per channel and never
43/// changes, so the first answer is kept.
44pub fn install_id() -> Option<String> {
45    if let Some(id) = INSTALL_ID.get() {
46        return Some(id.clone());
47    }
48    let wan = crate::backend::storage::wan_identity::global()?;
49    let instance = wan
50        .instance_ensure(&crate::backend::reactive::registry::local_host_label())
51        .ok()?;
52    Some(INSTALL_ID.get_or_init(|| instance.instance_id).clone())
53}
54
55/// 1 for this channel plus every other channel of this machine with a live
56/// entry in the host-global shared registry (`swarm_remote::other_channels`,
57/// with its `HIDE_AFTER_MS`), clamped to 1..=[`MAX_CHANNELS_RUNNING`]. A
58/// channel with no agent registered has no entry and is not counted.
59pub fn count_channels_running(entries: &[AgentEntry], own_channel: &str, own_url: &str, now_ms: u64) -> u32 {
60    let others = crate::backend::swarm_remote::other_channels(entries, &Default::default(), own_channel, own_url, now_ms).len();
61    u32::try_from(others)
62        .unwrap_or(u32::MAX)
63        .saturating_add(1)
64        .clamp(1, MAX_CHANNELS_RUNNING)
65}
66
67/// The channel count the fleet feed last saw, for the UDP replies; `None`
68/// before its first look.
69pub fn latest_channels_running() -> Option<u32> {
70    match LATEST_CHANNELS_RUNNING.load(Ordering::Relaxed) {
71        0 => None,
72        n => Some(n),
73    }
74}
75
76/// Each agent's kind by name, from its block. An agent whose block can't be
77/// read is left out (a peer then shows no tag rather than a guess).
78pub fn kinds_by_name<'a>(
79    agents: impl IntoIterator<Item = (&'a str, &'a str)>,
80    kind_of_block: impl Fn(&str) -> Option<AgentKind>,
81) -> BTreeMap<String, AgentKind> {
82    agents
83        .into_iter()
84        .filter_map(|(name, block_id)| kind_of_block(block_id).map(|k| (name.to_string(), k)))
85        .collect()
86}
87
88type AgentList = Box<dyn Fn() -> Vec<(String, String)> + Send + Sync>;
89type KindOfBlock = Box<dyn Fn(&str) -> Option<AgentKind> + Send + Sync>;
90type StateOfBlock = Box<dyn Fn(&str) -> Option<AgentState> + Send + Sync>;
91type LineOfBlock = Box<dyn Fn(&str) -> Option<String> + Send + Sync>;
92type RegistryRead = Box<dyn Fn() -> Vec<AgentEntry> + Send + Sync>;
93
94/// The fleet feed's view of this instance.
95pub struct FleetSource {
96    /// `(agent name, block id)` of every reachable agent.
97    agents: AgentList,
98    kind_of_block: KindOfBlock,
99    /// The block's state now (`agent_state::current_state`); read on every
100    /// look, unlike the kind.
101    state_of_block: StateOfBlock,
102    /// The block's summary line now (`agent_line`), `None` while sharing is
103    /// off; read on every look.
104    line_of_block: LineOfBlock,
105    /// When each state began; a block no longer listed is forgotten.
106    since: &'static SinceTracker,
107    shared_registry: RegistryRead,
108    own_channel: String,
109    own_url: String,
110    /// Kinds already read, by block id. A block's `agentMode` is fixed when
111    /// the agent is created, so each block is read once while it is listed.
112    kinds: parking_lot::Mutex<HashMap<String, AgentKind>>,
113    channels: parking_lot::Mutex<Option<(Instant, u32)>>,
114}
115
116impl FleetSource {
117    /// The live source: the reactive registry, the object store, the
118    /// settings and the host-global shared registry.
119    pub fn live(
120        handler: &'static crate::backend::reactive::handler::ReactiveHandler,
121        mstore: Arc<Store>,
122        config: Arc<crate::backend::wconfig::ConfigState>,
123        own_url: String,
124    ) -> Self {
125        crate::backend::background_set::watch(Arc::clone(&mstore));
126        let state_store = Arc::clone(&mstore);
127        let line_store = Arc::clone(&mstore);
128        Self::new(
129            Box::new(move || {
130                handler
131                    .list_agents()
132                    .into_iter()
133                    .map(|a| (a.agent_id, a.block_id))
134                    .collect()
135            }),
136            Box::new(move |block_id| crate::backend::operator_config_seed::agent_kind_of_block(&mstore, block_id)),
137            Box::new(move |block_id| crate::backend::agent_state::current_state(&state_store, block_id)),
138            Box::new(move |block_id| {
139                crate::backend::agent_line::sharing_on(&config.get_full_config().settings)
140                    .then(|| crate::backend::agent_line::agent_line_of_block(&line_store, block_id))
141                    .flatten()
142            }),
143            crate::backend::agent_state::global_tracker(),
144            Box::new(|| {
145                crate::registry::resolve_shared_reactive_dir()
146                    .map(|dir| crate::backend::reactive::registry::list_all_shared(&dir))
147                    .unwrap_or_default()
148            }),
149            crate::backend::reactive::registry::local_channel_id(),
150            own_url,
151        )
152    }
153
154    fn new(
155        agents: AgentList,
156        kind_of_block: KindOfBlock,
157        state_of_block: StateOfBlock,
158        line_of_block: LineOfBlock,
159        since: &'static SinceTracker,
160        shared_registry: RegistryRead,
161        own_channel: String,
162        own_url: String,
163    ) -> Self {
164        Self {
165            agents,
166            kind_of_block,
167            state_of_block,
168            line_of_block,
169            since,
170            shared_registry,
171            own_channel,
172            own_url,
173            kinds: parking_lot::Mutex::new(HashMap::new()),
174            channels: parking_lot::Mutex::new(None),
175        }
176    }
177
178    /// One look. Blocking: reads the store and the registry directory.
179    pub fn observe(&self) -> FleetObservation {
180        let listed = (self.agents)();
181        self.since.retain(|block_id| listed.iter().any(|(_, b)| b == block_id));
182        let now_ms = agentmux_common::time::now_ms_u64();
183        let agent_status: BTreeMap<_, _> = listed
184            .iter()
185            .filter_map(|(name, block_id)| {
186                let status = self.since.record(block_id, (self.state_of_block)(block_id), now_ms)?;
187                Some((name.clone(), status))
188            })
189            .collect();
190        // Shadow only (SPEC_AGENT_STATE_BACKGROUND_WORK §9 step 1): which idle agents would read Background.
191        let idle: Vec<(String, String)> =
192            listed.iter().filter(|(name, _)| agent_status.get(name).is_some_and(|s| s.state == AgentState::Idle)).cloned().collect();
193        crate::backend::background_set::shadow_sample(&idle, now_ms);
194        let agent_lines = listed
195            .iter()
196            .filter_map(|(name, block_id)| Some((name.clone(), (self.line_of_block)(block_id)?)))
197            .collect();
198        let agents = {
199            let mut cache = self.kinds.lock();
200            cache.retain(|block_id, _| listed.iter().any(|(_, b)| b == block_id));
201            listed
202                .into_iter()
203                .map(|(name, block_id)| {
204                    let kind = match cache.get(&block_id) {
205                        Some(kind) => Some(*kind),
206                        None => {
207                            let kind = (self.kind_of_block)(&block_id);
208                            if let Some(kind) = kind {
209                                cache.insert(block_id, kind);
210                            }
211                            kind
212                        }
213                    };
214                    (name, kind)
215                })
216                .collect()
217        };
218        FleetObservation {
219            agents,
220            channels_running: self.channels_running(),
221            agent_status,
222            agent_lines,
223        }
224    }
225
226    fn channels_running(&self) -> u32 {
227        let mut last = self.channels.lock();
228        if let Some((at, n)) = *last {
229            if at.elapsed() < CHANNELS_REREAD {
230                return n;
231            }
232        }
233        let n = count_channels_running(
234            &(self.shared_registry)(),
235            &self.own_channel,
236            &self.own_url,
237            agentmux_common::time::now_ms_u64(),
238        );
239        *last = Some((Instant::now(), n));
240        LATEST_CHANNELS_RUNNING.store(n, Ordering::Relaxed);
241        n
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248    use std::sync::atomic::AtomicUsize;
249
250    const NOW: u64 = 1_000_000_000;
251
252    fn entry(name: &str, channel: &str, age_ms: u64) -> AgentEntry {
253        AgentEntry {
254            agent_id: name.to_string(),
255            local_url: format!("http://127.0.0.1/{channel}"),
256            block_id: format!("block-{name}"),
257            pid: 1,
258            updated_at: NOW - age_ms,
259            auth_key: String::new(),
260            channel: channel.to_string(),
261            registration_nonce: 0,
262            jekt_public_key: String::new(),
263            uid: String::new(),
264            uid_public_key: String::new(),
265            jekt_features: Vec::new(),
266        }
267    }
268
269    #[test]
270    fn channels_running_counts_this_channel_and_live_others() {
271        assert_eq!(count_channels_running(&[], "stable", "", NOW), 1);
272        let entries = [
273            entry("a", "stable", 0),
274            entry("b", "dev", 0),
275            entry("c", "dev", 0),
276            entry("d", "local-main", 1_000),
277            entry("e", "crashed", crate::backend::swarm_remote::HIDE_AFTER_MS + 1),
278        ];
279        assert_eq!(
280            count_channels_running(&entries, "stable", "", NOW),
281            3,
282            "this one, dev and local-main; not the hidden one"
283        );
284        let many: Vec<_> = (0..150).map(|i| entry("x", &format!("ch-{i}"), 0)).collect();
285        assert_eq!(count_channels_running(&many, "stable", "", NOW), MAX_CHANNELS_RUNNING);
286    }
287
288    #[test]
289    fn kinds_leave_out_unreadable_blocks() {
290        let kinds = kinds_by_name([("AgentX", "b1"), ("Camper", "b2"), ("Ghost", "b3")], |b| match b {
291            "b1" => Some("container"),
292            "b2" => Some("host"),
293            _ => None,
294        });
295        assert_eq!(
296            kinds,
297            BTreeMap::from([("AgentX".to_string(), "container"), ("Camper".to_string(), "host")])
298        );
299    }
300
301    #[test]
302    fn a_block_is_read_once_while_listed_and_an_unreadable_one_is_retried() {
303        let reads = Arc::new(AtomicUsize::new(0));
304        let counted = reads.clone();
305        let ready = Arc::new(std::sync::atomic::AtomicBool::new(false));
306        let ready_read = ready.clone();
307        let source = FleetSource::new(
308            Box::new(|| vec![("AgentX".into(), "b1".into()), ("Late".into(), "b2".into())]),
309            Box::new(move |b| {
310                counted.fetch_add(1, Ordering::SeqCst);
311                match b {
312                    "b1" => Some("container"),
313                    _ if ready_read.load(Ordering::SeqCst) => Some("host"),
314                    _ => None,
315                }
316            }),
317            Box::new(|_| None),
318            Box::new(|_| None),
319            tracker(),
320            Box::new(Vec::new),
321            "stable".into(),
322            String::new(),
323        );
324        let first = source.observe();
325        assert_eq!(
326            first.agents,
327            vec![("AgentX".to_string(), Some("container")), ("Late".to_string(), None)]
328        );
329        assert_eq!(first.channels_running, 1);
330        assert_eq!(reads.load(Ordering::SeqCst), 2);
331        source.observe();
332        assert_eq!(reads.load(Ordering::SeqCst), 3, "b1 cached, b2 retried");
333        ready.store(true, Ordering::SeqCst);
334        assert_eq!(source.observe().agents[1], ("Late".to_string(), Some("host")));
335        source.observe();
336        assert_eq!(reads.load(Ordering::SeqCst), 4, "both cached now");
337    }
338
339    /// A tracker of the test's own, not the live one the names route shares.
340    fn tracker() -> &'static SinceTracker {
341        Box::leak(Box::new(SinceTracker::default()))
342    }
343
344    #[test]
345    fn states_are_read_every_look_and_keep_their_start_while_unchanged() {
346        let states = Arc::new(parking_lot::Mutex::new(HashMap::from([
347            ("b1".to_string(), AgentState::Working),
348            ("b2".to_string(), AgentState::Idle),
349        ])));
350        let read = states.clone();
351        let listed = Arc::new(parking_lot::Mutex::new(vec![
352            ("AgentX".to_string(), "b1".to_string()),
353            ("Camper".to_string(), "b2".to_string()),
354            ("Term".to_string(), "b3".to_string()),
355        ]));
356        let list = listed.clone();
357        let since = tracker();
358        let source = FleetSource::new(
359            Box::new(move || list.lock().clone()),
360            Box::new(|_| Some("host")),
361            Box::new(move |b| read.lock().get(b).copied()),
362            Box::new(|_| None),
363            since,
364            Box::new(Vec::new),
365            "stable".into(),
366            String::new(),
367        );
368        let first = source.observe().agent_status;
369        assert_eq!(
370            first.keys().collect::<Vec<_>>(),
371            ["AgentX", "Camper"],
372            "the agent with no state is left out"
373        );
374        assert_eq!(first["AgentX"].state, AgentState::Working);
375
376        std::thread::sleep(Duration::from_millis(5));
377        let second = source.observe().agent_status;
378        assert_eq!(second, first, "nothing changed, the starts held");
379
380        states.lock().insert("b1".into(), AgentState::Idle);
381        let third = source.observe().agent_status;
382        assert_eq!(third["AgentX"].state, AgentState::Idle);
383        assert!(third["AgentX"].since_ms > first["AgentX"].since_ms, "a change starts again");
384        assert_eq!(third["Camper"], first["Camper"]);
385
386        listed.lock().remove(0);
387        source.observe();
388        assert_eq!(since.len(), 1, "an agent no longer listed is forgotten");
389    }
390}