agentmux_srv_core/muxbus/
cloud_installs.rs1use 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
22const FRESH_MS: u64 = 30_000;
24const KEEP_LAST_GOOD_MS: u64 = 10 * 60_000;
26const READ_BUDGET: Duration = Duration::from_millis(1_500);
28const MAX_RECORDS: usize = 500;
30const MAX_BODY_BYTES: usize = 8 * 1024 * 1024;
31
32#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct CloudInstall {
35 pub record: InstallPresence,
36 pub seen_at_ms: u64,
37}
38
39#[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 pub app_version: String,
50 pub record_version: u64,
52 pub seen_at_ms: u64,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum CloudState {
58 Off,
60 Ok,
61 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#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct CloudView {
78 pub installs: Vec<CloudInstall>,
79 pub newer: Vec<NewerInstall>,
81 pub state: CloudState,
82}
83
84#[derive(Debug)]
86pub enum Fetched {
87 SignedOut,
89 NoRoute,
91 Failed,
93 Records { raw: Vec<serde_json::Value>, relay_now_ms: Option<u64> },
95}
96
97pub trait Source: Send + Sync + 'static {
99 fn fetch(&self) -> impl Future<Output = Fetched> + Send;
100}
101
102pub 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
109fn 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
115fn 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
138pub 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 read_at_ms: Option<u64>,
185 good_at_ms: Option<u64>,
187 generation: u64,
189 reading: Option<watch::Receiver<()>>,
191}
192
193fn off() -> CloudView {
194 CloudView { installs: Vec::new(), newer: Vec::new(), state: CloudState::Off }
195}
196
197struct 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
212pub 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 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 let _ = tokio::time::timeout(READ_BUDGET, reading.changed()).await;
241 self.cache().view.clone()
242 }
243
244 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 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 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 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
310pub 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
355pub 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
360pub async fn view() -> Option<CloudView> {
362 Some(READER.get()?.view(agentmux_common::time::now_ms_u64()).await)
363}
364
365pub fn cached() -> Option<CloudView> {
368 Some(READER.get()?.cached(agentmux_common::time::now_ms_u64()))
369}
370
371pub fn invalidate() {
373 if let Some(reader) = READER.get() {
374 reader.invalidate();
375 }
376}
377
378#[cfg(test)]
379mod tests;