Skip to main content

coven/
builder.rs

1//! Compose database, custody, operation and file owners at the store boundary.
2
3use crate::*;
4use coven_crypto::custody::{
5    Custody, CustodyChoice, InMemoryCustody, KeyMaterial, KeySession, Keychain, KeyringCustody,
6    PassphraseCustody, PersonEntries, StoreCustody, StoreKeychain,
7};
8use coven_database::{DatabaseBuilder, OpenStep};
9use coven_foundation::files::StoreDirAccess;
10use coven_foundation::files::StoreFile;
11use coven_foundation::progress::Progress;
12#[cfg(test)]
13use coven_foundation::progress::RecordingClock;
14use coven_storage::{
15    providers::{OAuthExchange, OAuthFlow, StorageConnector},
16    Storage,
17};
18use std::sync::Arc;
19
20#[path = "builder_joining.rs"]
21mod joining;
22use joining::JoiningHook;
23
24#[path = "builder_before_commit.rs"]
25mod before_commit;
26use before_commit::BeforeCommit;
27
28/// The choices for creating or opening a store (E1).
29pub struct CovenBuilder {
30    tables: Option<Vec<SyncedTable>>,
31    namespaces: Vec<coven_database::Namespace>,
32    migrations: Option<Vec<Migration>>,
33    directories: coven_foundation::files::StoreDirectories,
34    keychain: Arc<Keychain>,
35    ids: IdSourceRef,
36    clock: ClockRef,
37    connector: Option<Arc<dyn StorageConnector>>,
38    transfers: Arc<coven_storage::TransferBudget>,
39    /// The installation's places for open files, which every file owner this
40    /// builder makes shares.
41    files: coven_foundation::files::FileBudget,
42    /// Where the store's watch hears about the device's network (§6.7).
43    network: coven_foundation::network_watch::NetworkSource,
44    oauth: Option<OAuthClients>,
45    presenter: Option<Arc<dyn OAuthPresenter>>,
46    /// The latest sign-in, held for this session until bootstrap or setup
47    /// publishes it, or a join keeps it on the device beside its saved code.
48    authentication: Option<Arc<coven_sync::SessionSignIn>>,
49    keys: SessionSource<StoreKeyring>,
50    identity: SessionSource<MemberIdentity>,
51    sqlite: SqliteSettings,
52    sql_functions: coven_database::SqlFunctions,
53    /// The app's write for a member's device as its registration applies.
54    joining_write: Option<Arc<JoiningHook>>,
55    /// The app's function that each transaction changing its rows runs last.
56    before_commit: Option<Arc<BeforeCommit>>,
57    /// Stop a replacement right after its swap, as if the process ended there.
58    #[cfg(test)]
59    interrupt_after_swap: bool,
60    /// Fail the insert of the device-reset notice a reset commits, as a full
61    /// disk would.
62    #[cfg(test)]
63    fail_device_reset_notice: bool,
64    /// Have SQLite refuse to close the store this builder opens.
65    #[cfg(test)]
66    refuse_database_close: bool,
67    /// Stop a replacement right after its fresh device registered, before
68    /// its swap, as if the process ended there.
69    #[cfg(test)]
70    interrupt_after_registering: bool,
71    /// Stop the next commit of a new installation's custody right after it
72    /// writes the device id, as if the process ended there.
73    #[cfg(test)]
74    interrupt_commit: bool,
75    /// Records every value a bootstrap through this builder reports as it
76    /// loads; also the builder's clock.
77    #[cfg(test)]
78    loading_recorder: Option<Arc<RecordingClock<coven_database::LoadStep>>>,
79}
80
81/// What a store's owners continue from as its handle is made.
82enum Continuing {
83    /// The store's own files: a new sequence state, no connection yet, and
84    /// device credentials over this installation's keychain.
85    Fresh,
86    /// A bootstrap that loaded the store from storage: the sequence state
87    /// and connection it loaded through, and, for a join, the device
88    /// credentials its sign-in is kept in (§13.2).
89    Loaded {
90        state: Arc<coven_sync::SequenceState>,
91        storage: Arc<coven_storage::StorageConnection>,
92        credentials: Option<Arc<coven_sync::DeviceCredentials>>,
93    },
94}
95
96/// What a builder makes a key kind's session from: the configured choice, or
97/// the unlocked session a reset or restore transfers into the replacement.
98enum SessionSource<T: KeyMaterial> {
99    Configured(CustodyChoice<T>),
100    Session(Arc<KeySession<T>>),
101}
102
103impl CovenBuilder {
104    pub(crate) fn new(
105        directories: coven_foundation::files::StoreDirectories,
106        keychain: Arc<Keychain>,
107        network: coven_foundation::network_watch::NetworkSource,
108        files: coven_foundation::files::FileBudget,
109    ) -> Self {
110        let ids: IdSourceRef = Arc::new(UuidIds);
111        let clock: ClockRef = Arc::new(SystemClock);
112        Self {
113            tables: None,
114            namespaces: Vec::new(),
115            migrations: None,
116            directories,
117            keychain,
118            ids,
119            clock,
120            connector: None,
121            oauth: None,
122            #[cfg(not(any(target_os = "ios", target_os = "android")))]
123            presenter: Some(Arc::new(DesktopOAuthPresenter)),
124            #[cfg(any(target_os = "ios", target_os = "android"))]
125            presenter: None,
126            authentication: None,
127            transfers: Arc::new(coven_storage::TransferBudget::new(TransferLimits::default())),
128            files,
129            network,
130            keys: SessionSource::Configured(CustodyChoice::Keyring),
131            identity: SessionSource::Configured(CustodyChoice::Keyring),
132            sqlite: SqliteSettings::default(),
133            sql_functions: coven_database::SqlFunctions::default(),
134            joining_write: None,
135            before_commit: None,
136            #[cfg(test)]
137            interrupt_after_swap: false,
138            #[cfg(test)]
139            fail_device_reset_notice: false,
140            #[cfg(test)]
141            refuse_database_close: false,
142            #[cfg(test)]
143            interrupt_after_registering: false,
144            #[cfg(test)]
145            interrupt_commit: false,
146            #[cfg(test)]
147            loading_recorder: None,
148        }
149    }
150
151    /// The tables that sync (E2). Required.
152    pub fn synced_tables(mut self, tables: Vec<SyncedTable>) -> Self {
153        self.tables = Some(tables);
154        self
155    }
156    /// The file namespaces, each with its kind and cache budget (E1). A file
157    /// is staged into one of them.
158    pub fn namespaces(mut self, namespaces: Vec<coven_database::Namespace>) -> Self {
159        self.namespaces = namespaces;
160        self
161    }
162    /// The app's schema migrations, numbered from 1 with no gaps (E13).
163    /// Required.
164    pub fn migrations(mut self, migrations: Vec<Migration>) -> Self {
165        self.migrations = Some(migrations);
166        self
167    }
168    /// The wall clock that timestamps use (§7.2). Defaults to the system clock.
169    pub fn clock(mut self, clock: ClockRef) -> Self {
170        self.clock = clock;
171        self
172    }
173    /// The source of new ids: store, circle, member, key, invite, file and
174    /// stored object ids, the ids of S3 detection runs and upload sessions, and
175    /// this install's device id (Appendix F.2).
176    /// Defaults to `UuidIds`.
177    pub fn id_source(mut self, ids: IdSourceRef) -> Self {
178        self.ids = ids;
179        self
180    }
181    /// Replace provider construction in tests while exercising setup, credential
182    /// custody, reconnect, restore and recovery through the production graph.
183    /// `coven_storage::test_utils::MemoryStorage` implements this connector.
184    #[cfg(any(test, feature = "test-utils"))]
185    pub fn storage_connector(mut self, connector: Arc<dyn StorageConnector>) -> Self {
186        self.connector = Some(connector);
187        self
188    }
189    fn connector(&mut self) -> Arc<dyn StorageConnector> {
190        self.connector
191            .get_or_insert_with(|| {
192                Arc::new(coven_storage::providers::ProviderConnector::new(
193                    self.clock.clone(),
194                    self.ids.clone(),
195                ))
196            })
197            .clone()
198    }
199
200    /// Configure this app's own sign-in clients. Coven supplies no client ids.
201    pub fn oauth_clients(mut self, clients: OAuthClients) -> Self {
202        self.oauth = Some(clients);
203        self
204    }
205    /// Present sign-in through the app's platform sheet. Desktop defaults to
206    /// `DesktopOAuthPresenter`; iOS and Android require the app's presenter.
207    pub fn oauth_presenter(mut self, presenter: Arc<dyn OAuthPresenter>) -> Self {
208        self.presenter = Some(presenter);
209        self
210    }
211
212    /// Sign in and keep tokens in session custody for restore, join or opening.
213    /// Replaces the prior sign-in only on success. Dropping the future cancels it.
214    pub async fn authenticate(&mut self, access: OAuthAccess) -> Result<(), OAuthError> {
215        let exchange = self.oauth_exchange();
216        let flow = Self::oauth_flow(exchange.clone(), self.presenter.clone())
217            .ok_or(OAuthError::Unavailable(access.provider()))?;
218        let tokens = flow.authenticate(access).await?;
219        self.authentication = Some(coven_sync::SessionSignIn::new(tokens, exchange));
220        Ok(())
221    }
222
223    /// The app's sign-in clients, sending their token requests with this
224    /// builder's clock and a client of their own.
225    fn oauth_exchange(&self) -> Option<OAuthExchange> {
226        Some(OAuthExchange::new(self.oauth.clone()?, self.clock.clone()))
227    }
228
229    /// Whether the app configured sign-in: its clients and its presenter.
230    fn signs_in(&self) -> bool {
231        self.oauth.is_some() && self.presenter.is_some()
232    }
233
234    fn oauth_flow(
235        exchange: Option<OAuthExchange>,
236        presenter: Option<Arc<dyn OAuthPresenter>>,
237    ) -> Option<OAuthFlow> {
238        Some(OAuthFlow::new(exchange?, presenter?))
239    }
240
241    /// Limit file uploads running together; defaults to one.
242    pub fn max_concurrent_uploads(self, n: std::num::NonZeroUsize) -> Self {
243        let mut limits = self.transfers.limits();
244        limits.uploads = n;
245        self.transfers.set_limits(limits);
246        self
247    }
248    /// Limit file downloads running together; defaults to one. The
249    /// sequence's own reads don't count against it.
250    pub fn max_concurrent_downloads(self, n: std::num::NonZeroUsize) -> Self {
251        let mut limits = self.transfers.limits();
252        limits.downloads = n;
253        self.transfers.set_limits(limits);
254        self
255    }
256
257    /// Where this device keeps the store keys: the OS keychain by default, a
258    /// file sealed with a passphrase, memory for this session only, or the
259    /// app's own `Custody<StoreKeyring>`.
260    pub fn key_custody(mut self, custody: CustodyChoice<StoreKeyring>) -> Self {
261        self.keys = SessionSource::Configured(custody);
262        self
263    }
264    /// Where this device keeps its member's keys, with the same four choices
265    /// and the app's own `Custody<MemberIdentity>` as the last.
266    pub fn identity_custody(mut self, custody: CustodyChoice<MemberIdentity>) -> Self {
267        self.identity = SessionSource::Configured(custody);
268        self
269    }
270
271    /// SQLite settings for every connection a handle opens to the store's
272    /// database (§4). Unset ones keep SQLite's defaults, except that
273    /// `checkpoint_fullfsync` is on for macOS and iOS; the page size and
274    /// auto-vacuum mode apply only when the database is created.
275    pub fn sqlite_settings(mut self, settings: SqliteSettings) -> Self {
276        self.sqlite = settings;
277        self
278    }
279
280    /// Apple's protection class for the store's files: when they can be read
281    /// and written against whether the device is locked (E1). Creating,
282    /// restoring, joining or replacing a store gives each new installation's
283    /// directory the class before anything is made there. A writable open,
284    /// a resumed restore or join, and a replacement give it to every file
285    /// already there, unless they were last given this class. On a volume
286    /// that keeps no classes each of them fails before any file changes.
287    /// Unset, coven leaves every class as it is, and new files take their
288    /// folder's.
289    #[cfg(target_vendor = "apple")]
290    pub fn file_protection(mut self, protection: FileProtection) -> Self {
291        self.directories = self.directories.file_protection(protection);
292        self
293    }
294
295    /// A collation the app's SQL names with `COLLATE name` (§4), ordering
296    /// text by `compare` at `version`, on every connection a handle opens to
297    /// the store's database. The order is part of the store's schema:
298    /// `compare` must be deterministic, the same on every device and in every
299    /// app version that registers this `version`, and a total order. Every
300    /// change to the order takes a new version, and a writable open then
301    /// rebuilds the indexes in it. A name that is SQLite's own (`BINARY`,
302    /// `NOCASE`, `RTRIM`) or given twice fails the open, and a panic in
303    /// `compare` ends the process.
304    pub fn collation<F>(mut self, name: impl Into<String>, version: u32, compare: F) -> Self
305    where
306        F: Fn(&str, &str) -> std::cmp::Ordering + Send + Sync + 'static,
307    {
308        self.sql_functions =
309            std::mem::take(&mut self.sql_functions).collation(name, version, compare);
310        self
311    }
312
313    /// A scalar function the app's SQL calls as `name(...)` with exactly
314    /// `arguments` arguments (§4), on every connection a handle opens to the
315    /// store's database. `compute` reads the arguments and returns the
316    /// result, or an error that fails the statement calling it.
317    /// A deterministic function can appear in indexes, CHECKs and generated
318    /// columns, and is then part of the store's schema: at its version it
319    /// must give the same result for the same arguments on every device and
320    /// in every app version, and takes at least one argument. Every change
321    /// to its results takes a new version, and a writable open then rebuilds
322    /// the indexes that call it. A name SQLite or coven
323    /// already has, one with coven's prefix `coven_` or `_coven_`, or one
324    /// given twice fails the open, and a panic in `compute` ends the process.
325    pub fn function<F, T>(
326        mut self,
327        name: impl Into<String>,
328        arguments: u8,
329        determinism: Determinism,
330        compute: F,
331    ) -> Self
332    where
333        F: Fn(&FunctionArguments<'_>) -> SqliteResult<T> + Send + Sync + 'static,
334        T: Into<types::Value>,
335    {
336        self.sql_functions =
337            std::mem::take(&mut self.sql_functions).scalar(name, arguments, determinism, compute);
338        self
339    }
340
341    /// Opens the store for reading and writing, taking the store's lock.
342    /// Opening creates coven's tables, when the database holds none, before the app's schema, then
343    /// unlocks both custody sessions before resuming unfinished operations and
344    /// committed file work. Empty custody is allowed; an unlock failure prevents
345    /// opening. No sync loop starts, and local database calls need no key material.
346    /// `on_progress` is called on this task with each step the open runs and
347    /// how much of it is done, at most a few times a second (§4).
348    pub async fn open(
349        self,
350        store: StoreId,
351        on_progress: impl Fn(Progress<OpenStep>),
352    ) -> CovenResult<CovenHandle> {
353        // Its work rides on the heap, as every bootstrap's does, so an app's
354        // future holding this call stays small.
355        Box::pin(async move {
356            let opening = self.open_graph(store, Opening::ForUse).await?;
357            let progress = opening.database.subscribe_progress();
358            progress.forward(opening.open(), on_progress).await
359        })
360        .await
361    }
362
363    /// Finishes this device's recorded deletion of `store`, which
364    /// `CovenHandle::delete_store` began and couldn't finish: it opens the
365    /// store as `open` does, then goes on as the deletion would, with the
366    /// choice for unsent work it recorded. Before the device's removal is
367    /// journaled, a refusal or failure removes the record and leaves the
368    /// store as it was; from the journal on, a failure is
369    /// `StoreDeletionError::Unfinished` and the deletion stays recorded
370    /// (§11.6, E1). A store with no deletion recorded fails with
371    /// `StoreDeletionError::NoUnfinishedDeletion`.
372    pub async fn resume_deletion(self, store: StoreId) -> Result<(), StoreDeletionError> {
373        Box::pin(async move {
374            let directory = self.directories.store_dir(&store);
375            let bugs = directory.bugs().clone();
376            let unsent =
377                crate::task::blocking_completing("read the deletion record", bugs, move || {
378                    directory.unfinished_deletion()
379                })
380                .await??
381                .ok_or(StoreDeletionError::NoUnfinishedDeletion(store))?;
382            let opening = self
383                .open_graph(store, Opening::ToDelete)
384                .await
385                .map_err(StoreDeletionError::Open)?;
386            let handle = opening.open().await.map_err(StoreDeletionError::Open)?;
387            handle.leave(unsent).await
388        })
389        .await
390    }
391
392    /// Replace this installation with a new device loaded from storage
393    /// (§19.3), whenever the app chooses: after sync found another copy using
394    /// this device's id, a damaged database, or a device entry `open` found
395    /// missing. Uses saved settings, credentials and member keys; nothing
396    /// unsent is salvaged. The new device loads beside the old copy, which
397    /// moves aside only once loading is complete; saved member keys that
398    /// history has replaced fail with `MemberKeysReplaced` and change nothing.
399    /// Just before the fresh device registers, the reset records itself and
400    /// only goes forward: the store refuses opens with
401    /// `StoreLockError::ReplacementUnfinished` until this call, or
402    /// `resume_replacement`, finishes it. An interrupted call resumes with the
403    /// same fresh id. A replacement `restore_device` began is refused with
404    /// `StoreLockError::ReplacementUnfinished`, changing nothing. The returned
405    /// handle's `device_reset()` names the old and new ids. `on_status` hears
406    /// how far the new device has come, as the other bootstrap calls report
407    /// it.
408    pub async fn reset_device(
409        self,
410        store: StoreId,
411        device_name: &str,
412        on_status: impl Fn(BootstrapStatus),
413    ) -> Result<CovenHandle, BootstrapError> {
414        Box::pin(bootstrap::reset_device(self, store, device_name, on_status)).await
415    }
416
417    /// Restore this device's installation of `store` from the person's
418    /// current restore code, for a device whose member keys were replaced
419    /// (§13.1). The code must name this store, and its pair must be current,
420    /// checked against history before the store or keychain changes. The new
421    /// device loads beside the old copy, which stays openable until the
422    /// restore records itself, just before its fresh device registers; from
423    /// then on the store refuses opens and the restore only goes forward,
424    /// and once registered it swaps in and the old copy is removed. Cancelling
425    /// past the record waits for the registration, then fails with
426    /// `RestoreRegistered`. An interrupted call is finished by retrying it, or
427    /// by `resume_replacement`; a replacement `reset_device` began is refused
428    /// with `StoreLockError::ReplacementUnfinished`, changing nothing. A
429    /// device whose custody and applied history already hold the code's pair
430    /// just opens. S3 requires the separately held key, as
431    /// `restore_from_code` does. `prepare` is the app's step on the new
432    /// installation: one bulk write (`CovenHandle::write_bulk`) of its
433    /// device-local tables, run after loading and before the record, so what
434    /// it writes, such as preferences read from the old copy before the call,
435    /// takes the old copy's place with the new installation or not at all. A
436    /// call that finds the replacement recorded, or the pair already
437    /// installed, doesn't run it.
438    pub async fn restore_device(
439        self,
440        store: StoreId,
441        code: &str,
442        s3_credentials: Option<S3Credentials>,
443        device_name: &str,
444        prepare: impl FnOnce(BulkSqlContext<'_>) -> CovenResult<()> + Send + 'static,
445        on_status: impl Fn(BootstrapStatus),
446        cancel: &tokio::sync::watch::Receiver<bool>,
447    ) -> Result<CovenHandle, BootstrapError> {
448        Box::pin(bootstrap::restore_device(
449            self,
450            store,
451            code,
452            s3_credentials,
453            device_name,
454            Box::new(prepare),
455            on_status,
456            cancel,
457        ))
458        .await
459    }
460
461    /// Finishes this device's replacement of `store` past its record, as the
462    /// call that began it would: `reset_device` or `restore_device`, from
463    /// what the replacement kept on the device, with neither the code nor a
464    /// new sign-in (§19.3). On Dropbox and OneDrive it connects through the
465    /// kept sign-in, or a sign-in this builder holds once it grants the
466    /// location's access. A store with no replacement under way, or a
467    /// connected reset whose kept device name is gone, fails with
468    /// `BootstrapError::NoUnfinishedReplacement`.
469    pub async fn resume_replacement(
470        self,
471        store: StoreId,
472        on_status: impl Fn(BootstrapStatus),
473        cancel: &tokio::sync::watch::Receiver<bool>,
474    ) -> Result<CovenHandle, BootstrapError> {
475        Box::pin(bootstrap::resume_replacement(self, store, on_status, cancel)).await
476    }
477
478    /// The joins under way on this device, ordered by store id (§13.2). A
479    /// saved code coven can't read fails the call; it is never skipped. An
480    /// unfinished installation that keeps neither a saved code nor a
481    /// restore's record, and that no call holds, is deleted: a crash left it
482    /// before its call wrote to storage (§13.4).
483    pub async fn unfinished_joins(&self) -> Result<Vec<InviteInfo>, BootstrapError> {
484        bootstrap::unfinished_joins(self).await
485    }
486
487    /// Continues an unfinished join from its saved code and device name, as
488    /// `join_with_invite` does. On Dropbox and OneDrive it connects through
489    /// the sign-in the join keeps on the device, or through a sign-in this
490    /// builder holds, which replaces the kept one once it is shown to grant
491    /// the location's access. With neither, or with a kept sign-in the
492    /// provider refuses even after its one refresh, it fails with
493    /// `OAuthError::Reauthorize` and the join stays unfinished (§13.2).
494    /// Returns `None` when the request was declined or the invite expired,
495    /// after deleting the kept sign-in and the saved code. A store with no
496    /// saved code fails with `BootstrapError::NoUnfinishedJoin`.
497    pub async fn resume_join(
498        self,
499        store: StoreId,
500        on_status: impl Fn(BootstrapStatus),
501        control: &JoinControl,
502    ) -> Result<Option<CovenHandle>, BootstrapError> {
503        Box::pin(bootstrap::resume_join(self, store, on_status, control)).await
504    }
505
506    /// The restores under way on this device, ordered by store id: each
507    /// restore that recorded itself before registering the device and has
508    /// not ended, as `decode_code_info` reads its code (§13.1). A record coven
509    /// can't read fails the call; it is never skipped. An unfinished
510    /// installation that keeps neither a record nor a join's saved code, and
511    /// that no call holds, is deleted, as `unfinished_joins` does (§13.4).
512    pub async fn unfinished_restores(&self) -> Result<Vec<CodeMetadata>, BootstrapError> {
513        bootstrap::unfinished_restores(self).await
514    }
515
516    /// Continues an unfinished restore from its record, as `restore_from_code`
517    /// does: the code and device name it recorded, and the S3 key or sign-in
518    /// it kept on the device. On Dropbox and OneDrive a sign-in this builder
519    /// holds replaces the kept one once it is shown to grant the location's
520    /// access; with neither, or with a kept sign-in the provider refuses even
521    /// after its one refresh, it fails with `OAuthError::Reauthorize` and the
522    /// restore stays unfinished. Cancelling ends it as `restore_from_code`'s
523    /// cancel does. A store with no record fails with
524    /// `BootstrapError::NoUnfinishedRestore`.
525    pub async fn resume_restore(
526        self,
527        store: StoreId,
528        on_status: impl Fn(BootstrapStatus),
529        cancel: &tokio::sync::watch::Receiver<bool>,
530    ) -> Result<CovenHandle, BootstrapError> {
531        Box::pin(bootstrap::resume_restore(self, store, on_status, cancel)).await
532    }
533
534    fn database(&self, directory: StoreDir) -> CovenResult<DatabaseBuilder> {
535        let tables = self
536            .tables
537            .clone()
538            .ok_or(CovenError::MissingConfiguration { field: "synced_tables" })?;
539        let migrations = self
540            .migrations
541            .clone()
542            .ok_or(CovenError::MissingConfiguration { field: "migrations" })?;
543        let database = DatabaseBuilder::new(directory)
544            .migration_operation(coven_sync::SequenceSync::migration_operation)
545            .sync_functions(coven_sync::sync_functions())
546            .synced_tables(tables)
547            .namespaces(self.namespaces.clone())
548            .migrations(migrations)
549            .clock(self.clock.clone())
550            .id_source(self.ids.clone())
551            .sqlite_settings(self.sqlite.clone())
552            .sql_functions(self.sql_functions.clone());
553        let database = match &self.joining_write {
554            Some(write) => {
555                let write = Arc::clone(write);
556                database.joining_write(move |sql, joining| write(sql, joining))
557            }
558            None => database,
559        };
560        let database = match &self.before_commit {
561            Some(function) => {
562                let function = Arc::clone(function);
563                database.before_commit(move |sql| function(sql))
564            }
565            None => database,
566        };
567        #[cfg(test)]
568        let database = if self.refuse_database_close { database.refuse_close() } else { database };
569        Ok(database)
570    }
571
572    fn keychain(&self) -> Result<Arc<Keychain>, KeyError> {
573        Ok(self.keychain.clone())
574    }
575
576    async fn open_graph(self, store: StoreId, opening: Opening) -> CovenResult<OpeningStore> {
577        let directory = self.directories.store_dir(&store);
578        let database = self.database(directory.clone())?;
579        let lock = directory.lock_for_open().await?;
580        let closing = lock.closing_guard();
581        let bugs = directory.bugs().clone();
582        let result =
583            crate::task::blocking_completing("open the store's custody", bugs, move || {
584                let mut builder = self;
585                let settings = lock.settings()?;
586                let keychain = Arc::new(StoreKeychain::new(builder.keychain()?, settings.id));
587                // An interrupted replacement resumes only through the call that
588                // began it (§19.3).
589                refuse_unfinished_replacement(&directory, settings.id)?;
590                // A store this device is leaving opens only to finish that.
591                if opening == Opening::ForUse {
592                    refuse_unfinished_deletion(&directory, settings.id)?;
593                }
594                // A copy restored without its non-backed-up custody id, or a
595                // keychain that no longer names it, changes nothing (§19.3).
596                if keychain.device_id()? != Some(settings.device_id) {
597                    let identity = Self::make_session(
598                        std::mem::replace(
599                            &mut builder.identity,
600                            SessionSource::Configured(CustodyChoice::InMemory),
601                        ),
602                        &directory,
603                        settings.id,
604                        keychain,
605                    );
606                    let store = settings.id;
607                    // Without member keys a connected store can only be restored
608                    // with its code; reset_device reads them from custody.
609                    let connected = coven_storage::recorded_config(&directory)
610                        .map_err(|error| SettingsError::Corrupt(Box::new(error)))?
611                        .is_some();
612                    return Err(match identity?.read()? {
613                        None if connected => CovenError::MemberKeysMissing { store },
614                        _ => CovenError::DeviceKeyMissing { store },
615                    });
616                }
617                // Before the database opens, so its WAL and shared-memory files
618                // are made with the class (E1).
619                coven_foundation::files::settle_files(&directory, &lock).map_err(|error| {
620                    match error {
621                        coven_foundation::files::FileError::DeviceLocked { path } => {
622                            CovenError::DeviceLocked { path }
623                        }
624                        error => DbError::from(error).into(),
625                    }
626                })?;
627                // A join that published and stopped before deleting its code (§13.4).
628                if !directory.is_unpublished().map_err(DbError::from)? {
629                    keychain.delete_invite_code()?;
630                }
631                Ok(OpeningStore { database, lock, builder, directory, keychain })
632            })
633            .await
634            .unwrap_or_else(|shutdown| Err(shutdown.into()));
635        closing.disarm();
636        result
637    }
638
639    fn owners(
640        mut self,
641        directory: StoreDir,
642        keychain: Arc<StoreKeychain>,
643        continuing: Continuing,
644    ) -> CovenResult<OpeningOwners> {
645        let clients = self.oauth_exchange();
646        let oauth = Self::oauth_flow(clients.clone(), self.presenter.clone());
647        let settings = directory.settings()?;
648        let person = Arc::new(PersonEntries::new(self.keychain()?, settings.id));
649        let (state, storage, credentials) = match continuing {
650            Continuing::Fresh => (Arc::new(coven_sync::SequenceState::new()), None, None),
651            Continuing::Loaded { state, storage, credentials } => {
652                (state, Some(storage), credentials)
653            }
654        };
655        // A restore keeps no sign-in in device credentials: the absence is
656        // designed, not a default over a failure.
657        let credentials = credentials.unwrap_or_else(|| {
658            Arc::new(coven_sync::DeviceCredentials::new(
659                keychain.clone(),
660                person.clone(),
661                directory.clone(),
662                clients.clone(),
663            ))
664        });
665        let connector = self.connector();
666        let keys = Self::make_session(self.keys, &directory, settings.id, keychain.clone())?;
667        let identity =
668            Self::make_session(self.identity, &directory, settings.id, keychain.clone())?;
669        let network = coven_foundation::network_watch::NetworkWatch::start(
670            &self.network,
671            self.directories.bugs(),
672        )
673        .map_err(CovenError::NetworkWatch)?;
674        Ok(OpeningOwners {
675            directory,
676            custody: StoreCustody::new(keys.clone(), identity.clone(), keychain.clone()),
677            keychain,
678            person,
679            credentials,
680            connector,
681            oauth,
682            clients,
683            authentication: self.authentication,
684            transfers: self.transfers,
685            files: self.files,
686            network,
687            device: settings.device_id,
688            keys,
689            identity,
690            state,
691            clock: self.clock,
692            ids: self.ids,
693            storage,
694            #[cfg(test)]
695            interrupt_commit: self.interrupt_commit,
696        })
697    }
698
699    fn make_session<T: KeyMaterial>(
700        chosen: SessionSource<T>,
701        directory: &StoreDir,
702        id: StoreId,
703        keychain: Arc<StoreKeychain>,
704    ) -> Result<Arc<KeySession<T>>, KeyError> {
705        let custody = match chosen {
706            SessionSource::Session(session) => return Ok(session),
707            SessionSource::Configured(custody) => custody,
708        };
709        let custody: Arc<dyn Custody<T>> = match custody {
710            CustodyChoice::Keyring => Arc::new(KeyringCustody::new(keychain)),
711            CustodyChoice::Passphrase(secret) => {
712                Arc::new(PassphraseCustody::new(secret, directory.owned_file(T::FILE), id))
713            }
714            CustodyChoice::InMemory => Arc::new(InMemoryCustody::empty()),
715            CustodyChoice::Custom(custody) => custody,
716        };
717        Ok(Arc::new(KeySession::open(custody)?))
718    }
719}
720
721/// Retains the graph while its asynchronous database opening is in progress.
722struct OpeningStore {
723    database: DatabaseBuilder,
724    lock: coven_foundation::files::StoreLock,
725    builder: CovenBuilder,
726    directory: StoreDir,
727    keychain: Arc<StoreKeychain>,
728}
729
730pub(crate) struct OpeningOwners {
731    transfers: Arc<coven_storage::TransferBudget>,
732    files: coven_foundation::files::FileBudget,
733    /// The store's watch of the device's network, from opening to closing.
734    network: coven_foundation::network_watch::NetworkWatch,
735    keychain: Arc<StoreKeychain>,
736    /// The person's entries, deleted when they leave the store (§14.1).
737    person: Arc<PersonEntries>,
738    credentials: Arc<coven_sync::DeviceCredentials>,
739    connector: Arc<dyn StorageConnector>,
740    oauth: Option<OAuthFlow>,
741    clients: Option<OAuthExchange>,
742    authentication: Option<Arc<coven_sync::SessionSignIn>>,
743    device: DeviceId,
744    directory: StoreDir,
745    custody: StoreCustody,
746    keys: Arc<KeySession<StoreKeyring>>,
747    identity: Arc<KeySession<MemberIdentity>>,
748    /// This installation's sequence state, shared by the handle's transfers.
749    state: Arc<coven_sync::SequenceState>,
750    clock: ClockRef,
751    ids: IdSourceRef,
752    /// A loaded installation's connection, made through `state`.
753    storage: Option<Arc<coven_storage::StorageConnection>>,
754    /// Stop the commit right after it writes the device id.
755    #[cfg(test)]
756    interrupt_commit: bool,
757}
758
759impl OpeningStore {
760    async fn open(self) -> CovenResult<CovenHandle> {
761        let database = self.database.open_locked(self.lock).await?;
762        let state = database.store_state().await?;
763        if let Some(identity) = &state.store {
764            check_store_settings(identity, &self.directory)?;
765        }
766        let waits = Arc::new(
767            coven_sync::RetryWaits::open(database.clone(), self.builder.clock.clone()).await?,
768        );
769        let bugs = database.bugs().clone();
770        let owners = crate::task::blocking_completing("open the store's owners", bugs, move || {
771            let owners = self.builder.owners(self.directory, self.keychain, Continuing::Fresh)?;
772            // The saved restore code's name catches up with this store's
773            // when the store's is newer, and an unreadable entry is replaced
774            // with this device's current code (§13.1). A store never set up
775            // has no saved code.
776            if let Some(identity) = &state.store {
777                coven_sync::follow_name(
778                    &owners.person,
779                    &coven_sync::SavedName::of(identity),
780                    || {
781                        let location = coven_storage::recorded_config(&owners.directory)
782                            .map_err(|error| CovenError::from(SyncError::from(error)))?;
783                        coven_sync::replacement_code(
784                            &state,
785                            owners.identity.read()?.as_ref(),
786                            location.as_ref(),
787                        )
788                        .map_err(CovenError::from)
789                    },
790                )?;
791                // Where each write chooses the cloud backup, as Block Store's
792                // does, the entries are stored again, so a screen lock added
793                // since they were written lets them reach it (§13.1).
794                owners.person.store_again()?;
795            }
796            Ok::<_, CovenError>(owners)
797        })
798        .await??;
799        let location = owners.credentials.location().map_err(CovenError::from)?;
800        let configured = location.is_connected();
801        // A setup a crash cut is undone, or left for the first connection
802        // to finish, before the handle exists (§11.6).
803        let finishing = Box::pin(crate::storage::settle_opened(&database, &owners.keychain))
804            .await
805            .map_err(CovenError::from)?;
806        // Boxed, so `open`'s future stays as small as an app's stack needs
807        // (`application_api_tests.rs`).
808        Box::pin(crate::storage::record_opened(&database, &owners.clock, location, None))
809            .await
810            .map_err(CovenError::from)?;
811        Ok(owners.into_handle(database, waits, configured, finishing))
812    }
813}
814
815/// Why the store opens.
816#[derive(Clone, Copy, PartialEq, Eq)]
817enum Opening {
818    /// For the app's use.
819    ForUse,
820    /// To finish this device's recorded deletion of it.
821    ToDelete,
822}
823
824/// A store this device is deleting and leaving opens only to finish that
825/// (E1, §11.6).
826pub(crate) fn refuse_unfinished_deletion(
827    directory: &impl StoreDirAccess,
828    store: StoreId,
829) -> CovenResult<()> {
830    match directory.unfinished_deletion().map_err(DbError::from)? {
831        Some(_) => Err(StoreLockError::DeletionUnfinished(store).into()),
832        None => Ok(()),
833    }
834}
835
836/// An interrupted replacement resumes only through the call that began it
837/// (§19.3).
838fn refuse_unfinished_replacement(
839    directory: &impl StoreDirAccess,
840    store: StoreId,
841) -> CovenResult<()> {
842    match directory.unfinished_replacement()? {
843        Some(record) => Err(StoreLockError::ReplacementUnfinished { store, by: record.by }.into()),
844        None => Ok(()),
845    }
846}
847
848/// The store's identity names the store its directory's settings were
849/// written for.
850fn check_store_settings(
851    identity: &coven_database::StoreIdentity,
852    directory: &impl StoreDirAccess,
853) -> CovenResult<()> {
854    Ok(identity.check_settings(&directory.settings()?)?)
855}
856
857/// The device-custody credentials of `store`'s installation.
858pub(crate) fn device_credentials(
859    keychain: Arc<Keychain>,
860    store: StoreId,
861    directory: StoreDir,
862    oauth: Option<OAuthExchange>,
863) -> Arc<coven_sync::DeviceCredentials> {
864    Arc::new(coven_sync::DeviceCredentials::new(
865        Arc::new(StoreKeychain::new(keychain.clone(), store)),
866        Arc::new(PersonEntries::new(keychain, store)),
867        directory,
868        oauth,
869    ))
870}
871
872impl OpeningOwners {
873    /// Construction after publication performs no fallible work and cannot suspend.
874    fn into_handle(
875        self,
876        database: coven_database::StoreDatabase,
877        waits: Arc<coven_sync::RetryWaits>,
878        configured: bool,
879        setup_finishing: bool,
880    ) -> CovenHandle {
881        let files = coven_sync::Files::new(
882            coven_database::FileDatabase::new(database.clone()),
883            self.directory.clone(),
884            self.storage.clone().map(|storage| storage as Arc<dyn coven_storage::Storage>),
885            self.state.clone(),
886            waits.clone(),
887            self.ids.clone(),
888            self.transfers.clone(),
889            self.files.clone(),
890            self.clock.clone(),
891            self.network.view(),
892        );
893        let network =
894            coven_sync::NetworkFollow::start(self.network, waits.clone(), database.clone());
895        let steps = Arc::new(coven_sync::OperationSteps::new(
896            self.device,
897            self.identity.clone(),
898            self.ids.clone(),
899            self.clock.clone(),
900            self.directory.clone(),
901            self.credentials.clone(),
902            waits.clone(),
903            self.state.clone(),
904        ));
905        let codes = coven_sync::RestoreCodes::new(
906            self.directory.clone(),
907            database.clone(),
908            self.identity.clone(),
909            self.credentials.clone(),
910        );
911        let storage = crate::storage::StorageConnections::new(
912            database.clone(),
913            files.clone(),
914            self.identity,
915            self.person,
916            self.credentials,
917            codes.clone(),
918            self.state.clone(),
919            self.directory.clone(),
920            waits.clone(),
921            self.transfers,
922            self.keys,
923            self.connector,
924            self.oauth,
925            self.clients,
926            self.authentication,
927            self.storage,
928            configured,
929            self.keychain.clone(),
930            setup_finishing,
931            self.device,
932            self.ids,
933            self.clock,
934        );
935        CovenHandle::new(
936            database,
937            self.custody,
938            files,
939            steps,
940            waits,
941            self.state,
942            codes,
943            Arc::new(network),
944            Arc::new(storage),
945            self.directory,
946            self.keychain,
947            self.device,
948        )
949    }
950}
951
952#[cfg(test)]
953#[path = "builder_tests.rs"]
954mod tests;
955
956#[path = "builder_creation.rs"]
957mod creation;
958
959#[path = "bootstrap.rs"]
960mod bootstrap;
961#[path = "builder_hooks.rs"]
962mod hooks;
963#[path = "builder_read_only.rs"]
964mod read_only;
965pub use bootstrap::{
966    join_with_invite, join_with_pairing, restore_from_code, restore_from_saved_code,
967    BootstrapError, BootstrapStatus, JoinControl,
968};