Skip to main content

agentmux_srv/server/remote_ops/
sync_loop.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The sync layer's loop on the LAN (SPEC_USER_DATA_SYNC_LAYER ยง4.2): the sending half of the `sync.*` ops. Every few
5//! seconds (or at once when something calls [`wake`]) this machine looks at the collections it is a member of and, for
6//! each other member it can see on the LAN, runs one round (`backend::user_sync::round`) when something changed here
7//! since the last round with it, when it has not been synced for a while (to heal a lost push), or when it was never
8//! synced. A peer that is offline, unproven or without the ops is left alone until a retry time. Nothing is sent when
9//! nothing changed, so the audit trails carry only real work.
10//!
11//! Only an install that holds the computer's sync lock plans anything, and a round lends the store to the sync layer
12//! one step at a time (never across a call to the peer), so this machine keeps answering the peer's own requests
13//! while its round is running.
14
15use std::collections::HashMap;
16use std::sync::Arc;
17use std::time::{Duration, Instant};
18
19use serde::de::DeserializeOwned;
20use serde_json::{json, Value};
21use tokio::runtime::Handle;
22
23use super::op::{OpStatus, RemoteOpResult};
24use super::sync_ops::{self, HelloAns};
25use super::{enabled, fleet_sync, send};
26use crate::backend::storage::store::Store;
27use crate::backend::storage::wan_identity::{self, WanIdentityStore};
28use crate::backend::user_sync::members::Kind;
29use crate::backend::user_sync::ops::{self, Ctx, Held, KeysAns, KeysReq, MembersAns, MembersReq, PullAns, PullReq, PushAns, PushReq};
30use crate::backend::user_sync::round::{self, CallError, Ended, PeerCalls, Round, Session};
31use crate::backend::user_sync::{chain_store, log};
32use crate::server::AppState;
33
34/// How often this machine checks whether it has something new for its peers.
35const TICK: Duration = Duration::from_secs(15);
36/// A peer is synced again after this long even if nothing here changed, to heal a lost push.
37const RESYNC: Duration = Duration::from_secs(10 * 60);
38/// A peer that failed is left alone this long.
39const RETRY: Duration = Duration::from_secs(5 * 60);
40const REASON: &str = "sync layer";
41
42static WAKE: tokio::sync::Notify = tokio::sync::Notify::const_new();
43
44/// Wakes the loop now: something here changed a collection, so its peers should hear of it within a second instead of
45/// at the next tick.
46#[allow(dead_code)]
47pub(crate) fn wake() {
48    WAKE.notify_one();
49}
50
51/// A collection this machine is a member of, the other machines in it and what this machine holds of it now.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub(super) struct Plan {
54    pub collection: String,
55    pub kind: String,
56    pub members: Vec<String>,
57    /// Changes whenever this machine's chain or records of the collection do.
58    pub fingerprint: String,
59}
60
61/// A machine seen on the LAN: the install id it advertises (what a chain names it by) and the `host` a send takes.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub(super) struct Seen {
64    pub install_id: String,
65    pub host: String,
66}
67
68/// One round to run: a collection with one of its members that is reachable now.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub(super) struct Target {
71    pub collection: String,
72    pub kind: String,
73    pub machine: String,
74    pub host: String,
75    pub fingerprint: String,
76}
77
78/// What the last round with one peer left behind.
79#[derive(Debug, Clone)]
80pub(super) struct Last {
81    fingerprint: String,
82    at: Instant,
83    /// Set after a round that did not finish: the peer is skipped until then.
84    retry_at: Option<Instant>,
85}
86
87/// Start the loop. Does nothing while remote operations are off.
88pub(crate) fn install(state: AppState) {
89    tokio::spawn(async move {
90        let mut last: HashMap<(String, String), Last> = HashMap::new();
91        let mut tick = tokio::time::interval(TICK);
92        tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
93        loop {
94            tokio::select! {
95                _ = tick.tick() => {}
96                _ = WAKE.notified() => {}
97            }
98            if enabled(&state) {
99                sync_once(&state, &mut last).await;
100            }
101        }
102    });
103}
104
105/// The collections to sync, read from this machine's state under the lock: none unless this install holds it.
106fn plans(store: &Store, wan: &WanIdentityStore) -> Result<Vec<Plan>, String> {
107    // An install with no collection never asks for the computer's sync lock: another install of this computer may be
108    // the one that holds collections, and the lock is theirs to keep.
109    let any = {
110        let conn = store.conn().lock().map_err(|_| "the store is busy".to_string())?;
111        log::init(&conn).map_err(|e| e.to_string())?;
112        !chain_store::load_all(&conn).map_err(|e| format!("{e:?}"))?.is_empty()
113    };
114    if !any {
115        return Ok(Vec::new());
116    }
117    sync_ops::with_ctx(store, wan, None, |ctx: &mut Ctx| {
118        if !ctx.active {
119            return Vec::new();
120        }
121        let mut out = Vec::new();
122        for (collection, chain) in ctx.chains.iter() {
123            let Ok(state) = chain.state(collection) else { continue };
124            if !state.members.get(ctx.me.id).is_some_and(|m| m.kind == Kind::Machine) {
125                continue;
126            }
127            let members: Vec<String> = state.members.values().filter(|m| m.kind == Kind::Machine && m.id != ctx.me.id).map(|m| m.id.clone()).collect();
128            if members.is_empty() {
129                continue;
130            }
131            let (Ok(kind), Ok(vector)) = (ops::kind_of(ctx.conn, collection), log::vector(ctx.conn, collection)) else { continue };
132            let fingerprint = format!("{}:{}:{}:{}", state.n, state.epoch, state.head.clone().unwrap_or_default(), json!(vector));
133            out.push(Plan { collection: collection.clone(), kind, members, fingerprint });
134        }
135        out
136    })
137    .map_err(|e| e.message)
138}
139
140/// The rounds to run: each collection with each of its members that is on the LAN now.
141pub(super) fn targets(plans: &[Plan], seen: &[Seen]) -> Vec<Target> {
142    let mut out = Vec::new();
143    for plan in plans {
144        for member in &plan.members {
145            if let Some(peer) = seen.iter().find(|p| !p.install_id.is_empty() && &p.install_id == member) {
146                out.push(Target { collection: plan.collection.clone(), kind: plan.kind.clone(), machine: member.clone(), host: peer.host.clone(), fingerprint: plan.fingerprint.clone() });
147            }
148        }
149    }
150    out
151}
152
153/// Whether a round with this peer is due: it never ran, or its retry time has come, or what this machine holds changed,
154/// or it has been a while.
155pub(super) fn due(last: Option<&Last>, fingerprint: &str, now: Instant) -> bool {
156    match last {
157        None => true,
158        Some(l) => match l.retry_at {
159            Some(at) => now >= at,
160            None => l.fingerprint != fingerprint || now.duration_since(l.at) >= RESYNC,
161        },
162    }
163}
164
165/// What to remember of a round: a peer that answered is left alone until something changes; one that did not is left
166/// alone for a while. A round that changed what this machine holds is looked at again at the next tick, so what it
167/// took goes on to the other members.
168pub(super) fn remember(round: &Round, fingerprint: &str, now: Instant) -> Last {
169    let finished = matches!(round.ended, Ended::Synced);
170    if finished && !round.changed() {
171        Last { fingerprint: fingerprint.to_string(), at: now, retry_at: None }
172    } else if finished {
173        Last { fingerprint: String::new(), at: now, retry_at: None }
174    } else {
175        Last { fingerprint: String::new(), at: now, retry_at: Some(now + RETRY) }
176    }
177}
178
179fn seen_on_lan(state: &AppState) -> Vec<Seen> {
180    state
181        .lan_discovery
182        .get_instances()
183        .into_iter()
184        .map(|p| {
185            let name = p.hostname.trim().to_string();
186            let host = if p.channel.is_empty() { name } else { format!("{name}/{}", p.channel) };
187            Seen { install_id: p.install_id, host }
188        })
189        .collect()
190}
191
192async fn sync_once(state: &AppState, last: &mut HashMap<(String, String), Last>) {
193    let Some(slug) = fleet_sync::signer(state) else { return };
194    let Some(wan) = state.mstore.wan_identity().or_else(wan_identity::global) else { return };
195    let store = state.id_store.clone();
196    let planned = {
197        let (store, wan) = (store.clone(), wan.clone());
198        match tokio::task::spawn_blocking(move || plans(&store, &wan)).await {
199            Ok(Ok(planned)) => planned,
200            Ok(Err(e)) => {
201                tracing::debug!(error = %e, "sync: could not read what this machine holds");
202                return;
203            }
204            Err(_) => return,
205        }
206    };
207    last.retain(|(collection, _), _| planned.iter().any(|p| &p.collection == collection));
208    let now = Instant::now();
209    for target in targets(&planned, &seen_on_lan(state)) {
210        let key = (target.collection.clone(), target.machine.clone());
211        if !due(last.get(&key), &target.fingerprint, now) {
212            continue;
213        }
214        let done = run_round(state.clone(), store.clone(), wan.clone(), slug.clone(), target.clone()).await;
215        match done {
216            Some(r) => {
217                report(&target, &r);
218                last.insert(key, remember(&r, &target.fingerprint, Instant::now()));
219            }
220            None => {
221                last.insert(key, Last { fingerprint: String::new(), at: now, retry_at: Some(now + RETRY) });
222            }
223        }
224    }
225}
226
227fn report(target: &Target, r: &Round) {
228    if let Ended::Removed { by } = &r.ended {
229        tracing::warn!(collection = %target.collection, peer = %target.host, removed_by = %by, "sync: this machine was removed from a collection");
230    } else if r.changed() {
231        tracing::info!(collection = %target.collection, peer = %target.host, pulled = r.pulled, pushed = r.pushed, entries = r.entries_taken + r.entries_given, keys = r.keys_taken, "sync: a round with another machine");
232    } else if !matches!(r.ended, Ended::Synced) {
233        tracing::debug!(collection = %target.collection, peer = %target.host, ended = ?r.ended, "sync: a round left for later");
234    }
235}
236
237/// One round on a blocking thread: its calls to the peer wait on this runtime, and its steps on this machine's state
238/// each take the store for their own length.
239async fn run_round(state: AppState, store: Arc<Store>, wan: Arc<WanIdentityStore>, slug: String, target: Target) -> Option<Round> {
240    let handle = Handle::current();
241    tokio::task::spawn_blocking(move || {
242        let adapter = sync_ops::adapter_for(&target.kind)?;
243        let mut mine = Mine { store: &store, wan: &wan };
244        let mut peer = Peer { state, slug, host: target.host, handle };
245        Some(round::sync_collection(&mut mine, &mut peer, &target.collection, adapter.as_ref()))
246    })
247    .await
248    .ok()
249    .flatten()
250}
251
252struct Mine<'a> {
253    store: &'a Store,
254    wan: &'a WanIdentityStore,
255}
256
257impl Session for Mine<'_> {
258    fn with<R>(&mut self, f: impl FnOnce(&mut Ctx) -> R) -> Result<R, String> {
259        sync_ops::with_ctx(self.store, self.wan, None, f).map_err(|e| e.message)
260    }
261}
262
263/// The calls to one peer, as signed remote ops sent by one of this machine's agents.
264struct Peer {
265    state: AppState,
266    slug: String,
267    host: String,
268    handle: Handle,
269}
270
271impl Peer {
272    fn call<Ans: DeserializeOwned>(&self, op: &'static str, params: Value) -> Result<Ans, CallError> {
273        let answer = self.handle.block_on(send::call(&self.state, &self.slug, &self.host, op, params, REASON));
274        answer_of(answer)
275    }
276
277    fn params<T: serde::Serialize>(req: &T) -> Result<Value, CallError> {
278        serde_json::to_value(req).map_err(|e| CallError::Unreachable(format!("a request that cannot be written: {e}")))
279    }
280}
281
282impl PeerCalls for Peer {
283    fn hello(&mut self, collections: &[String]) -> Result<Vec<Held>, CallError> {
284        Ok(self.call::<HelloAns>("sync.hello", json!({ "collections": collections }))?.held)
285    }
286    fn members(&mut self, req: &MembersReq) -> Result<MembersAns, CallError> {
287        self.call("sync.members", Self::params(req)?)
288    }
289    fn keys(&mut self, req: &KeysReq) -> Result<KeysAns, CallError> {
290        self.call("sync.keys", Self::params(req)?)
291    }
292    fn pull(&mut self, req: &PullReq) -> Result<PullAns, CallError> {
293        self.call("sync.pull", Self::params(req)?)
294    }
295    fn push(&mut self, req: &PushReq) -> Result<PushAns, CallError> {
296        self.call("sync.push", Self::params(req)?)
297    }
298}
299
300/// A peer's answer as the round reads it: what it says, a refusal with its code, or the machine not answering.
301pub(super) fn answer_of<Ans: DeserializeOwned>(answer: RemoteOpResult) -> Result<Ans, CallError> {
302    match answer.status {
303        OpStatus::Done => serde_json::from_value(answer.result).map_err(|e| CallError::Refused(format!("bad_answer: {e}"))),
304        OpStatus::Refused => Err(CallError::Refused(answer.refused_reason.unwrap_or_else(|| "refused".to_string()))),
305        OpStatus::Failed => {
306            let why = answer.result.get("error").and_then(Value::as_str).unwrap_or("failed").to_string();
307            Err(CallError::Unreachable(why))
308        }
309        other => Err(CallError::Refused(format!("not_done: {other:?}"))),
310    }
311}
312
313#[cfg(test)]
314mod tests;