Skip to main content

coven_sync/
operation_outcome.rs

1//! How an operation ended (§11.4, api.md E6): an entry's outcome as the
2//! call that waits for it reads it, and as `coven_operations` lists it in
3//! the outcome type of the operation's kind.
4
5use crate::{OperationKind, OperationRejection, SyncError};
6use coven_database::types::{FromSql, FromSqlError, FromSqlResult, ValueRef};
7use coven_database::{ChangeOutcome, FreshChangeOutcome, ListedOutcome};
8use coven_merge::Slot;
9
10/// How an operation that claims an admin entry ended (§11.2): every kind
11/// the operation journal runs ends one of these ways.
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub(crate) enum EntryOutcome {
14    /// Its entry landed at this slot, which this device has applied.
15    Landed(Slot),
16    /// The applied state already had what it asked for, so it claimed no
17    /// slot.
18    Satisfied,
19    /// The caught-up state refused it; its preparation was undone.
20    Rejected(OperationRejection),
21}
22
23impl EntryOutcome {
24    /// The landed slot, or the rejection as the error of a call that waits
25    /// for the operation itself.
26    pub(crate) fn into_slot(self) -> Result<Option<Slot>, SyncError> {
27        match self {
28            Self::Landed(slot) => Ok(Some(slot)),
29            Self::Satisfied => Ok(None),
30            Self::Rejected(reason) => Err(SyncError::Rejected(reason)),
31        }
32    }
33}
34
35/// An entry's outcome in `ChangeOutcome`, the listed outcome type that
36/// holds every way an entry ends.
37impl From<EntryOutcome> for ChangeOutcome {
38    fn from(outcome: EntryOutcome) -> Self {
39        match outcome {
40            EntryOutcome::Landed(slot) => Self::Landed(slot),
41            EntryOutcome::Satisfied => Self::Satisfied,
42            EntryOutcome::Rejected(reason) => Self::Rejected(reason),
43        }
44    }
45}
46
47impl TryFrom<EntryOutcome> for FreshChangeOutcome {
48    type Error = SyncError;
49
50    /// A fresh change's entry names what no applied state holds yet, so
51    /// one that ends satisfied is a bug.
52    fn try_from(outcome: EntryOutcome) -> Result<Self, SyncError> {
53        match outcome {
54            EntryOutcome::Landed(slot) => Ok(Self::Landed(slot)),
55            EntryOutcome::Rejected(reason) => Ok(Self::Rejected(reason)),
56            EntryOutcome::Satisfied => Err(coven_database::DbError::Invariant {
57                what: "a change naming a new circle or pair is never satisfied",
58            }
59            .into()),
60        }
61    }
62}
63
64/// How a call that journals an operation and runs the pass that settles it
65/// reads the operation's listed outcome: it ended in the pass, so it landed
66/// or was rejected.
67#[cfg(test)]
68pub(crate) trait SettledByPass: std::fmt::Debug + Sized {
69    /// Whether the operation took effect, or the rejection as the error.
70    /// An outcome the pass can't give, a device that stopped, panics.
71    fn settled(self) -> Result<(), SyncError>;
72}
73
74#[cfg(test)]
75impl SettledByPass for FreshChangeOutcome {
76    fn settled(self) -> Result<(), SyncError> {
77        match self {
78            Self::Landed(_) => Ok(()),
79            Self::Rejected(reason) => Err(SyncError::Rejected(reason)),
80            other => panic!("the pass ended the operation {other:?}"),
81        }
82    }
83}
84
85#[cfg(test)]
86impl SettledByPass for ChangeOutcome {
87    fn settled(self) -> Result<(), SyncError> {
88        match self {
89            Self::Landed(_) | Self::Satisfied => Ok(()),
90            Self::Rejected(reason) => Err(SyncError::Rejected(reason)),
91            other => panic!("the pass ended the operation {other:?}"),
92        }
93    }
94}
95
96/// The outcome types `coven_operations` lists outcomes in, one for each
97/// group of kinds that end the same ways.
98#[derive(PartialEq)]
99enum OutcomeType {
100    Change,
101    FreshChange,
102    Invite,
103    StorageSetup,
104}
105
106impl OperationKind {
107    /// The type `coven_operations` lists this kind's outcomes in; `None` for
108    /// a kind no app write or call journals there.
109    fn outcome_type(self) -> Option<OutcomeType> {
110        use OperationKind as K;
111        match self {
112            K::RenameStore
113            | K::SetRole
114            | K::RemoveMember
115            | K::RemoveDevice
116            | K::RenameCircle
117            | K::DeleteCircle
118            | K::AddCircleMember
119            | K::RemoveCircleMember
120            | K::ApproveJoin => Some(OutcomeType::Change),
121            K::CreateCircle | K::ReplaceMemberKeys => Some(OutcomeType::FreshChange),
122            K::Invite => Some(OutcomeType::Invite),
123            K::StorageSetup => Some(OutcomeType::StorageSetup),
124            K::CreateStore
125            | K::SetUpStorage
126            | K::AddDevice
127            | K::SetAccess
128            | K::RetainSequence
129            | K::RetainFiles
130            | K::WriteSnapshot
131            | K::SchemaChange
132            | K::Reset
133            | K::ReloadFromSnapshot
134            | K::RequiredReload
135            | K::RotateKey
136            | K::SendKeyCopy
137            | K::Pairing
138            | K::RevokeAccess => None,
139        }
140    }
141
142    /// Whether `coven_operations` lists this kind's outcomes in the type
143    /// `outcome` has, which a test's outcome outside a store must be.
144    #[cfg(any(test, feature = "test-utils"))]
145    pub fn lists(self, outcome: &ListedOutcome) -> bool {
146        let of_outcome = match outcome {
147            ListedOutcome::Change(_) => OutcomeType::Change,
148            ListedOutcome::FreshChange(_) => OutcomeType::FreshChange,
149            ListedOutcome::Invite(_) => OutcomeType::Invite,
150            ListedOutcome::StorageSetup(_) => OutcomeType::StorageSetup,
151        };
152        self.outcome_type() == Some(of_outcome)
153    }
154
155    /// How `coven_operations` lists an operation of this kind that ended
156    /// `outcome`, in the outcome type of its kind; `None` for a kind it
157    /// never lists, whose outcome is nobody's to read.
158    pub(crate) fn listed_outcome(
159        self,
160        outcome: EntryOutcome,
161    ) -> Result<Option<ListedOutcome>, SyncError> {
162        Ok(match self.outcome_type() {
163            Some(OutcomeType::Change) => Some(ChangeOutcome::from(outcome).into()),
164            Some(OutcomeType::FreshChange) => Some(FreshChangeOutcome::try_from(outcome)?.into()),
165            Some(OutcomeType::Invite | OutcomeType::StorageSetup) => {
166                return Err(coven_database::DbError::Invariant {
167                    what:
168                        "an invite or a storage setup ends with its own outcome, never an entry's",
169                }
170                .into())
171            }
172            None => None,
173        })
174    }
175
176    /// The kind's name, as `coven_operations.kind` lists it.
177    pub fn listed(self) -> String {
178        match serde_json::to_value(self) {
179            Ok(serde_json::Value::String(name)) => name,
180            other => unreachable!("an operation kind is named by its variant: {other:?}"),
181        }
182    }
183}
184
185/// Reads `coven_operations.kind`.
186impl FromSql for OperationKind {
187    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
188        serde_json::from_value(serde_json::Value::String(value.as_str()?.to_owned()))
189            .map_err(|error| FromSqlError::Other(Box::new(error)))
190    }
191}