Skip to main content

rightkit_sync/
traits.rs

1//! Adapter traits. Apps implement these; the engine owns the algorithm.
2
3use std::collections::BTreeMap;
4
5use crate::error::SyncResult;
6use crate::record::RawRecord;
7
8/// Immutable identity + version of one syncable item.
9#[derive(Debug, Clone, PartialEq)]
10pub struct ItemHeader {
11    pub id: String,
12    /// Immutable origin timestamp; ordering key for publication.
13    pub created_at_ms: i64,
14    /// Version used for last-writer-wins.
15    pub updated_at_ms: i64,
16    pub origin_device: Option<String>,
17}
18
19/// Domain <-> wire mapping for the one syncable item type.
20pub trait RecordMapper: Send + Sync {
21    type Item: Clone + Send + Sync;
22
23    fn record_type(&self) -> &str;
24    fn header(&self, item: &Self::Item) -> ItemHeader;
25    /// Record name for an item id (default: the id itself).
26    fn record_name(&self, id: &str) -> String {
27        id.to_string()
28    }
29    /// Write the domain fields. The engine has already set `id`, `createdAt`
30    /// and `updatedAt` from `header` and cleared `deletedAt`.
31    fn encode(&self, item: &Self::Item, record: &mut RawRecord);
32    /// Decode a live (non-tombstone) record; `Err` quarantines the record.
33    fn decode(&self, record: &RawRecord) -> Result<Self::Item, String>;
34    /// Extra fields a tombstone keeps beyond `id`/`updatedAt`/`deletedAt`.
35    fn tombstone_keep_fields(&self) -> &[&str] {
36        &[]
37    }
38}
39
40/// Result of landing one downloaded item locally.
41#[derive(Debug, Clone, PartialEq)]
42pub enum ApplyOutcome {
43    Applied,
44    /// Could not land yet (engine busy, dependency missing). The engine
45    /// stashes the raw record durably and retries every pass, because the
46    /// change feed never replays it.
47    Deferred(String),
48}
49
50/// The app's local data. All calls are synchronous.
51pub trait LocalStore<T>: Send + Sync {
52    fn all(&self) -> SyncResult<Vec<T>>;
53    /// Remove a locally held item because of a tombstone. Idempotent.
54    fn remove(&self, id: &str) -> SyncResult<()>;
55    /// Upsert downloaded items; one outcome per input, in order. `Err`
56    /// aborts the pass WITHOUT advancing the change token.
57    fn apply_remote(&self, items: &[T]) -> SyncResult<Vec<ApplyOutcome>>;
58}
59
60/// Last-writer-wins by default. Tombstones and duplicate-alias reduction are
61/// fixed by the shared contract and not pluggable here.
62pub trait ConflictPolicy<T>: Send + Sync {
63    /// Should the local item overwrite the remote live record?
64    fn upload_local_over_remote(
65        &self,
66        local: &ItemHeader,
67        _local_item: &T,
68        remote: &ItemHeader,
69        _remote_item: &T,
70    ) -> bool {
71        local.updated_at_ms > remote.updated_at_ms
72    }
73    /// Should the remote live record replace the local item?
74    fn accept_remote_over_local(&self, local: &ItemHeader, remote: &ItemHeader) -> bool {
75        remote.updated_at_ms > local.updated_at_ms
76    }
77}
78
79pub struct LastWriterWins;
80impl<T> ConflictPolicy<T> for LastWriterWins {}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum SavePolicy {
84    /// Full-field overwrite (CloudKit `.allKeys`). The only policy the
85    /// engine uses: a write never needs a read first, and deletion is
86    /// authoritative.
87    Overwrite,
88    /// Conditional save (CloudKit `.ifServerRecordUnchanged`): the record's
89    /// `change_tag` must still be the server's (no tag = must not exist). A
90    /// mismatch yields `SyncError::Conflict` plus the server record in
91    /// `RecordOutcome::server_record`; the engine resolves it with the
92    /// conflict policy and retries, never overwriting blindly.
93    IfServerUnchanged,
94}
95
96#[derive(Debug, Default)]
97pub struct ChangePage {
98    pub records: Vec<RawRecord>,
99    /// Record names hard-deleted server-side.
100    pub deleted_record_names: Vec<String>,
101    pub new_token: Option<Vec<u8>>,
102    pub more_coming: bool,
103}
104
105#[derive(Debug, Clone)]
106pub struct RecordOutcome {
107    pub record_name: String,
108    pub result: SyncResult<()>,
109    /// Server's current record when `result` is `Err(Conflict)`.
110    pub server_record: Option<RawRecord>,
111}
112
113/// The cloud zone. Method set mirrors the iOS `CloudSyncService`.
114pub trait Backend: Send + Sync {
115    /// Create zone/subscription (idempotent).
116    fn prepare(&self) -> SyncResult<()>;
117    /// ONE delta page since `since` (None = first fetch). Report an expired
118    /// token as `SyncError::TokenExpired` and a missing zone as `ZoneMissing`.
119    fn fetch_changes(&self, since: Option<&[u8]>) -> SyncResult<ChangePage>;
120    /// Point read, used to obtain a change tag for a known record.
121    fn fetch_record(&self, record_name: &str) -> SyncResult<Option<RawRecord>>;
122    /// Non-atomic batch save: one outcome per input. `Err` = whole call failed.
123    fn save_records(
124        &self,
125        records: &[RawRecord],
126        policy: SavePolicy,
127    ) -> SyncResult<Vec<RecordOutcome>>;
128    fn max_batch(&self) -> usize {
129        200
130    }
131}
132
133/// Account state and session credentials. `generation` changes on account
134/// switch; an in-flight pass observing a different generation cancels itself.
135pub trait AuthProvider: Send + Sync {
136    /// Master switch (user toggle).
137    fn enabled(&self) -> bool {
138        true
139    }
140    fn availability(&self) -> SyncResult<()>;
141    fn generation(&self) -> u64 {
142        0
143    }
144    /// Stable opaque identity of the signed-in account/container/zone
145    /// (CloudKit helper: `sha256(container|zone|userRecordName)`), valid
146    /// after a successful `availability()`. The engine binds its ledger to
147    /// it and resets the ledger when it changes. `None` = no isolation.
148    fn account_scope(&self) -> Option<String> {
149        None
150    }
151    /// Bearer value for HTTP-style backends, fetched per pass by the app's
152    /// own secure store; CloudKit backends return None.
153    fn bearer(&self) -> SyncResult<Option<String>> {
154        Ok(None)
155    }
156}
157
158pub struct AlwaysAvailable;
159impl AuthProvider for AlwaysAvailable {
160    fn availability(&self) -> SyncResult<()> {
161        Ok(())
162    }
163}
164
165pub trait Clock: Send + Sync {
166    fn now_ms(&self) -> i64;
167}
168
169pub struct SystemClock;
170impl Clock for SystemClock {
171    fn now_ms(&self) -> i64 {
172        std::time::SystemTime::now()
173            .duration_since(std::time::UNIX_EPOCH)
174            .unwrap_or_default()
175            .as_millis() as i64
176    }
177}
178
179/// Free-form diagnostics hook (no logging dependency baked in).
180pub trait SyncObserver: Send + Sync {
181    fn event(&self, name: &'static str, detail: &str);
182}
183
184pub struct NullObserver;
185impl SyncObserver for NullObserver {
186    fn event(&self, _name: &'static str, _detail: &str) {}
187}
188
189/// Durable app-owned scratch the engine persists inside its ledger.
190pub type Extras = BTreeMap<String, serde_json::Value>;
191
192/// Optional domain extension for record types the engine does not own
193/// (device announcements, request queues, ...).
194pub trait PassHooks: Send + Sync {
195    /// Records to write at the start of a pass (e.g. device announce).
196    /// A failure to write them fails the pass.
197    fn outbound(&self, _extras: &mut Extras) -> Vec<RawRecord> {
198        Vec::new()
199    }
200    /// Records of other types seen in this pass's delta. Returned records are
201    /// written back; a failed write is reported and retried because the hook
202    /// must be idempotent over the ledger extras.
203    fn on_foreign_records(&self, _records: &[RawRecord], _extras: &mut Extras) -> Vec<RawRecord> {
204        Vec::new()
205    }
206    /// The account scope changed. The engine resets its own ledger for the
207    /// new scope (its `extras` start empty again); drop any app-owned state
208    /// that belonged to `from`.
209    fn on_account_switch(&self, _from: &str, _to: &str) {}
210}
211
212pub struct NoHooks;
213impl PassHooks for NoHooks {}