Skip to main content

coven_database/
internal_schema_sync_status.rs

1//! What this installation's sync state is computed from that the sync loop
2//! knows (§19.1, api.md E4, E5), kept as a table so the app's live queries
3//! and local triggers can follow it (§9.4), as they follow `coven_pins`.
4//!
5//! It has one row from the store's creation on, which says no storage is set
6//! up until the first open writes over it, so a read always finds one. Each
7//! fact is written in the step that changes it: opening writes whether a
8//! location is recorded and this device holds its credentials (`storage`,
9//! with the location's `provider` and the `location` itself, with its
10//! labels) and that no pass moves; a connection that records a new label of
11//! the location writes it again; setup, joining
12//! and restoring write storage set up and their finish as the last synced
13//! time; each start of sync adds one to `starts`, so even a start that ends
14//! the way the last one did writes the row; a store-wide worker's panic
15//! halts sync until the store reopens (`halted`), after which no pass writes
16//! the row; the loop writes what its pass moved last, a slot it read or one it claimed (`moved`) and how the
17//! pass ended (`last_pass`, which sync encodes as JSON and the app reads as
18//! `LastPass`), with a synced pass's finish as `last_synced`, in milliseconds
19//! since the Unix epoch by the store's clock. That time never goes backward:
20//! a write keeps the later of it and the new one, so a clock set back moves
21//! nothing.
22//!
23//! Only the handle that holds the store's writer lock reads it: a read-only
24//! handle can't tell whether that writer still runs, so app SQL there may not
25//! read the table (`app_policy.rs`).
26
27use crate::sqlite::StoreSql;
28use crate::DbError;
29use std::time::SystemTime;
30
31/// The sync status table, which the app's triggers may follow.
32pub(crate) const SYNC_STATUS: &str = "coven_sync_status";
33
34/// Records the location, for `save_location` and its outside-store form.
35const SAVE_LOCATION: &str = "UPDATE coven_sync_status SET storage=?1,provider=?2,location=?5,
36             moved=CASE WHEN ?4 THEN NULL ELSE moved END,
37             halted=CASE WHEN ?4 THEN 0 ELSE halted END,
38             last_synced=CASE WHEN ?3 IS NULL THEN last_synced
39                 ELSE max(coalesce(last_synced,?3),?3) END
40         WHERE singleton=1 AND (storage IS NOT ?1 OR provider IS NOT ?2 OR location IS NOT ?5
41             OR (?4 AND (moved IS NOT NULL OR halted=1))
42             OR (?3 IS NOT NULL AND (last_synced IS NULL OR last_synced<?3)))";
43
44/// Records how the last pass ended, for `save_last_pass` and its
45/// outside-store form.
46const SAVE_LAST_PASS: &str = "UPDATE coven_sync_status SET last_pass=?1,moved=NULL
47         WHERE singleton=1 AND halted=0 AND (last_pass IS NOT ?1 OR moved IS NOT NULL)";
48
49/// The table and its one row, as every store holds them from its creation.
50pub(super) const TABLE: &str = "CREATE TABLE coven_sync_status (
51        singleton INTEGER PRIMARY KEY NOT NULL CHECK(singleton=1),
52        storage TEXT NOT NULL CHECK(storage IN ('none','signed_out','connected')),
53        provider TEXT,
54        location TEXT,
55        last_pass BLOB,
56        moved TEXT CHECK(moved IN ('read','claimed')),
57        last_synced INTEGER CHECK(last_synced>=0),
58        starts INTEGER NOT NULL CHECK(starts>=0),
59        halted INTEGER NOT NULL CHECK(halted IN (0,1)),
60        CHECK((storage='none')=(provider IS NULL)),
61        CHECK((storage='none')=(location IS NULL))
62    ) STRICT;
63    INSERT INTO coven_sync_status(singleton,storage,provider,location,last_pass,moved,last_synced,starts,halted)
64        VALUES(1,'none',NULL,NULL,NULL,NULL,NULL,0,0);";
65
66/// Whether a storage location is recorded on this device, and whether this
67/// device holds credentials for it (§19.1), with the location's provider.
68/// The database keeps the provider as the name sync gives it.
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub enum RecordedLocation<P> {
71    /// No location is recorded.
72    None,
73    /// A location is recorded, but this device holds no credentials for it.
74    SignedOut(P),
75    /// A location is recorded, and this device holds its credentials.
76    Connected(P),
77}
78
79impl<P> RecordedLocation<P> {
80    /// A location is recorded and this device holds its credentials.
81    pub fn is_connected(&self) -> bool {
82        matches!(self, Self::Connected(_))
83    }
84
85    /// The same location, with its provider as `name` gives it.
86    pub fn map<Q>(self, name: impl FnOnce(P) -> Q) -> RecordedLocation<Q> {
87        match self {
88            Self::None => RecordedLocation::None,
89            Self::SignedOut(provider) => RecordedLocation::SignedOut(name(provider)),
90            Self::Connected(provider) => RecordedLocation::Connected(name(provider)),
91        }
92    }
93
94    /// The same location, with its provider as `name` gives it, or the
95    /// error `name` fails with.
96    pub fn try_map<Q, E>(
97        self,
98        name: impl FnOnce(P) -> Result<Q, E>,
99    ) -> Result<RecordedLocation<Q>, E> {
100        Ok(match self {
101            Self::None => RecordedLocation::None,
102            Self::SignedOut(provider) => RecordedLocation::SignedOut(name(provider)?),
103            Self::Connected(provider) => RecordedLocation::Connected(name(provider)?),
104        })
105    }
106}
107
108/// What a running pass moved: a slot it read that it hadn't, or one it claimed
109/// for a write (§19.1). The sync state shows syncing, receiving or sending.
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub enum PassMove {
112    /// The pass read a slot it hadn't.
113    Read,
114    /// The pass claimed a slot.
115    Claimed,
116}
117
118impl PassMove {
119    fn column(self) -> &'static str {
120        match self {
121            Self::Read => "read",
122            Self::Claimed => "claimed",
123        }
124    }
125
126    fn from_column(column: &str) -> Result<Self, DbError> {
127        match column {
128            "read" => Ok(Self::Read),
129            "claimed" => Ok(Self::Claimed),
130            _ => Err(DbError::DamagedDatabase),
131        }
132    }
133}
134
135/// A recorded location as `coven_sync_status` keeps it: its provider's
136/// name, which the sync state reads, and the location with its labels, as
137/// the text the app reads as `StorageConfig` (api.md E4).
138#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct StoredLocation {
140    /// The provider's name, as sync gives it.
141    pub provider: String,
142    /// The location with its labels, as the settings file's text.
143    pub location: String,
144}
145
146/// `coven_sync_status`'s row as it is read.
147#[derive(Clone, Debug, PartialEq, Eq)]
148pub struct SyncStatusRow {
149    /// Whether a location is recorded and its credentials held.
150    pub location: RecordedLocation<String>,
151    /// How the last pass ended, as sync encodes it; none until a pass ends
152    /// on this device.
153    pub last_pass: Option<Vec<u8>>,
154    /// What the running pass moved last; none while it has moved nothing.
155    pub moved: Option<PassMove>,
156    /// When a pass last reached the end of the sequence, or setup, joining
157    /// or restoring finished, by the store's clock.
158    pub last_synced: Option<SystemTime>,
159}
160
161/// Milliseconds since the Unix epoch, rounded down so a stored finish never
162/// comes after the pass's own.
163fn millis(time: SystemTime) -> Result<i64, DbError> {
164    crate::stored_millis::since_epoch(time, crate::stored_millis::Round::Down).ok_or(
165        DbError::Invariant {
166            what: "a sync finishes between the Unix epoch and SQLite's last millisecond",
167        },
168    )
169}
170
171/// The `storage` column of `location`, with what it stores of the location.
172fn columns(location: &RecordedLocation<StoredLocation>) -> (&'static str, Option<&StoredLocation>) {
173    match location {
174        RecordedLocation::None => ("none", None),
175        RecordedLocation::SignedOut(stored) => ("signed_out", Some(stored)),
176        RecordedLocation::Connected(stored) => ("connected", Some(stored)),
177    }
178}
179
180/// The row as it stands.
181#[cfg(test)]
182pub(crate) fn read(db: &StoreSql) -> Result<SyncStatusRow, DbError> {
183    db.query_row(
184        "SELECT storage,provider,last_pass,moved,last_synced FROM coven_sync_status
185         WHERE singleton=1",
186        [],
187        |row| Ok(decode(row, 0)),
188    )?
189}
190
191/// The row from `storage`, `provider`, `last_pass`, `moved` and
192/// `last_synced`, in that order from `first` on. For a value the table's
193/// checks would refuse, `decode` returns `DamagedDatabase`.
194pub(crate) fn decode(
195    values: &impl crate::sync_facts::FactValues,
196    first: usize,
197) -> Result<SyncStatusRow, DbError> {
198    let storage: String = values.get(first)?;
199    let provider: Option<String> = values.get(first + 1)?;
200    let moved: Option<String> = values.get(first + 3)?;
201    let last_synced: Option<i64> = values.get(first + 4)?;
202    let location = match (storage.as_str(), provider) {
203        ("none", None) => RecordedLocation::None,
204        ("signed_out", Some(provider)) => RecordedLocation::SignedOut(provider),
205        ("connected", Some(provider)) => RecordedLocation::Connected(provider),
206        _ => return Err(DbError::DamagedDatabase),
207    };
208    Ok(SyncStatusRow {
209        location,
210        last_pass: values.get(first + 2)?,
211        moved: moved.as_deref().map(PassMove::from_column).transpose()?,
212        last_synced: last_synced.map(crate::stored_millis::stored_time).transpose()?,
213    })
214}
215
216/// Save `$location` on `$db`, a store's open write or a test's connection
217/// outside any store, with `$finished` in milliseconds and whether `$opening`.
218/// Both expand this one body, so a test records a location as a store does.
219macro_rules! save_location_row {
220    ($db:expr, $location:expr, $finished:expr, $opening:expr) => {{
221        let (storage, stored) = columns($location);
222        let provider = stored.map(|stored| stored.provider.as_str());
223        let recorded = stored.map(|stored| stored.location.as_str());
224        let finished: Option<i64> = $finished;
225        $db.execute(
226            SAVE_LOCATION,
227            sqlive::rusqlite::params![storage, provider, finished, $opening, recorded],
228        )?;
229        Ok::<(), DbError>(())
230    }};
231}
232
233/// Write whether a location is recorded and its credentials held, with the
234/// location and its labels, and, when `finished` names one, that sync
235/// finished then. Opening also writes that no pass moves and that no halt
236/// holds. A row that already says this is left alone.
237pub(crate) fn save_location(
238    db: &StoreSql,
239    location: &RecordedLocation<StoredLocation>,
240    finished: Option<SystemTime>,
241    opening: bool,
242) -> Result<(), DbError> {
243    let finished = finished.map(millis).transpose()?;
244    save_location_row!(db, location, finished, opening)
245}
246
247/// Write what the running pass moved last, when that changes it.
248pub(crate) fn save_moved(db: &StoreSql, moved: PassMove) -> Result<(), DbError> {
249    db.execute(
250        "UPDATE coven_sync_status SET moved=?1 WHERE singleton=1 AND halted=0 AND moved IS NOT ?1",
251        [moved.column()],
252    )?;
253    Ok(())
254}
255
256/// Write that sync started once more.
257pub(crate) fn save_start(db: &StoreSql) -> Result<(), DbError> {
258    db.execute("UPDATE coven_sync_status SET starts=starts+1 WHERE singleton=1", [])?;
259    Ok(())
260}
261
262/// Write how the last pass ended, as sync encodes it, when sync failed
263/// outside a pass's end, and that nothing moves: a loop that ends in a pass
264/// that moved a slot shows its failure, never syncing. Once a halt holds,
265/// it writes nothing: the halt's failure stands.
266pub(crate) fn save_last_pass(db: &StoreSql, last_pass: &[u8]) -> Result<(), DbError> {
267    db.execute(SAVE_LAST_PASS, [last_pass])?;
268    Ok(())
269}
270
271/// Write `location` as the recorded location on `connection`, a test's
272/// connection outside any store, as `save_location` does.
273#[cfg(any(test, feature = "test-utils"))]
274pub fn save_location_outside_store(
275    connection: &sqlive::rusqlite::Connection,
276    location: &RecordedLocation<StoredLocation>,
277) -> Result<(), DbError> {
278    save_location_row!(connection, location, None, false)
279}
280
281/// Write `last_pass` as how the last pass ended on `connection`, a test's
282/// connection outside any store, as `save_last_pass` does.
283#[cfg(any(test, feature = "test-utils"))]
284pub fn save_last_pass_outside_store(
285    connection: &sqlive::rusqlite::Connection,
286    last_pass: &[u8],
287) -> Result<(), DbError> {
288    connection.execute(SAVE_LAST_PASS, [last_pass])?;
289    Ok(())
290}
291
292/// Write that a store-wide worker's panic halted sync until the store
293/// reopens, with its failure as how the last pass ended, and that nothing
294/// moves: from here no pass writes the row.
295pub(crate) fn save_halt(db: &StoreSql, last_pass: &[u8]) -> Result<(), DbError> {
296    db.execute(
297        "UPDATE coven_sync_status SET last_pass=?1,moved=NULL,halted=1 WHERE singleton=1",
298        [last_pass],
299    )?;
300    Ok(())
301}
302
303/// Write how the running pass ended and that it moves no more, and, when
304/// `finished` names one, that it reached the end of the sequence then. A
305/// pass that ends after a halt writes nothing: the halt's failure stands.
306pub(crate) fn save_pass_end(
307    db: &StoreSql,
308    last_pass: &[u8],
309    finished: Option<SystemTime>,
310) -> Result<(), DbError> {
311    let finished = finished.map(millis).transpose()?;
312    db.execute(
313        "UPDATE coven_sync_status SET last_pass=?1,moved=NULL,
314             last_synced=CASE WHEN ?2 IS NULL THEN last_synced
315                 ELSE max(coalesce(last_synced,?2),?2) END
316         WHERE singleton=1 AND halted=0 AND (last_pass IS NOT ?1 OR moved IS NOT NULL
317             OR (?2 IS NOT NULL AND (last_synced IS NULL OR last_synced<?2)))",
318        sqlive::rusqlite::params![last_pass, finished],
319    )?;
320    Ok(())
321}
322
323#[cfg(test)]
324#[path = "internal_schema_sync_status_tests.rs"]
325mod tests;