Skip to main content

agentmux_srv_core/muxbus/
cloud_installs.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The account's other installs, read back from the relay for the Swarm's cloud tier
5//! (`docs/specs/SPEC_SWARM_CLOUD_TIER_2026_11_14.md`): the presence records `wan_presence` publishes, listed by
6//! the relay for the signed-in account.
7//!
8//! A record is display data. Each one is verified before it is used (the install's own signature, its id against
9//! its key, the bounds), so the relay's list is trusted for availability and not for correctness; nothing acts on
10//! one. The read is on demand, behind a 30-second cache: nothing runs while nobody asks. Signed out, a relay
11//! without the route, a refusal or a network error each leave no cloud tier and no error in an answer; after a
12//! network error the last good list is kept for ten minutes, ageing as time goes.
13
14use std::future::Future;
15use std::sync::{Arc, Mutex, OnceLock};
16use std::time::Duration;
17
18use tokio::sync::watch;
19
20use super::install_presence::{text_in_bounds, InstallPresence, MAX_PRESENCE_NAME_CHARS, MAX_PRESENCE_VERSION_CHARS, PRESENCE_VERSION_LINES};
21
22/// A read this old is read again on the next ask.
23const FRESH_MS: u64 = 30_000;
24/// How long the last good list is kept while the relay cannot be read.
25const KEEP_LAST_GOOD_MS: u64 = 10 * 60_000;
26/// How long an ask waits for a read before it answers from the cache.
27const READ_BUDGET: Duration = Duration::from_millis(1_500);
28/// The relay answers at most this many records, and a body past this size is not read.
29const MAX_RECORDS: usize = 500;
30const MAX_BODY_BYTES: usize = 8 * 1024 * 1024;
31
32/// One verified record of another install, with when the relay heard from it on this machine's clock.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct CloudInstall {
35    pub record: InstallPresence,
36    pub seen_at_ms: u64,
37}
38
39/// A record of a version this build cannot read (a newer AgentMux published it), as far as it can be told: only the fields a
40/// plain reading of it gives, none of them verified, since its signature covers material this build cannot rebuild. It is
41/// shown as a computer that needs a newer AgentMux, never as one with agents, and never used for anything else.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct NewerInstall {
44    pub instance_id: String,
45    pub hostname: String,
46    pub channel: String,
47    pub os: String,
48    /// The AgentMux version the record says it was made by; empty when it does not say, or says something that is not a version.
49    pub app_version: String,
50    /// The record's own format version.
51    pub record_version: u64,
52    pub seen_at_ms: u64,
53}
54
55/// How the last read went.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum CloudState {
58    /// Signed out, or the relay has no such list.
59    Off,
60    Ok,
61    /// The last read failed: the list is the one kept, or empty.
62    Unavailable,
63}
64
65impl CloudState {
66    pub fn label(self) -> &'static str {
67        match self {
68            Self::Off => "off",
69            Self::Ok => "ok",
70            Self::Unavailable => "unavailable",
71        }
72    }
73}
74
75/// What the Swarm reads.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct CloudView {
78    pub installs: Vec<CloudInstall>,
79    /// Computers whose records this build cannot read because they are newer: shown as needing a newer AgentMux.
80    pub newer: Vec<NewerInstall>,
81    pub state: CloudState,
82}
83
84/// What one read of the relay came to.
85#[derive(Debug)]
86pub enum Fetched {
87    /// No sign-in, or the relay refused it.
88    SignedOut,
89    /// The relay does not have the list (an older relay).
90    NoRoute,
91    /// Unreachable, a server error or an answer that is not the list.
92    Failed,
93    /// The records as the relay sent them, and the relay's clock.
94    Records { raw: Vec<serde_json::Value>, relay_now_ms: Option<u64> },
95}
96
97/// Where the list is read from.
98pub trait Source: Send + Sync + 'static {
99    fn fetch(&self) -> impl Future<Output = Fetched> + Send;
100}
101
102/// The records that verify, with their ages moved onto this machine's clock. A record the relay heard from
103/// `age` ago was seen `age` before `local_now_ms`, whatever this clock says about the relay's: so a wrong local
104/// clock does not make a live machine stale. A goodbye is left out.
105pub fn verified(raw: Vec<serde_json::Value>, relay_now_ms: Option<u64>, local_now_ms: u64) -> Vec<CloudInstall> {
106    split(raw, relay_now_ms, local_now_ms).0
107}
108
109/// A plain-text field of a record this build cannot verify: kept only when it is the bounded, control-free text a verified
110/// record's field must be.
111fn plain(value: &serde_json::Value, key: &str, max_chars: usize) -> Option<String> {
112    value.get(key).and_then(serde_json::Value::as_str).filter(|s| text_in_bounds(s, max_chars)).map(str::to_string)
113}
114
115/// A record of a format newer than this build reads, seen as far as can be told, or `None` when it is not one (a record of a
116/// known version that did not verify is damaged or forged and is left out). The line it logs names the format and the computer.
117fn newer_install(value: &serde_json::Value, received_at_ms: u64, seen_at_ms: u64) -> Option<NewerInstall> {
118    let record_version = value.get("v").and_then(serde_json::Value::as_u64).filter(|v| *v > u64::from(PRESENCE_VERSION_LINES))?;
119    let instance_id = plain(value, "instance_id", 64).filter(|id| id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'))?;
120    let hostname = plain(value, "hostname", MAX_PRESENCE_NAME_CHARS)?;
121    let channel = plain(value, "channel", MAX_PRESENCE_NAME_CHARS).unwrap_or_default();
122    let os = plain(value, "os", 16).filter(|os| os.chars().all(|c| c.is_ascii_lowercase())).unwrap_or_default();
123    let app_version = plain(value, "version", MAX_PRESENCE_VERSION_CHARS)
124        .filter(|v| v.starts_with(|c: char| c.is_ascii_digit()) && v.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+')))
125        .unwrap_or_default();
126    let _ = received_at_ms;
127    static TOLD: OnceLock<Mutex<std::collections::HashSet<(String, u64)>>> = OnceLock::new();
128    let mut told = TOLD.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
129    if told.len() >= 64 {
130        told.clear();
131    }
132    if told.insert((instance_id.clone(), record_version)) {
133        tracing::warn!(computer = %hostname, channel = %channel, record_version, agentmux = %app_version, "cloud installs: a record of a format this AgentMux does not read (made by a newer one): shown as needing a newer AgentMux, not used");
134    }
135    Some(NewerInstall { instance_id, hostname, channel, os, app_version, record_version, seen_at_ms })
136}
137
138/// [`verified`], and the records that are of a newer format than this build reads, each as far as can be told.
139pub fn split(raw: Vec<serde_json::Value>, relay_now_ms: Option<u64>, local_now_ms: u64) -> (Vec<CloudInstall>, Vec<NewerInstall>) {
140    let mut dropped = 0usize;
141    let mut out: Vec<CloudInstall> = Vec::new();
142    let mut newer: Vec<NewerInstall> = Vec::new();
143    for value in raw.into_iter().take(MAX_RECORDS) {
144        let received = value.get("received_at_ms").and_then(serde_json::Value::as_u64);
145        let seen = |received: u64| match relay_now_ms {
146            Some(relay_now) => local_now_ms.saturating_sub(relay_now.saturating_sub(received)),
147            None => received,
148        };
149        let record = serde_json::from_value::<InstallPresence>(value.clone()).ok().filter(InstallPresence::verify);
150        let (Some(record), Some(received)) = (record, received) else {
151            match received.and_then(|r| newer_install(&value, r, seen(r))) {
152                Some(n) if !newer.iter().any(|k| k.instance_id == n.instance_id && k.seen_at_ms >= n.seen_at_ms) => {
153                    newer.retain(|k| k.instance_id != n.instance_id);
154                    newer.push(n);
155                }
156                Some(_) => {}
157                None => dropped += 1,
158            }
159            continue;
160        };
161        if record.gone {
162            continue;
163        }
164        let seen_at_ms = match relay_now_ms {
165            Some(relay_now) => local_now_ms.saturating_sub(relay_now.saturating_sub(received)),
166            None => received,
167        };
168        match out.iter_mut().find(|c| c.record.instance_id == record.instance_id) {
169            Some(known) if known.seen_at_ms >= seen_at_ms => {}
170            Some(known) => *known = CloudInstall { record, seen_at_ms },
171            None => out.push(CloudInstall { record, seen_at_ms }),
172        }
173    }
174    if dropped > 0 {
175        tracing::warn!(dropped, "cloud installs: records that did not verify were left out");
176    }
177    (out, newer)
178}
179
180struct Cache {
181    view: CloudView,
182    /// When the cache was last filled, on this machine's clock; `None` before the first read and after
183    /// [`Reader::invalidate`].
184    read_at_ms: Option<u64>,
185    /// When the list last came from a read that worked.
186    good_at_ms: Option<u64>,
187    /// Counts [`Reader::invalidate`]s: a read that began before one is not let into the cache.
188    generation: u64,
189    /// The read in flight, if any: dropped (so a waiter wakes) when it ends.
190    reading: Option<watch::Receiver<()>>,
191}
192
193fn off() -> CloudView {
194    CloudView { installs: Vec::new(), newer: Vec::new(), state: CloudState::Off }
195}
196
197/// Ends a read's claim on the cache when the read ends, however it ends.
198struct Claim<S: Source> {
199    reader: Arc<Reader<S>>,
200    generation: u64,
201}
202
203impl<S: Source> Drop for Claim<S> {
204    fn drop(&mut self) {
205        let mut cache = self.reader.cache();
206        if cache.generation == self.generation {
207            cache.reading = None;
208        }
209    }
210}
211
212/// The cache and the one read at a time.
213pub struct Reader<S: Source> {
214    source: S,
215    cache: Mutex<Cache>,
216}
217
218impl<S: Source> Reader<S> {
219    pub fn new(source: S) -> Arc<Self> {
220        let cache = Cache { view: off(), read_at_ms: None, good_at_ms: None, generation: 0, reading: None };
221        Arc::new(Self { source, cache: Mutex::new(cache) })
222    }
223
224    fn cache(&self) -> std::sync::MutexGuard<'_, Cache> {
225        self.cache.lock().unwrap_or_else(|e| e.into_inner())
226    }
227
228    /// The list as of `now_ms`: the cache when it is fresh; else one read is started (never a second while
229    /// one runs), which goes on in the background however long it takes, and this ask waits for it at most
230    /// [`READ_BUDGET`] before it answers from the cache as it is.
231    pub async fn view(self: &Arc<Self>, now_ms: u64) -> CloudView {
232        let mut reading = {
233            let mut cache = self.cache();
234            if Self::is_fresh(&cache, now_ms) {
235                return cache.view.clone();
236            }
237            self.reading_of(&mut cache, now_ms)
238        };
239        // Ends when the read does (its sender is dropped); a timeout leaves the read running.
240        let _ = tokio::time::timeout(READ_BUDGET, reading.changed()).await;
241        self.cache().view.clone()
242    }
243
244    /// The cache as it is, without waiting: when it is not fresh a read is started to fill it for the next ask.
245    pub fn cached(self: &Arc<Self>, now_ms: u64) -> CloudView {
246        let mut cache = self.cache();
247        if !Self::is_fresh(&cache, now_ms) {
248            let _ = self.reading_of(&mut cache, now_ms);
249        }
250        cache.view.clone()
251    }
252
253    fn is_fresh(cache: &Cache, now_ms: u64) -> bool {
254        cache.read_at_ms.is_some_and(|at| now_ms.saturating_sub(at) < FRESH_MS)
255    }
256
257    /// The read in flight, or a new one.
258    fn reading_of(self: &Arc<Self>, cache: &mut Cache, now_ms: u64) -> watch::Receiver<()> {
259        if let Some(reading) = &cache.reading {
260            return reading.clone();
261        }
262        let (done, reading) = watch::channel(());
263        cache.reading = Some(reading.clone());
264        let generation = cache.generation;
265        let reader = Arc::clone(self);
266        tokio::spawn(async move {
267            // Dropped last: the claim goes first, then the waiters wake.
268            let _done = done;
269            let _claim = Claim { reader: Arc::clone(&reader), generation };
270            let fetched = reader.source.fetch().await;
271            reader.absorb(fetched, now_ms, generation);
272        });
273        reading
274    }
275
276    /// A sign-in changed: what was read for the old one is dropped, a read still out for it is not let in, and
277    /// the next ask reads again.
278    pub fn invalidate(&self) {
279        let mut cache = self.cache();
280        cache.generation += 1;
281        cache.view = off();
282        cache.read_at_ms = None;
283        cache.good_at_ms = None;
284        cache.reading = None;
285    }
286
287    fn absorb(&self, fetched: Fetched, now_ms: u64, generation: u64) {
288        let mut cache = self.cache();
289        if cache.generation != generation {
290            return;
291        }
292        cache.read_at_ms = Some(now_ms);
293        cache.view = match fetched {
294            Fetched::SignedOut | Fetched::NoRoute => off(),
295            Fetched::Records { raw, relay_now_ms } => {
296                cache.good_at_ms = Some(now_ms);
297                let (installs, newer) = split(raw, relay_now_ms, now_ms);
298                CloudView { installs, newer, state: CloudState::Ok }
299            }
300            Fetched::Failed => {
301                let kept = cache.good_at_ms.is_some_and(|at| now_ms.saturating_sub(at) < KEEP_LAST_GOOD_MS);
302                let installs = if kept { std::mem::take(&mut cache.view.installs) } else { Vec::new() };
303                let newer = if kept { std::mem::take(&mut cache.view.newer) } else { Vec::new() };
304                CloudView { installs, newer, state: CloudState::Unavailable }
305            }
306        };
307    }
308}
309
310/// The relay's list, with the MuxBus sign-in's token.
311pub struct RelaySource {
312    id_store: Arc<crate::backend::storage::store::Store>,
313    http: reqwest::Client,
314}
315
316impl Source for RelaySource {
317    async fn fetch(&self) -> Fetched {
318        let Some(scheduler) = crate::broker::get_global() else { return Fetched::SignedOut };
319        if scheduler.state(crate::muxbus::CREDENTIAL_ID).is_none() {
320            return Fetched::SignedOut;
321        }
322        let Some(token) = crate::muxbus::cloud_subscriber::load_valid_token(&self.id_store, &scheduler).await else {
323            return Fetched::SignedOut;
324        };
325        let url = format!("{}/wan-instances", crate::muxbus::relay::rest_base_url().trim_end_matches('/'));
326        let Ok(reply) = self.http.get(url).header("Authorization", format!("Bearer {token}")).timeout(Duration::from_secs(5)).send().await else {
327            return Fetched::Failed;
328        };
329        match reply.status().as_u16() {
330            404 => return Fetched::NoRoute,
331            401 | 403 => return Fetched::SignedOut,
332            200..=299 => {}
333            _ => return Fetched::Failed,
334        }
335        let relay_now_ms = reply.headers().get(reqwest::header::DATE).and_then(|v| v.to_str().ok()).and_then(super::wan_presence::parse_http_date);
336        if reply.content_length().is_some_and(|n| n > MAX_BODY_BYTES as u64) {
337            return Fetched::Failed;
338        }
339        let Ok(body) = reply.bytes().await else { return Fetched::Failed };
340        if body.len() > MAX_BODY_BYTES {
341            return Fetched::Failed;
342        }
343        match serde_json::from_slice::<serde_json::Value>(&body).ok().and_then(|v| match v.get("instances") {
344            Some(serde_json::Value::Array(list)) => Some(list.clone()),
345            _ => None,
346        }) {
347            Some(raw) => Fetched::Records { raw, relay_now_ms },
348            None => Fetched::Failed,
349        }
350    }
351}
352
353static READER: OnceLock<Arc<Reader<RelaySource>>> = OnceLock::new();
354
355/// Start reading with this srv's sign-in. The first call wins.
356pub fn install(id_store: Arc<crate::backend::storage::store::Store>, http: reqwest::Client) {
357    let _ = READER.set(Reader::new(RelaySource { id_store, http }));
358}
359
360/// The account's other installs now, or `None` before [`install`] (a build with no sign-in to read with).
361pub async fn view() -> Option<CloudView> {
362    Some(READER.get()?.view(agentmux_common::time::now_ms_u64()).await)
363}
364
365/// The account's other installs as they are cached, at once; a read to fill the cache is started when it is old.
366/// `None` before [`install`].
367pub fn cached() -> Option<CloudView> {
368    Some(READER.get()?.cached(agentmux_common::time::now_ms_u64()))
369}
370
371/// A sign-in or sign-out happened: the old list is dropped and the next ask reads again.
372pub fn invalidate() {
373    if let Some(reader) = READER.get() {
374        reader.invalidate();
375    }
376}
377
378#[cfg(test)]
379mod tests;