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    /// Optional paged listing so a pass never materialises the whole store. Return up to
54    /// `limit` items whose `ItemHeader::id` is strictly greater (byte-wise) than `after`
55    /// (`None` = from the start), in ascending id order, with no item skipped or repeated across
56    /// consecutive calls over an unchanged store. `Ok(None)` (the default) means the store does
57    /// not page and the engine falls back to `all()`; it must answer the same way on every call.
58    fn list_page(&self, _after: Option<&str>, _limit: usize) -> SyncResult<Option<Vec<T>>> {
59        Ok(None)
60    }
61    /// Remove a locally held item because of a tombstone. Idempotent.
62    fn remove(&self, id: &str) -> SyncResult<()>;
63    /// Upsert downloaded items; one outcome per input, in order. `Err`
64    /// aborts the pass WITHOUT advancing the change token.
65    fn apply_remote(&self, items: &[T]) -> SyncResult<Vec<ApplyOutcome>>;
66}
67
68/// Last-writer-wins by default. Tombstones and duplicate-alias reduction are
69/// fixed by the shared contract and not pluggable here.
70pub trait ConflictPolicy<T>: Send + Sync {
71    /// Should the local item overwrite the remote live record?
72    fn upload_local_over_remote(
73        &self,
74        local: &ItemHeader,
75        _local_item: &T,
76        remote: &ItemHeader,
77        _remote_item: &T,
78    ) -> bool {
79        local.updated_at_ms > remote.updated_at_ms
80    }
81    /// Should the remote live record replace the local item?
82    fn accept_remote_over_local(&self, local: &ItemHeader, remote: &ItemHeader) -> bool {
83        remote.updated_at_ms > local.updated_at_ms
84    }
85}
86
87pub struct LastWriterWins;
88impl<T> ConflictPolicy<T> for LastWriterWins {}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum SavePolicy {
92    /// Full-field overwrite (CloudKit `.allKeys`). The only policy the
93    /// engine uses: a write never needs a read first, and deletion is
94    /// authoritative.
95    Overwrite,
96    /// Conditional save (CloudKit `.ifServerRecordUnchanged`): the record's
97    /// `change_tag` must still be the server's (no tag = must not exist). A
98    /// mismatch yields `SyncError::Conflict` plus the server record in
99    /// `RecordOutcome::server_record`; the engine resolves it with the
100    /// conflict policy and retries, never overwriting blindly.
101    IfServerUnchanged,
102}
103
104#[derive(Debug, Default)]
105pub struct ChangePage {
106    pub records: Vec<RawRecord>,
107    /// Record names hard-deleted server-side.
108    pub deleted_record_names: Vec<String>,
109    pub new_token: Option<Vec<u8>>,
110    pub more_coming: bool,
111}
112
113#[derive(Debug, Clone)]
114pub struct RecordOutcome {
115    pub record_name: String,
116    pub result: SyncResult<()>,
117    /// Server's current record when `result` is `Err(Conflict)`.
118    pub server_record: Option<RawRecord>,
119}
120
121/// The cloud zone. Method set mirrors the iOS `CloudSyncService`.
122pub trait Backend: Send + Sync {
123    /// Create zone/subscription (idempotent).
124    fn prepare(&self) -> SyncResult<()>;
125    /// ONE delta page since `since` (None = first fetch). Report an expired
126    /// token as `SyncError::TokenExpired` and a missing zone as `ZoneMissing`.
127    fn fetch_changes(&self, since: Option<&[u8]>) -> SyncResult<ChangePage>;
128    /// Point read, used to obtain a change tag for a known record.
129    fn fetch_record(&self, record_name: &str) -> SyncResult<Option<RawRecord>>;
130    /// Non-atomic batch save: one outcome per input. `Err` = whole call failed.
131    fn save_records(
132        &self,
133        records: &[RawRecord],
134        policy: SavePolicy,
135    ) -> SyncResult<Vec<RecordOutcome>>;
136    fn max_batch(&self) -> usize {
137        200
138    }
139}
140
141/// Account state and session credentials. `generation` changes on account
142/// switch; an in-flight pass observing a different generation cancels itself.
143pub trait AuthProvider: Send + Sync {
144    /// Master switch (user toggle).
145    fn enabled(&self) -> bool {
146        true
147    }
148    fn availability(&self) -> SyncResult<()>;
149    fn generation(&self) -> u64 {
150        0
151    }
152    /// Stable opaque identity of the signed-in account/container/zone
153    /// (CloudKit helper: `sha256(container|zone|userRecordName)`), valid
154    /// after a successful `availability()`. The engine binds its ledger to
155    /// it and resets the ledger when it changes. `None` = no isolation.
156    fn account_scope(&self) -> Option<String> {
157        None
158    }
159    /// Bearer value for HTTP-style backends, fetched per pass by the app's
160    /// own secure store; CloudKit backends return None.
161    fn bearer(&self) -> SyncResult<Option<String>> {
162        Ok(None)
163    }
164}
165
166pub struct AlwaysAvailable;
167impl AuthProvider for AlwaysAvailable {
168    fn availability(&self) -> SyncResult<()> {
169        Ok(())
170    }
171}
172
173pub trait Clock: Send + Sync {
174    fn now_ms(&self) -> i64;
175}
176
177pub struct SystemClock;
178impl Clock for SystemClock {
179    fn now_ms(&self) -> i64 {
180        std::time::SystemTime::now()
181            .duration_since(std::time::UNIX_EPOCH)
182            .unwrap_or_default()
183            .as_millis() as i64
184    }
185}
186
187/// Free-form diagnostics hook (no logging dependency baked in).
188pub trait SyncObserver: Send + Sync {
189    fn event(&self, name: &'static str, detail: &str);
190}
191
192pub struct NullObserver;
193impl SyncObserver for NullObserver {
194    fn event(&self, _name: &'static str, _detail: &str) {}
195}
196
197/// Durable app-owned scratch the engine persists inside its ledger.
198pub type Extras = BTreeMap<String, serde_json::Value>;
199
200/// Optional domain extension for record types the engine does not own
201/// (device announcements, request queues, ...).
202pub trait PassHooks: Send + Sync {
203    /// Records to write at the start of a pass (e.g. device announce).
204    /// A failure to write them fails the pass.
205    fn outbound(&self, _extras: &mut Extras) -> Vec<RawRecord> {
206        Vec::new()
207    }
208    /// Records of other types seen in this pass's delta. Returned records are
209    /// written back; a failed write is reported and retried because the hook
210    /// must be idempotent over the ledger extras.
211    fn on_foreign_records(&self, _records: &[RawRecord], _extras: &mut Extras) -> Vec<RawRecord> {
212        Vec::new()
213    }
214    /// The account scope changed. The engine resets its own ledger for the
215    /// new scope (its `extras` start empty again); drop any app-owned state
216    /// that belonged to `from`.
217    fn on_account_switch(&self, _from: &str, _to: &str) {}
218}
219
220pub struct NoHooks;
221impl PassHooks for NoHooks {}