Skip to main content

coven/
storage_setup.rs

1//! Storage setup as an operation (§11.6, §20.8). Setup journals itself
2//! before its first write to storage, keeping the credentials it connects
3//! with apart from the committed ones. Until its point of no return a
4//! cancel or a failure undoes it, and opening the store undoes one a crash
5//! cut. Past that point it finishes: in the call, or after a crash in the
6//! first connection attempt, with the credentials it kept. Only finishing
7//! commits the connection.
8
9use super::*;
10use coven_crypto::custody::StoreKeychain;
11use coven_database::{OperationRejection, StorageSetupOutcome, UndoCause};
12use coven_storage::CheckEnd;
13use coven_sync::SetupJournal;
14
15/// Where this session's storage setup stands, which a cancel reads (E5).
16pub(crate) enum SetupRun {
17    /// No setup runs.
18    Idle,
19    /// A setup call has started and journaled nothing yet; `cancelled` once
20    /// the app asked to cancel it, which it keeps until it journals.
21    Called { cancelled: bool },
22    /// A setup checks the provider; `cancelled` once the app asked to
23    /// cancel it.
24    Checking { cancelled: bool },
25    /// A setup is past its point of no return: this session's, or one a
26    /// crash cut, which the first connection finishes.
27    Finishing,
28}
29
30/// A setup call from its start until it journals itself, when a cancel
31/// already reaches it (§11.6). A call that ends before its journal ends it.
32pub(super) struct SetupCall(Arc<StorageConnections>);
33
34impl SetupCall {
35    /// The call has journaled itself: it checks the provider now, keeping
36    /// a cancel that came before. Answers whether one did.
37    fn journaled(self) -> Result<bool, StorageSetupError> {
38        let mut run = lock_unpoisoned(&self.0.setup);
39        match *run {
40            SetupRun::Called { cancelled } => {
41                *run = SetupRun::Checking { cancelled };
42                Ok(cancelled)
43            }
44            SetupRun::Idle | SetupRun::Checking { .. } | SetupRun::Finishing => {
45                Err(setup_error(DbError::Invariant { what: "a setup call runs alone" }.into()))
46            }
47        }
48    }
49}
50
51impl Drop for SetupCall {
52    fn drop(&mut self) {
53        let mut run = lock_unpoisoned(&self.0.setup);
54        if matches!(*run, SetupRun::Called { .. }) {
55            *run = SetupRun::Idle;
56        }
57    }
58}
59
60/// What cancelling storage setup did (E5).
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub enum SetupCancellation {
63    /// Setup hadn't reached its point of no return: it undoes what it
64    /// wrote and fails with `StorageSetupError::Cancelled`.
65    Undoing,
66    /// Setup is past its point of no return, and finishes.
67    Finishing,
68    /// No setup is running.
69    NoSetup,
70}
71
72/// A place between two of setup's steps, where a test stops it as a crash
73/// would, or holds it.
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub(crate) enum SetupStop {
76    /// Its call has started and journaled nothing.
77    Called,
78    /// Its row and credentials are journaled.
79    Journaled,
80    /// S3 detection is done.
81    Detected,
82    /// The provider check is done.
83    Checked,
84    /// Its row is past the point of no return.
85    Claiming,
86    /// What it claims has landed.
87    Created,
88    /// The connection is committed.
89    Committed,
90    /// Its row has ended.
91    Finished,
92}
93
94/// What a test does to the next setup at one of its stops.
95#[cfg(test)]
96pub(crate) enum SetupHook {
97    /// Stop there as a crash would: the call returns at once, undoing and
98    /// finishing nothing.
99    Crash(SetupStop),
100    /// Say it got there on `entered`, then wait for `resume`.
101    Pause {
102        at: SetupStop,
103        entered: tokio::sync::oneshot::Sender<()>,
104        resume: tokio::sync::oneshot::Receiver<()>,
105    },
106}
107
108/// The error a crash hook stops setup with.
109#[cfg(test)]
110#[derive(Debug, thiserror::Error)]
111#[error("setup stopped as a crash would")]
112struct Crashed;
113
114/// Whether `error` is a crash hook's.
115#[cfg(test)]
116fn crashed(error: &(dyn std::error::Error + 'static)) -> bool {
117    let mut cause = Some(error);
118    while let Some(error) = cause {
119        if error.is::<Crashed>() {
120            return true;
121        }
122        cause = error.source();
123    }
124    false
125}
126
127/// The connections a setup past its point of no return finishes on: the
128/// store's, which it commits, and the one its own requests go through.
129struct FinishingConnections {
130    storage: Arc<StorageConnection>,
131    setup: Arc<StorageConnection>,
132}
133
134/// A setup failure, and the undo or start that failed after it.
135#[derive(Debug, thiserror::Error)]
136#[error("{operation}; cleanup failed: {cleanup}")]
137struct SetupCleanup {
138    operation: StorageSetupError,
139    #[source]
140    cleanup: SyncError,
141}
142
143pub(super) fn with_cleanup(operation: StorageSetupError, cleanup: SyncError) -> StorageSetupError {
144    StorageSetupError::Internal(Box::new(SetupCleanup { operation, cleanup }))
145}
146
147/// Settle a setup a crash cut, as the store opens (§11.6). One before its
148/// point of no return is undone: its credentials go, and `coven_operations`
149/// lists it undone. One past it stays for the first connection to finish.
150/// Credentials a finished setup left behind go too. Answers whether a setup
151/// is finishing.
152pub(crate) async fn settle_opened(
153    database: &coven_database::StoreDatabase,
154    keychain: &Arc<StoreKeychain>,
155) -> Result<bool, SyncError> {
156    let running = SetupJournal::running(database).await?;
157    if running.as_ref().is_some_and(|journal| journal.location().is_some()) {
158        return Ok(true);
159    }
160    let kept = keychain.clone();
161    let bugs = database.bugs().clone();
162    crate::task::blocking_completing("undo storage setup's local state", bugs, move || {
163        if kept.setup_credentials()?.is_some() {
164            kept.delete_setup_credentials()?;
165        }
166        Ok::<_, KeyError>(())
167    })
168    .await??;
169    if let Some(journal) = running {
170        journal.end(database, StorageSetupOutcome::Undone(UndoCause::Interrupted)).await?;
171    }
172    Ok(false)
173}
174
175impl StorageConnections {
176    /// Cancel this session's setup (E5): before its point of no return it
177    /// undoes what it wrote; past it, it finishes.
178    pub(crate) fn cancel_setup(&self) -> SetupCancellation {
179        let answer = match &mut *lock_unpoisoned(&self.setup) {
180            SetupRun::Idle => SetupCancellation::NoSetup,
181            SetupRun::Called { cancelled } | SetupRun::Checking { cancelled } => {
182                *cancelled = true;
183                SetupCancellation::Undoing
184            }
185            SetupRun::Finishing => SetupCancellation::Finishing,
186        };
187        self.setup_cancelled.notify_waiters();
188        answer
189    }
190
191    /// Whether a setup is past its point of no return and not yet finished.
192    pub(super) fn setup_finishing(&self) -> bool {
193        matches!(*lock_unpoisoned(&self.setup), SetupRun::Finishing)
194    }
195
196    pub(super) fn check_cancel(&self) -> Result<(), StorageSetupError> {
197        match *lock_unpoisoned(&self.setup) {
198            SetupRun::Checking { cancelled: true } => Err(StorageSetupError::Cancelled),
199            _ => Ok(()),
200        }
201    }
202
203    /// Resolves once the app has cancelled the setup checking now.
204    async fn cancelled(&self) {
205        loop {
206            let notified = self.setup_cancelled.notified();
207            tokio::pin!(notified);
208            notified.as_mut().enable();
209            if self.check_cancel().is_err() {
210                return;
211            }
212            notified.await;
213        }
214    }
215
216    /// Where a test stops or holds setup.
217    pub(super) async fn reached(
218        &self,
219        #[cfg_attr(not(test), expect(unused_variables, reason = "only tests stop setup"))]
220        at: SetupStop,
221    ) -> Result<(), StorageError> {
222        #[cfg(test)]
223        {
224            let hook = {
225                let mut held = lock_unpoisoned(&self.setup_hook);
226                match &*held {
227                    Some(SetupHook::Crash(stop) | SetupHook::Pause { at: stop, .. })
228                        if *stop == at =>
229                    {
230                        held.take()
231                    }
232                    _ => None,
233                }
234            };
235            match hook {
236                Some(SetupHook::Crash(_)) => {
237                    return Err(StorageFailure::Network.with_source(Crashed));
238                }
239                Some(SetupHook::Pause { entered, resume, .. }) => {
240                    entered.send(()).expect("the test waits for the pause");
241                    resume.await.expect("the test resumes the pause");
242                }
243                None => {}
244            }
245        }
246        Ok(())
247    }
248
249    /// Have the next setup stop or wait at one of its stops.
250    #[cfg(test)]
251    pub(crate) fn test_setup_hook(&self, hook: SetupHook) {
252        *lock_unpoisoned(&self.setup_hook) = Some(hook);
253    }
254
255    /// Start a setup call, which a cancel reaches from now on (§11.6).
256    /// Refused while another runs, or one past its point of no return is
257    /// still finishing.
258    pub(super) fn start_setup(self: &Arc<Self>) -> Result<SetupCall, StorageSetupError> {
259        let mut run = lock_unpoisoned(&self.setup);
260        if !matches!(*run, SetupRun::Idle) {
261            return Err(StorageSetupError::SetupRunning);
262        }
263        *run = SetupRun::Called { cancelled: false };
264        Ok(SetupCall(self.clone()))
265    }
266
267    /// Journal `call`'s setup before its first write to storage: its row,
268    /// then `credentials`, kept apart from the committed ones (§11.6). A
269    /// cancel that came before the row undoes it at once.
270    pub(super) async fn begin_setup(
271        &self,
272        call: SetupCall,
273        credentials: &StorageCredentials,
274    ) -> Result<SetupJournal, StorageSetupError> {
275        self.reached(SetupStop::Called).await?;
276        let creating = self.codes.location().await.map_err(setup_error)?.is_none();
277        let journal = SetupJournal::start(&self.database, creating).await.map_err(setup_error)?;
278        match call.journaled() {
279            Ok(false) => {}
280            Ok(true) => return Err(self.undo_setup(&journal, StorageSetupError::Cancelled).await),
281            Err(error) => return Err(self.undo_setup(&journal, error).await),
282        }
283        let kept = credentials
284            .encode()
285            .map_err(StorageSetupError::from)
286            .and_then(|bytes| Ok(self.keychain.set_setup_credentials(&bytes)?));
287        if let Err(error) = kept {
288            return Err(self.undo_setup(&journal, error).await);
289        }
290        self.reached(SetupStop::Journaled).await?;
291        Ok(journal)
292    }
293
294    /// Run setup's `steps` under `journal`. A failure before the point of no
295    /// return undoes setup. One after it leaves setup finishing, unless a
296    /// refusal undid it, and starts the loop, whose connection finishes it
297    /// (§11.6).
298    pub(super) async fn run_setup<T>(
299        self: &Arc<Self>,
300        mut journal: SetupJournal,
301        steps: impl AsyncFnOnce(&mut SetupJournal) -> Result<T, StorageSetupError>,
302    ) -> Result<T, StorageSetupError> {
303        let error = match steps(&mut journal).await {
304            Ok(done) => return Ok(done),
305            Err(error) => error,
306        };
307        #[cfg(test)]
308        if crashed(&error) {
309            return Err(error);
310        }
311        if journal.location().is_none() {
312            return Err(self.undo_setup(&journal, error).await);
313        }
314        if self.setup_finishing() {
315            if let Err(cleanup) = self.start_locked().await {
316                return Err(with_cleanup(error, cleanup));
317            }
318        }
319        Err(error)
320    }
321
322    /// Undo a setup before its point of no return: its credentials go, then
323    /// its row ends cancelled, or undone with `error` (§11.6). Nothing it
324    /// wrote to storage is state: a test object or a probe is space.
325    async fn undo_setup(
326        &self,
327        journal: &SetupJournal,
328        error: StorageSetupError,
329    ) -> StorageSetupError {
330        let outcome = match &error {
331            StorageSetupError::Cancelled => StorageSetupOutcome::Cancelled,
332            error => StorageSetupOutcome::Undone(UndoCause::Failed { error: error.to_string() }),
333        };
334        let undone = async {
335            self.keychain.delete_setup_credentials()?;
336            journal.end(&self.database, outcome).await?;
337            *lock_unpoisoned(&self.setup) = SetupRun::Idle;
338            Ok::<_, SyncError>(())
339        }
340        .await;
341        match undone {
342            Ok(()) => error,
343            Err(cleanup) => with_cleanup(error, cleanup),
344        }
345    }
346
347    /// Pass setup's point of no return, claiming at `location`, unless the
348    /// app has cancelled it: from here on a cancel is answered `Finishing`.
349    async fn pass_point(
350        &self,
351        journal: &mut SetupJournal,
352        location: StorageConfig,
353    ) -> Result<(), StorageSetupError> {
354        {
355            let mut run = lock_unpoisoned(&self.setup);
356            if matches!(*run, SetupRun::Checking { cancelled: true }) {
357                return Err(StorageSetupError::Cancelled);
358            }
359            *run = SetupRun::Finishing;
360        }
361        if let Err(error) = journal.claim(&self.database, location).await {
362            *lock_unpoisoned(&self.setup) = SetupRun::Checking { cancelled: false };
363            return Err(setup_error(error));
364        }
365        Ok(())
366    }
367
368    /// Check and connect `config` reached through `auth`, under `journal`.
369    /// A new OAuth sign-in is `sign_in`, the session custody `auth`
370    /// refreshes in until setup commits it to device custody. Reconnecting
371    /// then loads what other devices published; a cancel still undoes setup
372    /// meanwhile. Then setup passes its point of no return and finishes.
373    /// The setup call's own requests, its checks and its claims, go through
374    /// a connection made beside the store's that takes the call's `waits`
375    /// and sends rate-limited requests again while they allow; the store's
376    /// connection, which the sequence, the files and the sync loop keep,
377    /// never does (§20.8). Its steps go to `progress`, from `Connecting` on.
378    pub(super) async fn setup_connection(
379        &self,
380        journal: &mut SetupJournal,
381        config: StorageConfig,
382        auth: ProviderAuth,
383        sign_in: Option<Arc<SessionSignIn>>,
384        waits: SetupWaits,
385        progress: &mut ProgressReport<StorageSetupStep>,
386    ) -> Result<StorageSetup, StorageSetupError> {
387        progress.begin(StorageSetupStep::Connecting, 1);
388        let credentials = auth.credentials();
389        let storage = self
390            .connector
391            .connect(
392                config.clone(),
393                auth,
394                self.device,
395                self.state.clone(),
396                self.waits.clone(),
397                self.transfers.clone(),
398            )
399            .await?;
400        let setup = Arc::new(storage.during_setup(waits));
401        if !journal.creating() {
402            setup.check_location_claim(self.store()).await?;
403        }
404        // The folder's label as this sign-in reads it, never one the app
405        // passed (§20.2).
406        let config = setup.labelled_config().await?;
407        let path = ObjectPath::file(self.store(), self.device, ObjectId(self.ids.new_id()));
408        let checked = check_provider(&setup, &self.state, path, || self.check_cancel().is_err());
409        match checked.await.map_err(setup_error)? {
410            Ok(CheckEnd::Passed) => {}
411            Ok(CheckEnd::Stopped) => return Err(StorageSetupError::Cancelled),
412            Err(error) => return Err(error.into()),
413        }
414        progress.done(1);
415        self.reached(SetupStop::Checked).await?;
416        self.check_cancel()?;
417        let mut live = self.live.lock().await;
418        let sync = self.sequence(storage.clone(), &live).await.map_err(setup_error)?;
419        // The claims, and the catch-up an existing store needs, are the
420        // setup call's own requests, sent on its connection.
421        let claiming = Arc::new(sync.reconnect(setup.clone()));
422        if !journal.creating() {
423            let relayed = std::sync::Mutex::new(&mut *progress);
424            let loading = claiming.subscribe_progress().forward(claiming.unlock(), |load| {
425                lock_unpoisoned(&relayed).relay(setup_step::loading(load))
426            });
427            // Loading claims nothing, so a cancel still undoes setup.
428            tokio::select! {
429                biased;
430                () = self.cancelled() => return Err(StorageSetupError::Cancelled),
431                loaded = loading => loaded.map_err(setup_error)?,
432            }
433        }
434        self.pass_point(journal, config.clone()).await?;
435        self.reached(SetupStop::Claiming).await?;
436        let restore_code = self
437            .finish_setup(
438                &mut live,
439                journal,
440                sync,
441                claiming,
442                FinishingConnections { storage, setup },
443                credentials,
444                sign_in,
445                false,
446                true,
447                progress,
448            )
449            .await
450            .map_err(setup_error)?;
451        Ok(StorageSetup {
452            connection: ConnectedStorage { storage: config, key_state: StoreKeyState::Available },
453            restore_code,
454        })
455    }
456
457    /// Finish a setup a crash cut past its point of no return, connecting
458    /// with the credentials it kept, as the first connection after opening
459    /// does (§11.6). An OAuth sign-in refreshes in this session's custody
460    /// until finishing commits it.
461    pub(super) async fn resume_setup(
462        &self,
463        live: &mut ConnectionState,
464        journal: SetupJournal,
465    ) -> Result<(), SyncError> {
466        let location = journal
467            .location()
468            .ok_or(DbError::Invariant { what: "a finishing setup is past its point of no return" })?
469            .clone();
470        let bytes = self
471            .keychain
472            .setup_credentials()?
473            .ok_or(DbError::Invariant { what: "a finishing setup keeps its credentials" })?;
474        let credentials = StorageCredentials::decode(bytes.as_bytes())?;
475        let (auth, sign_in) = match &credentials {
476            StorageCredentials::S3(keys) => (ProviderAuth::S3(keys.clone()), None),
477            StorageCredentials::CloudKit => (ProviderAuth::CloudKit, None),
478            StorageCredentials::OAuth(tokens) => {
479                let sign_in = SessionSignIn::new(tokens.clone(), self.clients.clone());
480                let auth = ProviderAuth::OAuth { tokens: tokens.clone(), custody: sign_in.clone() };
481                (auth, Some(sign_in))
482            }
483        };
484        let storage = self
485            .connector
486            .connect(
487                location,
488                auth,
489                self.device,
490                self.state.clone(),
491                self.waits.clone(),
492                self.transfers.clone(),
493            )
494            .await?;
495        let sync = self.sequence(storage.clone(), live).await?;
496        let claiming = Arc::new(sync.reconnect(storage.clone()));
497        let mut progress =
498            ProgressReport::new(tokio::sync::watch::channel(None).0, self.clock.clone());
499        self.finish_setup(
500            live,
501            &journal,
502            sync,
503            claiming,
504            FinishingConnections { storage: storage.clone(), setup: storage },
505            credentials,
506            sign_in,
507            true,
508            false,
509            &mut progress,
510        )
511        .await
512        .map(drop)
513    }
514
515    /// Past the point of no return: claim what creating the store or a
516    /// changed access needs on the candidate's own connection, commit its
517    /// store connection, end the
518    /// journal row with its outcome and install `sync`, starting its loop
519    /// when `start` (§11.6). A reconnect resumed after a crash catches up
520    /// first, when `catch_up`. A claim refused before it landed undoes
521    /// setup.
522    #[expect(
523        clippy::too_many_arguments,
524        reason = "the call and a crash's resumption differ in each"
525    )]
526    async fn finish_setup(
527        &self,
528        live: &mut ConnectionState,
529        journal: &SetupJournal,
530        sync: Arc<SequenceSync>,
531        claiming: Arc<SequenceSync>,
532        candidate: FinishingConnections,
533        credentials: StorageCredentials,
534        sign_in: Option<Arc<SessionSignIn>>,
535        catch_up: bool,
536        start: bool,
537        progress: &mut ProgressReport<StorageSetupStep>,
538    ) -> Result<SecretText, SyncError> {
539        let location = journal
540            .location()
541            .ok_or(DbError::Invariant { what: "a finishing setup is past its point of no return" })?
542            .clone();
543        // The location the setup commits below, which the row records once
544        // it has.
545        let committed = location.clone();
546        let FinishingConnections { storage, setup } = candidate;
547        let access = member_access(&credentials, &setup).await?;
548        // The old provider remains installed until every fallible step
549        // succeeds. Its stopped or started state survives a refused claim.
550        let prepared = Self::with_passes_held(live, async {
551            let claimed = if journal.creating() {
552                progress.begin(StorageSetupStep::CreatingStore, 1);
553                match setup.claim_location(self.store()).await {
554                    Ok(()) => self.claim_creation(&claiming, access, progress).await,
555                    Err(error) => Err(error.into()),
556                }
557            } else {
558                self.claim_access(&claiming, access, catch_up, progress).await
559            };
560            let slot = match claimed {
561                Ok(slot) => slot,
562                Err(error) if refused(&error) => {
563                    return Err(self.refuse_setup(journal, error).await)
564                }
565                Err(error) => return Err(error),
566            };
567            self.reached(SetupStop::Created).await?;
568            let (commit, restore_code) = self
569                .codes
570                .prepare_setup(ConnectionCredentials { location, credentials }, sign_in)
571                .await?;
572            // Claims may use file transfers; only the custody commit runs
573            // inside the transfer exclusion needed to replace their provider.
574            self.files.set_storage(Some(storage), async { commit().map(drop) }).await?;
575            self.reached(SetupStop::Committed).await?;
576            Ok::<_, SyncError>((slot, restore_code))
577        })
578        .await;
579        let (slot, restore_code) = prepared?;
580        let outcome = match slot {
581            Some(slot) => StorageSetupOutcome::Landed(slot),
582            None => StorageSetupOutcome::Satisfied,
583        };
584        journal.end(&self.database, outcome).await?;
585        *lock_unpoisoned(&self.setup) = SetupRun::Idle;
586        self.reached(SetupStop::Finished).await?;
587        // The row has ended, so these are credentials nothing uses. They are
588        // the provider's secrets, so a delete that fails fails the setup's
589        // end to its caller, after the connection below is activated: the
590        // setup stands, and a call that retries the delete finds it done
591        // (an absent entry succeeds).
592        let deleted = self.keychain.delete_setup_credentials();
593        let released = self.close_live(live).await;
594        let started = self.activate(live, sync, start).await;
595        // Custody and provider are committed, and setup read the store to its
596        // end. Worker failures now belong to the sync state; setup must
597        // return the connection it published. A row that can't be written
598        // has failed the handle, which every later call reports; what it
599        // would have recorded goes to the log.
600        let recorded = coven_database::RecordedLocation::Connected(committed);
601        if let Err(written) = self.record_location(recorded, Some(self.clock.now())).await {
602            tracing::warn!("storage set up after setup can't be recorded: {written}");
603        }
604        let result = match (released, started) {
605            (Ok(()), result) | (result, Ok(())) => result,
606            (Err(operation), Err(cleanup)) => Err(SyncError::cleanup(operation, cleanup)),
607        };
608        if let Err(error) = result {
609            let failure = LastPass::failed(error);
610            if let Err(written) = self.show(failure.clone()).await {
611                tracing::warn!(
612                    ?failure,
613                    "how sync failed after setup can't be recorded: {written}"
614                );
615            }
616        }
617        deleted.map_err(SyncError::from)?;
618        Ok(restore_code)
619    }
620
621    /// Create the store, once its location is claimed where it holds one
622    /// store (§20.3): send the slot 1 creation decided, then claim Set up
623    /// storage (§10.3). A crash may have left either sent or applied: they
624    /// are settled first, and an applied one claims nothing more.
625    async fn claim_creation(
626        &self,
627        sync: &Arc<SequenceSync>,
628        access: coven_format::MemberAccess,
629        progress: &mut ProgressReport<StorageSetupStep>,
630    ) -> Result<Option<coven_merge::Slot>, SyncError> {
631        sync.publish_creation().await?;
632        sync.administer_at(coven_format::admin::StoreChange::SetUpStorage { access }).await?;
633        progress.done(1);
634        Ok(Some(coven_merge::Slot::FIRST))
635    }
636
637    /// Record changed access for an existing device (§10.1, §14.2), once a
638    /// reconnect resumed after a crash has caught up, when `catch_up`.
639    async fn claim_access(
640        &self,
641        sync: &Arc<SequenceSync>,
642        access: coven_format::MemberAccess,
643        catch_up: bool,
644        progress: &mut ProgressReport<StorageSetupStep>,
645    ) -> Result<Option<coven_merge::Slot>, SyncError> {
646        if catch_up {
647            sync.unlock().await?;
648        }
649        let member = self.identity.read()?.ok_or(StorageFailure::MemberKeysMissing)?;
650        let state = self.database.store_state().await?;
651        match access_change(&state, member.member(), access)? {
652            Some(change) => {
653                let recording = sync.administer_at(change);
654                setup_step::single(progress, StorageSetupStep::RecordingAccess, recording).await
655            }
656            None => Ok(None),
657        }
658    }
659
660    /// Undo a setup whose claim was refused before anything it claimed
661    /// landed: its credentials go, and its row ends with the refusal
662    /// (§11.2, §11.6).
663    async fn refuse_setup(&self, journal: &SetupJournal, error: SyncError) -> SyncError {
664        let outcome = match &error {
665            SyncError::Rejected(reason) => StorageSetupOutcome::Rejected(reason.clone()),
666            SyncError::StoreOwner => StorageSetupOutcome::Rejected(OperationRejection::StoreOwner),
667            error => StorageSetupOutcome::Undone(UndoCause::Failed { error: error.to_string() }),
668        };
669        let undone = async {
670            self.keychain.delete_setup_credentials()?;
671            journal.end(&self.database, outcome).await?;
672            *lock_unpoisoned(&self.setup) = SetupRun::Idle;
673            Ok::<_, SyncError>(())
674        }
675        .await;
676        match undone {
677            Ok(()) => error,
678            Err(cleanup) => SyncError::cleanup(error, cleanup),
679        }
680    }
681}
682
683/// Run the provider check (§20.8) on `connection` with a sealed test object
684/// at `path`, which `state` lets the check publish, stopping between its
685/// steps once `stopped` answers true. The outer error is a failure to seal
686/// the object; the inner one the check's.
687pub(super) async fn check_provider(
688    connection: &StorageConnection,
689    state: &coven_sync::SequenceState,
690    path: ObjectPath,
691    stopped: impl Fn() -> bool,
692) -> Result<Result<CheckEnd, StorageCheckError>, SyncError> {
693    let plaintext = b"coven storage check";
694    let header = coven_format::file::FileHeader::new(plaintext.len() as u64);
695    let key = coven_crypto::FileKey::generate()?;
696    let mut bytes = header.encode().to_vec();
697    bytes.extend(header.seal_chunk(&key, path.as_str(), 0, plaintext).map_err(
698        |error| match error {
699            coven_format::file::FileError::Format(error) => SyncError::from(error),
700            coven_format::file::FileError::Crypto(error) => SyncError::from(error),
701        },
702    )?);
703    let _permit = state.permit_provider_check(&path);
704    Ok(coven_storage::check_provider(connection, &path, &bytes, stopped).await)
705}
706
707/// Whether a claim past the point of no return was refused before it
708/// landed: another store holds the location or slot 1, or the caught-up
709/// history refuses the access change. Any other failure is retried.
710fn refused(error: &SyncError) -> bool {
711    match error {
712        SyncError::Rejected(_) | SyncError::StoreOwner => true,
713        SyncError::Storage(error) => matches!(
714            error.failure(),
715            StorageFailure::StoreExists | StorageFailure::OwnLocationRequired
716        ),
717        _ => false,
718    }
719}
720
721#[cfg(test)]
722#[path = "storage_setup_tests.rs"]
723mod tests;