Skip to main content

lean_ctx_cloud/sync/
auto.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Background vault sync (3.12.3): the daemon syncs every shared vault of
3//! this machine without a manual `lean-ctx cloud sync`.
4//!
5//! One `cloud-sync` thread per machine, started beside the scheduler
6//! ([`super::super::scheduler::spawn`]). A vault syncs when
7//! - its local data changed (the project's knowledge journal moved, or its
8//!   replica was written: docs, task and knowledge events queued there),
9//!   `DEBOUNCE` after the last change, at the latest `MAX_HOLD` after the
10//!   first one of a stream of changes;
11//! - Cloud said its log or trust advanced (`log.advanced`,
12//!   `trust.advanced` on the bus, [`nudge_place`]); a purge at once;
13//! - or `[cloud] pull_interval_minutes` passed since its last attempt (the
14//!   fallback that works without any bus frame).
15//!
16//! The process that wrote a fact pushes it itself within about a second
17//! ([`super::on_write`]); this thread is the fallback for writes of other
18//! processes and the receiving side of a bus hint.
19//!
20//! Bounded: one sync at a time, at most `MAX_PER_PASS` vaults per pass,
21//! at most one attempt per `MIN_SPACING` and, after a burst of `BURST_MAX`,
22//! one per `BURST_EVERY` per vault (a purge excepted), and a failed vault
23//! backs off
24//! exponentially up to `BACKOFF_MAX`, or as long as Cloud's `Retry-After`
25//! asks. The burst cap and the backoff are shared with every other process
26//! of the machine that syncs (`super::budget`). Offline only backs off:
27//! pending events stay in the replica and go out with the next sync that
28//! reaches Cloud.
29//!
30//! Never unshared data: only vaults Cloud already resolved for this machine
31//! (`projects.json`) sync, only against a C0 2.x Cloud, and this thread never
32//! maps a new project (no resolve); capture keeps its gate and screening.
33//!
34//! The thread writes `<data>/cloud/sync/status.json` (kind `cloud.sync`).
35
36use std::collections::{BTreeMap, BTreeSet};
37use std::path::{Path, PathBuf};
38use std::sync::atomic::{AtomicBool, Ordering};
39use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
40use std::time::{Duration, Instant, SystemTime};
41
42use lean_ctx_time::UtcDateTime;
43use serde::{Deserialize, Serialize};
44
45use crate::CloudError;
46use crate::config::CloudConfig;
47use crate::state::{CloudStore, write_private};
48use crate::vault::{VaultMap, VaultRecord};
49
50/// How often the thread looks for local changes.
51const POLL: Duration = Duration::from_secs(2);
52/// Quiet time after the last local change before a sync.
53pub(crate) const DEBOUNCE: Duration = Duration::from_secs(1);
54/// A stream of local changes syncs at the latest this long after its first
55/// change, quiet or not.
56pub(crate) const MAX_HOLD: Duration = Duration::from_secs(5);
57/// Least time between two attempts on one vault (a purge excepted). It was
58/// 30 s, which held a fact or a bus hint up to 30 s after the vault's last
59/// sync: past the 10 s a fact needs to reach another Instance (#270).
60pub(crate) const MIN_SPACING: Duration = Duration::from_secs(2);
61/// The burst budget of one vault (a purge excepted): a burst of up to
62/// `BURST_MAX` changes or hints is answered at once, a steady stream is
63/// held to `BURST_MAX` attempts per `BURST_WINDOW`, one per `BURST_EVERY`
64/// ([`burst_take`]).
65pub(crate) const BURST_MAX: usize = 6;
66/// The time an empty burst budget takes to fill again.
67pub(crate) const BURST_WINDOW: Duration = Duration::from_secs(60);
68/// After a spent burst, one more attempt per this long.
69pub(crate) const BURST_EVERY: Duration =
70    Duration::from_secs(BURST_WINDOW.as_secs() / BURST_MAX as u64);
71
72/// The burst budget, a token bucket (GCRA): `BURST_MAX` turns, one back
73/// every `BURST_EVERY`. Its whole state is `ahead`, how long from now
74/// until the bucket is full again (zero: full). Returns the `ahead` after
75/// one more attempt when the budget lets it start now (a purge always
76/// starts and is still charged), `None` when it is spent.
77///
78/// A spent burst holds a vault for `BURST_EVERY` at most, never until the
79/// oldest attempt has left a whole `BURST_WINDOW`: that blackout of up to a
80/// minute kept a vault from pulling a peer's change in time. The state is
81/// kept, not rebuilt from the attempts within the last `BURST_WINDOW`:
82/// rebuilt, the bucket refilled as the first burst aged out and a flood
83/// got a second full burst every window (11 attempts a minute, not 6;
84/// review of 5!235). `ahead` is cut to an empty bucket's refill, so a run
85/// of purges or a stepped clock holds a vault no longer than that.
86pub(crate) fn burst_take(ahead: Duration, purge: bool) -> Option<Duration> {
87    let ahead = ahead.min(BURST_WINDOW);
88    let spent = ahead > BURST_WINDOW.saturating_sub(BURST_EVERY);
89    (purge || !spent).then(|| (ahead + BURST_EVERY).min(BURST_WINDOW))
90}
91
92const BACKOFF_FIRST: Duration = Duration::from_secs(30);
93pub(crate) const BACKOFF_MAX: Duration = Duration::from_mins(30);
94/// The longest any vault is held after a failure: the longest backoff
95/// (`BACKOFF_MAX` plus 20 % jitter). It also caps Cloud's `Retry-After`
96/// and any hold the shared budget file keeps, so a server asking for
97/// hours or a wall clock stepped back cannot stop every process for longer.
98pub(crate) const WAIT_MAX: Duration = Duration::from_secs(BACKOFF_MAX.as_secs() / 5 * 6);
99/// How long a parked vault (its LeanCTX Cloud storage is full, or Cloud
100/// answered `404` `NOT_FOUND_PARK` times in a row) waits before the
101/// background sync tries it again. Waiting does not free storage or make
102/// Cloud know an instance, so the batch is not resent every backoff; a
103/// person's `lean-ctx cloud sync` tries at once, and its success unparks
104/// the vault (a reconnect unparks a `not_found` park as well).
105pub(crate) const PARK_RECHECK: Duration = Duration::from_hours(6);
106/// How many `404`s in a row (each at least [`NOT_FOUND_SPACING`] after the
107/// last one counted) park a vault as `not_found`. Cloud names no
108/// instance-level code for an unknown instance (its `404 not_found` also
109/// answers a snapshot revision that rotated mid-clone, and a proxy in front
110/// of Cloud can answer a bare `404` while it is deployed), so one `404` is
111/// never enough: below this count it backs off like any other failure.
112pub(crate) const NOT_FOUND_PARK: u32 = 3;
113/// The least time between two `404`s that both count towards
114/// `NOT_FOUND_PARK`; a `404` sooner after the last counted one is not
115/// counted (a burst of retries is one signal, not three).
116pub(crate) const NOT_FOUND_SPACING: Duration = Duration::from_mins(10);
117/// The `code` of a vault whose link Cloud refused (`401`): the background
118/// sync holds it until a login or reconnect, rechecking it after
119/// [`LOGIN_RECHECK_FIRST`], then every [`LOGIN_RECHECK`].
120pub(crate) const NEEDS_LOGIN: &str = "needs_login";
121/// How long a vault held by `needs_login` waits after its first `401` before
122/// the background sync tries it again by itself. A short auth outage on
123/// Cloud's side (a deploy) answers `401` too; without a recheck it would
124/// stop the sync of every machine until each one reconnected.
125pub(crate) const LOGIN_RECHECK_FIRST: Duration = Duration::from_hours(6);
126/// How long a vault held by `needs_login` waits after each further `401` in
127/// a row (a recheck that Cloud refused again).
128pub(crate) const LOGIN_RECHECK: Duration = Duration::from_hours(24);
129/// How long a vault waits by itself while it waits for a state change
130/// rather than for time: in effect never (no retry loop). A vault parked by
131/// `plan_required` waits for this machine's plan state to differ from the
132/// one stored with the park (a newly received lease, a lock that ends), or
133/// for a person's `lean-ctx cloud sync` that succeeds.
134pub(crate) const PLAN_PARK: Duration = Duration::from_hours(30 * 24);
135/// Vaults synced in one pass at most; the rest follow in the next pass.
136pub(crate) const MAX_PER_PASS: usize = 16;
137/// How often the status file is rewritten while nothing happens, so a
138/// reader can tell a live thread from a stale file.
139const HEARTBEAT: Duration = Duration::from_secs(30);
140/// A status older than this many seconds is shown as `running: false`.
141const STALE_AFTER_S: i64 = 120;
142
143const SYNC_DIR: &str = "sync";
144const STATUS_FILE: &str = "status.json";
145const STATUS_LOCK: &str = "status.lock";
146
147/// What started a sync.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
149pub enum Trigger {
150    Local,
151    Bus,
152    /// `log.advanced` with priority `purge`: no debounce, no spacing.
153    BusPurge,
154    Periodic,
155    Manual,
156}
157
158impl Trigger {
159    pub fn as_str(self) -> &'static str {
160        match self {
161            Self::Local => "local",
162            Self::Bus | Self::BusPurge => "bus",
163            Self::Periodic => "periodic",
164            Self::Manual => "manual",
165        }
166    }
167}
168
169// ---------------------------------------------------------------------------
170// Wake-ups from the bus (same process: the daemon runs the relay too).
171
172static WANTS: Mutex<BTreeMap<String, Trigger>> = Mutex::new(BTreeMap::new());
173static WAKE: Condvar = Condvar::new();
174static STOPPED: AtomicBool = AtomicBool::new(false);
175static RUNNING: AtomicBool = AtomicBool::new(false);
176
177fn wants() -> MutexGuard<'static, BTreeMap<String, Trigger>> {
178    WANTS.lock().unwrap_or_else(PoisonError::into_inner)
179}
180
181/// The vault id of a bus place (`vault:<uuid>`); `None` for other places.
182pub(crate) fn vault_of_place(place: &str) -> Option<String> {
183    let id = place.strip_prefix("vault:")?;
184    (!id.is_empty()).then(|| super::place::place_id(id))
185}
186
187/// Cloud announced a change of `place` (`log.advanced`, `trust.advanced`):
188/// sync that vault soon. A hint only: the sync verifies what it fetches.
189pub fn nudge_place(place: &str, trigger: Trigger) {
190    let Some(vault) = vault_of_place(place) else {
191        return;
192    };
193    {
194        let mut pending = wants();
195        let slot = pending.entry(vault).or_insert(trigger);
196        // A purge wins over a plain advance.
197        if trigger == Trigger::BusPurge {
198            *slot = trigger;
199        }
200    }
201    WAKE.notify_all();
202}
203
204/// End the thread (the scheduler stopped: disconnected, revoked, lapsed).
205pub fn stop() {
206    STOPPED.store(true, Ordering::SeqCst);
207    WAKE.notify_all();
208}
209
210fn wait(timeout: Duration) -> BTreeMap<String, Trigger> {
211    let mut pending = wants();
212    if pending.is_empty() && !STOPPED.load(Ordering::SeqCst) {
213        pending = WAKE
214            .wait_timeout(pending, timeout)
215            .unwrap_or_else(PoisonError::into_inner)
216            .0;
217    }
218    std::mem::take(&mut *pending)
219}
220
221/// How long the thread may sleep at `now`: until the spacing or debounce of
222/// a vault with a hint or a local change waiting ends, at most `POLL`. A
223/// hint that came during the spacing goes out when the spacing ends, not
224/// up to a whole `POLL` later. Anything held for another reason (burst,
225/// backoff, the shared budget) is looked at again after `POLL`.
226pub(crate) fn next_wake<'a>(dues: impl IntoIterator<Item = &'a Due>, now: Instant) -> Duration {
227    let mut wake = POLL;
228    for due in dues {
229        let spaced = due.last_attempt.map(|last| last + MIN_SPACING);
230        let mut at = None;
231        if due.urgent.is_some() {
232            at = spaced;
233        }
234        if let Some(changed) = due.last_change {
235            let quiet = changed + DEBOUNCE;
236            let ready = spaced.map_or(quiet, |s| s.max(quiet));
237            at = Some(at.map_or(ready, |a: Instant| a.min(ready)));
238        }
239        if let (Some(a), Some(retry)) = (at, due.retry_at) {
240            at = Some(a.max(retry));
241        }
242        if let Some(at) = at.filter(|at| *at > now) {
243            wake = wake.min(at - now);
244        }
245    }
246    wake
247}
248
249// ---------------------------------------------------------------------------
250// Scheduling decisions (pure, tested).
251
252/// What the thread knows of one vault between passes.
253#[derive(Debug, Clone, Default)]
254pub(crate) struct Due {
255    pub last_attempt: Option<Instant>,
256    /// When the burst budget is full again ([`burst_take`]).
257    pub full_at: Option<Instant>,
258    /// The newest local change not synced yet.
259    pub last_change: Option<Instant>,
260    /// The first local change not synced yet.
261    pub first_change: Option<Instant>,
262    pub urgent: Option<Trigger>,
263    pub retry_at: Option<Instant>,
264}
265
266impl Due {
267    /// Whether the spacing and the burst budget let an attempt run `now`.
268    fn spaced(&self, now: Instant) -> bool {
269        if self
270            .last_attempt
271            .is_some_and(|last| now.saturating_duration_since(last) < MIN_SPACING)
272        {
273            return false;
274        }
275        burst_take(self.ahead(now), false).is_some()
276    }
277
278    /// How long from `now` until the burst budget is full again.
279    fn ahead(&self, now: Instant) -> Duration {
280        self.full_at
281            .map_or(Duration::ZERO, |full| full.saturating_duration_since(now))
282    }
283
284    /// Record an attempt at `now` (a purge too: it is charged).
285    fn attempted(&mut self, now: Instant) {
286        self.full_at = burst_take(self.ahead(now), true).map(|ahead| now + ahead);
287        self.last_attempt = Some(now);
288        self.urgent = None;
289        self.last_change = None;
290        self.first_change = None;
291    }
292}
293
294/// Whether the vault syncs now, and why.
295pub(crate) fn decide(due: &Due, now: Instant, interval: Duration) -> Option<Trigger> {
296    if due.retry_at.is_some_and(|at| at > now) {
297        return None;
298    }
299    if due.urgent == Some(Trigger::BusPurge) {
300        return Some(Trigger::BusPurge);
301    }
302    if !due.spaced(now) {
303        return None;
304    }
305    if let Some(trigger) = due.urgent {
306        return Some(trigger);
307    }
308    let quiet = due
309        .last_change
310        .is_some_and(|changed| now.saturating_duration_since(changed) >= DEBOUNCE);
311    let held = due
312        .first_change
313        .is_some_and(|first| now.saturating_duration_since(first) >= MAX_HOLD);
314    if quiet || held {
315        return Some(Trigger::Local);
316    }
317    match due.last_attempt {
318        None => Some(Trigger::Periodic),
319        Some(last) if now.duration_since(last) >= interval => Some(Trigger::Periodic),
320        Some(_) => None,
321    }
322}
323
324/// The wait after the `failures`-th failure in a row (`failures >= 1`),
325/// `jitter` in `0..1000` spreading it by ±20 %.
326pub(crate) fn backoff(failures: u32, jitter: u32) -> Duration {
327    let base = BACKOFF_FIRST
328        .saturating_mul(1u32 << failures.saturating_sub(1).min(16))
329        .min(BACKOFF_MAX);
330    let permille = 800 + u64::from(jitter.min(999)) * 400 / 1000;
331    let millis = u64::try_from(base.as_millis()).unwrap_or(u64::MAX);
332    Duration::from_millis(millis / 1000 * permille)
333}
334
335fn jitter() -> u32 {
336    SystemTime::now()
337        .duration_since(SystemTime::UNIX_EPOCH)
338        .map_or(0, |d| d.subsec_nanos() % 1000)
339}
340
341// ---------------------------------------------------------------------------
342// Status (kind `cloud.sync`).
343
344#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
345#[serde(default)]
346pub struct VaultSyncStatus {
347    pub vault_id: String,
348    /// `@ns/name`.
349    pub vault: String,
350    pub last_sync_at: Option<String>,
351    pub last_ok_at: Option<String>,
352    pub last_trigger: Option<String>,
353    /// Signed events waiting in the replica for Cloud.
354    pub pending: u64,
355    /// Of the last successful sync.
356    pub stored: u64,
357    pub pushed: u64,
358    pub failures: u32,
359    pub error: Option<String>,
360    pub next_attempt_at: Option<String>,
361    /// LeanCTX Cloud storage is full (`code` `storage_full`): the background
362    /// sync holds the vault (rechecked every 6 h) until a sync succeeds (a
363    /// manual one, or the recheck once storage has freed). The plan does not
364    /// allow it (`code` `plan_required`): held until the plan state changes
365    /// or a manual sync succeeds, never retried by itself. Cloud answered
366    /// `404` `NOT_FOUND_PARK` times in a row (`code` `not_found`): held,
367    /// rechecked every 6 h, until a sync succeeds or a reconnect or another
368    /// configured Cloud changes the link state. A `401` is no park
369    /// (`parked` stays `false`): see [`Self::needs_login`]. Always written.
370    pub parked: bool,
371    /// Cloud refused this instance's credentials (`401`, `code`
372    /// `needs_login`): the background sync and a push on write stop for the
373    /// vault until a login or reconnect changes the link state or a sync
374    /// succeeds; the background sync rechecks it after 6 h, then every
375    /// 24 h (`next_attempt_at`). Never together with `parked`. Always
376    /// written.
377    pub needs_login: bool,
378    /// The last failure's machine-readable kind (`rate_limited`,
379    /// `upload_rate_limited`, `plan_required`, `storage_full`,
380    /// `quota_exceeded`, `policy_denied`, `offline`, `needs_login`,
381    /// `upgrade_required`, `not_found`, `error`); `null` after a success.
382    /// `not_found` only while `parked` (a `404` below `NOT_FOUND_PARK` in
383    /// a row is noted as `error`).
384    /// `needs_login` (Cloud refused this instance's credentials, `401`):
385    /// see [`Self::needs_login`].
386    pub code: Option<String>,
387    /// The seconds the cloud asked to wait with the failure that set `code`
388    /// (`Retry-After`, a quota's reset); `null` when it asked for none.
389    pub retry_after_s: Option<u64>,
390    /// Set only while the vault is parked by `plan_required`: the plan
391    /// state (`plan_state`) the park was taken under. Kept in the status
392    /// file, so any process (a restarted daemon too) unparks the vault once
393    /// this machine's plan state differs, a newly received lease included.
394    #[serde(skip_serializing_if = "Option::is_none")]
395    pub plan_park: Option<String>,
396    /// Set only while the vault is held by a `not_found` park or by
397    /// `needs_login`: the link state (`link_state`: enrolled instance, its
398    /// origin and enrollment, the configured Cloud) it was taken under. Any
399    /// process ends the hold once this machine's link state differs (a
400    /// login or reconnect, a new `[cloud] url`); do not parse it.
401    #[serde(skip_serializing_if = "Option::is_none")]
402    pub link_park: Option<String>,
403    /// `404`s counted in a row towards a `not_found` park (see
404    /// `NOT_FOUND_PARK`); `0` (left out) after a success or another failure.
405    #[serde(skip_serializing_if = "is_zero")]
406    pub not_found_streak: u32,
407    /// When the last counted `404` was noted (RFC 3339); left out with a
408    /// streak of `0`.
409    #[serde(skip_serializing_if = "Option::is_none")]
410    pub not_found_at: Option<String>,
411}
412
413#[allow(clippy::trivially_copy_pass_by_ref)] // serde's `skip_serializing_if` passes a reference
414fn is_zero(n: &u32) -> bool {
415    *n == 0
416}
417
418/// Whether Cloud answered `404`: a `404 not_found` (it does not know the
419/// instance, the vault, or a snapshot revision that just rotated), or a
420/// `404` that names no code (an edge proxy's page, for example while Cloud
421/// is deployed). Both are `not_found`; only `NOT_FOUND_PARK` of them in a
422/// row park the vault.
423pub(crate) fn is_unknown(error: &CloudError) -> bool {
424    matches!(
425        error,
426        CloudError::NotFound | CloudError::Server { status: 404, .. }
427    )
428}
429
430/// The `code` of a failed sync's `error`.
431pub(crate) fn code_of(error: &CloudError) -> &'static str {
432    if is_unknown(error) {
433        return "not_found";
434    }
435    match error {
436        CloudError::RateLimited { .. } => "rate_limited",
437        CloudError::UploadRateLimited { .. } => "upload_rate_limited",
438        CloudError::PlanRequired(_) => "plan_required",
439        CloudError::StorageFull(_) => "storage_full",
440        CloudError::QuotaExceeded(_) => "quota_exceeded",
441        CloudError::PolicyDenied(_) => "policy_denied",
442        CloudError::Offline(_) => "offline",
443        CloudError::Unauthorized => NEEDS_LOGIN,
444        CloudError::UpgradeRequired { .. } => "upgrade_required",
445        _ => "error",
446    }
447}
448
449#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
450#[serde(default)]
451pub struct SyncStatus {
452    pub interval_s: u64,
453    pub last_pass_at: Option<String>,
454    /// Rewritten at least every 30 s by a live thread.
455    pub heartbeat_at: Option<String>,
456    pub vaults: Vec<VaultSyncStatus>,
457}
458
459impl SyncStatus {
460    /// Whether a live thread wrote this status (heartbeat recent).
461    pub fn running_at(&self, now: lean_ctx_time::UtcDateTime) -> bool {
462        self.heartbeat_at
463            .as_deref()
464            .and_then(|t| lean_ctx_time::OffsetDateTime::parse_from_rfc3339(t).ok())
465            .is_some_and(|at| (now - at.to_utc()).num_seconds() < STALE_AFTER_S)
466    }
467}
468
469pub(crate) fn sync_dir(data_dir: &Path) -> PathBuf {
470    data_dir.join(SYNC_DIR)
471}
472
473/// Read, change and write the status file under its own lock, so two
474/// processes noting a sync never drop each other's rows (or a backoff).
475/// Without the lock (it cannot be created) the change is still made.
476fn with_status<T>(data_dir: &Path, change: impl FnOnce(&mut SyncStatus) -> T) -> T {
477    use fs2::FileExt as _;
478    let dir = sync_dir(data_dir);
479    let lock = std::fs::create_dir_all(&dir).ok().and_then(|()| {
480        std::fs::OpenOptions::new()
481            .create(true)
482            .truncate(false)
483            .write(true)
484            .open(dir.join(STATUS_LOCK))
485            .ok()
486    });
487    if let Some(file) = &lock {
488        let _ = file.lock_exclusive();
489    }
490    // Unlocked when dropped (see `VaultLock`).
491    let lock = lock.map(VaultLock);
492    let mut status = load_status(data_dir);
493    let out = change(&mut status);
494    save_status(data_dir, &status);
495    drop(lock);
496    out
497}
498
499/// Write the thread's `status`, keeping what other processes noted since
500/// (see [`merge_manual`]), under the status lock.
501fn store_status(data_dir: &Path, status: &mut SyncStatus, shared: &VaultMap) {
502    with_status(data_dir, |disk| {
503        merge_manual(status, disk, shared);
504        disk.clone_from(status);
505    });
506}
507
508pub fn load_status(data_dir: &Path) -> SyncStatus {
509    std::fs::read(sync_dir(data_dir).join(STATUS_FILE))
510        .ok()
511        .and_then(|b| serde_json::from_slice(&b).ok())
512        .unwrap_or_default()
513}
514
515fn save_status(data_dir: &Path, status: &SyncStatus) {
516    if let Ok(bytes) = serde_json::to_vec_pretty(status) {
517        let _ = write_private(&sync_dir(data_dir), STATUS_FILE, &bytes);
518    }
519}
520
521fn stamp(at: lean_ctx_time::UtcDateTime) -> String {
522    at.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
523}
524
525// ---------------------------------------------------------------------------
526// Single flight with `lean-ctx cloud sync`.
527
528/// A held vault sync lock (or the status lock). Dropping it unlocks the
529/// file explicitly before closing it: closing alone does not release an
530/// `flock` while a child process forked meanwhile by another thread (a
531/// `git` spawn, say) still holds a copy of the descriptor, and the next
532/// sync of the vault would find it busy until that child execs or exits.
533#[derive(Debug)]
534pub struct VaultLock(std::fs::File);
535
536impl Drop for VaultLock {
537    fn drop(&mut self) {
538        let _ = fs2::FileExt::unlock(&self.0);
539    }
540}
541
542/// The advisory lock of one vault's sync. `wait`: block until free (the
543/// CLI); otherwise `Ok(None)` when another sync holds it (the thread skips).
544pub fn lock_vault(
545    data_dir: &Path,
546    vault_id: &str,
547    wait: bool,
548) -> Result<Option<VaultLock>, CloudError> {
549    use fs2::FileExt as _;
550    let local = |e: std::io::Error| CloudError::Local(format!("sync lock: {e}"));
551    let dir = sync_dir(data_dir);
552    std::fs::create_dir_all(&dir).map_err(local)?;
553    let file = std::fs::OpenOptions::new()
554        .create(true)
555        .truncate(false)
556        .write(true)
557        .open(dir.join(format!("{}.lock", lock_name(vault_id))))
558        .map_err(local)?;
559    if wait {
560        file.lock_exclusive().map_err(local)?;
561        return Ok(Some(VaultLock(file)));
562    }
563    match file.try_lock_exclusive() {
564        Ok(()) => Ok(Some(VaultLock(file))),
565        Err(_) => Ok(None),
566    }
567}
568
569/// The file name stem of a vault's sync files (lock, budget).
570pub(crate) fn lock_name(vault_id: &str) -> String {
571    super::place::place_id(vault_id)
572        .chars()
573        .filter(|c| c.is_ascii_alphanumeric() || *c == '-')
574        .collect()
575}
576
577// ---------------------------------------------------------------------------
578// Local change signals.
579
580/// What a vault's local data looks like: the knowledge journal's head and
581/// the replica database's modification times. A change of either is a
582/// local write to sync.
583#[derive(Debug, Clone, Default, PartialEq, Eq)]
584pub(crate) struct Mark {
585    knowledge: u64,
586    replica: Option<SystemTime>,
587}
588
589impl Mark {
590    /// The baseline a sync that started at `self` leaves, given the marks
591    /// `after` it: the replica as the sync wrote it (its own writes are not
592    /// a local change), the knowledge journal as the sync found it. A fact
593    /// remembered while the sync ran was not captured by it; taking the
594    /// journal head from `after` hid that write until the next unrelated
595    /// change or the interval, and push on write, held by the sync's lock
596    /// or the burst budget, leaves such a write to this thread.
597    pub(crate) fn after_sync(&self, after: &Mark) -> Mark {
598        Mark {
599            knowledge: self.knowledge,
600            replica: after.replica,
601        }
602    }
603}
604
605fn mark_of(data_dir: &Path, record: &VaultRecord, root: &str) -> Mark {
606    let knowledge = lean_ctx::core::knowledge::knowledge_dir_of(root)
607        .map_or(0, |dir| lean_ctx::core::knowledge::journal::head_lsn(&dir));
608    let dir = crate::replica::store::place_dir(data_dir, &record.vault_id);
609    let replica = ["replica.db", "replica.db-wal"]
610        .iter()
611        .filter_map(|name| std::fs::metadata(dir.join(name)).ok()?.modified().ok())
612        .max();
613    Mark { knowledge, replica }
614}
615
616/// The local checkout to sync `record` from: its first recorded root that
617/// still exists.
618pub fn root_of(record: &VaultRecord) -> Option<String> {
619    record
620        .roots
621        .iter()
622        .find(|root| Path::new(root.as_str()).is_dir())
623        .cloned()
624}
625
626// ---------------------------------------------------------------------------
627// The thread.
628
629#[derive(Default)]
630struct VaultRun {
631    due: Due,
632    mark: Option<Mark>,
633    failures: u32,
634    /// The thread's view of the status row's `parked`.
635    parked: bool,
636}
637
638/// Whether the status row of `vault` (a place id) is held: parked, or its
639/// link needs a login.
640fn row_parked(status: &SyncStatus, vault: &str) -> bool {
641    row_park(status, vault).is_some()
642}
643
644/// How long the held status row of `vault` waits by itself
645/// ([`PLAN_PARK`] for `plan_required`, [`LOGIN_RECHECK_FIRST`] for
646/// `needs_login`, else [`PARK_RECHECK`]); `None` when it is not held.
647fn row_park(status: &SyncStatus, vault: &str) -> Option<Duration> {
648    status
649        .vaults
650        .iter()
651        .find(|v| v.vault_id == vault && holds(v))
652        .map(park_wait)
653}
654
655fn park_wait(row: &VaultSyncStatus) -> Duration {
656    if waits_for_plan(row) {
657        PLAN_PARK
658    } else if row.needs_login {
659        LOGIN_RECHECK_FIRST
660    } else {
661        PARK_RECHECK
662    }
663}
664
665/// Whether `row` is parked by `plan_required` (it waits for the plan
666/// state, not for time).
667fn waits_for_plan(row: &VaultSyncStatus) -> bool {
668    row.parked && row.plan_park.is_some()
669}
670
671/// Whether the background sync holds `row`: parked, or its link needs a
672/// login.
673fn holds(row: &VaultSyncStatus) -> bool {
674    row.parked || row.needs_login
675}
676
677/// Whether the background sync holds `vault_id` because its LeanCTX Cloud
678/// storage is full, the plan does not allow it, Cloud answered `404`
679/// `NOT_FOUND_PARK` times in a row, or its link needs a login (a push on
680/// write skips it too).
681pub(crate) fn is_parked(data_dir: &Path, vault_id: &str) -> bool {
682    row_parked(&load_status(data_dir), &super::place::place_id(vault_id))
683}
684
685/// End, in the status file, every hold whose plan or link state this
686/// machine no longer has (as the daemon's loop does), so a process that
687/// is not the daemon (a push on write) sees a login or a new lease at once.
688/// The file is written only when a hold ends, and the plan and link state
689/// are read only when a row is held (a push on write calls this each time).
690pub(crate) fn release_holds(store: &CloudStore, config: &CloudConfig) {
691    let data = store.data_dir();
692    let mut status = load_status(data);
693    if !status.vaults.iter().any(holds) {
694        return;
695    }
696    let (plan, link) = (plan_state(store), link_state(store, config));
697    // Both run: `|`, not `||`.
698    if unpark_plan(&mut status, &plan) | unpark_link(&mut status, &link) {
699        with_status(data, |status| {
700            unpark_plan(status, &plan);
701            unpark_link(status, &link);
702        });
703    }
704}
705
706/// Take a park or unpark another process noted (a manual `cloud sync`) into
707/// the thread's run of `vault`: parked, it waits `park` from `now`;
708/// unparked, it is due again at once.
709fn adopt_park(run: &mut VaultRun, park: Option<Duration>, now: Instant) {
710    let parked = park.is_some();
711    if run.parked == parked {
712        return;
713    }
714    run.parked = parked;
715    if let Some(wait) = park {
716        run.due.retry_at = Some(now + wait);
717    } else {
718        run.due.retry_at = None;
719        run.failures = 0;
720    }
721}
722
723/// What a `plan_required` park waits for: the lease's plan and rights, when
724/// it was received, and the workspace lock, as this machine last stored
725/// them. Every newly received lease changes it, even one with the same plan
726/// and rights (a Team trial that became a paid Team): the cloud issues no
727/// lease to a locked workspace, so a new lease is itself a reason to try again.
728pub(crate) fn plan_state(store: &CloudStore) -> String {
729    let lease = store
730        .read_config::<crate::state::LeaseRecord>(crate::state::LEASE_FILE)
731        .ok()
732        .flatten();
733    let at = |pointer: &str| {
734        lease
735            .as_ref()
736            .and_then(|l| l.envelope.pointer(pointer))
737            .map_or_else(String::new, ToString::to_string)
738    };
739    format!(
740        "{}|{}|{}|{}",
741        at("/lease/plan"),
742        at("/lease/rights"),
743        lease.as_ref().map_or("", |l| l.received_at.as_str()),
744        store.activity().locked.unwrap_or_default()
745    )
746}
747
748/// Unpark every vault `plan_required` parked under a plan state other than
749/// `state` (due again at once). The comparison is against the state stored
750/// with each park, so it holds across restarts of the thread. Returns
751/// whether any was unparked.
752pub(crate) fn unpark_plan(status: &mut SyncStatus, state: &str) -> bool {
753    let mut any = false;
754    for row in &mut status.vaults {
755        if waits_for_plan(row) && row.plan_park.as_deref() != Some(state) {
756            row.parked = false;
757            row.plan_park = None;
758            row.next_attempt_at = None;
759            any = true;
760        }
761    }
762    any
763}
764
765/// What a `not_found` park and a `needs_login` hold wait for: the enrolled
766/// instance (its id, the origin it is enrolled with, when it was enrolled)
767/// and the configured Cloud (`[cloud] url`), as this machine has them now.
768/// A login or reconnect (a fresh login or device link writes a new
769/// enrollment) or another configured Cloud changes it; nothing else does.
770pub(crate) fn link_state(store: &CloudStore, config: &CloudConfig) -> String {
771    let instance = store.instance().ok().flatten();
772    let (id, url, enrolled) = instance.as_ref().map_or(("", "", ""), |i| {
773        (
774            i.instance_id.as_str(),
775            i.url.as_str(),
776            i.enrolled_at.as_str(),
777        )
778    });
779    format!(
780        "{id}|{url}|{enrolled}|{}",
781        config.url.as_deref().unwrap_or_default()
782    )
783}
784
785/// End every `not_found` park and `needs_login` hold taken under a link
786/// state other than `state` (due again at once), and clear what it left in
787/// the row (`code`, `error`, the failure count, the `404` streak), so the
788/// app no longer shows the old reason. Like [`unpark_plan`], the
789/// comparison is against the state stored with each hold, so it holds
790/// across restarts. The daemon's loop calls it every turn, and a push on
791/// write through [`release_holds`]; a manual `lean-ctx cloud sync` that
792/// succeeds ends a hold through `note` instead. Returns whether any ended.
793pub(crate) fn unpark_link(status: &mut SyncStatus, state: &str) -> bool {
794    let mut any = false;
795    for row in &mut status.vaults {
796        if holds(row) && row.link_park.as_deref().is_some_and(|park| park != state) {
797            row.parked = false;
798            row.needs_login = false;
799            row.link_park = None;
800            row.next_attempt_at = None;
801            row.code = None;
802            row.error = None;
803            row.retry_after_s = None;
804            row.failures = 0;
805            row.not_found_streak = 0;
806            row.not_found_at = None;
807            any = true;
808        }
809    }
810    any
811}
812
813/// Start the thread once per process (the daemon). A second call while it
814/// runs does nothing.
815pub fn spawn(store: CloudStore, config: CloudConfig) {
816    STOPPED.store(false, Ordering::SeqCst);
817    if RUNNING.swap(true, Ordering::SeqCst) {
818        return;
819    }
820    let started = std::thread::Builder::new()
821        .name("cloud-sync".into())
822        .spawn(move || {
823            run(&store, config);
824            RUNNING.store(false, Ordering::SeqCst);
825        });
826    if started.is_err() {
827        RUNNING.store(false, Ordering::SeqCst);
828    }
829}
830
831fn run(store: &CloudStore, mut config: CloudConfig) {
832    let data = store.data_dir().to_path_buf();
833    let mut status = load_status(&data);
834    let mut runs: BTreeMap<String, VaultRun> = BTreeMap::new();
835    let mut last_write: Option<Instant> = None;
836    let mut reloaded = Instant::now();
837    let mut sleep = POLL;
838    while !STOPPED.load(Ordering::SeqCst) {
839        let nudged = wait(sleep);
840        if STOPPED.load(Ordering::SeqCst) {
841            break;
842        }
843        if reloaded.elapsed() >= Duration::from_secs(60) {
844            config = lean_ctx::core::config::Config::load().cloud.clone();
845            reloaded = Instant::now();
846        }
847        // A `plan_required` park waits for the plan state, not for time; a
848        // `not_found` park or a `needs_login` hold ends with a login or
849        // reconnect, or another configured Cloud.
850        unpark_plan(&mut status, &plan_state(store));
851        unpark_link(&mut status, &link_state(store, &config));
852        let interval = Duration::from_secs(u64::from(config.pull_interval()) * 60);
853        status.interval_s = interval.as_secs();
854        let map = current_map(store);
855        let active = config.enabled != Some(false) && crate::bus::relay_v2::speaks_v2(store);
856        let due_now = plan_pass(
857            &map,
858            &mut runs,
859            &mut status,
860            &nudged,
861            Instant::now(),
862            interval,
863            active,
864            &|record, root| mark_of(&data, record, root),
865        );
866        let mut wrote = false;
867        if !due_now.is_empty() {
868            match pass(store, &config, &due_now, &mut runs, &mut status) {
869                Ok(()) => {}
870                Err(PassEnd::Stop(reason)) => {
871                    store.record_error(&format!("background sync: {reason}"));
872                    store_status(&data, &mut status, &map);
873                    break;
874                }
875            }
876            status.last_pass_at = Some(stamp(UtcDateTime::now()));
877            wrote = true;
878        }
879        if wrote || last_write.is_none_or(|at| at.elapsed() >= HEARTBEAT) {
880            status.heartbeat_at = Some(stamp(UtcDateTime::now()));
881            store_status(&data, &mut status, &map);
882            last_write = Some(Instant::now());
883        }
884        sleep = next_wake(runs.values().map(|run| &run.due), Instant::now());
885    }
886    status.heartbeat_at = None;
887    store_status(&data, &mut status, &current_map(store));
888}
889
890/// The vault map without stale resolutions (dropped from the file; when
891/// that write fails, still left out of this pass): a pass never plans a
892/// vault the checkout left.
893fn current_map(store: &CloudStore) -> VaultMap {
894    match crate::resolution::load_current(store.data_dir()) {
895        Ok((map, _)) => map,
896        Err(error) => {
897            store.record_error(&format!("background sync: {error}"));
898            crate::resolution::current_view(store.data_dir())
899        }
900    }
901}
902
903/// Keep the rows a manual `cloud sync` wrote to the file since this thread
904/// last wrote it (newer `last_sync_at`). A row of a vault no longer shared
905/// on this machine (not in `shared`) is not brought back.
906pub(crate) fn merge_manual(status: &mut SyncStatus, disk: &SyncStatus, shared: &VaultMap) {
907    let shared: BTreeSet<String> = shared
908        .vaults
909        .values()
910        .map(|record| super::place::place_id(&record.vault_id))
911        .collect();
912    status.vaults.retain(|v| shared.contains(&v.vault_id));
913    for row in disk.vaults.iter().filter(|v| shared.contains(&v.vault_id)) {
914        match status
915            .vaults
916            .iter_mut()
917            .find(|v| v.vault_id == row.vault_id)
918        {
919            Some(mine) if row.last_sync_at > mine.last_sync_at => *mine = row.clone(),
920            Some(_) => {}
921            None => status.vaults.push(row.clone()),
922        }
923    }
924    status.vaults.sort_by(|a, b| a.vault_id.cmp(&b.vault_id));
925}
926
927/// One pass's plan: look at every shared vault's local marks (`mark`), take
928/// the bus nudges, and return the vaults to sync now (purges first, then the
929/// oldest attempt; at most [`MAX_PER_PASS`]). Nothing is planned while not
930/// `active` (Cloud off, not C0 2.x), but local changes are still noted.
931#[allow(clippy::too_many_arguments)]
932fn plan_pass(
933    map: &VaultMap,
934    runs: &mut BTreeMap<String, VaultRun>,
935    status: &mut SyncStatus,
936    nudged: &BTreeMap<String, Trigger>,
937    now: Instant,
938    interval: Duration,
939    active: bool,
940    mark: &dyn Fn(&VaultRecord, &str) -> Mark,
941) -> Vec<(VaultRecord, String, Trigger)> {
942    let mut due_now: Vec<(VaultRecord, String, Trigger)> = Vec::new();
943    let mut seen = BTreeSet::new();
944    for record in map.vaults.values() {
945        let vault = super::place::place_id(&record.vault_id);
946        if !seen.insert(vault.clone()) {
947            continue;
948        }
949        let Some(root) = root_of(record) else {
950            continue;
951        };
952        let run = runs.entry(vault.clone()).or_default();
953        adopt_park(run, row_park(status, &vault), now);
954        if let Some(trigger) = nudged.get(&vault) {
955            run.due.urgent = Some(run.due.urgent.map_or(*trigger, |t| t.max(*trigger)));
956        }
957        let now_mark = mark(record, &root);
958        match &run.mark {
959            // The first look is the baseline, not a change.
960            None => run.mark = Some(now_mark),
961            Some(previous) if *previous != now_mark => {
962                run.due.last_change = Some(now);
963                run.due.first_change.get_or_insert(now);
964                run.mark = Some(now_mark);
965            }
966            Some(_) => {}
967        }
968        if !active {
969            continue;
970        }
971        if let Some(trigger) = decide(&run.due, now, interval) {
972            due_now.push((record.clone(), root, trigger));
973        }
974    }
975    // Vaults no longer shared on this machine leave the status.
976    runs.retain(|vault, _| seen.contains(vault));
977    status.vaults.retain(|v| seen.contains(&v.vault_id));
978    // Purges first, then the oldest attempt.
979    due_now.sort_by_key(|(record, _, trigger)| {
980        let vault = super::place::place_id(&record.vault_id);
981        (
982            *trigger != Trigger::BusPurge,
983            runs.get(&vault).and_then(|r| r.due.last_attempt),
984        )
985    });
986    due_now.truncate(MAX_PER_PASS);
987    due_now
988}
989
990enum PassEnd {
991    Stop(String),
992}
993
994fn pass(
995    store: &CloudStore,
996    config: &CloudConfig,
997    due: &[(VaultRecord, String, Trigger)],
998    runs: &mut BTreeMap<String, VaultRun>,
999    status: &mut SyncStatus,
1000) -> Result<(), PassEnd> {
1001    let data = store.data_dir().to_path_buf();
1002    let plan = || plan_state(store);
1003    let link = || link_state(store, config);
1004    let states = ParkStates {
1005        plan: &plan,
1006        link: &link,
1007    };
1008    let mut screen = crate::knowledge::screening::Screen::for_installation();
1009    // A screening rule that does not compile pauses every content channel.
1010    let session = match screen.problem() {
1011        Some(problem) => Err(CloudError::Local(problem)),
1012        None => crate::scheduler::connected_session(store, config),
1013    };
1014    let session = match session {
1015        Ok(session) => session,
1016        Err(
1017            error @ (CloudError::Revoked(_) | CloudError::LeaseLapsed | CloudError::NotConnected),
1018        ) => {
1019            return Err(PassEnd::Stop(error.to_string()));
1020        }
1021        Err(error) => {
1022            // Offline or a local refusal: every due vault waits.
1023            for (record, _, trigger) in due {
1024                note(record, *trigger, Err(&error), runs, status, None, &states);
1025            }
1026            return Ok(());
1027        }
1028    };
1029    for (record, root, trigger) in due {
1030        let Ok(lock) = lock_vault(&data, &record.vault_id, false) else {
1031            continue;
1032        };
1033        // A manual `cloud sync` holds it: its result is just as good.
1034        let Some(_lock) = lock else {
1035            continue;
1036        };
1037        // The budget every process of this machine shares: a push on write
1038        // that just ran (or failed and backs off) counts here too. Held
1039        // back, the vault stays due and goes out once the budget allows.
1040        let purge = *trigger == Trigger::BusPurge;
1041        if super::budget::admit_sync(&data, &record.vault_id, purge, UtcDateTime::now())
1042            != super::budget::Admit::Go
1043        {
1044            continue;
1045        }
1046        // The journal as this sync starts: it captures what is written up
1047        // to here, nothing written while it runs.
1048        let before = mark_of(&data, record, root);
1049        let was_parked = row_parked(status, &super::place::place_id(&record.vault_id));
1050        let done = super::place::sync_vault(&session, record, Path::new(root), &mut screen);
1051        let pending = pending_events(store, record);
1052        let wait = match done {
1053            Ok(done) => {
1054                let wait = note(record, *trigger, Ok(&done), runs, status, pending, &states);
1055                // A fresh session's `ctx_tasks` answers from this cache.
1056                if let Err(error) = crate::tasks::cache::warm(Path::new(root)) {
1057                    tracing::debug!(
1058                        "cloud: task lists of {} not warmed: {error}",
1059                        record.vault_id
1060                    );
1061                }
1062                wait
1063            }
1064            Err(error @ (CloudError::Revoked(_) | CloudError::LeaseLapsed)) => {
1065                let wait = note(
1066                    record,
1067                    *trigger,
1068                    Err(&error),
1069                    runs,
1070                    status,
1071                    pending,
1072                    &states,
1073                );
1074                super::budget::settle(&data, &record.vault_id, wait, UtcDateTime::now());
1075                return Err(PassEnd::Stop(error.to_string()));
1076            }
1077            Err(error) => {
1078                let wait = note(
1079                    record,
1080                    *trigger,
1081                    Err(&error),
1082                    runs,
1083                    status,
1084                    pending,
1085                    &states,
1086                );
1087                // Said once, when the vault becomes held; the status row
1088                // keeps it.
1089                if !was_parked && row_parked(status, &super::place::place_id(&record.vault_id)) {
1090                    store.record_error(&park_line(record, &error));
1091                }
1092                wait
1093            }
1094        };
1095        super::budget::settle(&data, &record.vault_id, wait, UtcDateTime::now());
1096        // What this sync wrote itself is not a local change; a fact
1097        // remembered while it ran is.
1098        if let Some(run) = runs.get_mut(&super::place::place_id(&record.vault_id)) {
1099            run.mark = Some(before.after_sync(&mark_of(&data, record, root)));
1100        }
1101    }
1102    // LeanCTX Cloud usage (capability `usage` only, at most every 10 min):
1103    // one log line when a quota first reaches warn (80 %) or full.
1104    crate::usage::background(&session, UtcDateTime::now());
1105    // Task proposals queued locally go out with the vault sync.
1106    for problem in crate::tasks::propose::drain(&session).problems {
1107        store.record_error(&format!("tasks: {problem}"));
1108    }
1109    // Workers no session used for a day, and those of ended app sessions,
1110    // leave the book and are retired on Cloud (owner 09.11.: workers that
1111    // are not active do not count).
1112    if let Err(error) = crate::workers::register::sweep(&session) {
1113        store.record_error(&format!("worker retirement: {error}"));
1114    }
1115    Ok(())
1116}
1117
1118/// Signed events of `record` still waiting for Cloud; `None` when the
1119/// replica cannot be read (no replica yet, no key).
1120fn pending_events(store: &CloudStore, record: &VaultRecord) -> Option<u64> {
1121    if !crate::replica::store::place_dir(store.data_dir(), &record.vault_id).is_dir() {
1122        return Some(0);
1123    }
1124    let (mk, _) = crate::replica::crypt::master_key(store.config_dir(), false).ok()?;
1125    let (replica, _) =
1126        crate::replica::Replica::open(store.data_dir(), &record.vault_id, &mk).ok()?;
1127    replica
1128        .pending()
1129        .ok()
1130        .map(|p| u64::try_from(p.len()).unwrap_or(u64::MAX))
1131}
1132
1133/// The states a hold that waits for a change (not for time) is stored with,
1134/// each read only when a failure takes a hold for that reason.
1135pub(crate) struct ParkStates<'a> {
1136    /// This machine's plan state ([`plan_state`]), for `plan_required`.
1137    pub plan: &'a dyn Fn() -> String,
1138    /// This machine's link state ([`link_state`]), for a `not_found` park
1139    /// and for `needs_login`.
1140    pub link: &'a dyn Fn() -> String,
1141}
1142
1143/// Count the `404` noted `at` towards a `not_found` park: only when it
1144/// comes at least [`NOT_FOUND_SPACING`] after the last counted one (or is
1145/// the first). An unreadable stamp counts as none.
1146fn count_not_found(row: &mut VaultSyncStatus, at: UtcDateTime) {
1147    let spaced = row
1148        .not_found_at
1149        .as_deref()
1150        .and_then(|t| lean_ctx_time::OffsetDateTime::parse_from_rfc3339(t).ok())
1151        .is_none_or(|last| {
1152            (at - last.to_utc()).num_seconds()
1153                >= i64::try_from(NOT_FOUND_SPACING.as_secs()).unwrap_or(i64::MAX)
1154        });
1155    if spaced {
1156        row.not_found_streak = row.not_found_streak.saturating_add(1);
1157        row.not_found_at = Some(stamp(at));
1158    }
1159}
1160
1161/// Note one sync's `result` in `runs` and `status`; the wait a failure asks
1162/// for (`None` on success). `states` gives the plan state, read only when
1163/// the failure is `plan_required`, and the link state, read only when it
1164/// parks as `not_found` or is a `401` (each stored with its hold).
1165fn note(
1166    record: &VaultRecord,
1167    trigger: Trigger,
1168    result: Result<&super::place::VaultSync, &CloudError>,
1169    runs: &mut BTreeMap<String, VaultRun>,
1170    status: &mut SyncStatus,
1171    pending: Option<u64>,
1172    states: &ParkStates<'_>,
1173) -> Option<Duration> {
1174    let vault = super::place::place_id(&record.vault_id);
1175    let now = Instant::now();
1176    let at = UtcDateTime::now();
1177    let run = runs.entry(vault.clone()).or_default();
1178    run.due.attempted(now);
1179    let index = status
1180        .vaults
1181        .iter()
1182        .position(|v| v.vault_id == vault)
1183        .unwrap_or_else(|| {
1184            status.vaults.push(VaultSyncStatus {
1185                vault_id: vault.clone(),
1186                ..VaultSyncStatus::default()
1187            });
1188            status.vaults.len() - 1
1189        });
1190    let row = &mut status.vaults[index];
1191    row.vault = format!("@{}/{}", record.ns, record.name);
1192    row.last_sync_at = Some(stamp(at));
1193    row.last_trigger = Some(trigger.as_str().to_string());
1194    if let Some(pending) = pending {
1195        row.pending = pending;
1196    }
1197    match result {
1198        Ok(done) => {
1199            run.failures = 0;
1200            run.due.retry_at = None;
1201            run.parked = false;
1202            row.failures = 0;
1203            row.error = None;
1204            row.next_attempt_at = None;
1205            row.parked = false;
1206            row.needs_login = false;
1207            row.code = None;
1208            row.retry_after_s = None;
1209            row.plan_park = None;
1210            row.link_park = None;
1211            row.not_found_streak = 0;
1212            row.not_found_at = None;
1213            row.last_ok_at = Some(stamp(at));
1214            row.stored = u64::try_from(done.stored).unwrap_or(u64::MAX);
1215            row.pushed = u64::try_from(done.pushed).unwrap_or(u64::MAX);
1216        }
1217        Err(error) => {
1218            run.failures = row.failures.max(run.failures).saturating_add(1);
1219            // Storage full parks the vault: waiting does not free it, so the
1220            // batch is not resent every backoff. A plan that does not allow
1221            // the sync parks it too, until the plan state stored with the
1222            // park changes. A `404` parks it only as the
1223            // `NOT_FOUND_PARK`-th in a row (spaced [`NOT_FOUND_SPACING`]):
1224            // a snapshot that rotated mid-clone or a proxy during a Cloud
1225            // deploy answers one too. That park is rechecked every
1226            // [`PARK_RECHECK`] and ends early when the link state stored with
1227            // it changes. A `401` parks nothing but holds the vault as
1228            // `needs_login` until the link state changes, rechecked after
1229            // [`LOGIN_RECHECK_FIRST`] and, refused again, every
1230            // [`LOGIN_RECHECK`] (a short Cloud auth outage heals by itself).
1231            // Only a success (or a change of the stored state) ends
1232            // a hold; another failure of a held vault keeps the long wait,
1233            // and its reason (`code`, `retry_after_s`).
1234            let was_login = row.needs_login;
1235            let unknown = is_unknown(error);
1236            if unknown {
1237                count_not_found(row, at);
1238            } else {
1239                row.not_found_streak = 0;
1240                row.not_found_at = None;
1241            }
1242            let login = matches!(error, CloudError::Unauthorized);
1243            let lost = unknown && row.not_found_streak >= NOT_FOUND_PARK;
1244            let parks = lost
1245                || matches!(
1246                    error,
1247                    CloudError::StorageFull(_) | CloudError::PlanRequired(_)
1248                );
1249            if parks || login || !holds(row) {
1250                // `not_found` names a park only; a `404` below the count is
1251                // an `error` that backs off.
1252                let code = if unknown && !lost {
1253                    "error"
1254                } else {
1255                    code_of(error)
1256                };
1257                row.code = Some(code.to_string());
1258                row.retry_after_s = error.retry_after_at(at);
1259            }
1260            if matches!(error, CloudError::PlanRequired(_)) {
1261                row.plan_park = Some((states.plan)());
1262                row.link_park = None;
1263            } else if lost || login {
1264                row.link_park = Some((states.link)());
1265                row.plan_park = None;
1266            } else if parks {
1267                row.plan_park = None;
1268                row.link_park = None;
1269            }
1270            // `needs_login` is no park: it replaces one, and a park
1271            // replaces it (Cloud took the credentials).
1272            row.parked = !login && (row.parked || parks);
1273            row.needs_login = login || (row.needs_login && !parks);
1274            run.parked = holds(row);
1275            let wait = if login && was_login {
1276                LOGIN_RECHECK
1277            } else if run.parked {
1278                park_wait(row)
1279            } else {
1280                failure_wait(error, run.failures, at)
1281            };
1282            run.due.retry_at = Some(now + wait);
1283            row.failures = run.failures;
1284            row.error = Some(error.to_string());
1285            // A plan park has no attempt planned: it waits for a change of
1286            // the plan state.
1287            row.next_attempt_at = (!waits_for_plan(row))
1288                .then(|| lean_ctx_time::Duration::from_std(wait).ok())
1289                .flatten()
1290                .map(|wait| stamp(at + wait));
1291            status.vaults.sort_by(|a, b| a.vault_id.cmp(&b.vault_id));
1292            return Some(wait);
1293        }
1294    }
1295    status.vaults.sort_by(|a, b| a.vault_id.cmp(&b.vault_id));
1296    None
1297}
1298
1299/// The one line a vault's hold leaves in the error log.
1300pub(crate) fn park_line(record: &VaultRecord, error: &CloudError) -> String {
1301    if matches!(error, CloudError::PlanRequired(_)) {
1302        return format!(
1303            "background sync: @{}/{} is paused: {error}. It is tried again when the plan changes, or by `lean-ctx cloud sync`",
1304            record.ns, record.name
1305        );
1306    }
1307    if matches!(error, CloudError::Unauthorized) {
1308        return format!(
1309            "background sync: @{}/{} is paused: {error}. It is also tried again after {} h, then every {} h, or by `lean-ctx cloud sync`",
1310            record.ns,
1311            record.name,
1312            LOGIN_RECHECK_FIRST.as_secs() / 3600,
1313            LOGIN_RECHECK.as_secs() / 3600
1314        );
1315    }
1316    if is_unknown(error) {
1317        return format!(
1318            "background sync: @{}/{} is paused: {error} ({NOT_FOUND_PARK} times in a row). It is tried again every {} h, after `lean-ctx cloud connect`, when `[cloud] url` changes, or by `lean-ctx cloud sync`",
1319            record.ns,
1320            record.name,
1321            PARK_RECHECK.as_secs() / 3600
1322        );
1323    }
1324    format!(
1325        "background sync: @{}/{} is paused: {error}. Run `lean-ctx cloud sync` once storage has room (it is also tried again every {} h)",
1326        record.ns,
1327        record.name,
1328        PARK_RECHECK.as_secs() / 3600
1329    )
1330}
1331
1332/// How long a vault waits after its `failures`-th failure in a row: what
1333/// Cloud asked for (`Retry-After` of a 429, a waiting quota's reset), else
1334/// the exponential backoff; never longer than `WAIT_MAX`. A `rate_limited`
1335/// in a row also backs off exponentially, with its `Retry-After` as the
1336/// floor: a server that keeps answering a short `Retry-After` is not asked
1337/// again at that pace forever (an upload rate limit names when its hour has
1338/// room again, so it waits exactly that).
1339pub(crate) fn failure_wait(
1340    error: &CloudError,
1341    failures: u32,
1342    now: lean_ctx_time::UtcDateTime,
1343) -> Duration {
1344    match error.retry_after_at(now) {
1345        Some(seconds) if matches!(error, CloudError::RateLimited { .. }) => {
1346            Duration::from_secs(seconds.max(1)).max(backoff(failures, jitter()))
1347        }
1348        Some(seconds) => Duration::from_secs(seconds.max(1)),
1349        None => backoff(failures, jitter()),
1350    }
1351    .min(WAIT_MAX)
1352}
1353
1354/// Record a manual `lean-ctx cloud sync` of `record` in the status, so the
1355/// app shows it like a background one. Called with the vault's sync lock:
1356/// a person's sync is never held to the shared budget, but it counts as an
1357/// attempt there (the burst cap of every other sync sees it), and its
1358/// result sets (or clears) the backoff every other sync keeps.
1359pub fn note_manual(
1360    store: &CloudStore,
1361    record: &VaultRecord,
1362    result: Result<&super::place::VaultSync, &CloudError>,
1363) {
1364    let wait = note_outside(store, record, Trigger::Manual, result);
1365    let now = UtcDateTime::now();
1366    super::budget::record(store.data_dir(), &record.vault_id, wait, now);
1367}
1368
1369/// Record a sync that ran outside this thread (the CLI, a push on write),
1370/// under the status lock; the wait a failure asks for (`None` on success).
1371pub(crate) fn note_outside(
1372    store: &CloudStore,
1373    record: &VaultRecord,
1374    trigger: Trigger,
1375    result: Result<&super::place::VaultSync, &CloudError>,
1376) -> Option<Duration> {
1377    let pending = pending_events(store, record);
1378    let plan = || plan_state(store);
1379    let link = || link_state(store, &lean_ctx::core::config::Config::load().cloud);
1380    let states = ParkStates {
1381        plan: &plan,
1382        link: &link,
1383    };
1384    with_status(store.data_dir(), |status| {
1385        let mut runs = BTreeMap::new();
1386        note(record, trigger, result, &mut runs, status, pending, &states)
1387    })
1388}
1389
1390#[cfg(test)]
1391#[path = "auto_tests.rs"]
1392mod tests;