Skip to main content

coven_sync/
last_pass.rs

1//! How the last pass ended (E5), as `coven_sync_status.last_pass` keeps it:
2//! one of the facts the sync state is computed from (§19.1).
3
4use crate::{DeviceIdEvidence, PendingRecord, SyncFailure};
5use coven_database::DbError;
6use coven_storage::{StorageError, StorageFailure};
7use std::time::SystemTime;
8
9/// How the last pass that reached storage, or failed trying, ended (E5), as
10/// `coven_sync_status.last_pass` holds it. It outlives each connection:
11/// opening keeps it, and the running loop writes it as each pass ends. An
12/// error is kept as its text, which names every cause below it with secrets
13/// and URLs already cut, so a pass read after the process that ran it ended
14/// still says why.
15#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
16pub enum LastPass {
17    /// The pass reached its observed end; other subjects may still be pending.
18    Synced,
19    /// The request preventing the pass received no usable provider response.
20    Offline {
21        /// The network failure, as the provider adapter classified it.
22        failure: StorageFailure,
23        /// The failure's text.
24        error: String,
25    },
26    /// This slot invokes §5.4's stuck-device rule.
27    Blocked {
28        /// The slot that cannot apply.
29        #[serde(with = "coven_database::slot_json")]
30        slot: coven_merge::Slot,
31        /// Why it cannot apply.
32        reason: crate::PendingReason,
33        /// The text of the error that blocked the slot: the cause the
34        /// slot's pending record keeps. A device that opens already blocked
35        /// has none until a pass of its own meets the error.
36        error: Option<String>,
37    },
38    /// Storage refused the whole pass, or coven's own operation failed.
39    Failed {
40        /// What failed.
41        failure: StatusFailure,
42        /// The failure's text.
43        error: String,
44    },
45}
46
47/// What stopped a pass as a whole, as `LastPass` keeps it: a `SyncFailure`
48/// without the error objects, whose text it holds beside it (E5).
49#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
50pub enum StatusFailure {
51    /// A schema or stored object format is newer than this implementation.
52    UpdateRequired(crate::RequiredUpdate),
53    /// This device is not in the store (§13.2, §14.1).
54    Removed(coven_database::Removal),
55    /// Another copy uses this device's id; this copy sends nothing more (§19.3).
56    DeviceIdInUse(DeviceIdEvidence),
57    /// The provider refused or failed a request, as its adapter classified it.
58    Storage(StorageFailure),
59    /// The pass finished, but this work of coven's own failed its last
60    /// attempt; it retries under backoff.
61    Operation(PendingRecord),
62    /// Any other failure.
63    Other,
64}
65
66impl LastPass {
67    /// How a pass that failed as a whole ended.
68    pub fn failed(failure: impl Into<SyncFailure>) -> Self {
69        let failure = failure.into();
70        let error = failure.to_string();
71        let failure = match failure {
72            SyncFailure::UpdateRequired(update) => StatusFailure::UpdateRequired(update),
73            SyncFailure::Removed(removal) => StatusFailure::Removed(removal),
74            SyncFailure::DeviceIdInUse(evidence) => StatusFailure::DeviceIdInUse(evidence),
75            SyncFailure::Storage(storage) => StatusFailure::Storage(storage.failure()),
76            SyncFailure::Operation(record) => StatusFailure::Operation(*record),
77            SyncFailure::Other(_) => StatusFailure::Other,
78        };
79        Self::Failed { failure, error }
80    }
81
82    fn encoded(&self) -> Result<Vec<u8>, DbError> {
83        serde_json::to_vec(self).map_err(DbError::StateEncoding)
84    }
85
86    /// Write this as how the last pass ended when sync failed outside a
87    /// pass's end: starting, stopping, or a local failure or panic of the
88    /// loop's, in a pass or outside one; and that nothing moves, so the
89    /// state shows the failure (IO `failed_worker_shows`). A
90    /// failure fails the store's handle with its cause
91    /// (`DbError::StatePersistence`), so the caller stops the work that
92    /// failed.
93    pub async fn record(&self, database: &coven_database::StoreDatabase) -> Result<(), DbError> {
94        database.record_last_pass(self.encoded()?).await
95    }
96
97    /// Write this, a store-wide worker's panic, as how the last pass ended,
98    /// halting sync until the store reopens: nothing moves, and no pass
99    /// writes over it (IO `halt`). A failure fails the store's handle, as
100    /// `record`'s does.
101    pub async fn record_halt(
102        &self,
103        database: &coven_database::StoreDatabase,
104    ) -> Result<(), DbError> {
105        database.record_halt(self.encoded()?).await
106    }
107
108    /// Write this as how the running pass ended, `now` by the store's clock,
109    /// and that it moves no more. A synced pass's end becomes the last
110    /// synced time, unless that is later. A failure fails the store's
111    /// handle, as `record`'s does.
112    pub async fn record_end(
113        &self,
114        database: &coven_database::StoreDatabase,
115        now: SystemTime,
116    ) -> Result<(), DbError> {
117        let finished = matches!(self, Self::Synced).then_some(now);
118        database.record_pass_end(self.encoded()?, finished).await
119    }
120
121    /// Write this as how the last pass ended on `connection`, a test's
122    /// connection outside any store, as `record_end` writes it.
123    #[cfg(any(test, feature = "test-utils"))]
124    pub fn record_outside_store(
125        &self,
126        connection: &coven_database::test_utils::Connection,
127    ) -> Result<(), DbError> {
128        coven_database::test_utils::save_last_pass_outside_store(connection, &self.encoded()?)
129    }
130
131    /// Follow `coven_sync_status.last_pass` with a live query, as an app's
132    /// SQL does: `None` until a pass ends on this device.
133    #[cfg(any(test, feature = "test-utils"))]
134    pub fn follow(
135        database: &coven_database::StoreDatabase,
136    ) -> coven_database::test_utils::Followed<Option<Self>, coven_database::DbError> {
137        coven_database::test_utils::Followed::new(database.subscribe(|sql| {
138            Ok(sql.query_row("SELECT last_pass FROM coven_sync_status", [], |row| row.get(0))?)
139        }))
140    }
141}
142
143/// Reads `coven_sync_status.last_pass`.
144impl coven_database::types::FromSql for LastPass {
145    fn column_result(
146        value: coven_database::types::ValueRef<'_>,
147    ) -> coven_database::types::FromSqlResult<Self> {
148        serde_json::from_slice(value.as_blob()?)
149            .map_err(|error| coven_database::types::FromSqlError::Other(Box::new(error)))
150    }
151}
152
153/// Why a pass, or the connection attempt that begins one, failed: how it
154/// ended (`LastPass`, E5).
155#[derive(Clone, Debug)]
156pub enum PassFailure {
157    /// The request preventing the pass received no usable provider response.
158    Offline {
159        /// The network failure and its original cause.
160        error: std::sync::Arc<StorageError>,
161    },
162    /// This slot invokes §5.4's stuck-device rule.
163    Blocked {
164        /// The slot that cannot apply.
165        slot: coven_merge::Slot,
166        /// Why it cannot apply.
167        reason: crate::PendingReason,
168        /// The text of the error that blocked the slot: the cause the slot's
169        /// pending record keeps.
170        error: Option<String>,
171    },
172    /// Storage refused the whole pass, or coven's own operation failed.
173    Failed {
174        /// The failure and its original cause.
175        error: SyncFailure,
176    },
177}
178
179impl From<PassFailure> for LastPass {
180    fn from(failure: PassFailure) -> Self {
181        match failure {
182            PassFailure::Offline { error } => {
183                Self::Offline { failure: error.failure(), error: error.to_string() }
184            }
185            PassFailure::Blocked { slot, reason, error } => Self::Blocked { slot, reason, error },
186            PassFailure::Failed { error } => Self::failed(error),
187        }
188    }
189}