coven_sync/
setup_journal.rs1use 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#[derive(Serialize, Deserialize)]
16struct SetupWork {
17 creating: bool,
19 step: SetupStep,
20}
21
22#[derive(Serialize, Deserialize)]
23enum SetupStep {
24 Checking,
26 Claiming { location: StorageConfig },
30}
31
32pub struct SetupJournal {
34 id: OperationId,
35 last_step: u32,
36 work: SetupWork,
37}
38
39impl SetupJournal {
40 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 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 pub fn id(&self) -> OperationId {
73 self.id
74 }
75
76 pub fn creating(&self) -> bool {
78 self.work.creating
79 }
80
81 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 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 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}