Skip to main content

coven_database/
internal_schema_retry_effect.rs

1//! What the person's retry would do if made now (§6.7, api.md E5), kept as a
2//! table so the app's live queries and local triggers can follow it (§9.4),
3//! as they follow `coven_sync_status`.
4//!
5//! Its one row holds what decides it: whether a started connection will
6//! plan (`syncing`), whether a failure only new credentials, an update or a
7//! reset can clear holds every pass (`held`), and when the provider cooldown
8//! holding every pass ends (`cooling_until`, milliseconds since the Unix
9//! epoch by the store's clock). `effect` is computed from them, so it never
10//! disagrees with them. While sync is stopped no owner would write a
11//! cooldown's end, so the row keeps none: the table refuses one. A held
12//! failure stays across stopping and starting, as the connection's retry
13//! state does. Opening writes the stopped row with nothing held, and each
14//! change writes the row in the step that makes it, on the writer, where
15//! the retry's own answer is decided from the same row
16//! (`StoreDatabase::change_retry_state`).
17//!
18//! Like the sync status, only the handle that holds the store's writer lock
19//! reads it (`app_policy.rs`): a read-only handle can't tell whether the
20//! writer that last wrote it still runs.
21
22use crate::sqlite::StoreSql;
23use crate::stored_millis::{since_epoch, stored_time, Round};
24use crate::DbError;
25use std::time::SystemTime;
26
27/// The retry effect table, which the app's triggers may follow.
28pub(crate) const RETRY_EFFECT: &str = "coven_retry_effect";
29
30/// The table and its one row, as every store holds them from its creation.
31pub(super) const TABLE: &str = "CREATE TABLE coven_retry_effect (
32        singleton INTEGER PRIMARY KEY NOT NULL CHECK(singleton=1),
33        syncing INTEGER NOT NULL CHECK(syncing IN (0,1)),
34        held INTEGER NOT NULL CHECK(held IN (0,1)),
35        cooling_until INTEGER,
36        effect TEXT NOT NULL GENERATED ALWAYS AS (CASE
37            WHEN syncing=0 THEN 'not_syncing'
38            WHEN held=1 THEN 'failed'
39            WHEN cooling_until IS NOT NULL THEN 'cooling_down'
40            ELSE 'pass' END) STORED,
41        CHECK(syncing=1 OR cooling_until IS NULL)
42    ) STRICT;
43    INSERT INTO coven_retry_effect(singleton,syncing,held,cooling_until) VALUES(1,0,0,NULL);";
44
45/// What decides the person's retry, as `coven_retry_effect` holds it.
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47pub struct RetryState {
48    /// Whether a started connection will plan, and the cooldown holding
49    /// its passes.
50    pub sync: RetrySync,
51    /// A failure only new credentials, an update or a reset can clear
52    /// holds every pass.
53    pub held: bool,
54}
55
56/// Whether a started connection will plan.
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum RetrySync {
59    /// None will: a retry is answered at once that sync isn't running.
60    Stopped,
61    /// One will.
62    Started {
63        /// A provider cooldown holds every pass until then, by the store's
64        /// clock, in whole milliseconds rounded up.
65        cooling_until: Option<SystemTime>,
66    },
67}
68
69impl RetryState {
70    /// The state a store opens in: no connection plans yet, and its owner
71    /// has found nothing holding a pass.
72    pub(crate) const OPENED: Self = Self { sync: RetrySync::Stopped, held: false };
73}
74
75/// Milliseconds since the Unix epoch, rounded up so a stored end never comes
76/// before the cooldown's own. A time before the epoch or past SQLite's
77/// integers is an invariant failure.
78fn millis(time: SystemTime) -> Result<i64, DbError> {
79    since_epoch(time, Round::Up).ok_or(DbError::Invariant {
80        what: "a cooldown ends between the Unix epoch and SQLite's last millisecond",
81    })
82}
83
84/// The state as the row holds it.
85pub(crate) fn read(db: &StoreSql) -> Result<RetryState, DbError> {
86    let (syncing, held, cooling_until) = db.query_row(
87        "SELECT syncing,held,cooling_until FROM coven_retry_effect WHERE singleton=1",
88        [],
89        |row| Ok((row.get::<_, bool>(0)?, row.get::<_, bool>(1)?, row.get::<_, Option<i64>>(2)?)),
90    )?;
91    Ok(RetryState { sync: sync(syncing, cooling_until)?, held })
92}
93
94/// Whether a started connection will plan, from `syncing` and
95/// `cooling_until` as the row holds them.
96pub(crate) fn sync(syncing: bool, cooling_until: Option<i64>) -> Result<RetrySync, DbError> {
97    Ok(if syncing {
98        RetrySync::Started { cooling_until: cooling_until.map(stored_time).transpose()? }
99    } else {
100        RetrySync::Stopped
101    })
102}
103
104/// Write the state whole, leaving the row alone when it already says this.
105/// The cooldown's end is stored rounded up to the millisecond.
106pub(crate) fn save(db: &StoreSql, state: RetryState) -> Result<(), DbError> {
107    let held = state.held;
108    let (syncing, cooling_until) = match state.sync {
109        RetrySync::Stopped => (false, None),
110        RetrySync::Started { cooling_until } => (true, cooling_until.map(millis).transpose()?),
111    };
112    db.execute(
113        "UPDATE coven_retry_effect SET syncing=?1,held=?2,cooling_until=?3
114         WHERE singleton=1 AND (syncing IS NOT ?1 OR held IS NOT ?2 OR cooling_until IS NOT ?3)",
115        sqlive::rusqlite::params![syncing, held, cooling_until],
116    )?;
117    Ok(())
118}
119
120/// The state rounded as the row stores it, so a decision made from a state
121/// before it is written matches one made from the row after.
122pub(crate) fn stored(state: RetryState) -> Result<RetryState, DbError> {
123    let sync = match state.sync {
124        RetrySync::Stopped => RetrySync::Stopped,
125        RetrySync::Started { cooling_until } => RetrySync::Started {
126            cooling_until: cooling_until
127                .map(|until| millis(until).and_then(stored_time))
128                .transpose()?,
129        },
130    };
131    Ok(RetryState { sync, ..state })
132}
133
134#[cfg(test)]
135#[path = "internal_schema_retry_effect_tests.rs"]
136mod tests;