1use 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
34const TICK: Duration = Duration::from_secs(15);
36const RESYNC: Duration = Duration::from_secs(10 * 60);
38const 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#[allow(dead_code)]
47pub(crate) fn wake() {
48 WAKE.notify_one();
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
53pub(super) struct Plan {
54 pub collection: String,
55 pub kind: String,
56 pub members: Vec<String>,
57 pub fingerprint: String,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
63pub(super) struct Seen {
64 pub install_id: String,
65 pub host: String,
66}
67
68#[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#[derive(Debug, Clone)]
80pub(super) struct Last {
81 fingerprint: String,
82 at: Instant,
83 retry_at: Option<Instant>,
85}
86
87pub(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
105fn plans(store: &Store, wan: &WanIdentityStore) -> Result<Vec<Plan>, String> {
107 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
140pub(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
153pub(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
165pub(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
237async 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
263struct 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
300pub(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;