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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
21#[serde(default)]
22pub struct Ledger {
23    /// Account scope this ledger belongs to (`AuthProvider::account_scope`).
24    pub scope: Option<String>,
25    pub change_token: Option<Vec<u8>>,
26    pub has_synced: bool,
27    /// Item id -> deletion time. Blocks re-import and re-upload forever.
28    pub tombstones: BTreeMap<String, i64>,
29    /// Tombstones still to be written to the zone.
30    pub pending_tombstones: BTreeSet<String>,
31    /// Last version known to exist remotely (survives cursor-only deltas).
32    pub remote_versions: BTreeMap<String, RemoteVersion>,
33    /// Logical id -> every record name seen for it (legacy duplicates).
34    pub aliases: BTreeMap<String, BTreeSet<String>>,
35    /// Offline queue: ids with local changes not yet confirmed uploaded.
36    pub pending_uploads: BTreeSet<String>,
37    /// Downloaded records whose local apply was deferred.
38    pub pending_apply: BTreeMap<String, RawRecord>,
39    /// Wall-clock ms before which no pass runs (backoff / server hint).
40    pub retry_after_ms: Option<i64>,
41    pub consecutive_failures: u32,
42    pub quarantined_total: u64,
43    /// One-shot migration markers (e.g. a full replay already done).
44    pub flags: BTreeSet<String>,
45    pub extras: Extras,
46}
47
48impl Ledger {
49    /// A deletion anywhere: forget pending work for the id, block it.
50    pub fn bury(&mut self, id: &str, deleted_at_ms: i64) {
51        self.tombstones.insert(id.to_string(), deleted_at_ms);
52        self.pending_uploads.remove(id);
53        self.pending_apply.remove(id);
54    }
55}
56
57pub struct LedgerStore {
58    storage: Box<dyn LedgerStorage>,
59    ledger: Ledger,
60    /// True when stored bytes existed but could not be decoded. The ledger
61    /// restarts empty, which forces a full zone replay; remote tombstones
62    /// are replayed with it, so deletions are not lost.
63    pub recovered_from_corruption: bool,
64}
65
66impl LedgerStore {
67    pub fn open(storage: Box<dyn LedgerStorage>) -> SyncResult<Self> {
68        let bytes = storage.load().map_err(SyncError::Persistence)?;
69        let (ledger, corrupt) = match bytes {
70            None => (Ledger::default(), false),
71            Some(b) => match serde_json::from_slice::<Ledger>(&b) {
72                Ok(l) => (l, false),
73                Err(_) => (Ledger::default(), true),
74            },
75        };
76        Ok(Self {
77            storage,
78            ledger,
79            recovered_from_corruption: corrupt,
80        })
81    }
82
83    pub fn ledger(&self) -> &Ledger {
84        &self.ledger
85    }
86
87    /// Mutate then persist; a failed write rolls the in-memory change back.
88    pub fn mutate<R>(&mut self, change: impl FnOnce(&mut Ledger) -> R) -> SyncResult<R> {
89        let before = self.ledger.clone();
90        let out = change(&mut self.ledger);
91        let bytes =
92            serde_json::to_vec(&self.ledger).map_err(|e| SyncError::Persistence(e.to_string()))?;
93        if let Err(e) = self.storage.save(&bytes) {
94            self.ledger = before;
95            return Err(SyncError::Persistence(e));
96        }
97        Ok(out)
98    }
99}