Skip to main content

rightkit_sync/
ledger.rs

1//! The durable sync ledger: change token, tombstones, remote versions,
2//! offline queues. One atomic document, so token and version cache can never
3//! disagree (iOS keeps them separate and needs a replay rule for that).
4
5use std::collections::{BTreeMap, BTreeSet};
6
7use serde::{Deserialize, Serialize};
8
9use crate::error::{SyncError, SyncResult};
10use crate::record::RawRecord;
11use crate::storage::LedgerStorage;
12use crate::traits::Extras;
13
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
15pub struct RemoteVersion {
16    pub record_name: String,
17    pub updated_at_ms: i64,
18}
19
20/// A change of the signed-in account or sync scope that the app has not yet consented to.
21/// `from` is the scope the local store last synced with; `to` is the scope now signed in.
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct ConsentRequest {
24    pub from: String,
25    pub to: String,
26}
27
28#[derive(Debug, Clone, Default, Serialize, Deserialize)]
29#[serde(default)]
30pub struct Ledger {
31    /// Account scope this ledger belongs to (`AuthProvider::account_scope`).
32    pub scope: Option<String>,
33    /// Set while sync is paused on a scope change awaiting consent
34    /// (`SyncConfig::require_consent_on_scope_change`). Durable with the bound `scope`.
35    pub pending_consent: Option<ConsentRequest>,
36    /// Item ids that existed locally when the user chose `ConsentChoice::StartFresh`: they stay
37    /// on this device and are never published to the new account.
38    pub withheld: BTreeSet<String>,
39    pub change_token: Option<Vec<u8>>,
40    pub has_synced: bool,
41    /// Item id -> deletion time. Blocks re-import and re-upload forever.
42    pub tombstones: BTreeMap<String, i64>,
43    /// Tombstones still to be written to the zone.
44    pub pending_tombstones: BTreeSet<String>,
45    /// Last version known to exist remotely (survives cursor-only deltas).
46    pub remote_versions: BTreeMap<String, RemoteVersion>,
47    /// Logical id -> every record name seen for it (legacy duplicates).
48    pub aliases: BTreeMap<String, BTreeSet<String>>,
49    /// Offline queue: ids with local changes not yet confirmed uploaded.
50    pub pending_uploads: BTreeSet<String>,
51    /// Downloaded records whose local apply was deferred.
52    pub pending_apply: BTreeMap<String, RawRecord>,
53    /// Wall-clock ms before which no pass runs (backoff / server hint).
54    pub retry_after_ms: Option<i64>,
55    pub consecutive_failures: u32,
56    pub quarantined_total: u64,
57    /// One-shot migration markers (e.g. a full replay already done).
58    pub flags: BTreeSet<String>,
59    pub extras: Extras,
60}
61
62impl Ledger {
63    /// A deletion anywhere: forget pending work for the id, block it.
64    pub fn bury(&mut self, id: &str, deleted_at_ms: i64) {
65        self.tombstones.insert(id.to_string(), deleted_at_ms);
66        self.pending_uploads.remove(id);
67        self.pending_apply.remove(id);
68    }
69}
70
71pub struct LedgerStore {
72    storage: Box<dyn LedgerStorage>,
73    ledger: Ledger,
74    /// The bytes last persisted (or loaded intact): the rollback source. `None` while the
75    /// in-memory ledger is the empty default that was never written or was reset after
76    /// corruption. Keeping the encoded form instead of cloning the ledger per mutation bounds
77    /// the cost to one compact buffer that each successful save replaces.
78    saved: Option<Vec<u8>>,
79    /// True when stored bytes existed but could not be decoded. The ledger
80    /// restarts empty, which forces a full zone replay; remote tombstones
81    /// are replayed with it, so deletions are not lost.
82    pub recovered_from_corruption: bool,
83}
84
85impl LedgerStore {
86    pub fn open(storage: Box<dyn LedgerStorage>) -> SyncResult<Self> {
87        let bytes = storage.load().map_err(SyncError::Persistence)?;
88        let (ledger, saved, corrupt) = match bytes {
89            None => (Ledger::default(), None, false),
90            Some(b) => match serde_json::from_slice::<Ledger>(&b) {
91                Ok(l) => (l, Some(b), false),
92                Err(_) => (Ledger::default(), None, true),
93            },
94        };
95        Ok(Self {
96            storage,
97            ledger,
98            saved,
99            recovered_from_corruption: corrupt,
100        })
101    }
102
103    pub fn ledger(&self) -> &Ledger {
104        &self.ledger
105    }
106
107    /// Mutate then persist; a failed write rolls the in-memory change back.
108    pub fn mutate<R>(&mut self, change: impl FnOnce(&mut Ledger) -> R) -> SyncResult<R> {
109        let out = change(&mut self.ledger);
110        let bytes = match serde_json::to_vec(&self.ledger) {
111            Ok(b) => b,
112            Err(e) => {
113                self.rollback();
114                return Err(SyncError::Persistence(e.to_string()));
115            }
116        };
117        if let Err(e) = self.storage.save(&bytes) {
118            self.rollback();
119            return Err(SyncError::Persistence(e));
120        }
121        self.saved = Some(bytes);
122        Ok(out)
123    }
124
125    /// Restore the in-memory ledger to the last persisted state (the decode `open` uses).
126    fn rollback(&mut self) {
127        self.ledger = match &self.saved {
128            None => Ledger::default(),
129            Some(b) => serde_json::from_slice(b).unwrap_or_default(),
130        };
131    }
132}