Skip to main content

coven_sync/
operation_steps.rs

1//! The steps of the app's write that journal an operation (§4, §11.1).
2
3use crate::sequence_sync::make_retry_due;
4use crate::sequence_sync::sequence_invites::{approve_request, end_invite, make_invite, NewInvite};
5use crate::sequence_sync::sequence_pairings;
6use crate::{AddDevice, AddDeviceId, AddDeviceRequest};
7use crate::{RetryWaits, SequenceState, SyncError};
8use coven_crypto::{custody::KeySession, MemberIdentity};
9use coven_database::{OperationId, SqlContext};
10use coven_format::admin::StoreChange;
11use coven_foundation::{
12    clock::ClockRef,
13    files::StoreDir,
14    id_source::{DeviceId, IdSourceRef, InviteId, MemberId},
15};
16use coven_storage::{ProviderSignOut, StorageFailure};
17use std::sync::Arc;
18
19#[path = "admin_steps.rs"]
20mod admin;
21
22/// The steps of the app's write that journal an operation (§4, §11.1):
23/// checked against the state this device has applied, journaled with or
24/// without storage, and run by a later pass. One per writer handle.
25pub struct OperationSteps {
26    device: DeviceId,
27    identity: Arc<KeySession<MemberIdentity>>,
28    ids: IdSourceRef,
29    clock: ClockRef,
30    directory: StoreDir,
31    /// This device's storage credentials, which an invite giving its own S3
32    /// key reads (§14.3).
33    credentials: Arc<crate::DeviceCredentials>,
34    waits: Arc<RetryWaits>,
35    state: Arc<SequenceState>,
36}
37
38impl OperationSteps {
39    /// Compose where the writer handle is made.
40    pub fn new(
41        device: DeviceId,
42        identity: Arc<KeySession<MemberIdentity>>,
43        ids: IdSourceRef,
44        clock: ClockRef,
45        directory: StoreDir,
46        credentials: Arc<crate::DeviceCredentials>,
47        waits: Arc<RetryWaits>,
48        state: Arc<SequenceState>,
49    ) -> Self {
50        Self { device, identity, ids, clock, directory, credentials, waits, state }
51    }
52
53    /// The member pair this installation holds, which an admin step checks
54    /// the applied binding against.
55    fn held(&self) -> Result<MemberIdentity, SyncError> {
56        Ok(self.identity.read()?.ok_or(StorageFailure::MemberKeysMissing)?)
57    }
58
59    /// Journal a device's removal as a step of an app's write, and say how
60    /// its member signs out of the provider, if anything is left to do
61    /// there, from the recorded location (§14.2).
62    pub fn remove_device(
63        &self,
64        sql: &SqlContext<'_, '_>,
65        device: DeviceId,
66    ) -> Result<(Option<OperationId>, Option<ProviderSignOut>), SyncError> {
67        let location =
68            coven_storage::recorded_config(&self.directory)?.ok_or(SyncError::NoStorage)?;
69        let operation = self.administer(sql, StoreChange::RemoveDevice { device })?;
70        Ok((operation, location.provider().sign_out()))
71    }
72
73    /// Make an invite, as a step of a write (§13.2), and return its id, the
74    /// member id it fixes and its operation. The write checks the invite
75    /// against the slots this device has applied, then journals it, with or
76    /// without storage; the invite is listed in `coven_invites` from its
77    /// commit, without a code. Once the write commits, a pass is asked for,
78    /// which checks the invite again against the history it catches up with,
79    /// grants its storage access and fixes its code. A check that fails
80    /// there, or a failed grant, is the invite's pending record in
81    /// `coven_pending`, under its operation; the app cancels the invite to
82    /// end it. The invite expires after its lifetime by this device's clock,
83    /// from now. The invite is made at the store's recorded location; a store
84    /// with none fails with `NoStorage`.
85    ///
86    /// Made by a device that isn't a registered admin, the step fails with
87    /// `Rejected(NotAllowed)`; for a replacement of a member who isn't
88    /// active, with `Rejected(TargetGone)`, and of this device's own member,
89    /// with `Rejected(NotAllowed)`. A name that isn't one fails with
90    /// `Format`, and access that doesn't fit the location with its storage
91    /// failure.
92    pub fn create_invite(
93        &self,
94        sql: &SqlContext<'_, '_>,
95        invite: NewInvite,
96    ) -> Result<(InviteId, MemberId, OperationId), SyncError> {
97        let location =
98            coven_storage::recorded_config(&self.directory)?.ok_or(SyncError::NoStorage)?;
99        let made = make_invite(
100            sql,
101            self.device,
102            &self.held()?,
103            self.ids.as_ref(),
104            self.clock.now(),
105            &location,
106            &self.credentials,
107            invite,
108        )?;
109        let state = self.state.clone();
110        sql.after_commit(move || state.request_pass());
111        Ok(made)
112    }
113
114    /// Approve exactly this checked request, as a step of a write (§13.2),
115    /// and return the operation that binds its pair: the
116    /// write journals it, and the invite's approval begins, with or without
117    /// storage. Once the write commits, a pass is asked for, which catches
118    /// up and claims one admission: the entry admitting the member with the
119    /// request's pair, or rebinding their pair, and registering the request's
120    /// device, carrying copies of every store key and the held circle keys
121    /// for that pair; once begun, approval finishes. The operation's outcome is
122    /// listed in `coven_operations`: a rejection ends the invite as a
123    /// decline does. The step doesn't check the approval against the applied
124    /// state, so the app is never refused an approval it was shown as
125    /// waiting: one the history refuses, as when this admin was demoted, is
126    /// refused by the pass, as its binding's outcome. A request the invite no
127    /// longer shows, and an invite whose lifetime ended, fail the step with
128    /// `InvitationChanged`.
129    pub fn approve_join_request(
130        &self,
131        sql: &SqlContext<'_, '_>,
132        request: &crate::JoinRequest,
133    ) -> Result<OperationId, SyncError> {
134        let (invite, binding) = approve_request(sql, self.clock.now(), request)?;
135        self.wake_after_commit(sql, invite);
136        Ok(binding)
137    }
138
139    /// Decline an invite's checked request, as a step of a write (§13.2):
140    /// the write ends the invite, which takes it out of `coven_invites`, with
141    /// or without storage. Once the write commits, a pass is asked for, which
142    /// deletes the request, so the requester's join ends as declined, and
143    /// takes back the access the invite granted. A request the invite no
144    /// longer shows, an invite whose approval has begun, and one whose
145    /// lifetime ended fail the step with `InvitationChanged`.
146    pub fn decline_join_request(
147        &self,
148        sql: &SqlContext<'_, '_>,
149        request: &crate::JoinRequest,
150    ) -> Result<(), SyncError> {
151        let ended = end_invite(sql, self.clock.now(), request.invite, Some(request))?;
152        self.wake_after_commit(sql, ended);
153        Ok(())
154    }
155
156    /// Cancel an invite before anyone joins with it, as a step of a write
157    /// (§13.2): the write ends the invite, which takes it out of
158    /// `coven_invites`, with or without storage. Once the write commits, a
159    /// pass is asked for, which deletes a waiting request, so the requester's
160    /// join ends as declined, and takes back the access the invite granted.
161    /// An invite whose approval has begun, and one whose lifetime ended, fail
162    /// the step with `InvitationChanged`.
163    pub fn cancel_invite(
164        &self,
165        sql: &SqlContext<'_, '_>,
166        invite: InviteId,
167    ) -> Result<(), SyncError> {
168        let ended = end_invite(sql, self.clock.now(), invite, None)?;
169        self.wake_after_commit(sql, ended);
170        Ok(())
171    }
172
173    /// Make a pairing, as a step of a write (§13.2): the write checks that
174    /// this device is registered and its member active in the slots it has
175    /// applied, fixes the pairing's codes and journals it, with or without
176    /// storage. `key` is the S3 key this device connects with, which an S3
177    /// pairing's QR code carries; one without it fails with
178    /// `InvalidConfiguration`. Once the write commits, a pass is asked for,
179    /// which looks for the pairing's request.
180    pub fn add_device(
181        &self,
182        sql: &SqlContext<'_, '_>,
183        key: Option<coven_storage::S3Credentials>,
184    ) -> Result<AddDevice, SyncError> {
185        let location =
186            coven_storage::recorded_config(&self.directory)?.ok_or(SyncError::NoStorage)?;
187        let made = sequence_pairings::make_pairing(
188            sql,
189            self.device,
190            &self.held()?,
191            self.ids.as_ref(),
192            self.clock.now(),
193            &location,
194            key,
195        )?;
196        self.pass_after_commit(sql);
197        Ok(made)
198    }
199
200    /// Approve exactly this checked request, as a step of a write (§13.2):
201    /// `request` is the one the app was shown, which the pairing compares
202    /// with the one it holds before it seals the member's current private
203    /// pair to that request's sealing key and journals the handover. Once
204    /// the write commits, a pass is asked for, which puts the handover in the
205    /// request's place. A request the pairing no longer shows, and a pairing
206    /// whose lifetime ended, fail the step with `InvitationChanged`.
207    pub fn approve_add_device(
208        &self,
209        sql: &SqlContext<'_, '_>,
210        request: &AddDeviceRequest,
211    ) -> Result<(), SyncError> {
212        sequence_pairings::approve_request(
213            sql,
214            self.directory.id(),
215            self.clock.now(),
216            &self.held()?,
217            request,
218        )?;
219        self.pass_after_commit(sql);
220        Ok(())
221    }
222
223    /// Decline exactly this checked request, as a step of a write (§13.2):
224    /// the pairing ends as declined, and a pass is asked for, which puts the
225    /// marker in the request's place. A request the pairing no longer shows,
226    /// an approved pairing, and one whose lifetime ended, fail the step with
227    /// `InvitationChanged`.
228    pub fn decline_add_device(
229        &self,
230        sql: &SqlContext<'_, '_>,
231        request: &AddDeviceRequest,
232    ) -> Result<(), SyncError> {
233        sequence_pairings::decline_request(sql, self.clock.now(), request)?;
234        self.pass_after_commit(sql);
235        Ok(())
236    }
237
238    /// The screen showing the pairing's code closed, as a step of a write
239    /// (§13.2): the pairing ends at whatever stage it is and is forgotten
240    /// once a pass has put the marker in the place of its request or
241    /// handover. A pairing that has ended is forgotten as it is; one already
242    /// forgotten changes nothing.
243    pub fn end_add_device(
244        &self,
245        sql: &SqlContext<'_, '_>,
246        pairing: AddDeviceId,
247    ) -> Result<(), SyncError> {
248        sequence_pairings::end_add_device(sql, pairing)?;
249        self.pass_after_commit(sql);
250        Ok(())
251    }
252
253    /// Once the write commits, a pass is asked for.
254    fn pass_after_commit(&self, sql: &SqlContext<'_, '_>) {
255        let state = self.state.clone();
256        sql.after_commit(move || state.request_pass());
257    }
258
259    /// Once the write commits, the invite's wait ends in this session and a
260    /// pass is asked for.
261    fn wake_after_commit(&self, sql: &SqlContext<'_, '_>, invite: OperationId) {
262        let (waits, state) = (self.waits.clone(), self.state.clone());
263        sql.after_commit(move || {
264            waits.operation_advanced(invite);
265            state.request_pass();
266        });
267    }
268
269    /// Make an operation due now, as a step of a write (E6): its pending
270    /// record and retry wait end in the write's transaction. It cannot
271    /// resurrect an invalidated action, or one that waits for an update not
272    /// installed yet, and it can't bypass a provider cooldown or the
273    /// stuck-device rule. Once the write commits, the operation's wait ends
274    /// in this session too, and a pass is asked for to run it.
275    pub fn retry_pending_operation(
276        &self,
277        sql: &SqlContext<'_, '_>,
278        id: OperationId,
279    ) -> Result<(), SyncError> {
280        make_retry_due(sql, id)?;
281        let (waits, state) = (self.waits.clone(), self.state.clone());
282        sql.after_commit(move || {
283            waits.retried(id);
284            state.request_pass();
285        });
286        Ok(())
287    }
288}