Skip to main content

coven_sync/
sync_status.rs

1//! The sync state a status screen shows (§19.1, api.md E5), computed in one
2//! read from what coven knows and never stored: whether a location is
3//! recorded and its credentials held, how the last pass ended, what the
4//! running pass moved, each bound upload in the queue, whether the
5//! send queue holds a write, and the pending records the state reads. Each
6//! fact names one candidate state or none, and when several hold the one of
7//! highest rank shows, as `state` of the Lean model in
8//! `spec/proofs/io/CovenIO/SyncState.lean` computes it; the differential
9//! test checks this against that model's runner.
10//!
11//! A trailing upload never reaches the state. What it is doing is its
12//! phase in the upload queue, computed from the same facts by
13//! `Facts::upload_phase` as the model's `Upload.phase` in `Transfers.lean`
14//! computes it.
15//!
16//! The database registers `SyncStatus::row` as the SQL function
17//! `_coven_sync_state` (`sync_functions`), which the `coven_sync_state`
18//! view calls over the facts it reads: an app's screen reads the state in
19//! its own live query, joined to its rows, and this code stays the one
20//! definition of the state that the Lean model checks. `sync_status` reads
21//! the view.
22
23use crate::{
24    DeviceIdEvidence, KeyHolder, LastPass, LocalFailure, PendingReason, PendingRecord,
25    Prerequisite, StatusFailure, SyncError,
26};
27use coven_database::{
28    DbError, RecordedLocation, Removal, RetrySync, SqlReadContext, SyncFacts, SyncStateRow,
29    UnsentWork,
30};
31use coven_foundation::id_source::{KeyId, MemberId};
32use coven_merge::Audience;
33use coven_storage::{CloudProvider, StorageFailure};
34use std::time::SystemTime;
35
36/// What a status screen shows (E5, §19.1): the sync state and when sync
37/// last finished, as `coven_sync_state` shows them and `sync_status()` reads
38/// them.
39#[derive(Clone, Debug, PartialEq)]
40pub struct SyncStatus {
41    /// The sync state.
42    pub state: SyncState,
43    /// When a pass last reached the end of the sequence, by the store's
44    /// clock; kept across every state and never earlier than before.
45    pub last_synced: Option<SystemTime>,
46}
47
48/// The sync state (§19.1). With several candidates, the first of `Removed`,
49/// `NeedsReset`, `UpdateNeeded`, `SignedOut`, `NoAccess`, `FolderMissing`,
50/// `ClockWrong`, `StorageFull`, `OfflineWithUnsentChanges`, `Offline`,
51/// `Failed`, `Syncing`, `WaitingToSync`, `Synced` shows; `NotSynced` comes
52/// before them all. `coven_sync_state.detail` holds it as JSON, which this
53/// type reads.
54#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
55pub enum SyncState {
56    /// No storage location is recorded on this device.
57    NotSynced,
58    /// Work that clears by itself is under way or next in line, with
59    /// nothing holding it: what moves now, else a bound file, else a write,
60    /// else the next pass.
61    Syncing(SyncActivity),
62    /// Nothing moves, and something holds the work for a while: the last
63    /// pass was held back, at a slot that can't apply yet or by a provider's
64    /// cooldown, or it or a bound file waits out a retry, or a write in the
65    /// send queue waits for the pass: what the pass waits for, else what the
66    /// first such file waits for, else what the write waits for.
67    WaitingToSync(SyncWait),
68    /// The last pass reached the end of the sequence, every bound file this
69    /// device uploads is stored, the send queue is empty, and nothing below
70    /// holds: nothing waits. A trailing file never holds it.
71    Synced,
72    /// The last pass got no provider response.
73    Offline(SyncCause),
74    /// Offline, and the send queue holds a write or the upload queue a bound
75    /// file with bytes to send.
76    OfflineWithUnsentChanges(SyncCause),
77    /// A location is recorded, but this device holds no credentials for it
78    /// (no cause), or storage refused them.
79    SignedOut {
80        /// The recorded location's provider.
81        provider: CloudProvider,
82        /// What refused the credentials; none when this device holds none.
83        cause: Option<SyncCause>,
84    },
85    /// Signed in, but the account isn't allowed.
86    NoAccess(SyncCause),
87    /// The provider's quota is used up.
88    StorageFull(SyncCause),
89    /// The storage folder or bucket is gone.
90    FolderMissing(SyncCause),
91    /// The device's clock is too far from the provider's.
92    ClockWrong(SyncCause),
93    /// A newer app or coven is needed.
94    UpdateNeeded(SyncCause),
95    /// This device isn't in the store, and won't be again. What was written
96    /// here and not sent never will be.
97    Removed {
98        /// Why this device isn't in the store.
99        removal: Removal,
100        /// What this device committed and will not send.
101        unsent: UnsentWork,
102    },
103    /// This installation can't send under its keys or id. What was written
104    /// here and not sent never will be.
105    NeedsReset {
106        /// Why it can't send.
107        reason: ResetReason,
108        /// What this device committed and will not send.
109        unsent: UnsentWork,
110    },
111    /// Any other failure, or a bound file that can't be uploaded or read,
112    /// whose pending record is the cause.
113    Failed(SyncCause),
114}
115
116/// Why this installation can't send under its keys or id, as `NeedsReset`
117/// names it (§19.3, §12.3).
118#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
119pub enum ResetReason {
120    /// A reset or restore registered another installation in this one's place
121    /// (§19.3).
122    Replaced,
123    /// Another installation uses this device's id: this copy is the one
124    /// behind, which the app resets without asking, and the reset registers a
125    /// new device (§19.3).
126    DeviceIdInUse,
127    /// This member's keys were replaced with a pair this device doesn't hold
128    /// (§12.3).
129    MemberKeysReplaced {
130        /// The member whose held keys were replaced.
131        member: MemberId,
132    },
133}
134
135/// What Syncing is doing, as `Syncing` names it (§19.1): the first of what the
136/// running pass moved last, a bound file moving or next in line, a write next
137/// in line, and the next pass's turn.
138#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
139pub enum SyncActivity {
140    /// The running pass reads slots it hadn't, which are changes from other
141    /// devices; or the next pass's turn has come, after a cooldown or a
142    /// newer floor.
143    Receiving,
144    /// A write goes out: the pass claimed a slot for one, or one waits in the
145    /// send queue with nothing holding it.
146    Sending,
147    /// A bound file uploads or waits its turn in the bound lane; the writes
148    /// it holds go out once it is stored.
149    UploadingBoundFile,
150}
151
152/// What waiting to sync waits for, as `WaitingToSync` names it: what holds
153/// every transfer, the pass's and each file's alike, first; then, for a
154/// bound file waiting in the upload queue, what holds that file, then a
155/// write's own key (§19.1).
156#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
157pub enum SyncWait {
158    /// Sync isn't running (`start_sync`, `stop_sync`).
159    NotSyncing,
160    /// The provider asked every request to wait until then (§6.7).
161    CoolingDown {
162        /// When the cooldown ends, by the store's clock.
163        until: SystemTime,
164    },
165    /// A slot, or the first write in the send queue, needs a key this device
166    /// holds no copy of; another device of a member holding it sends one
167    /// (§12.1). A slot waiting on it holds everything: nothing goes out or
168    /// comes in until the key arrives (§5.4).
169    KeyCopy {
170        /// The key's audience.
171        #[serde(with = "crate::pending_encoding::audience")]
172        audience: Audience,
173        /// The key.
174        key: KeyId,
175        /// The members that hold the key, as the history this device applied
176        /// names them: their devices to open, or, for a holder that no longer
177        /// reads the audience, a member of the audience to add it back (§12.1).
178        /// Empty only when the record was made without the history; a key no
179        /// member holds is never sent, and shows Failed.
180        holders: Vec<KeyHolder>,
181    },
182    /// A slot holds a raise or reset of `audience`, and no snapshot announced
183    /// after it is named yet; another device takes one (§16.5). Nothing goes
184    /// out or comes in until then.
185    Snapshot {
186        /// The audience whose snapshot is awaited.
187        #[serde(with = "crate::pending_encoding::audience")]
188        audience: Audience,
189    },
190    /// A failure that clears by itself and names no state of its own, on the
191    /// pass, a slot's application, coven's own operation or a bound file's
192    /// attempt, has failed, and the next try is then, or at the person's
193    /// retry (§6.7); the pending list says why.
194    Retrying {
195        /// When its backoff ends, by the store's clock.
196        at: SystemTime,
197    },
198}
199
200/// What names a state: the last pass, or the first pending record, in the
201/// order they arose, that names it, with the cause `coven_pending` keeps.
202#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
203pub enum SyncCause {
204    /// How the last pass ended.
205    Pass(LastPass),
206    /// A pending record.
207    Pending(#[serde(with = "with_cause")] PendingRecord),
208}
209
210/// Encodes a pending record that names a state together with its cause,
211/// because the record's own encoding leaves the cause to
212/// `coven_pending.cause`.
213mod with_cause {
214    use crate::PendingRecord;
215
216    #[derive(serde::Serialize, serde::Deserialize)]
217    struct Recorded {
218        record: PendingRecord,
219        cause: Option<String>,
220    }
221
222    pub(super) fn serialize<S: serde::Serializer>(
223        record: &PendingRecord,
224        serializer: S,
225    ) -> Result<S::Ok, S::Error> {
226        serde::Serialize::serialize(
227            &Recorded { record: record.clone(), cause: record.cause.clone() },
228            serializer,
229        )
230    }
231
232    pub(super) fn deserialize<'de, D: serde::Deserializer<'de>>(
233        deserializer: D,
234    ) -> Result<PendingRecord, D::Error> {
235        let Recorded { mut record, cause } = serde::Deserialize::deserialize(deserializer)?;
236        record.cause = cause;
237        Ok(record)
238    }
239}
240
241/// The states that name a cause, as the model's `State.named` lists them;
242/// removed and needs reset name the removal or reset reason instead.
243#[derive(Clone, Copy, Debug, PartialEq, Eq)]
244enum Named {
245    SignedOut,
246    NoAccess,
247    StorageFull,
248    FolderMissing,
249    ClockWrong,
250    UpdateNeeded,
251    Removed(Removal),
252    NeedsReset(ResetReason),
253    Failed,
254}
255
256impl Named {
257    /// Its place among the states, as `SyncState::rank` orders them.
258    fn rank(self) -> u8 {
259        match self {
260            Self::Failed => 3,
261            Self::StorageFull => 6,
262            Self::ClockWrong => 7,
263            Self::FolderMissing => 8,
264            Self::NoAccess => 9,
265            Self::SignedOut => 10,
266            Self::UpdateNeeded => 11,
267            Self::NeedsReset(_) => 12,
268            Self::Removed(_) => 13,
269        }
270    }
271
272    /// The state, named by `cause`, at a location of `provider`; the
273    /// standing states say what is unsent instead.
274    fn state(self, cause: SyncCause, provider: CloudProvider, unsent: UnsentWork) -> SyncState {
275        match self {
276            Self::SignedOut => SyncState::SignedOut { provider, cause: Some(cause) },
277            Self::NoAccess => SyncState::NoAccess(cause),
278            Self::StorageFull => SyncState::StorageFull(cause),
279            Self::FolderMissing => SyncState::FolderMissing(cause),
280            Self::ClockWrong => SyncState::ClockWrong(cause),
281            Self::UpdateNeeded => SyncState::UpdateNeeded(cause),
282            Self::Removed(removal) => SyncState::Removed { removal, unsent },
283            Self::NeedsReset(reason) => SyncState::NeedsReset { reason, unsent },
284            Self::Failed => SyncState::Failed(cause),
285        }
286    }
287}
288
289impl SyncState {
290    /// The state's kind, as `coven_sync_state.state` names it.
291    fn kind(&self) -> &'static str {
292        match self {
293            Self::NotSynced => "not_synced",
294            Self::Syncing(_) => "syncing",
295            Self::WaitingToSync(_) => "waiting_to_sync",
296            Self::Synced => "synced",
297            Self::Offline(_) => "offline",
298            Self::OfflineWithUnsentChanges(_) => "offline_with_unsent_changes",
299            Self::SignedOut { .. } => "signed_out",
300            Self::NoAccess(_) => "no_access",
301            Self::StorageFull(_) => "storage_full",
302            Self::FolderMissing(_) => "folder_missing",
303            Self::ClockWrong(_) => "clock_wrong",
304            Self::UpdateNeeded(_) => "update_needed",
305            Self::Removed { .. } => "removed",
306            Self::NeedsReset { .. } => "needs_reset",
307            Self::Failed(_) => "failed",
308        }
309    }
310
311    /// What names the state, where something does.
312    fn cause(&self) -> Option<&SyncCause> {
313        match self {
314            Self::Offline(cause)
315            | Self::OfflineWithUnsentChanges(cause)
316            | Self::NoAccess(cause)
317            | Self::StorageFull(cause)
318            | Self::FolderMissing(cause)
319            | Self::ClockWrong(cause)
320            | Self::UpdateNeeded(cause)
321            | Self::Failed(cause) => Some(cause),
322            Self::SignedOut { cause, .. } => cause.as_ref(),
323            Self::NotSynced
324            | Self::Syncing(_)
325            | Self::WaitingToSync(_)
326            | Self::Synced
327            | Self::Removed { .. }
328            | Self::NeedsReset { .. } => None,
329        }
330    }
331
332    /// Which state shows when several hold: the highest. The device's own
333    /// standing first, then signing in, then what storage said of the
334    /// account or location, then reachability, then the catch-all failure,
335    /// then activity: syncing, then waiting.
336    fn rank(&self) -> u8 {
337        match self {
338            Self::Synced => 0,
339            Self::WaitingToSync(_) => 1,
340            Self::Syncing(_) => 2,
341            Self::Failed(_) => Named::Failed.rank(),
342            Self::Offline(_) => 4,
343            Self::OfflineWithUnsentChanges(_) => 5,
344            Self::StorageFull(_) => Named::StorageFull.rank(),
345            Self::ClockWrong(_) => Named::ClockWrong.rank(),
346            Self::FolderMissing(_) => Named::FolderMissing.rank(),
347            Self::NoAccess(_) => Named::NoAccess.rank(),
348            Self::SignedOut { .. } => Named::SignedOut.rank(),
349            Self::UpdateNeeded(_) => Named::UpdateNeeded.rank(),
350            Self::NeedsReset { reason, .. } => Named::NeedsReset(*reason).rank(),
351            Self::Removed { removal, .. } => Named::Removed(*removal).rank(),
352            Self::NotSynced => 14,
353        }
354    }
355}
356
357/// The state a provider failure names: what storage said of this account or
358/// location that a person must see, or coven's own bug (the model's
359/// `Failure.named`).
360#[deny(clippy::wildcard_enum_match_arm)]
361fn storage_names(failure: StorageFailure) -> Option<Named> {
362    use StorageFailure::*;
363    match failure {
364        Authentication => Some(Named::SignedOut),
365        PermissionDenied | AccessNotGranted { .. } => Some(Named::NoAccess),
366        QuotaExceeded => Some(Named::StorageFull),
367        ContainerNotFound => Some(Named::FolderMissing),
368        ClockSkew => Some(Named::ClockWrong),
369        // Its work retries, as a local bug's does, and shows failed meanwhile.
370        Bug => Some(Named::Failed),
371        ProviderUnavailable
372        | AccessNotRegistered { .. }
373        | DropboxAppFolderNotShareable
374        | CatchUpRequired
375        | Network
376        | Corrupted
377        | NotFound
378        | AlreadyExists
379        | Conflict
380        | RegionMismatch
381        | StoreExists
382        | OwnLocationRequired
383        | RateLimited
384        | InvalidConfiguration
385        | Refused
386        | Protocol
387        | InvalidPath
388        | InvalidRange
389        | NotStoreOwner
390        | InviteeIsStoreOwner
391        | SharingRefused(_)
392        | AccountIdUnavailable
393        | InvitationMismatch
394        | SessionMismatch
395        | SessionExpired
396        | InvalidPart
397        | SingleRequestTooLarge { .. }
398        | CopyTooLarge { .. }
399        | Encoding
400        | File
401        | MemberKeysMissing => None,
402    }
403}
404
405impl PendingReason {
406    /// The state a pending record names, by its reason (the model's
407    /// `Reason.state`). A wait names none, nor does a verdict on an admin
408    /// operation or on another member's writes, which the app shows with
409    /// that operation. A provider failure that clears by itself names none
410    /// either: it retries on its own, and the pass says whether storage is
411    /// reachable. A file that can't be uploaded or read names failed: it
412    /// holds back what waits for it and is never skipped, so it shows until
413    /// the file uploads or the person acts. Any other failure names the
414    /// state its cause does, or failed. A cleanup names what its cleanup
415    /// waits on, as it retries that.
416    #[deny(clippy::wildcard_enum_match_arm)]
417    fn names(&self) -> Option<Named> {
418        match self {
419            Self::Storage { failure, .. } => storage_names(*failure).or_else(|| {
420                (crate::pending::storage_clears(*failure) != crate::pending::Clears::ByItself)
421                    .then_some(Named::Failed)
422            }),
423            Self::UpdateRequired(_) => Some(Named::UpdateNeeded),
424            Self::Removed(removal) => Some(Named::Removed(*removal)),
425            Self::MemberKeysReplaced { member } => {
426                Some(Named::NeedsReset(ResetReason::MemberKeysReplaced { member: *member }))
427            }
428            Self::Refused(_) | Self::FileUnavailable(_) | Self::Original { .. } => {
429                Some(Named::Failed)
430            }
431            Self::Failed(LocalFailure::Shutdown) => None,
432            Self::Failed(
433                LocalFailure::Database
434                | LocalFailure::DiskFull
435                | LocalFailure::DiskDenied
436                | LocalFailure::DiskOther
437                | LocalFailure::KeyCustody
438                | LocalFailure::Crypto
439                | LocalFailure::Operation
440                | LocalFailure::Bug,
441            ) => Some(Named::Failed),
442            Self::Cleanup { cleanup, .. } => cleanup.names(),
443            // A key no member holds is never sent: that is no wait.
444            Self::KeyUnavailable { holders, .. } => {
445                holders.as_ref().is_some_and(Vec::is_empty).then_some(Named::Failed)
446            }
447            Self::Missing { .. }
448            | Self::Waits(_)
449            | Self::NoStorage
450            | Self::WritesRefused { .. }
451            | Self::ProviderPending { .. }
452            | Self::AccountInUse { .. }
453            | Self::AccessRemains { .. }
454            | Self::Rejected(_)
455            | Self::Paused => None,
456        }
457    }
458
459    /// The wait a slot blocked with this reason names (the model's
460    /// `Reason.slotWait`): the key it needs, or the snapshot it waits for. A
461    /// newer floor names none: the next pass retries it.
462    #[deny(clippy::wildcard_enum_match_arm)]
463    pub(super) fn slot_wait(&self) -> Option<SyncWait> {
464        match self {
465            Self::KeyUnavailable { holders: Some(holders), .. } if holders.is_empty() => None,
466            Self::KeyUnavailable { audience, key, holders } => Some(SyncWait::KeyCopy {
467                audience: audience.clone(),
468                key: *key,
469                holders: holders.clone().unwrap_or_default(),
470            }),
471            Self::Waits(Prerequisite::Reload(audience)) => {
472                Some(SyncWait::Snapshot { audience: audience.clone() })
473            }
474            Self::Waits(Prerequisite::Floor | Prerequisite::SequenceCatchUp)
475            | Self::Missing { .. }
476            | Self::UpdateRequired(_)
477            | Self::NoStorage
478            | Self::Storage { .. }
479            | Self::Refused(_)
480            | Self::WritesRefused { .. }
481            | Self::ProviderPending { .. }
482            | Self::AccountInUse { .. }
483            | Self::AccessRemains { .. }
484            | Self::FileUnavailable(_)
485            | Self::Original { .. }
486            | Self::Failed(_)
487            | Self::Rejected(_)
488            | Self::Cleanup { .. }
489            | Self::Paused
490            | Self::Removed(_)
491            | Self::MemberKeysReplaced { .. } => None,
492        }
493    }
494
495    /// What a slot blocked with this reason names (the model's
496    /// `Reason.slotState`). The reasons that wait (`slot_wait`, a newer
497    /// floor), the failures that clear by themselves and those that name a
498    /// state keep what `names` says. A slot blocks with no other reason, so
499    /// one that did would be coven's own bug: it names failed.
500    #[deny(clippy::wildcard_enum_match_arm)]
501    fn slot_names(&self) -> Option<Named> {
502        match self {
503            Self::Waits(Prerequisite::Reload(_) | Prerequisite::Floor) => None,
504            // It waits for the copy, or, with no holder to send one, is failed.
505            Self::KeyUnavailable { .. } => self.names(),
506            Self::Waits(Prerequisite::SequenceCatchUp)
507            | Self::Missing { .. }
508            | Self::UpdateRequired(_)
509            | Self::NoStorage
510            | Self::Storage { .. }
511            | Self::Refused(_)
512            | Self::WritesRefused { .. }
513            | Self::ProviderPending { .. }
514            | Self::AccountInUse { .. }
515            | Self::AccessRemains { .. }
516            | Self::FileUnavailable(_)
517            | Self::Original { .. }
518            | Self::Failed(_)
519            | Self::Rejected(_)
520            | Self::Cleanup { .. }
521            | Self::Paused
522            | Self::Removed(_)
523            | Self::MemberKeysReplaced { .. } => {
524                self.names().or_else(|| (!self.clears_by_itself()).then_some(Named::Failed))
525            }
526        }
527    }
528
529    /// Whether the record names a state of its own, which fails the
530    /// upload it is about (the model's `Reason.state` is some).
531    pub(crate) fn names_a_state(&self) -> bool {
532        self.names().is_some()
533    }
534
535    /// Whether the reason clears by itself (the model's `Reason.byItself`).
536    fn clears_by_itself(&self) -> bool {
537        self.clears() == Some(crate::pending::Clears::ByItself)
538    }
539
540    /// Whether a pass that met this reason retries under the sync scope's
541    /// backoff: it names no state and clears by itself (the model's
542    /// `PassFailure.retries`).
543    fn retries(&self) -> bool {
544        self.names().is_none() && self.clears_by_itself()
545    }
546}
547
548impl StatusFailure {
549    /// The state a pass that failed as a whole names (the model's
550    /// `PassFailure.state` but for offline); none for a failure that clears
551    /// by itself and names no state of its own, a provider's cooldown
552    /// included, on the pass or on coven's own operation.
553    #[deny(clippy::wildcard_enum_match_arm)]
554    fn names(&self) -> Option<Named> {
555        match self {
556            Self::UpdateRequired(_) => Some(Named::UpdateNeeded),
557            Self::Removed(removal) => Some(Named::Removed(*removal)),
558            Self::DeviceIdInUse(DeviceIdEvidence::Replaced) => {
559                Some(Named::NeedsReset(ResetReason::Replaced))
560            }
561            Self::DeviceIdInUse(DeviceIdEvidence::UnattemptedSlot { .. }) => {
562                Some(Named::NeedsReset(ResetReason::DeviceIdInUse))
563            }
564            Self::Storage(failure) => storage_names(*failure).or_else(|| {
565                (crate::pending::storage_clears(*failure) != crate::pending::Clears::ByItself)
566                    .then_some(Named::Failed)
567            }),
568            Self::Operation(record) => record
569                .reason
570                .names()
571                .or_else(|| (!record.reason.clears_by_itself()).then_some(Named::Failed)),
572            Self::Other => Some(Named::Failed),
573        }
574    }
575
576    /// Whether the pass retries under the sync scope's backoff (the model's
577    /// `PassFailure.retries`).
578    fn retries(&self) -> bool {
579        match self {
580            Self::Storage(failure) => {
581                storage_names(*failure).is_none()
582                    && crate::pending::storage_clears(*failure) == crate::pending::Clears::ByItself
583            }
584            Self::Operation(record) => record.reason.retries(),
585            Self::UpdateRequired(_) | Self::Removed(_) | Self::DeviceIdInUse(_) | Self::Other => {
586                false
587            }
588        }
589    }
590}
591
592impl LastPass {
593    /// Whether the pass ended on a failure that retries under the sync
594    /// scope's backoff (the model's `Facts.lastRetries`).
595    fn retries(&self) -> bool {
596        match self {
597            Self::Synced | Self::Offline { .. } => false,
598            Self::Blocked { reason, .. } => reason.retries(),
599            Self::Failed { failure, .. } => failure.retries(),
600        }
601    }
602
603    /// What this pass says, with no slot moving (the model's `Facts.ended`):
604    /// a pass held back by a wait, at a slot or by a provider's cooldown, or
605    /// one that failed with a failure that clears by itself, waits to sync,
606    /// for what `wait` says the next pass waits for; with `wait` none its
607    /// turn has come, and that is syncing, receiving; offline is offline with
608    /// unsent changes while a write or a file waits to go out.
609    fn ended(
610        &self,
611        unsent_work: bool,
612        unsent: UnsentWork,
613        wait: Option<SyncWait>,
614        provider: CloudProvider,
615    ) -> SyncState {
616        let cause = || SyncCause::Pass(self.clone());
617        let waiting =
618            || wait.map_or(SyncState::Syncing(SyncActivity::Receiving), SyncState::WaitingToSync);
619        match self {
620            Self::Synced => SyncState::Synced,
621            Self::Offline { .. } if unsent_work => SyncState::OfflineWithUnsentChanges(cause()),
622            Self::Offline { .. } => SyncState::Offline(cause()),
623            Self::Blocked { reason, .. } => reason
624                .slot_names()
625                .map_or_else(waiting, |named| named.state(cause(), provider, unsent)),
626            Self::Failed { failure, .. } => {
627                failure.names().map_or_else(waiting, |named| named.state(cause(), provider, unsent))
628            }
629        }
630    }
631}
632
633/// Reads `coven_sync_state.detail`.
634impl coven_database::types::FromSql for SyncState {
635    fn column_result(
636        value: coven_database::types::ValueRef<'_>,
637    ) -> coven_database::types::FromSqlResult<Self> {
638        serde_json::from_str(value.as_str()?)
639            .map_err(|error| coven_database::types::FromSqlError::Other(Box::new(error)))
640    }
641}
642
643impl SyncStatus {
644    /// The state as `coven_sync_state` shows it, from the facts its subquery
645    /// reads: what `_coven_sync_state` returns. The view reads when sync last
646    /// finished from the status row itself.
647    pub(crate) fn row(facts: SyncFacts<PendingRecord>) -> Result<SyncStateRow, DbError> {
648        let positions: Vec<(i64, crate::PendingSubject)> = facts
649            .records
650            .iter()
651            .map(|(position, record)| (*position, record.subject.clone()))
652            .collect();
653        let (facts, _last_synced) = Facts::read(facts)?;
654        let state = facts.state();
655        // The cause's record is one of the facts' records, and its subject
656        // is the key `coven_pending` holds it under.
657        let pending = match state.cause() {
658            Some(SyncCause::Pending(record)) => Some(
659                positions
660                    .iter()
661                    .find_map(|(position, subject)| {
662                        (*subject == record.subject).then_some(*position)
663                    })
664                    .ok_or(DbError::Invariant {
665                        what: "the state's pending record is among the facts' records",
666                    })?,
667            ),
668            Some(SyncCause::Pass(_)) | None => None,
669        };
670        Ok(SyncStateRow {
671            state: state.kind(),
672            pending,
673            detail: serde_json::to_value(&state).map_err(DbError::StateEncoding)?,
674        })
675    }
676
677    /// The sync state and when sync last finished, as `coven_sync_state`
678    /// shows them in the caller's read.
679    pub fn read(sql: SqlReadContext<'_>) -> Result<Self, DbError> {
680        let (state, last_synced) =
681            sql.query_row("SELECT detail,last_synced FROM coven_sync_state", [], |row| {
682                Ok((row.get(0)?, row.get::<_, Option<i64>>(1)?))
683            })?;
684        Ok(Self { state, last_synced: last_synced.map(coven_database::stored_time).transpose()? })
685    }
686
687    /// A closed store's sync status (api.md E1, E5): the state opening shows
688    /// before sync starts, from the facts its database holds, with what
689    /// opening writes over them: `location`, read from the keychain as
690    /// opening reads it; no pass moving, whatever a process that ended
691    /// mid-pass left; and sync not running. The facts read with nothing sent,
692    /// as nothing moves while the store is closed.
693    pub fn closed(
694        facts: coven_database::SyncFacts<PendingRecord>,
695        location: RecordedLocation<CloudProvider>,
696    ) -> Result<Self, DbError> {
697        let (facts, last_synced) = Facts::read(facts)?;
698        let facts = Facts { location, moved: None, sync: RetrySync::Stopped, ..facts };
699        Ok(Self { state: facts.state(), last_synced })
700    }
701}
702
703/// The sync state and when sync last finished, as `coven_sync_state` shows
704/// them in one committed snapshot (§19.1).
705pub async fn sync_status(database: &coven_database::StoreDatabase) -> Result<SyncStatus, DbError> {
706    database.read(SyncStatus::read).await
707}
708
709/// The provider that `coven_sync_status.provider` names, or
710/// `DamagedDatabase` when the name matches no provider.
711fn named_provider(name: &str) -> Result<CloudProvider, DbError> {
712    name.parse().map_err(|_unknown| DbError::DamagedDatabase)
713}
714
715/// Write, as the store opens, whether a storage location is recorded here
716/// and its credentials held, with the location and its labels, and that no
717/// pass moves; `finished`, for a store joining or restoring read to its end,
718/// is when (E5). A failure fails the store's handle with its cause.
719pub async fn record_opened(
720    database: &coven_database::StoreDatabase,
721    location: RecordedLocation<coven_storage::StorageConfig>,
722    finished: Option<SystemTime>,
723) -> Result<(), SyncError> {
724    Ok(database.record_opened(stored(location)?, finished).await?)
725}
726
727/// Write whether a storage location is recorded here and its credentials
728/// held, with the location and its labels, as setup, a change of
729/// credentials, a connection's new label or releasing a connection finds
730/// it; `finished`, for setup, is when it read the store to its end. A
731/// failure fails the store's handle with its cause.
732pub async fn record_location(
733    database: &coven_database::StoreDatabase,
734    location: RecordedLocation<coven_storage::StorageConfig>,
735    finished: Option<SystemTime>,
736) -> Result<(), SyncError> {
737    Ok(database.record_location(stored(location)?, finished).await?)
738}
739
740/// `location` as `coven_sync_status` keeps it: its provider's name and the
741/// location's settings text.
742fn stored(
743    location: RecordedLocation<coven_storage::StorageConfig>,
744) -> Result<RecordedLocation<coven_database::StoredLocation>, SyncError> {
745    location.try_map(|location| {
746        Ok(coven_database::StoredLocation {
747            provider: location.provider().name().to_owned(),
748            location: location.recorded_text()?,
749        })
750    })
751}
752
753/// Write that `location` is recorded on `connection`, a test's connection
754/// outside any store, with this device holding its credentials, as
755/// `record_opened` writes it.
756#[cfg(any(test, feature = "test-utils"))]
757pub fn record_connected_outside_store(
758    connection: &coven_database::test_utils::Connection,
759    location: coven_storage::StorageConfig,
760) -> Result<(), SyncError> {
761    coven_database::test_utils::save_location_outside_store(
762        connection,
763        &stored(RecordedLocation::Connected(location))?,
764    )?;
765    Ok(())
766}
767
768#[path = "sync_status_facts.rs"]
769mod facts;
770pub(crate) use facts::{held_all, last_pass, Facts, Progress, Upload};
771
772#[cfg(test)]
773#[path = "sync_status_tests.rs"]
774mod tests;