1use std::collections::HashMap;
18use std::sync::Arc;
19use std::time::{Duration, Instant};
20
21use std::future::Future;
22
23use serde_json::{json, Value};
24
25use crate::server::remote_ops::op::{OpStatus, RemoteOpResult};
26
27use super::{enabled, send};
28use crate::backend::memory::fleet::{self, FleetMeta, Push};
29use crate::backend::storage::store::Store;
30use crate::server::AppState;
31
32const TICK: Duration = Duration::from_secs(15);
34const RESYNC: Duration = Duration::from_secs(10 * 60);
36const RETRY: Duration = Duration::from_secs(5 * 60);
38const REASON: &str = "fleet Global Memory sync";
39const SIGNING_SLACK: usize = 256;
41
42#[derive(Debug, Clone, PartialEq, Eq)]
44pub(super) struct Peer {
45 pub key: String,
46 pub host: String,
47}
48
49#[derive(Debug, Clone)]
51pub(super) struct Synced {
52 fingerprint: String,
53 at: Instant,
54 retry_at: Option<Instant>,
56}
57
58pub(crate) fn install(state: AppState) {
60 tokio::spawn(async move {
61 let mut seen: HashMap<String, Synced> = HashMap::new();
62 let mut tick = tokio::time::interval(TICK);
63 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
64 loop {
65 tick.tick().await;
66 if enabled(&state) {
67 sync_once(&state, &mut seen).await;
68 }
69 }
70 });
71}
72
73fn peers(state: &AppState) -> Vec<Peer> {
74 state
75 .lan_discovery
76 .get_instances()
77 .into_iter()
78 .map(|p| {
79 let name = p.hostname.trim().to_string();
80 let key = peer_key(&p.install_id, &name, &p.channel, &p.address, p.port);
81 let host = if p.channel.is_empty() { name } else { format!("{name}/{}", p.channel) };
82 Peer { key, host }
83 })
84 .collect()
85}
86
87fn peer_key(install_id: &str, hostname: &str, channel: &str, address: &str, port: u16) -> String {
93 if install_id.is_empty() {
94 format!("{hostname}/{channel}@{address}:{port}")
95 } else {
96 format!("{install_id}/{channel}")
97 }
98}
99
100pub(crate) fn signer(state: &AppState) -> Option<String> {
102 state.fleet_feed.snapshot().agents.iter().find(|a| !a.trim().is_empty()).cloned()
103}
104
105async fn sync_once(state: &AppState, seen: &mut HashMap<String, Synced>) {
106 let peers = peers(state);
107 if peers.is_empty() {
108 seen.clear();
109 return;
110 }
111 let Some(slug) = signer(state) else { return };
112 let call = |host: String, op: &'static str, params: Value| {
113 let slug = slug.clone();
114 async move { send::call(state, &slug, &host, op, params, REASON).await }
115 };
116 sync_peers(state.id_store.clone(), &peers, seen, &call, Instant::now()).await;
117}
118
119pub(super) async fn sync_peers<F, Fut>(store: Arc<Store>, peers: &[Peer], seen: &mut HashMap<String, Synced>, call: &F, now: Instant)
121where
122 F: Fn(String, &'static str, Value) -> Fut,
123 Fut: Future<Output = RemoteOpResult>,
124{
125 sync_peers_with(store, peers, seen, call, now, status::global()).await;
126}
127
128pub(super) async fn sync_peers_with<F, Fut>(
130 store: Arc<Store>,
131 peers: &[Peer],
132 seen: &mut HashMap<String, Synced>,
133 call: &F,
134 now: Instant,
135 report: &status::Status,
136) where
137 F: Fn(String, &'static str, Value) -> Fut,
138 Fut: Future<Output = RemoteOpResult>,
139{
140 seen.retain(|key, _| peers.iter().any(|p| &p.key == key));
142 report.keep_only(&peers.iter().map(|p| p.host.as_str()).collect::<Vec<_>>());
143 let local = match blocking(store.clone(), fleet::list_meta).await {
144 Ok(local) => local,
145 Err(e) => {
146 tracing::warn!(error = %e, "fleet memory sync: could not read what this machine holds");
147 return;
148 }
149 };
150 let fingerprint = fleet::fingerprint(&local);
151 for peer in peers {
152 let due = match seen.get(&peer.key) {
153 None => true,
154 Some(s) => match s.retry_at {
155 Some(at) => now >= at,
156 None => s.fingerprint != fingerprint || now.duration_since(s.at) >= RESYNC,
157 },
158 };
159 if !due {
160 continue;
161 }
162 match sync_peer(&store, peer, &local, call).await {
163 Ok((sent, not_applied)) => {
164 if sent > 0 {
165 tracing::info!(peer = %peer.host, sent, "fleet memory: sent entries to another machine");
166 }
167 for (id, why) in report.synced(&peer.host, agentmux_common::time::now_ms(), sent, not_applied) {
168 tracing::warn!(peer = %peer.host, entry = %id, why, "fleet memory: the other machine did not apply an entry");
169 }
170 seen.insert(peer.key.clone(), Synced { fingerprint: fingerprint.clone(), at: now, retry_at: None });
171 }
172 Err(why) => {
173 tracing::debug!(peer = %peer.host, why, "fleet memory sync: left for later");
174 report.failed(&peer.host, &why);
175 seen.insert(peer.key.clone(), Synced { fingerprint: String::new(), at: now, retry_at: Some(now + RETRY) });
176 }
177 }
178 }
179}
180
181async fn blocking<T: Send + 'static>(
182 store: Arc<Store>,
183 f: impl FnOnce(&Store) -> Result<T, crate::backend::storage::error::StoreError> + Send + 'static,
184) -> Result<T, String> {
185 tokio::task::spawn_blocking(move || f(&store))
186 .await
187 .map_err(|e| e.to_string())?
188 .map_err(|e| e.to_string())
189}
190
191fn why_not(answer: &RemoteOpResult) -> String {
192 answer
193 .refused_reason
194 .clone()
195 .or_else(|| answer.result.get("error").and_then(Value::as_str).map(str::to_string))
196 .unwrap_or_else(|| format!("{:?}", answer.status))
197}
198
199enum Answered {
204 Applied,
205 Skipped(String),
206 Nothing,
207}
208
209fn answered(result: &Value) -> Answered {
210 match result.get("outcome").and_then(Value::as_str) {
211 Some("skipped") => match result.get("reason").and_then(Value::as_str).unwrap_or("not_applied") {
212 "same" | "older" | "already_removed" | "unknown" => Answered::Nothing,
213 why => Answered::Skipped(why.to_string()),
214 },
215 _ => Answered::Applied,
217 }
218}
219
220async fn sync_peer<F, Fut>(
225 store: &Arc<Store>,
226 peer: &Peer,
227 local: &[FleetMeta],
228 call: &F,
229) -> Result<(usize, std::collections::BTreeMap<String, String>), String>
230where
231 F: Fn(String, &'static str, Value) -> Fut,
232 Fut: Future<Output = RemoteOpResult>,
233{
234 let answer = call(peer.host.clone(), "memory.global.list", json!({})).await;
235 if answer.status != OpStatus::Done {
236 return Err(format!("list: {}", why_not(&answer)));
237 }
238 let remote: Vec<FleetMeta> =
239 serde_json::from_value(answer.result.get("entries").cloned().unwrap_or(Value::Null)).map_err(|e| format!("list: not understood: {e}"))?;
240 let mut sent = 0;
241 let mut not_applied = std::collections::BTreeMap::new();
242 for push in fleet::to_push(local, &remote) {
243 let entry_id = match &push {
244 Push::Put { id } | Push::Remove { id, .. } => id.clone(),
245 };
246 let (op, params) = match push {
247 Push::Put { id } => match blocking(store.clone(), move |s| fleet::entry_for_push(s, &id)).await? {
248 Some(entry) => ("memory.global.put", serde_json::to_value(entry).map_err(|e| e.to_string())?),
249 None => continue,
251 },
252 Push::Remove { id, removed_at } => {
253 let removal = blocking(store.clone(), move |s| fleet::removal_for_push(s, &id, removed_at)).await?;
254 ("memory.global.remove", serde_json::to_value(removal).map_err(|e| e.to_string())?)
255 }
256 };
257 if params.to_string().len() + SIGNING_SLACK > super::max_params_of(op) {
260 tracing::warn!(peer = %peer.host, op, bytes = params.to_string().len(), "fleet memory: an entry is too big to send; skipped");
261 not_applied.insert(entry_id, "too_big".to_string());
262 continue;
263 }
264 let answer = call(peer.host.clone(), op, params).await;
265 match answer.status {
266 OpStatus::Done => match answered(&answer.result) {
267 Answered::Applied => sent += 1,
268 Answered::Skipped(why) => {
269 not_applied.insert(entry_id, why);
270 }
271 Answered::Nothing => {}
272 },
273 OpStatus::Refused if matches!(answer.refused_reason.as_deref(), Some("bad_params")) => {
275 tracing::warn!(peer = %peer.host, op, "fleet memory: the other machine refused an entry as malformed");
276 not_applied.insert(entry_id, "bad_params".to_string());
277 }
278 OpStatus::Failed if !answer.audit_id.is_empty() => {
282 let why = why_not(&answer);
283 tracing::warn!(peer = %peer.host, op, entry = %entry_id, why, "fleet memory: the other machine failed on an entry");
284 not_applied.insert(entry_id, format!("failed: {}", why.chars().take(120).collect::<String>()));
285 }
286 _ => return Err(format!("{op}: {}", why_not(&answer))),
287 }
288 }
289 Ok((sent, not_applied))
290}
291
292pub(crate) mod status;
293
294#[cfg(test)]
295mod tests;