Skip to main content

coven_sync/
setup_journal.rs

1//! The journal row of a storage setup (§11.6, §20.8): written before its
2//! first write to storage, moved past its point of no return before it
3//! claims anything, and ended with its outcome, which `coven_operations`
4//! lists until the app acknowledges it.
5
6use crate::{OperationKind, SyncError};
7use coven_database::{
8    operation_kind::STORAGE_SETUP, DbError, NewOperation, OperationId, OperationRecord,
9    StorageSetupOutcome, StoreDatabase,
10};
11use coven_storage::StorageConfig;
12use serde::{Deserialize, Serialize};
13
14/// What a setup's row records.
15#[derive(Serialize, Deserialize)]
16struct SetupWork {
17    /// Creating the store: no location was recorded when setup began.
18    creating: bool,
19    step: SetupStep,
20}
21
22#[derive(Serialize, Deserialize)]
23enum SetupStep {
24    /// Checking the provider, which claims nothing: a crash here is undone.
25    Checking,
26    /// Past the point of no return, claiming at `location` with the
27    /// credentials setup keeps beside the committed ones: a crash here is
28    /// finished.
29    Claiming { location: StorageConfig },
30}
31
32/// One storage setup's journal row, as its owner last committed it.
33pub struct SetupJournal {
34    id: OperationId,
35    last_step: u32,
36    work: SetupWork,
37}
38
39impl SetupJournal {
40    /// Journal a setup before its first write to storage, listed in
41    /// `coven_operations` as `StorageSetup` from this commit on.
42    pub async fn start(database: &StoreDatabase, creating: bool) -> Result<Self, SyncError> {
43        let work = SetupWork { creating, step: SetupStep::Checking };
44        let id = database
45            .start_listed_operation(
46                NewOperation {
47                    kind: STORAGE_SETUP.into(),
48                    data: serde_json::to_vec(&work)?,
49                    started_by: STORAGE_SETUP.into(),
50                    pauses_writes: false,
51                },
52                OperationKind::StorageSetup.listed(),
53            )
54            .await?;
55        Ok(Self { id, last_step: 0, work })
56    }
57
58    /// The setup a crash left running, if any.
59    pub async fn running(database: &StoreDatabase) -> Result<Option<Self>, SyncError> {
60        database.first_operation(STORAGE_SETUP).await?.map(Self::read).transpose()
61    }
62
63    fn read(record: OperationRecord) -> Result<Self, SyncError> {
64        Ok(Self {
65            id: record.id,
66            last_step: record.last_step,
67            work: serde_json::from_slice(&record.data)?,
68        })
69    }
70
71    /// The row's id, as `coven_operations` lists it.
72    pub fn id(&self) -> OperationId {
73        self.id
74    }
75
76    /// Whether setup creates the store, rather than reconnecting to it.
77    pub fn creating(&self) -> bool {
78        self.work.creating
79    }
80
81    /// Where setup claims, once past its point of no return.
82    pub fn location(&self) -> Option<&StorageConfig> {
83        match &self.work.step {
84            SetupStep::Checking => None,
85            SetupStep::Claiming { location } => Some(location),
86        }
87    }
88
89    /// Commit setup past its point of no return, claiming at `location`:
90    /// from here on it finishes (§11.6).
91    pub async fn claim(
92        &mut self,
93        database: &StoreDatabase,
94        location: StorageConfig,
95    ) -> Result<(), SyncError> {
96        let step = std::mem::replace(&mut self.work.step, SetupStep::Claiming { location });
97        let advanced = async {
98            let last_step = self
99                .last_step
100                .checked_add(1)
101                .ok_or(DbError::Invariant { what: "an operation's steps fit u32" })?;
102            database
103                .advance_operation(coven_database::OperationUpdate {
104                    id: self.id,
105                    previous: self.last_step,
106                    last_step,
107                    data: serde_json::to_vec(&self.work)?,
108                })
109                .await?;
110            Ok::<_, SyncError>(last_step)
111        }
112        .await;
113        match advanced {
114            Ok(last_step) => {
115                self.last_step = last_step;
116                Ok(())
117            }
118            Err(error) => {
119                self.work.step = step;
120                Err(error)
121            }
122        }
123    }
124
125    /// End the row with `outcome`, which `coven_operations` keeps until the
126    /// app acknowledges it (§11.4).
127    pub async fn end(
128        &self,
129        database: &StoreDatabase,
130        outcome: StorageSetupOutcome,
131    ) -> Result<(), SyncError> {
132        Ok(database.finish_operation_with_outcome(self.id, Some(outcome.into())).await?)
133    }
134}