agentmux_srv/server/remote_ops/
audit_ops.rs1use std::collections::HashSet;
13use std::sync::{LazyLock, Mutex};
14use std::time::{Duration, Instant};
15
16use serde_json::Value;
17
18use super::op::{OpStatus, RemoteOpResult};
19use super::{AppState, RemoteCaller, RemoteRefusal, RemoteResult};
20use crate::backend::audit_query::peers::{self, QUERY_OP, SETTING_AUDIT_SHARE};
21use crate::backend::lan::discovery::LanInstance;
22use crate::backend::rpc_types::{AuditPeerRows, AuditQueryReq, AuditQueryResult};
23
24const ASK_FOR: Duration = Duration::from_secs(4);
26const REASON: &str = "list its Audit";
27const REUSE_FOR: Duration = Duration::from_secs(5);
30
31type LastAsked = Option<(String, Instant, Vec<AuditPeerRows>)>;
33static LAST_ASKED: LazyLock<Mutex<LastAsked>> = LazyLock::new(Default::default);
34
35fn shares(state: &AppState) -> bool {
36 state.config_watcher.get_settings().extra.get(SETTING_AUDIT_SHARE).and_then(Value::as_bool).unwrap_or(false)
37}
38
39pub(super) async fn query(state: &AppState, _caller: &RemoteCaller, params: Value) -> RemoteResult {
41 if !shares(state) {
42 return Err(RemoteRefusal::new("not_shared", format!("this computer does not share its Audit with paired computers ({SETTING_AUDIT_SHARE})")));
43 }
44 let asked: AuditQueryReq = serde_json::from_value(params).map_err(|e| RemoteRefusal::failed(format!("audit.query: {e}")))?;
45 let req = peers::request_for_peer(&asked);
46 let mut page = crate::server::app_api::audit_query::machine_page(state, &req).await.map_err(RemoteRefusal::failed)?;
47 peers::without_local_links(&mut page.entries);
48 for channel in page.other_channels.iter_mut().flatten() {
49 peers::without_local_links(&mut channel.entries);
50 }
51 serde_json::to_value(&page).map_err(|e| RemoteRefusal::failed(format!("audit.query: {e}")))
52}
53
54fn lan_hosts(instances: &[LanInstance]) -> Vec<(String, String)> {
59 let mut seen = HashSet::new();
60 let mut out = Vec::new();
61 for p in instances {
62 let name = p.hostname.trim();
63 if name.is_empty() || !seen.insert(name.to_ascii_lowercase()) {
64 continue;
65 }
66 let same_name: Vec<&LanInstance> = instances.iter().filter(|q| q.hostname.trim().eq_ignore_ascii_case(name)).collect();
67 let same_channel = same_name.iter().filter(|q| q.channel.eq_ignore_ascii_case(&p.channel)).count();
68 let host = match (same_name.len(), same_channel) {
69 (1, _) => name.to_string(),
70 (_, 1) => format!("{name}/{}", p.channel),
71 _ => format!("{name}/{}/{}", p.channel, p.install),
72 };
73 out.push((name.to_string(), host));
74 }
75 out
76}
77
78fn rows_from(name: &str, answer: RemoteOpResult) -> AuditPeerRows {
80 if answer.status != OpStatus::Done {
81 let error = answer.result.get("error").and_then(Value::as_str);
82 return peers::no_rows(name, &peers::note_for(answer.refused_reason.as_deref(), error));
83 }
84 match serde_json::from_value::<AuditQueryResult>(answer.result) {
85 Ok(page) => peers::rows_of(name, page),
86 Err(e) => peers::no_rows(name, &format!("its answer was not understood: {e}")),
87 }
88}
89
90pub(crate) async fn ask_peers(state: &AppState, req: &AuditQueryReq) -> Vec<AuditPeerRows> {
93 if !super::enabled(state) {
94 return Vec::new();
95 }
96 let Some(slug) = super::fleet_sync::signer(state) else { return Vec::new() };
97 let params = serde_json::to_value(peers::request_for_peer(req)).unwrap_or(Value::Null);
98 let hosts = lan_hosts(&state.lan_discovery.get_instances());
99 let key = format!("{params}|{slug}|{}", hosts.iter().map(|(_, host)| host.as_str()).collect::<Vec<_>>().join(","));
101 if let Some((asked, at, rows)) = LAST_ASKED.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
102 if *asked == key && at.elapsed() < REUSE_FOR {
103 return rows.clone();
104 }
105 }
106 let rows = futures_util::future::join_all(hosts.into_iter().map(|(name, host)| {
107 let (slug, params) = (slug.clone(), params.clone());
108 async move {
109 match tokio::time::timeout(ASK_FOR, super::send::call(state, &slug, &host, QUERY_OP, params, REASON)).await {
110 Ok(answer) => rows_from(&name, answer),
111 Err(_) => peers::no_rows(&name, "it did not answer in time"),
112 }
113 }
114 }))
115 .await;
116 *LAST_ASKED.lock().unwrap_or_else(|e| e.into_inner()) = Some((key, Instant::now(), rows.clone()));
117 rows
118}
119
120#[cfg(test)]
121#[path = "audit_ops_tests.rs"]
122mod tests;