coven_database/sync_functions.rs
1//! `_coven_sync_state` and `_coven_upload_phase`, the SQL functions the
2//! `coven_sync_state` and `coven_upload_phases` views call over the facts
3//! they read (§17.9, §19.1, api.md E4).
4//!
5//! The sync state and each upload's phase are SQL functions so that an app's
6//! screen reads them in its own live query, joined to its own rows, and the
7//! query runs again whenever a fact they read changes. The computations stay
8//! sync's Rust code (`Facts::state` and `upload_phase` in coven-sync), which
9//! is the one definition of each: the Lean model's differential tests check
10//! them, and `uploads()` gives each upload the same phase. Sync gives them to
11//! the database as `SyncFunctions`, and the database registers them on every
12//! connection with the functions coven's views call
13//! (`coven_functions::register_views`).
14
15use std::sync::Arc;
16
17use sqlive::rusqlite::functions::{Context, FunctionFlags};
18use sqlive::Setup;
19
20use crate::sync_facts::{SyncFacts, UploadPhaseFacts};
21use crate::DbError;
22
23/// The sync state function's name, which only `coven_sync_state` calls.
24const STATE: &str = "_coven_sync_state";
25
26/// The upload phase function's name, which only `coven_upload_phases` calls.
27const UPLOAD_PHASE: &str = "_coven_upload_phase";
28
29/// The sync state as `coven_sync_state` shows it.
30#[derive(Clone, Debug, PartialEq)]
31pub struct SyncStateRow {
32 /// The state's kind, in snake case: `synced`, `waiting_to_sync`, and the
33 /// rest.
34 pub state: &'static str,
35 /// The pending record that names the state, by its position in
36 /// `coven_pending`; none when the last pass names it, or nothing does.
37 pub pending: Option<i64>,
38 /// The whole state as sync encodes it: the activity, the wait, the
39 /// cause and the rest.
40 pub detail: serde_json::Value,
41}
42
43/// One upload's phase as `coven_upload_phases` shows it.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum UploadPhaseRow {
46 /// An attempt is sending it now.
47 Uploading,
48 /// Storage holds its bytes; it waits for the rest of its move.
49 Stored,
50 /// It waits, for the wait this kind names in snake case: `queued`,
51 /// `paused` and the rest.
52 Waiting(&'static str),
53 /// It has failed, and the pending record at this position in
54 /// `coven_pending` says why.
55 Failed(i64),
56}
57
58impl UploadPhaseRow {
59 /// The row's columns: the phase's kind, what it waits for while it
60 /// waits, and the record a failure names.
61 fn columns(self) -> (&'static str, Option<&'static str>, Option<i64>) {
62 match self {
63 Self::Uploading => ("uploading", None, None),
64 Self::Stored => ("stored", None, None),
65 Self::Waiting(wait) => ("waiting", Some(wait), None),
66 Self::Failed(pending) => ("failed", None, Some(pending)),
67 }
68 }
69}
70
71type ComputeState = dyn Fn(&Context<'_>) -> Result<SyncStateRow, DbError> + Send + Sync;
72
73type ComputePhase = dyn Fn(&Context<'_>) -> Result<UploadPhaseRow, DbError> + Send + Sync;
74
75/// Sync's computations of the sync state from its facts (`SyncFacts`) and of
76/// an upload's phase from its own (`UploadPhaseFacts`), which the database
77/// registers as `_coven_sync_state` and `_coven_upload_phase`. Clones share
78/// them.
79#[derive(Clone)]
80pub struct SyncFunctions {
81 state: Arc<ComputeState>,
82 upload_phase: Arc<ComputePhase>,
83}
84
85impl SyncFunctions {
86 /// The functions that decode their arguments as the facts, with the
87 /// pending records as `P`, and compute the state with `state` and an
88 /// upload's phase with `upload_phase`. Each computation must read only
89 /// its facts and return at once: SQLite calls it inside a read, and coven
90 /// runs a live query again only when a table the query reads changes.
91 pub fn new<P: crate::PendingValue + Clone>(
92 state: fn(SyncFacts<P>) -> Result<SyncStateRow, DbError>,
93 upload_phase: fn(UploadPhaseFacts<P>) -> Result<UploadPhaseRow, DbError>,
94 ) -> Self {
95 Self {
96 state: Arc::new(move |context| state(SyncFacts::decode(context)?)),
97 upload_phase: Arc::new(move |context| upload_phase(UploadPhaseFacts::decode(context)?)),
98 }
99 }
100
101 /// Register the functions on a connection to the store's database. Each
102 /// result depends on its arguments alone, but coven marks neither
103 /// deterministic: the results change with coven's code, so no index,
104 /// CHECK or generated column may store one.
105 pub(crate) fn register(
106 &self,
107 setup: &Setup<'_, crate::app_policy::CovenPolicy>,
108 ) -> sqlive::rusqlite::Result<()> {
109 let state = Arc::clone(&self.state);
110 setup.scalar_function(
111 STATE,
112 crate::sync_facts::FACTS,
113 FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_INNOCUOUS,
114 move |call| {
115 let row = state(call.context())
116 .map_err(|error| sqlive::rusqlite::Error::UserFunctionError(Box::new(error)))?;
117 Ok(serde_json::json!({
118 "state": row.state,
119 "pending": row.pending,
120 "detail": row.detail,
121 })
122 .to_string())
123 },
124 )?;
125 let upload_phase = Arc::clone(&self.upload_phase);
126 setup.scalar_function(
127 UPLOAD_PHASE,
128 crate::sync_facts::UPLOAD_PHASE_FACTS,
129 FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_INNOCUOUS,
130 move |call| {
131 let (phase, wait, pending) = upload_phase(call.context())
132 .map_err(|error| sqlive::rusqlite::Error::UserFunctionError(Box::new(error)))?
133 .columns();
134 Ok(serde_json::json!({
135 "phase": phase,
136 "wait": wait,
137 "pending": pending,
138 })
139 .to_string())
140 },
141 )
142 }
143}