Skip to main content

coven_database/
operation_outcome.rs

1//! Why the applied state refuses an administrative operation (§10), and
2//! how an operation an app's write journaled ended, as `coven_operations`
3//! lists it until a write acknowledges it (§11.4): each kind it lists has
4//! an outcome type that holds only the outcomes coven gives that kind.
5
6use coven_foundation::id_source::{CircleId, DeviceId, MemberId};
7
8/// The target a proposed change can no longer affect.
9#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
10pub enum EntryTarget {
11    /// A store member.
12    Member(MemberId),
13    /// An installation.
14    Device(DeviceId),
15    /// A circle.
16    Circle(CircleId),
17}
18
19/// Why the current applied state refuses an administrative operation.
20#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
21pub enum OperationRejection {
22    /// The provider account owns the store: its member can't be removed, and
23    /// their access can't move to another account (§10.1): OneDrive and
24    /// CloudKit can't hand a store to another account, and coven doesn't use
25    /// Dropbox's ownership transfer (bae-fm/coven#237).
26    StoreOwner,
27    /// The target is absent, removed, or cannot be reused.
28    TargetGone(EntryTarget),
29    /// The resulting store would have no active admin.
30    NoAdminLeft,
31    /// Either proposed public key was already bound.
32    KeysAlreadyUsed,
33    /// Another replacement changed the expected binding.
34    MemberKeysChanged(MemberId),
35    /// The author's device, membership or role does not permit this change,
36    /// or, for a snapshot, this device's raise of its audience has not landed
37    /// yet (§16.2).
38    NotAllowed,
39    /// The admission approving a join would carry a copy of every store key
40    /// in history, more than one slot holds (format.md D2): about 22,000
41    /// keys, one per removal or exposed key (§13.2).
42    AdmissionTooLarge,
43}
44
45/// How an admin change an app's write journaled ended, for the kinds
46/// `RenameStore`, `SetRole`, `RemoveMember`, `RemoveDevice`, `RenameCircle`,
47/// `DeleteCircle`, `AddCircleMember`, `RemoveCircleMember` and
48/// `ApproveJoin` (§11.4):
49/// `coven_operations.outcome` holds it from the transaction that ends the
50/// operation's journal row until a write acknowledges it, so an outcome
51/// nobody awaited is still there to read.
52#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
53pub enum ChangeOutcome {
54    /// Its entry landed at this slot, which this device has applied.
55    Landed(#[serde(with = "slot_json")] coven_merge::Slot),
56    /// The applied state already had what it asked for, so it claimed no
57    /// slot (§11.2).
58    Satisfied,
59    /// The applied state refused it once this device had caught up; its
60    /// preparation was undone (§11.2, §11.3).
61    Rejected(OperationRejection),
62    /// This device stopped for good before the operation ended, so it never
63    /// will here. Nothing refused it: another device may still make the
64    /// same change, and for a copy of this installation, the other copy may
65    /// still land it (§14.1, §19.3).
66    Stopped(DeviceStop),
67}
68
69/// How an admin change an app's write journaled ended, for the kinds
70/// `CreateCircle` and `ReplaceMemberKeys`, as `coven_operations.outcome`
71/// holds it (§11.4). Each names something no applied state holds yet, a
72/// new circle or a member's new pair, so it is never satisfied: a state
73/// that already holds it refuses it (§12.3, §15.5).
74#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
75pub enum FreshChangeOutcome {
76    /// Its entry landed at this slot, which this device has applied.
77    Landed(#[serde(with = "slot_json")] coven_merge::Slot),
78    /// The applied state refused it once this device had caught up; its
79    /// preparation was undone (§11.2, §11.3).
80    Rejected(OperationRejection),
81    /// This device stopped for good before the operation ended, so it never
82    /// will here (§14.1, §19.3).
83    Stopped(DeviceStop),
84}
85
86/// How an invite ended, the kind `Invite`, as `coven_operations.outcome`
87/// holds it (§11.4, §13.2): `coven_operations` lists an invite only once a
88/// sharing refusal ends it. Its approval's binding is an operation of its
89/// own, of the kind `ApproveJoin`.
90#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
91pub enum InviteOutcome {
92    /// The invite ended because the provider refused to share the store for
93    /// a reason only a person can fix (§13.2). The invite is gone from
94    /// `coven_invites`; the outcome stays until a write acknowledges it,
95    /// for the app to say what went wrong and what to fix.
96    SharingRefused {
97        /// The address the invite was to share with.
98        account: String,
99        /// What was refused.
100        refusal: coven_foundation::sharing::SharingRefusal,
101    },
102}
103
104/// How a storage setup ended, the kind `StorageSetup`, as
105/// `coven_operations.outcome` holds it (§11.4, §11.6).
106#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
107pub enum StorageSetupOutcome {
108    /// Its entry landed at this slot: slot 1 for a creation, the
109    /// `Set access` slot for a reconnect.
110    Landed(#[serde(with = "slot_json")] coven_merge::Slot),
111    /// A reconnect had nothing to claim: the applied state already held
112    /// what it asked for (§11.2).
113    Satisfied,
114    /// The caught-up state refused the entry it claimed, and setup was
115    /// undone (§11.2, §11.6).
116    Rejected(OperationRejection),
117    /// This device stopped for good before setup ended, so it never will
118    /// here (§14.1).
119    Stopped(DeviceStop),
120    /// The app cancelled it before its point of no return, and what it had
121    /// written was undone (§11.6).
122    Cancelled,
123    /// It was undone before its point of no return, or refused after it
124    /// before anything it claimed landed (§11.6).
125    Undone(UndoCause),
126}
127
128/// An outcome as a write keeps it in `coven_operations.outcome`, in the
129/// outcome type of the kind the operation is listed under. The column
130/// holds the inner outcome, so each type reads its own kinds' rows.
131#[derive(Clone, Debug, PartialEq, Eq)]
132pub enum ListedOutcome {
133    /// An outcome of a kind `ChangeOutcome` lists.
134    Change(ChangeOutcome),
135    /// An outcome of a kind `FreshChangeOutcome` lists.
136    FreshChange(FreshChangeOutcome),
137    /// An outcome of the kind `Invite`.
138    Invite(InviteOutcome),
139    /// An outcome of the kind `StorageSetup`.
140    StorageSetup(StorageSetupOutcome),
141}
142
143impl ListedOutcome {
144    /// The outcome as `_coven_app_operations.outcome` keeps it.
145    pub(crate) fn encode(&self) -> Vec<u8> {
146        match self {
147            Self::Change(outcome) => encode(outcome),
148            Self::FreshChange(outcome) => encode(outcome),
149            Self::Invite(outcome) => encode(outcome),
150            Self::StorageSetup(outcome) => encode(outcome),
151        }
152    }
153}
154
155impl From<ChangeOutcome> for ListedOutcome {
156    fn from(outcome: ChangeOutcome) -> Self {
157        Self::Change(outcome)
158    }
159}
160
161impl From<FreshChangeOutcome> for ListedOutcome {
162    fn from(outcome: FreshChangeOutcome) -> Self {
163        Self::FreshChange(outcome)
164    }
165}
166
167impl From<InviteOutcome> for ListedOutcome {
168    fn from(outcome: InviteOutcome) -> Self {
169        Self::Invite(outcome)
170    }
171}
172
173impl From<StorageSetupOutcome> for ListedOutcome {
174    fn from(outcome: StorageSetupOutcome) -> Self {
175        Self::StorageSetup(outcome)
176    }
177}
178
179/// How a listed operation of any kind ends once this installation stops for
180/// good (`operation::end`) while it runs: landed at the slot its claim took,
181/// or stopped. The outcome type of every kind listed while it runs has both,
182/// encoded as here; an invite is listed only once it has ended.
183#[derive(serde::Serialize)]
184pub(crate) enum StopOutcome {
185    /// Its claim landed at this slot.
186    Landed(#[serde(with = "slot_json")] coven_merge::Slot),
187    /// Nothing of it landed.
188    Stopped(DeviceStop),
189}
190
191impl StopOutcome {
192    /// The outcome as `_coven_app_operations.outcome` keeps it.
193    pub(crate) fn encode(&self) -> Vec<u8> {
194        encode(self)
195    }
196}
197
198/// `outcome` as `_coven_app_operations.outcome` keeps it.
199pub(crate) fn encode(outcome: &impl serde::Serialize) -> Vec<u8> {
200    serde_json::to_vec(outcome).expect("an outcome is plain data, which always encodes")
201}
202
203/// Reads `coven_operations.outcome`, once it is not NULL, as `$outcome`: an
204/// outcome `$outcome` doesn't hold, which coven never gives its kinds, fails
205/// to read.
206macro_rules! read_outcome {
207    ($($outcome:ty),*) => {$(
208        impl sqlive::rusqlite::types::FromSql for $outcome {
209            fn column_result(
210                value: sqlive::rusqlite::types::ValueRef<'_>,
211            ) -> sqlive::rusqlite::types::FromSqlResult<Self> {
212                serde_json::from_slice(value.as_blob()?).map_err(|error| {
213                    sqlive::rusqlite::types::FromSqlError::Other(Box::new(error))
214                })
215            }
216        }
217    )*};
218}
219read_outcome!(ChangeOutcome, FreshChangeOutcome, InviteOutcome, StorageSetupOutcome);
220
221/// Why an operation was undone (§11.6).
222#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
223pub enum UndoCause {
224    /// The app or the device stopped before its point of no return, and
225    /// opening the store undid it.
226    Interrupted,
227    /// A step failed, with this error's text; the call that ran it returned
228    /// the error itself.
229    Failed {
230        /// The failure's text, secrets and URLs already cut.
231        error: String,
232    },
233}
234
235/// Why a device is not in the store, and won't be again (§13.2, §14.1).
236#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
237pub enum Removal {
238    /// An admin removed this device.
239    Device,
240    /// This device's member was removed, or left.
241    Member,
242    /// The admission that published this joined store was refused: its
243    /// device never became a member (§13.2).
244    NeverAdmitted,
245}
246
247/// Why a device stopped for good (§14.1, §19.3).
248#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
249pub enum DeviceStop {
250    /// The device is not in the store.
251    Removed(Removal),
252    /// A reset registered another installation in this device's place.
253    Replaced,
254    /// History shows another copy of this installation using its device id.
255    Copied,
256    /// Its member's keys were replaced with a pair it doesn't hold.
257    MemberKeysReplaced,
258}
259
260/// A slot as the JSON coven keeps it in: its number. For
261/// `#[serde(with = "coven_database::slot_json")]`.
262pub mod slot_json {
263    use serde::{Deserialize, Serialize};
264    /// Write the slot's number.
265    pub fn serialize<S: serde::Serializer>(
266        value: &coven_merge::Slot,
267        output: S,
268    ) -> Result<S::Ok, S::Error> {
269        value.get().serialize(output)
270    }
271    /// Read a slot from its number.
272    pub fn deserialize<'de, D: serde::Deserializer<'de>>(
273        input: D,
274    ) -> Result<coven_merge::Slot, D::Error> {
275        let number = u64::deserialize(input)?;
276        coven_merge::Slot::new(number).ok_or_else(|| {
277            serde::de::Error::invalid_value(
278                serde::de::Unexpected::Unsigned(number),
279                &"a positive slot number",
280            )
281        })
282    }
283
284    /// A list of slots in the same form, for
285    /// `#[serde(with = "coven_database::slot_json::list")]`.
286    pub mod list {
287        use serde::{Deserialize, Serialize};
288        /// Write each slot's number.
289        pub fn serialize<S: serde::Serializer>(
290            value: &[coven_merge::Slot],
291            output: S,
292        ) -> Result<S::Ok, S::Error> {
293            value.iter().map(|slot| slot.get()).collect::<Vec<_>>().serialize(output)
294        }
295        /// Read slots from their numbers, refusing 0.
296        pub fn deserialize<'de, D: serde::Deserializer<'de>>(
297            input: D,
298        ) -> Result<Vec<coven_merge::Slot>, D::Error> {
299            Vec::<u64>::deserialize(input)?
300                .into_iter()
301                .map(|number| {
302                    coven_merge::Slot::new(number).ok_or_else(|| {
303                        serde::de::Error::invalid_value(
304                            serde::de::Unexpected::Unsigned(number),
305                            &"a positive slot number",
306                        )
307                    })
308                })
309                .collect()
310        }
311    }
312}
313
314#[cfg(test)]
315#[path = "operation_outcome_tests.rs"]
316mod tests;