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    let dir = sync_dir(data_dir);
478    let lock = std::fs::create_dir_all(&dir).ok().and_then(|()| {
479        std::fs::OpenOptions::new()
480            .create(true)
481            .truncate(false)
482            .write(true)
483            .open(dir.join(STATUS_LOCK))
484            .ok()
485    });
486    // Unlocked when dropped (see `VaultLock`). A failed lock is ignored: the
487    // change is still made, and unlocking an unlocked file is harmless.
488    let lock = lock.map(|file| {
489        let _ = fs2::FileExt::lock_exclusive(&file);
490        VaultLock {
491            _guard: lean_ctx::core::file_lock::FlockGuard::from_locked(file),
492        }
493    });
494    let mut status = load_status(data_dir);
495    let out = change(&mut status);
496    save_status(data_dir, &status);
497    drop(lock);
498    out
499}
500
501/// Write the thread's `status`, keeping what other processes noted since
502/// (see [`merge_manual`]), under the status lock.
503fn store_status(data_dir: &Path, status: &mut SyncStatus, shared: &VaultMap) {
504    with_status(data_dir, |disk| {
505        merge_manual(status, disk, shared);
506        disk.clone_from(status);
507    });
508}
509
510pub fn load_status(data_dir: &Path) -> SyncStatus {
511    std::fs::read(sync_dir(data_dir).join(STATUS_FILE))
512        .ok()
513        .and_then(|b| serde_json::from_slice(&b).ok())
514        .unwrap_or_default()
515}
516
517fn save_status(data_dir: &Path, status: &SyncStatus) {
518    if let Ok(bytes) = serde_json::to_vec_pretty(status) {
519        let _ = write_private(&sync_dir(data_dir), STATUS_FILE, &bytes);
520    }
521}
522
523fn stamp(at: lean_ctx_time::UtcDateTime) -> String {
524    at.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
525}
526
527// ---------------------------------------------------------------------------
528// Single flight with `lean-ctx cloud sync`.
529
530/// A held vault sync lock (or the status lock). Dropping it unlocks the
531/// file explicitly before closing it: closing alone does not release an
532/// `flock` while a child process forked meanwhile by another thread (a
533/// `git` spawn, say) still holds a copy of the descriptor, and the next
534/// sync of the vault would find it busy until that child execs or exits.
535#[derive(Debug)]
536pub struct VaultLock {
537    _guard: lean_ctx::core::file_lock::FlockGuard,
538}
539
540/// The advisory lock of one vault's sync. `wait`: block until free (the
541/// CLI); otherwise `Ok(None)` when another sync holds it (the thread skips).
542pub fn lock_vault(
543    data_dir: &Path,
544    vault_id: &str,
545    wait: bool,
546) -> Result<Option<VaultLock>, CloudError> {
547    use fs2::FileExt as _;
548    let local = |e: std::io::Error| CloudError::Local(format!("sync lock: {e}"));
549    let dir = sync_dir(data_dir);
550    std::fs::create_dir_all(&dir).map_err(local)?;
551    let file = std::fs::OpenOptions::new()
552        .create(true)
553        .truncate(false)
554        .write(true)
555        .open(dir.join(format!("{}.lock", lock_name(vault_id))))
556        .map_err(local)?;
557    if wait {
558        let guard = lean_ctx::core::file_lock::FlockGuard::exclusive(file).map_err(local)?;
559        return Ok(Some(VaultLock { _guard: guard }));
560    }
561    match file.try_lock_exclusive() {
562        Ok(()) => Ok(Some(VaultLock {
563            _guard: lean_ctx::core::file_lock::FlockGuard::from_locked(file),
564        })),
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
831/// A folder the person unlinked is no sync root; a damaged opt-out store
832/// holds every root back (fail closed, bd 39936).
833fn without_unlinked(data: &Path, map: &mut VaultMap) {
834    for record in map.vaults.values_mut() {
835        record
836            .roots
837            .retain(|root| !crate::unlinked::contains(data, Path::new(root)));
838    }
839}
840
841fn run(store: &CloudStore, mut config: CloudConfig) {
842    let data = store.data_dir().to_path_buf();
843    let mut status = load_status(&data);
844    let mut runs: BTreeMap<String, VaultRun> = BTreeMap::new();
845    let mut last_write: Option<Instant> = None;
846    let mut reloaded = Instant::now();
847    let mut sleep = POLL;
848    while !STOPPED.load(Ordering::SeqCst) {
849        let nudged = wait(sleep);
850        if STOPPED.load(Ordering::SeqCst) {
851            break;
852        }
853        if reloaded.elapsed() >= Duration::from_secs(60) {
854            config = lean_ctx::core::config::Config::load().cloud.clone();
855            reloaded = Instant::now();
856        }
857        // A `plan_required` park waits for the plan state, not for time; a
858        // `not_found` park or a `needs_login` hold ends with a login or
859        // reconnect, or another configured Cloud.
860        unpark_plan(&mut status, &plan_state(store));
861        unpark_link(&mut status, &link_state(store, &config));
862        let interval = Duration::from_secs(u64::from(config.pull_interval()) * 60);
863        status.interval_s = interval.as_secs();
864        let mut map = current_map(store);
865        without_unlinked(&data, &mut map);
866        let active = config.enabled != Some(false) && crate::bus::relay_v2::speaks_v2(store);
867        let due_now = plan_pass(
868            &map,
869            &mut runs,
870            &mut status,
871            &nudged,
872            Instant::now(),
873            interval,
874            active,
875            &|record, root| mark_of(&data, record, root),
876        );
877        let mut wrote = false;
878        if !due_now.is_empty() {
879            match pass(store, &config, &due_now, &mut runs, &mut status) {
880                Ok(()) => {}
881                Err(PassEnd::Stop(reason)) => {
882                    store.record_error(&format!("background sync: {reason}"));
883                    store_status(&data, &mut status, &map);
884                    break;
885                }
886            }
887            status.last_pass_at = Some(stamp(UtcDateTime::now()));
888            wrote = true;
889        }
890        if wrote || last_write.is_none_or(|at| at.elapsed() >= HEARTBEAT) {
891            status.heartbeat_at = Some(stamp(UtcDateTime::now()));
892            store_status(&data, &mut status, &map);
893            last_write = Some(Instant::now());
894        }
895        sleep = next_wake(runs.values().map(|run| &run.due), Instant::now());
896    }
897    status.heartbeat_at = None;
898    store_status(&data, &mut status, &current_map(store));
899}
900
901/// The vault map without stale resolutions (dropped from the file; when
902/// that write fails, still left out of this pass): a pass never plans a
903/// vault the checkout left. Records of another Cloud are left out (rc3-81).
904fn current_map(store: &CloudStore) -> VaultMap {
905    let scope = crate::vault::connected_scope(store);
906    let map = match crate::resolution::load_current(store.data_dir(), scope.as_deref()) {
907        Ok((map, _)) => map,
908        Err(error) => {
909            store.record_error(&format!("background sync: {error}"));
910            crate::resolution::current_view(store.data_dir(), scope.as_deref())
911        }
912    };
913    crate::vault::for_connected(store, map)
914}
915
916/// Keep the rows a manual `cloud sync` wrote to the file since this thread
917/// last wrote it (newer `last_sync_at`). A row of a vault no longer shared
918/// on this machine (not in `shared`) is not brought back.
919pub(crate) fn merge_manual(status: &mut SyncStatus, disk: &SyncStatus, shared: &VaultMap) {
920    let shared: BTreeSet<String> = shared
921        .vaults
922        .values()
923        .map(|record| super::place::place_id(&record.vault_id))
924        .collect();
925    status.vaults.retain(|v| shared.contains(&v.vault_id));
926    for row in disk.vaults.iter().filter(|v| shared.contains(&v.vault_id)) {
927        match status
928            .vaults
929            .iter_mut()
930            .find(|v| v.vault_id == row.vault_id)
931        {
932            Some(mine) if row.last_sync_at > mine.last_sync_at => *mine = row.clone(),
933            Some(_) => {}
934            None => status.vaults.push(row.clone()),
935        }
936    }
937    status.vaults.sort_by(|a, b| a.vault_id.cmp(&b.vault_id));
938}
939
940/// One pass's plan: look at every shared vault's local marks (`mark`), take
941/// the bus nudges, and return the vaults to sync now (purges first, then the
942/// oldest attempt; at most [`MAX_PER_PASS`]). Nothing is planned while not
943/// `active` (Cloud off, not C0 2.x), but local changes are still noted.
944#[allow(clippy::too_many_arguments)]
945fn plan_pass(
946    map: &VaultMap,
947    runs: &mut BTreeMap<String, VaultRun>,
948    status: &mut SyncStatus,
949    nudged: &BTreeMap<String, Trigger>,
950    now: Instant,
951    interval: Duration,
952    active: bool,
953    mark: &dyn Fn(&VaultRecord, &str) -> Mark,
954) -> Vec<(VaultRecord, String, Trigger)> {
955    let mut due_now: Vec<(VaultRecord, String, Trigger)> = Vec::new();
956    let mut seen = BTreeSet::new();
957    for record in map.vaults.values() {
958        let vault = super::place::place_id(&record.vault_id);
959        if !seen.insert(vault.clone()) {
960            continue;
961        }
962        let Some(root) = root_of(record) else {
963            continue;
964        };
965        let run = runs.entry(vault.clone()).or_default();
966        adopt_park(run, row_park(status, &vault), now);
967        if let Some(trigger) = nudged.get(&vault) {
968            run.due.urgent = Some(run.due.urgent.map_or(*trigger, |t| t.max(*trigger)));
969        }
970        let now_mark = mark(record, &root);
971        match &run.mark {
972            // The first look is the baseline, not a change.
973            None => run.mark = Some(now_mark),
974            Some(previous) if *previous != now_mark => {
975                run.due.last_change = Some(now);
976                run.due.first_change.get_or_insert(now);
977                run.mark = Some(now_mark);
978            }
979            Some(_) => {}
980        }
981        if !active {
982            continue;
983        }
984        if let Some(trigger) = decide(&run.due, now, interval) {
985            due_now.push((record.clone(), root, trigger));
986        }
987    }
988    // Vaults no longer shared on this machine leave the status.
989    runs.retain(|vault, _| seen.contains(vault));
990    status.vaults.retain(|v| seen.contains(&v.vault_id));
991    // Purges first, then the oldest attempt.
992    due_now.sort_by_key(|(record, _, trigger)| {
993        let vault = super::place::place_id(&record.vault_id);
994        (
995            *trigger != Trigger::BusPurge,
996            runs.get(&vault).and_then(|r| r.due.last_attempt),
997        )
998    });
999    due_now.truncate(MAX_PER_PASS);
1000    due_now
1001}
1002
1003enum PassEnd {
1004    Stop(String),
1005}
1006
1007fn pass(
1008    store: &CloudStore,
1009    config: &CloudConfig,
1010    due: &[(VaultRecord, String, Trigger)],
1011    runs: &mut BTreeMap<String, VaultRun>,
1012    status: &mut SyncStatus,
1013) -> Result<(), PassEnd> {
1014    let data = store.data_dir().to_path_buf();
1015    let plan = || plan_state(store);
1016    let link = || link_state(store, config);
1017    let states = ParkStates {
1018        plan: &plan,
1019        link: &link,
1020    };
1021    let mut screen = crate::knowledge::screening::Screen::for_installation();
1022    // A screening rule that does not compile pauses every content channel.
1023    let session = match screen.problem() {
1024        Some(problem) => Err(CloudError::Local(problem)),
1025        None => crate::scheduler::connected_session(store, config),
1026    };
1027    let session = match session {
1028        Ok(session) => session,
1029        Err(
1030            error @ (CloudError::Revoked(_) | CloudError::LeaseLapsed | CloudError::NotConnected),
1031        ) => {
1032            return Err(PassEnd::Stop(error.to_string()));
1033        }
1034        Err(error) => {
1035            // Offline or a local refusal: every due vault waits.
1036            for (record, _, trigger) in due {
1037                note(record, *trigger, Err(&error), runs, status, None, &states);
1038            }
1039            return Ok(());
1040        }
1041    };
1042    for (record, root, trigger) in due {
1043        let Ok(lock) = lock_vault(&data, &record.vault_id, false) else {
1044            continue;
1045        };
1046        // A manual `cloud sync` holds it: its result is just as good.
1047        let Some(_lock) = lock else {
1048            continue;
1049        };
1050        // The budget every process of this machine shares: a push on write
1051        // that just ran (or failed and backs off) counts here too. Held
1052        // back, the vault stays due and goes out once the budget allows.
1053        let purge = *trigger == Trigger::BusPurge;
1054        if super::budget::admit_sync(&data, &record.vault_id, purge, UtcDateTime::now())
1055            != super::budget::Admit::Go
1056        {
1057            continue;
1058        }
1059        // The journal as this sync starts: it captures what is written up
1060        // to here, nothing written while it runs.
1061        let before = mark_of(&data, record, root);
1062        let was_parked = row_parked(status, &super::place::place_id(&record.vault_id));
1063        let done = super::place::sync_vault(&session, record, Path::new(root), &mut screen);
1064        let pending = pending_events(store, record);
1065        let wait = match done {
1066            Ok(done) => {
1067                let wait = note(record, *trigger, Ok(&done), runs, status, pending, &states);
1068                // A fresh session's `ctx_tasks` answers from this cache.
1069                if let Err(error) = crate::tasks::cache::warm(Path::new(root)) {
1070                    tracing::debug!(
1071                        "cloud: task lists of {} not warmed: {error}",
1072                        record.vault_id
1073                    );
1074                }
1075                wait
1076            }
1077            Err(error @ (CloudError::Revoked(_) | CloudError::LeaseLapsed)) => {
1078                let wait = note(
1079                    record,
1080                    *trigger,
1081                    Err(&error),
1082                    runs,
1083                    status,
1084                    pending,
1085                    &states,
1086                );
1087                super::budget::settle(&data, &record.vault_id, wait, UtcDateTime::now());
1088                return Err(PassEnd::Stop(error.to_string()));
1089            }
1090            Err(error) => {
1091                let wait = note(
1092                    record,
1093                    *trigger,
1094                    Err(&error),
1095                    runs,
1096                    status,
1097                    pending,
1098                    &states,
1099                );
1100                // Said once, when the vault becomes held; the status row
1101                // keeps it.
1102                if !was_parked && row_parked(status, &super::place::place_id(&record.vault_id)) {
1103                    store.record_error(&park_line(record, &error));
1104                }
1105                wait
1106            }
1107        };
1108        super::budget::settle(&data, &record.vault_id, wait, UtcDateTime::now());
1109        // What this sync wrote itself is not a local change; a fact
1110        // remembered while it ran is.
1111        if let Some(run) = runs.get_mut(&super::place::place_id(&record.vault_id)) {
1112            run.mark = Some(before.after_sync(&mark_of(&data, record, root)));
1113        }
1114    }
1115    // LeanCTX Cloud usage (capability `usage` only, at most every 10 min):
1116    // one log line when a quota first reaches warn (80 %) or full.
1117    crate::usage::background(&session, UtcDateTime::now());
1118    // Task proposals queued locally go out with the vault sync.
1119    for problem in crate::tasks::propose::drain(&session).problems {
1120        store.record_error(&format!("tasks: {problem}"));
1121    }
1122    // Workers no session used for a day, and those of ended app sessions,
1123    // leave the book and are retired on Cloud (owner 09.11.: workers that
1124    // are not active do not count).
1125    if let Err(error) = crate::workers::register::sweep(&session) {
1126        store.record_error(&format!("worker retirement: {error}"));
1127    }
1128    Ok(())
1129}
1130
1131/// Signed events of `record` still waiting for Cloud; `None` when the
1132/// replica cannot be read (no replica yet, no key).
1133fn pending_events(store: &CloudStore, record: &VaultRecord) -> Option<u64> {
1134    if !crate::replica::store::place_dir(store.data_dir(), &record.vault_id).is_dir() {
1135        return Some(0);
1136    }
1137    let (mk, _) = crate::replica::crypt::master_key(store.config_dir(), false).ok()?;
1138    let (replica, _) =
1139        crate::replica::Replica::open(store.data_dir(), &record.vault_id, &mk).ok()?;
1140    replica
1141        .pending()
1142        .ok()
1143        .map(|p| u64::try_from(p.len()).unwrap_or(u64::MAX))
1144}
1145
1146/// The states a hold that waits for a change (not for time) is stored with,
1147/// each read only when a failure takes a hold for that reason.
1148pub(crate) struct ParkStates<'a> {
1149    /// This machine's plan state ([`plan_state`]), for `plan_required`.
1150    pub plan: &'a dyn Fn() -> String,
1151    /// This machine's link state ([`link_state`]), for a `not_found` park
1152    /// and for `needs_login`.
1153    pub link: &'a dyn Fn() -> String,
1154}
1155
1156/// Count the `404` noted `at` towards a `not_found` park: only when it
1157/// comes at least [`NOT_FOUND_SPACING`] after the last counted one (or is
1158/// the first). An unreadable stamp counts as none.
1159fn count_not_found(row: &mut VaultSyncStatus, at: UtcDateTime) {
1160    let spaced = row
1161        .not_found_at
1162        .as_deref()
1163        .and_then(|t| lean_ctx_time::OffsetDateTime::parse_from_rfc3339(t).ok())
1164        .is_none_or(|last| {
1165            (at - last.to_utc()).num_seconds()
1166                >= i64::try_from(NOT_FOUND_SPACING.as_secs()).unwrap_or(i64::MAX)
1167        });
1168    if spaced {
1169        row.not_found_streak = row.not_found_streak.saturating_add(1);
1170        row.not_found_at = Some(stamp(at));
1171    }
1172}
1173
1174/// Note one sync's `result` in `runs` and `status`; the wait a failure asks
1175/// for (`None` on success). `states` gives the plan state, read only when
1176/// the failure is `plan_required`, and the link state, read only when it
1177/// parks as `not_found` or is a `401` (each stored with its hold).
1178fn note(
1179    record: &VaultRecord,
1180    trigger: Trigger,
1181    result: Result<&super::place::VaultSync, &CloudError>,
1182    runs: &mut BTreeMap<String, VaultRun>,
1183    status: &mut SyncStatus,
1184    pending: Option<u64>,
1185    states: &ParkStates<'_>,
1186) -> Option<Duration> {
1187    let vault = super::place::place_id(&record.vault_id);
1188    let now = Instant::now();
1189    let at = UtcDateTime::now();
1190    let run = runs.entry(vault.clone()).or_default();
1191    run.due.attempted(now);
1192    let index = status
1193        .vaults
1194        .iter()
1195        .position(|v| v.vault_id == vault)
1196        .unwrap_or_else(|| {
1197            status.vaults.push(VaultSyncStatus {
1198                vault_id: vault.clone(),
1199                ..VaultSyncStatus::default()
1200            });
1201            status.vaults.len() - 1
1202        });
1203    let row = &mut status.vaults[index];
1204    row.vault = format!("@{}/{}", record.ns, record.name);
1205    row.last_sync_at = Some(stamp(at));
1206    row.last_trigger = Some(trigger.as_str().to_string());
1207    if let Some(pending) = pending {
1208        row.pending = pending;
1209    }
1210    match result {
1211        Ok(done) => {
1212            run.failures = 0;
1213            run.due.retry_at = None;
1214            run.parked = false;
1215            row.failures = 0;
1216            row.error = None;
1217            row.next_attempt_at = None;
1218            row.parked = false;
1219            row.needs_login = false;
1220            row.code = None;
1221            row.retry_after_s = None;
1222            row.plan_park = None;
1223            row.link_park = None;
1224            row.not_found_streak = 0;
1225            row.not_found_at = None;
1226            row.last_ok_at = Some(stamp(at));
1227            row.stored = u64::try_from(done.stored).unwrap_or(u64::MAX);
1228            row.pushed = u64::try_from(done.pushed).unwrap_or(u64::MAX);
1229        }
1230        Err(error) => {
1231            run.failures = row.failures.max(run.failures).saturating_add(1);
1232            // Storage full parks the vault: waiting does not free it, so the
1233            // batch is not resent every backoff. A plan that does not allow
1234            // the sync parks it too, until the plan state stored with the
1235            // park changes. A `404` parks it only as the
1236            // `NOT_FOUND_PARK`-th in a row (spaced [`NOT_FOUND_SPACING`]):
1237            // a snapshot that rotated mid-clone or a proxy during a Cloud
1238            // deploy answers one too. That park is rechecked every
1239            // [`PARK_RECHECK`] and ends early when the link state stored with
1240            // it changes. A `401` parks nothing but holds the vault as
1241            // `needs_login` until the link state changes, rechecked after
1242            // [`LOGIN_RECHECK_FIRST`] and, refused again, every
1243            // [`LOGIN_RECHECK`] (a short Cloud auth outage heals by itself).
1244            // Only a success (or a change of the stored state) ends
1245            // a hold; another failure of a held vault keeps the long wait,
1246            // and its reason (`code`, `retry_after_s`).
1247            let was_login = row.needs_login;
1248            let unknown = is_unknown(error);
1249            if unknown {
1250                count_not_found(row, at);
1251            } else {
1252                row.not_found_streak = 0;
1253                row.not_found_at = None;
1254            }
1255            let login = matches!(error, CloudError::Unauthorized);
1256            let lost = unknown && row.not_found_streak >= NOT_FOUND_PARK;
1257            let parks = lost
1258                || matches!(
1259                    error,
1260                    CloudError::StorageFull(_) | CloudError::PlanRequired(_)
1261                );
1262            if parks || login || !holds(row) {
1263                // `not_found` names a park only; a `404` below the count is
1264                // an `error` that backs off.
1265                let code = if unknown && !lost {
1266                    "error"
1267                } else {
1268                    code_of(error)
1269                };
1270                row.code = Some(code.to_string());
1271                row.retry_after_s = error.retry_after_at(at);
1272            }
1273            if matches!(error, CloudError::PlanRequired(_)) {
1274                row.plan_park = Some((states.plan)());
1275                row.link_park = None;
1276            } else if lost || login {
1277                row.link_park = Some((states.link)());
1278                row.plan_park = None;
1279            } else if parks {
1280                row.plan_park = None;
1281                row.link_park = None;
1282            }
1283            // `needs_login` is no park: it replaces one, and a park
1284            // replaces it (Cloud took the credentials).
1285            row.parked = !login && (row.parked || parks);
1286            row.needs_login = login || (row.needs_login && !parks);
1287            run.parked = holds(row);
1288            let wait = if login && was_login {
1289                LOGIN_RECHECK
1290            } else if run.parked {
1291                park_wait(row)
1292            } else {
1293                failure_wait(error, run.failures, at)
1294            };
1295            run.due.retry_at = Some(now + wait);
1296            row.failures = run.failures;
1297            row.error = Some(error.to_string());
1298            // A plan park has no attempt planned: it waits for a change of
1299            // the plan state.
1300            row.next_attempt_at = (!waits_for_plan(row))
1301                .then(|| lean_ctx_time::Duration::from_std(wait).ok())
1302                .flatten()
1303                .map(|wait| stamp(at + wait));
1304            status.vaults.sort_by(|a, b| a.vault_id.cmp(&b.vault_id));
1305            return Some(wait);
1306        }
1307    }
1308    status.vaults.sort_by(|a, b| a.vault_id.cmp(&b.vault_id));
1309    None
1310}
1311
1312/// The one line a vault's hold leaves in the error log.
1313pub(crate) fn park_line(record: &VaultRecord, error: &CloudError) -> String {
1314    if matches!(error, CloudError::PlanRequired(_)) {
1315        return format!(
1316            "background sync: @{}/{} is paused: {error}. It is tried again when the plan changes, or by `lean-ctx cloud sync`",
1317            record.ns, record.name
1318        );
1319    }
1320    if matches!(error, CloudError::Unauthorized) {
1321        return format!(
1322            "background sync: @{}/{} is paused: {error}. It is also tried again after {} h, then every {} h, or by `lean-ctx cloud sync`",
1323            record.ns,
1324            record.name,
1325            LOGIN_RECHECK_FIRST.as_secs() / 3600,
1326            LOGIN_RECHECK.as_secs() / 3600
1327        );
1328    }
1329    if is_unknown(error) {
1330        return format!(
1331            "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`",
1332            record.ns,
1333            record.name,
1334            PARK_RECHECK.as_secs() / 3600
1335        );
1336    }
1337    format!(
1338        "background sync: @{}/{} is paused: {error}. Run `lean-ctx cloud sync` once storage has room (it is also tried again every {} h)",
1339        record.ns,
1340        record.name,
1341        PARK_RECHECK.as_secs() / 3600
1342    )
1343}
1344
1345/// How long a vault waits after its `failures`-th failure in a row: what
1346/// Cloud asked for (`Retry-After` of a 429, a waiting quota's reset), else
1347/// the exponential backoff; never longer than `WAIT_MAX`. A `rate_limited`
1348/// in a row also backs off exponentially, with its `Retry-After` as the
1349/// floor: a server that keeps answering a short `Retry-After` is not asked
1350/// again at that pace forever (an upload rate limit names when its hour has
1351/// room again, so it waits exactly that).
1352pub(crate) fn failure_wait(
1353    error: &CloudError,
1354    failures: u32,
1355    now: lean_ctx_time::UtcDateTime,
1356) -> Duration {
1357    match error.retry_after_at(now) {
1358        Some(seconds) if matches!(error, CloudError::RateLimited { .. }) => {
1359            Duration::from_secs(seconds.max(1)).max(backoff(failures, jitter()))
1360        }
1361        Some(seconds) => Duration::from_secs(seconds.max(1)),
1362        None => backoff(failures, jitter()),
1363    }
1364    .min(WAIT_MAX)
1365}
1366
1367/// Record a manual `lean-ctx cloud sync` of `record` in the status, so the
1368/// app shows it like a background one. Called with the vault's sync lock:
1369/// a person's sync is never held to the shared budget, but it counts as an
1370/// attempt there (the burst cap of every other sync sees it), and its
1371/// result sets (or clears) the backoff every other sync keeps.
1372pub fn note_manual(
1373    store: &CloudStore,
1374    record: &VaultRecord,
1375    result: Result<&super::place::VaultSync, &CloudError>,
1376) {
1377    let wait = note_outside(store, record, Trigger::Manual, result);
1378    let now = UtcDateTime::now();
1379    super::budget::record(store.data_dir(), &record.vault_id, wait, now);
1380}
1381
1382/// Record a sync that ran outside this thread (the CLI, a push on write),
1383/// under the status lock; the wait a failure asks for (`None` on success).
1384pub(crate) fn note_outside(
1385    store: &CloudStore,
1386    record: &VaultRecord,
1387    trigger: Trigger,
1388    result: Result<&super::place::VaultSync, &CloudError>,
1389) -> Option<Duration> {
1390    let pending = pending_events(store, record);
1391    let plan = || plan_state(store);
1392    let link = || link_state(store, &lean_ctx::core::config::Config::load().cloud);
1393    let states = ParkStates {
1394        plan: &plan,
1395        link: &link,
1396    };
1397    with_status(store.data_dir(), |status| {
1398        let mut runs = BTreeMap::new();
1399        note(record, trigger, result, &mut runs, status, pending, &states)
1400    })
1401}
1402
1403#[cfg(test)]
1404#[path = "auto_tests.rs"]
1405mod tests;