Skip to main content

coven/
handle.rs

1//! Application calls delegate to database, custody, operation and file owners.
2
3#[path = "file.rs"]
4mod file;
5
6#[path = "storage_credentials.rs"]
7mod credentials;
8
9#[path = "handle_sync.rs"]
10mod sync_control;
11
12#[path = "handle_sync_status.rs"]
13mod sync_status;
14
15#[path = "member_keys.rs"]
16mod member_keys;
17
18#[path = "handle_delete.rs"]
19mod deletion;
20pub use deletion::IfUnsent;
21
22#[path = "handle_folders.rs"]
23mod folders;
24
25#[path = "handle_file_cleanup.rs"]
26mod file_cleanup;
27
28#[path = "handle_discarded_devices.rs"]
29mod discarded_devices;
30
31#[path = "handle_local_bytes.rs"]
32mod local_bytes;
33
34#[path = "handle_device_only.rs"]
35mod device_only;
36
37#[path = "handle_transfers.rs"]
38mod transfers;
39
40#[path = "handle_uploads.rs"]
41mod uploads;
42
43#[path = "handle_pairing.rs"]
44mod handle_pairing;
45#[path = "handle_writes.rs"]
46mod writes;
47
48#[path = "circles.rs"]
49mod circles;
50pub use circles::Circles;
51
52use crate::*;
53use coven_crypto::custody::{StoreCustody, StoreKeychain};
54use coven_database::StoreDatabase;
55use coven_foundation::locks::lock_unpoisoned;
56use std::sync::{Arc, Mutex};
57
58/// A shared handle to the open store and its running work (Appendix F.4).
59/// Administrative changes catch up with storage before starting and report
60/// a refusal by the applied state as `SyncError::Rejected`, including its
61/// typed target.
62#[derive(Clone)]
63pub struct CovenHandle {
64    // Drops first, so the store is closing before this clone of the
65    // database goes.
66    _scope: Arc<HandleScope>,
67    database: StoreDatabase,
68    files: coven_sync::Files,
69    /// The store's operation steps, which an app's write runs.
70    steps: Arc<coven_sync::OperationSteps>,
71    waits: Arc<coven_sync::RetryWaits>,
72    state: Arc<coven_sync::SequenceState>,
73    /// The store's restore codes and recorded location.
74    codes: coven_sync::RestoreCodes,
75    /// Follows the store's watch of the device's network (§6.7).
76    network: Arc<coven_sync::NetworkFollow>,
77    storage: Arc<crate::storage::StorageConnections>,
78    custody: Arc<Mutex<Option<StoreCustody>>>,
79    directory: StoreDir,
80    keychain: Arc<StoreKeychain>,
81    device: DeviceId,
82}
83
84/// The app's hold on the store: ending it, as the last clone of the handle
85/// drops, marks the store closing though workers still hold the database
86/// (F.4).
87struct HandleScope(StoreDatabase);
88
89impl Drop for HandleScope {
90    fn drop(&mut self) {
91        self.0.begin_close();
92    }
93}
94
95impl std::fmt::Debug for CovenHandle {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        f.debug_struct("CovenHandle").finish_non_exhaustive()
98    }
99}
100
101impl CovenHandle {
102    pub(crate) fn new(
103        database: StoreDatabase,
104        custody: StoreCustody,
105        files: coven_sync::Files,
106        steps: Arc<coven_sync::OperationSteps>,
107        waits: Arc<coven_sync::RetryWaits>,
108        state: Arc<coven_sync::SequenceState>,
109        codes: coven_sync::RestoreCodes,
110        network: Arc<coven_sync::NetworkFollow>,
111        storage: Arc<crate::storage::StorageConnections>,
112        directory: StoreDir,
113        keychain: Arc<StoreKeychain>,
114        device: DeviceId,
115    ) -> Self {
116        Self {
117            _scope: Arc::new(HandleScope(database.clone())),
118            database,
119            files,
120            steps,
121            waits,
122            state,
123            codes,
124            network,
125            storage,
126            custody: Arc::new(Mutex::new(Some(custody))),
127            directory,
128            keychain,
129            device,
130        }
131    }
132
133    /// The store's stable id, including before storage is configured.
134    pub fn store_id(&self) -> StoreId {
135        self.directory.id()
136    }
137
138    /// The store's current name, from this device's committed state (E9).
139    pub async fn store_name(&self) -> CovenResult<String> {
140        self.database.store_name().await.map_err(CovenError::from)
141    }
142
143    /// The same name query, live (E4).
144    pub fn subscribe_store_name(&self) -> LiveQuery<String, CovenError> {
145        self.database.subscribe_store_name()
146    }
147
148    /// Renames the store, in a write of its own (`CovenWrite::rename_store`).
149    pub async fn rename_store(&self, name: &str) -> Result<Option<OperationId>, SyncError> {
150        let name = name.to_owned();
151        self.write(move |write| write.rename_store(&name)).await
152    }
153
154    /// This installation's device id, available before setup and retained after close.
155    pub fn device_id(&self) -> DeviceId {
156        self.device
157    }
158
159    /// The committed storage location, without credentials or provider requests.
160    /// None before setup; once set up, it stays. A closed handle refuses the call.
161    pub async fn storage_config(&self) -> Result<Option<StorageConfig>, SyncError> {
162        self.storage.storage_config().await
163    }
164
165    /// How many file uploads and file downloads run at once. Each upload checks the
166    /// upload limit as it starts; a pin captures the download limit.
167    pub fn transfer_limits(&self) -> TransferLimits {
168        self.files.transfer_limits()
169    }
170    /// Set limits for future transfers; transfers already running continue.
171    pub fn set_transfer_limits(&self, limits: TransferLimits) {
172        self.files.set_transfer_limits(limits);
173    }
174
175    /// Check S3 safety and provider operations, then set up S3 using this
176    /// member's own access key. The returned location is the recorded one,
177    /// carrying detected settings when the endpoint needed them.
178    /// `on_progress` is called on this task with each step as it runs (E1).
179    pub async fn setup_s3_storage(
180        &self,
181        storage: StorageConfig,
182        access_key_id: String,
183        secret_access_key: SecretText,
184        on_progress: impl Fn(Progress<StorageSetupStep>),
185    ) -> Result<StorageSetup, StorageSetupError> {
186        let (progress, watched) = tokio::sync::watch::channel(None);
187        let setup = self.setup_s3_reporting(storage, access_key_id, secret_access_key, progress);
188        coven_foundation::progress::forward(watched, setup, on_progress).await
189    }
190
191    /// The S3 setup [`Self::setup_s3_storage`] runs, reporting its steps
192    /// into `progress` as it runs them.
193    pub(crate) async fn setup_s3_reporting(
194        &self,
195        storage: StorageConfig,
196        access_key_id: String,
197        secret_access_key: SecretText,
198        progress: crate::storage::SetupProgress,
199    ) -> Result<StorageSetup, StorageSetupError> {
200        self.storage.setup_s3(storage, access_key_id, secret_access_key, progress).await
201    }
202    /// Probe the S3 service at this location with this member's key (§20.7),
203    /// writing only fresh objects under the store's `.coven-check` prefix and
204    /// deleting them, also on failure, then removing what earlier recorded
205    /// detection runs at that bucket and prefix left. Commits only its run's
206    /// record, kept until its probes and uploads are confirmed gone.
207    pub async fn detect_s3_settings(
208        &self,
209        storage: StorageConfig,
210        access_key_id: String,
211        secret_access_key: SecretText,
212    ) -> Result<S3Detection, StorageSetupError> {
213        self.storage.detect_s3(storage, access_key_id, secret_access_key).await
214    }
215    /// Present provider sign-in and keep tokens in coven's session custody.
216    /// Call setup to attach the chosen account to storage and persist credentials.
217    /// Dropping the future cancels sign-in without replacing the previous tokens.
218    pub async fn authenticate(&self, access: OAuthAccess) -> Result<(), StorageSetupError> {
219        self.storage.authenticate(access).await
220    }
221    /// Check provider operations and set up OAuth storage using coven's held sign-in.
222    /// `on_progress` is called on this task with each step as it runs (E1).
223    pub async fn setup_oauth_storage(
224        &self,
225        storage: StorageConfig,
226        on_progress: impl Fn(Progress<StorageSetupStep>),
227    ) -> Result<StorageSetup, StorageSetupError> {
228        let (progress, watched) = tokio::sync::watch::channel(None);
229        let setup = self.storage.setup_oauth(storage, progress);
230        coven_foundation::progress::forward(watched, setup, on_progress).await
231    }
232    /// Set up native iCloud storage in the entitled container. Coven obtains the
233    /// owner and creates a custom zone; reconnects retain the recorded location.
234    /// Unsupported platforms return `StorageFailure::ProviderUnavailable`.
235    /// `on_progress` is called on this task with each step as it runs (E1).
236    pub async fn setup_cloudkit_storage(
237        &self,
238        container: &str,
239        on_progress: impl Fn(Progress<StorageSetupStep>),
240    ) -> Result<StorageSetup, StorageSetupError> {
241        let (progress, watched) = tokio::sync::watch::channel(None);
242        let setup = self.storage.setup_cloudkit(container, progress);
243        coven_foundation::progress::forward(watched, setup, on_progress).await
244    }
245    /// Cancel the storage setup running on this store (§11.6). Before its
246    /// point of no return setup undoes what it wrote, fails with
247    /// `StorageSetupError::Cancelled`, and `coven_operations` lists it
248    /// cancelled. Past that point, from its `CreatingStore` or
249    /// `RecordingAccess` step on or once a crash cut it there, it finishes,
250    /// and the answer says so. Holds no lock: setup holds its call's.
251    pub fn cancel_storage_setup(&self) -> crate::storage::SetupCancellation {
252        self.storage.cancel_setup()
253    }
254    /// Have the next setup stop or wait at one of its stops.
255    #[cfg(test)]
256    pub(crate) fn test_setup_hook(&self, hook: crate::storage::SetupHook) {
257        self.storage.test_setup_hook(hook);
258    }
259    /// Open this member's sealed keys and connect without starting the loop.
260    pub async fn unlock_store_key(&self) -> Result<ConnectedStorage, StoreKeyUnlockError> {
261        self.storage.unlock().await
262    }
263    /// The first load of a store a join published once it found its
264    /// admission, reporting loading's steps to `progress` (§13.2).
265    pub(crate) async fn load_joined(
266        &self,
267        progress: tokio::sync::watch::Sender<Option<Progress<coven_database::LoadStep>>>,
268    ) -> Result<(), SyncError> {
269        self.storage.load_joined(progress).await
270    }
271    /// Whether custody holds opened store keys.
272    pub fn store_key_state(&self) -> Result<StoreKeyState, KeyError> {
273        self.storage.key_state()
274    }
275    /// The latest completed replacement stored in this installation, or None.
276    /// It survives reopening; unsent edits of the old copy were discarded (§19.3).
277    pub async fn device_reset(&self) -> CovenResult<Option<DeviceReset>> {
278        self.database.device_reset().await.map_err(CovenError::from)
279    }
280
281    /// The same pre-built query, including a replacement completed before opening.
282    pub fn subscribe_device_reset(&self) -> LiveQuery<Option<DeviceReset>, CovenError> {
283        self.database.subscribe_device_reset()
284    }
285
286    /// Current local conditions, including while disconnected, each with
287    /// the cause `coven_pending.cause` keeps beside it.
288    pub async fn pending(&self) -> CovenResult<Vec<PendingRecord>> {
289        self.database.pending().await.map_err(CovenError::from)
290    }
291
292    /// The members and their devices, as this device's applied slots have them (E9).
293    pub async fn members(&self) -> CovenResult<Vec<MemberInfo>> {
294        self.database.members().await.map_err(CovenError::from)
295    }
296
297    /// The same internal query, live (E4).
298    pub fn subscribe_members(&self) -> LiveQuery<Vec<MemberInfo>, CovenError> {
299        self.database.subscribe_members()
300    }
301
302    /// Changes a member's role, in a write of its own
303    /// (`CovenWrite::set_member_role`).
304    pub async fn set_member_role(
305        &self,
306        member: &MemberId,
307        role: MemberRole,
308    ) -> Result<Option<OperationId>, SyncError> {
309        let member = *member;
310        self.write(move |write| write.set_member_role(&member, role)).await
311    }
312    /// Removes a member, in a write of its own (`CovenWrite::remove_member`).
313    pub async fn remove_member(&self, member: &MemberId) -> Result<Option<OperationId>, SyncError> {
314        let member = *member;
315        self.write(move |write| write.remove_member(&member)).await
316    }
317    /// Removes a device, in a write of its own (`CovenWrite::remove_device`).
318    pub async fn remove_device(
319        &self,
320        device: DeviceId,
321    ) -> Result<(Option<OperationId>, Option<ProviderSignOut>), SyncError> {
322        self.write(move |write| write.remove_device(device)).await
323    }
324    /// The person did the provider step for a lost device of the account
325    /// that holds the store (§14.2): signed it out, so nothing it sent can
326    /// land any more. This device takes back every account that device's
327    /// invite shares named which no member or open invite uses, with
328    /// requests like any other revocation, which run after this call
329    /// returns. Needs the connection (`NoStorage` without it), and is refused
330    /// with `CutOffRefused` naming why: `NoAccountShared` on S3, `NotStoreOwner`
331    /// on a device that isn't of the member whose account holds the store (see
332    /// `holds_store`), and `DeviceNotGone` for a device not gone for good,
333    /// which a later pass may change. While a request to one of those accounts runs it fails with
334    /// `DbError::ProviderRequestRunning` and changes nothing: call again
335    /// once it ends (§20.9).
336    pub async fn confirm_device_cut_off(&self, device: DeviceId) -> Result<(), SyncError> {
337        self.storage.confirm_device_cut_off(device).await
338    }
339    /// Whether this device's member reaches storage through the account
340    /// that holds the store (§20.9): only their devices share it and take
341    /// sharing back, so only they can confirm a device cut off. False on S3,
342    /// where no account holds the store. Reads the sequence forward first;
343    /// needs the connection (`NoStorage` without it).
344    pub async fn holds_store(&self) -> Result<bool, SyncError> {
345        self.storage.holds_store().await
346    }
347    /// Waits for an operation the app's writes journaled to end and returns
348    /// its outcome, as `coven_operations` lists it, read as `O`, the outcome
349    /// type of its kind (§11.4, E6); the outcome stays listed until a write
350    /// acknowledges it. It waits for storage too: a pass runs the operation
351    /// once storage is connected. An operation not listed fails with
352    /// `OperationUnknown`, and one whose outcome `O` doesn't hold fails to read.
353    pub async fn operation_outcome<O: types::FromSql + Clone + PartialEq + Send + 'static>(
354        &self,
355        operation: OperationId,
356    ) -> Result<O, SyncError> {
357        let mut listed: LiveQuery<_, SyncError> = self.database.subscribe(move |sql| {
358            Ok(sql
359                .query(
360                    "SELECT outcome FROM coven_operations WHERE operation=?1",
361                    [operation.0],
362                    |row| row.get::<_, Option<O>>(0),
363                )?
364                .pop())
365        });
366        loop {
367            let (next, answer) = coven_database::next_result(listed).await;
368            listed = next;
369            let Some(answer) = answer else { break };
370            match answer? {
371                None => return Err(DbError::OperationUnknown(operation).into()),
372                Some(Some(outcome)) => return Ok(outcome),
373                Some(None) => {}
374            }
375        }
376        Err(DbError::StoreClosed.into())
377    }
378    /// The bucket, store prefix and filled member policy for making a key in
379    /// the provider's console (§20.10).
380    pub async fn guided_access_key(&self) -> Result<GuidedAccessKey, SyncError> {
381        self.storage.guided_access_key().await
382    }
383    /// Reload this device from snapshots, retaining and replaying its waiting writes (§19.2).
384    pub async fn reload_from_snapshot(&self) -> Result<(), OperationError> {
385        // An operation's state runs to tens of KiB; boxed, the future the
386        // app holds stays small (application_api_tests bounds it). The other
387        // operations below are boxed for the same reason.
388        Box::pin(self.storage.reload_from_snapshot()).await
389    }
390    /// Reset the store audience from this device as an admin, then reload locally (§19.4).
391    pub async fn reset_store(&self) -> Result<(), SyncError> {
392        self.storage.reset(Audience::Store).await
393    }
394    /// Make an operation's retry or undo due now, from its recorded
395    /// progress, in a write of its own (`CovenWrite::retry_pending_operation`).
396    pub async fn retry_pending_operation(
397        &self,
398        operation: OperationId,
399    ) -> Result<(), OperationError> {
400        self.write(move |write| write.retry_pending_operation(operation)).await
401    }
402    /// Makes an invite for a new person, in a write of its own
403    /// (`CovenWrite::create_invite`).
404    pub async fn create_invite(
405        &self,
406        role: MemberRole,
407        access: InviteAccess,
408        lifetime: InviteLifetime,
409        inviter: String,
410    ) -> Result<(InviteId, MemberId, OperationId), SyncError> {
411        self.write(move |write| write.create_invite(role, access, lifetime, inviter)).await
412    }
413    /// Makes an invite that adds a device to a member who lost every device,
414    /// in a write of its own (`CovenWrite::add_device_for`).
415    pub async fn add_device_for(
416        &self,
417        member: MemberId,
418        access: InviteAccess,
419        lifetime: InviteLifetime,
420        inviter: String,
421    ) -> Result<(InviteId, MemberId, OperationId), SyncError> {
422        self.write(move |write| write.add_device_for(member, access, lifetime, inviter)).await
423    }
424    /// Follow `coven_invites` with a live query, as an app does (E10).
425    #[cfg(any(test, feature = "test-utils"))]
426    pub fn test_invites(&self) -> coven_database::test_utils::Followed<Vec<Invite>, DbError> {
427        Invite::follow(&self.database)
428    }
429    /// Approves a request, in a write of its own
430    /// (`CovenWrite::approve_join_request`).
431    pub async fn approve_join_request(
432        &self,
433        request: &JoinRequest,
434    ) -> Result<OperationId, SyncError> {
435        let request = request.clone();
436        self.write(move |write| write.approve_join_request(&request)).await
437    }
438    /// Declines a request, in a write of its own
439    /// (`CovenWrite::decline_join_request`).
440    pub async fn decline_join_request(&self, request: &JoinRequest) -> Result<(), SyncError> {
441        let request = request.clone();
442        self.write(move |write| write.decline_join_request(&request)).await
443    }
444    /// Cancels an invite, in a write of its own (`CovenWrite::cancel_invite`).
445    pub async fn cancel_invite(&self, invite: &InviteId) -> Result<(), SyncError> {
446        let invite = *invite;
447        self.write(move |write| write.cancel_invite(&invite)).await
448    }
449    /// Circle calls borrowing this store's operation owner.
450    pub fn circles(&self) -> Circles<'_> {
451        Circles::new(self)
452    }
453
454    /// A read of one consistent snapshot, run when awaited. Attach `process`
455    /// to work on the result after the connection is released. It fails
456    /// with the closure's own error type, a database failure as its
457    /// `From<DbError>`.
458    pub fn read<F, R, E>(&self, read: F) -> Read<'_, F>
459    where
460        F: FnOnce(SqlReadContext<'_>) -> Result<R, E> + Send + 'static,
461        R: Send + 'static,
462        E: From<DbError> + task::CarriesBug + Send + 'static,
463    {
464        self.database.read(read)
465    }
466
467    /// A live query. Coven records the tables, columns and keys the query
468    /// reads, and reruns it only for writes that touch them.
469    pub fn subscribe<F, R, E>(&self, query: F) -> LiveQuery<R, E>
470    where
471        F: Fn(SqlReadContext<'_>) -> Result<R, E> + Send + Sync + 'static,
472        R: Send + 'static,
473        E: From<DbError> + task::CarriesBug + Send + 'static,
474    {
475        self.database.subscribe(query)
476    }
477
478    /// A live query whose request, such as a page or a search term, can be
479    /// replaced without starting a new subscription.
480    pub fn subscribe_reconfigurable<Q, F, R, E>(
481        &self,
482        initial_request: Q,
483        query: F,
484    ) -> ReconfigurableLiveQuery<Q, R, E>
485    where
486        Q: Clone + PartialEq + Send + Sync + 'static,
487        F: Fn(&Q, SqlReadContext<'_>) -> Result<R, E> + Send + Sync + 'static,
488        R: Send + 'static,
489        E: From<DbError> + task::CarriesBug + Send + 'static,
490    {
491        self.database.subscribe_reconfigurable(initial_request, query)
492    }
493
494    /// The SQLite settings the store's connections have in effect (§4).
495    pub async fn sqlite_settings(&self) -> Result<SqliteSettingsInEffect, DbError> {
496        self.database.sqlite_settings().await
497    }
498
499    /// Checkpoints the store's WAL between writes, returning what SQLite
500    /// reports (§4). `Restart` and `Truncate` wait up to the busy timeout for
501    /// reads still using the WAL, and report `busy` if they outlast it.
502    /// `NotStarted` when another connection was checkpointing or committing.
503    pub async fn checkpoint(&self, mode: CheckpointMode) -> Result<WalCheckpoint, DbError> {
504        self.database.checkpoint(mode).await
505    }
506
507    /// Gives back free pages of a store created with incremental auto-vacuum,
508    /// between writes (§4). On any other store it does nothing.
509    pub async fn incremental_vacuum(&self, pages: IncrementalVacuum) -> Result<(), DbError> {
510        self.database.incremental_vacuum(pages).await
511    }
512
513    /// Gives back the memory every connection's page cache holds, as SQLite's
514    /// `sqlite3_db_release_memory` does, for when the OS warns of low memory
515    /// or the app goes to the background (§4). SQLite keeps every
516    /// connection's unused pages in one pool for the process, so one release
517    /// on an idle reader frees them all. Safe at any time, and never waits
518    /// for a write. Later reads load the pages they need again.
519    pub async fn release_memory(&self) -> Result<(), DbError> {
520        self.database.release_memory().await
521    }
522
523    /// Every lost value and removed row, as `_coven_lost` holds them (§8.2, §8.4).
524    pub async fn lost_values(&self) -> CovenResult<Vec<LostValue>> {
525        self.database.lost_values().await.map_err(CovenError::from)
526    }
527
528    /// Dismisses lost values in a write of its own
529    /// (`CovenWrite::dismiss_lost_values`).
530    pub async fn dismiss_lost_values(&self, values: &[LostValue]) -> CovenResult<()> {
531        let values = values.to_vec();
532        self.write(move |write| Ok(write.dismiss_lost_values(&values)?)).await
533    }
534
535    /// The same, as a live query.
536    pub fn subscribe_lost_values(&self) -> LiveQuery<Vec<LostValue>, CovenError> {
537        self.database.subscribe_lost_values()
538    }
539
540    /// The file a row references, by the id the row holds: its size,
541    /// namespace, audience and place, read in one committed state. An id this
542    /// device has no record of returns `DbError::FileAbsent`; a malformed
543    /// record returns `DbError::DamagedDatabase`.
544    pub async fn file_ref(&self, file: FileId) -> Result<FileRef, DbError> {
545        self.database.file_ref(file).await
546    }
547
548    /// Reads a whole file, in one place of `lease`. A stored file is checked
549    /// against its content hash.
550    pub async fn read_file(
551        &self,
552        file: &FileRef,
553        lease: &FileLease,
554    ) -> Result<Vec<u8>, FileReadError> {
555        let stream = self.open_file_stream(file, lease).await?;
556        stream.read_at(0, stream.plaintext_size()).await
557    }
558
559    /// Opens a file for reading ranges (§17.7), as its record stands when it
560    /// opens; keep the stream for as long as the file is read. The stream
561    /// holds one place of `lease` until it drops. A file only on another
562    /// device fails with `FileReadError::DeviceOnly`. Its shared store lock
563    /// prevents deletion until it and its I/O finish.
564    pub async fn open_file_stream(
565        &self,
566        file: &FileRef,
567        lease: &FileLease,
568    ) -> Result<FileStream, FileReadError> {
569        self.files.open_file_stream(file, lease).await
570    }
571
572    /// The path, size and modification time coven recorded for a file's
573    /// user original on this device, or `None` when it has none.
574    pub async fn user_file(&self, file: FileId) -> Result<Option<UserFile>, DbError> {
575        self.database.user_file(file).await
576    }
577
578    /// Removes the store keys from key custody. A failed removal leaves the
579    /// custody failure visible to the caller; member identity is retained.
580    pub async fn forget_store_keys(&self) -> Result<(), KeyError> {
581        self.storage.forget_store_keys().await
582    }
583
584    /// Keeps an app secret, such as an API token, in the same keychain and
585    /// under the same access policy as coven's keys. Names are arbitrary strings.
586    /// Coven records the name in a keychain list before writing the value to its
587    /// own entry, retaining the platform's per-secret size limit. Deleting the
588    /// store removes every listed secret even if its database is damaged.
589    /// Failure may leave an extra name; retrying is safe.
590    pub fn set_host_secret(&self, name: &str, value: &str) -> Result<(), KeyError> {
591        lock_unpoisoned(&self.custody)
592            .as_ref()
593            .ok_or(KeyError::StoreClosed)?
594            .set_host_secret(name, value)
595    }
596    /// The secret, or `None` if it was never set.
597    pub fn host_secret(&self, name: &str) -> Result<Option<String>, KeyError> {
598        lock_unpoisoned(&self.custody).as_ref().ok_or(KeyError::StoreClosed)?.host_secret(name)
599    }
600    /// Deletes the secret before its recorded name; succeeds if absent.
601    /// Failure may leave an extra name; retrying is safe.
602    pub fn delete_host_secret(&self, name: &str) -> Result<(), KeyError> {
603        lock_unpoisoned(&self.custody)
604            .as_ref()
605            .ok_or(KeyError::StoreClosed)?
606            .delete_host_secret(name)
607    }
608
609    /// Stops operation and file work, closes connections and releases the writer
610    /// lock. Open file streams retain their shared deletion guards. Later
611    /// database calls on any clone fail with `DbError::StoreClosed`; custody
612    /// calls fail with `KeyError::StoreClosed`. Closing reports every failure:
613    /// one alone as itself, several chained as `SyncError::Cleanup`.
614    pub async fn close(&self) -> Result<(), SyncError> {
615        self.database.begin_close();
616        let handle = self.clone();
617        let bugs = self.database.bugs().clone();
618        let closing = async move {
619            // No network report reaches the store's waits once it closes.
620            handle.network.close().await;
621            let storage = handle.storage.close().await;
622            handle.files.close().await;
623            let custody = handle.custody.clone();
624            let bugs = handle.database.bugs().clone();
625            let custody = crate::task::blocking_completing("close custody", bugs, move || {
626                if let Some(custody) = lock_unpoisoned(&custody).take() {
627                    custody.close();
628                }
629                Ok::<_, std::convert::Infallible>(())
630            })
631            .await
632            .map(|closed| closed.unwrap_or_else(|never| match never {}));
633            let database = handle.database.close().await;
634            // Closing the connection can fail while releasing its provider.
635            // Finish closing every owner and erase custody before reporting.
636            let storage = match storage {
637                Err(SyncError::Database(DbError::StoreClosed)) => Ok(()),
638                result => result,
639            };
640            [storage, custody.map_err(SyncError::from), database.map_err(SyncError::from)]
641                .into_iter()
642                .filter_map(Result::err)
643                .reduce(SyncError::cleanup)
644                .map_or(Ok(()), Err)
645        };
646        crate::task::spawn_completing("close the store", bugs, closing).await?
647    }
648    /// The last slot this installation applied.
649    #[cfg(test)]
650    pub(crate) async fn applied_slot(&self) -> u64 {
651        self.database.applied_slot().await.unwrap()
652    }
653    /// Membership, keys and audience state as this installation applied them.
654    #[cfg(test)]
655    pub(crate) async fn store_state(&self) -> coven_database::StoreState {
656        self.database.store_state().await.unwrap()
657    }
658    /// Wait until the network follower, then the connection attempt, the
659    /// sync loop and the upload worker, those running, have each seen what
660    /// happened before this call, and what the ones before them did, and
661    /// wait.
662    /// Wait until a call finds the storage call lock held and waits, after
663    /// this call.
664    #[cfg(test)]
665    pub(crate) fn test_call_waits(&self) -> impl std::future::Future<Output = ()> {
666        self.storage.call_waits_from_now()
667    }
668    /// Wait until downloads have found the store's download limit full
669    /// `count` more times than before this call.
670    #[cfg(test)]
671    pub(crate) fn test_downloads_waiting(
672        &self,
673        count: usize,
674    ) -> impl std::future::Future<Output = ()> {
675        self.storage.downloads_waiting_from_now(count)
676    }
677    /// Follow the subject's persisted retry wait as failures arm it.
678    #[cfg(test)]
679    pub(crate) fn test_follow_retry_wait(
680        &self,
681        subject: coven_database::RetrySubject,
682    ) -> coven_database::test_utils::Followed<Option<coven_database::RetryWait>, DbError> {
683        coven_database::test_utils::Followed::new(self.database.subscribe_retry_wait(subject))
684    }
685    /// The store's database, for tests that read what the owners keep.
686    #[cfg(test)]
687    pub(crate) fn test_database(&self) -> &coven_database::StoreDatabase {
688        &self.database
689    }
690    /// Follow membership and audience state as passes apply it.
691    #[cfg(test)]
692    pub(crate) fn test_store_state(
693        &self,
694    ) -> coven_database::test_utils::Followed<coven_database::StoreState, DbError> {
695        coven_database::test_utils::Followed::new(self.database.subscribe_store_state())
696    }
697    /// Wait until a pause is asked of the sync loop after this call.
698    #[cfg(test)]
699    pub(crate) fn test_pause_asked(&self) -> impl std::future::Future<Output = ()> {
700        self.storage.pause_asked_from_now()
701    }
702    /// The handle's storage connections, for a test that calls them directly.
703    #[cfg(test)]
704    pub(crate) fn test_storage(&self) -> Arc<crate::storage::StorageConnections> {
705        self.storage.clone()
706    }
707    #[cfg(test)]
708    pub(crate) async fn test_parked(&self) {
709        self.network.parked_from_now().await;
710        self.storage.parked().await;
711    }
712    #[cfg(test)]
713    pub(crate) async fn test_connection_retry_wait(&self) -> Option<coven_database::RetryWait> {
714        self.database.retry_wait(coven_database::RetrySubject::Sync).await.unwrap()
715    }
716    /// Record `record` as a failure saved before a process stopped, without
717    /// the status that shows it.
718    #[cfg(test)]
719    pub(crate) async fn test_record_pending(&self, record: coven_sync::PendingRecord) {
720        self.database.record_pending(record).await.unwrap();
721    }
722    /// Halt sync with `bug`, as the upload worker's panic does (E15).
723    #[cfg(test)]
724    pub(crate) async fn test_halt(&self, bug: crate::task::Bug) {
725        self.waits.sync_halted(bug).await.unwrap();
726    }
727
728    /// Panic in the next write the store's writer judges, as a bug in it
729    /// would.
730    #[cfg(test)]
731    pub(crate) async fn test_panic_in_next_write(&self, message: &'static str) {
732        self.database.test_panic_in_next_write(message).await.unwrap();
733    }
734
735    /// Count the work the store's connections run into `counter`, in
736    /// application tests: its reads' SQLite steps, the app's and coven's
737    /// narrowing apart. Install it between calls, before the measured one.
738    #[cfg(any(test, feature = "test-utils"))]
739    pub async fn test_track_work(&self, counter: crate::WorkCounter) -> Result<(), DbError> {
740        self.database.test_track_work(counter).await
741    }
742
743    /// Record the statements the store's reads run from here on into `log`,
744    /// in application tests and measurements: each `query` and `query_row`
745    /// of a read or a live query's run, as SQLite's text with the bound
746    /// values written in, in order. Writes are not recorded.
747    #[cfg(any(test, feature = "test-utils"))]
748    pub async fn test_record_statements(&self, log: crate::StatementLog) -> Result<(), DbError> {
749        self.database.record_statements(log).await
750    }
751
752    /// The plaintext bytes each section of a store snapshot would hold now,
753    /// for a test measuring what a snapshot keeps (D7). Every section's place
754    /// is in `coven_format::snapshot::section`.
755    #[cfg(any(test, feature = "test-utils"))]
756    pub async fn test_snapshot_section_bytes(
757        &self,
758    ) -> Result<
759        [u64; coven_format::snapshot::SECTIONS],
760        coven_database::SnapshotWriteError<std::convert::Infallible>,
761    > {
762        let id = coven_format::admin::SnapshotId {
763            audience: coven_merge::Audience::Store,
764            device: self.device_id(),
765            number: 1,
766        };
767        self.database.test_snapshot_section_bytes(id).await
768    }
769
770    /// Make writes of the record a copy keeps when it stops on another
771    /// installation's use of its device id fail, as a full disk would, or
772    /// let them succeed again.
773    #[cfg(any(test, feature = "test-utils"))]
774    pub async fn test_fail_device_id_in_use(&self, fail: bool) -> Result<(), DbError> {
775        self.database.test_fail_device_id_in_use(fail).await
776    }
777
778    /// Follow how many reads of files wait for the connection that is coming,
779    /// in application tests: a test that checks a read waits goes on once
780    /// one does.
781    #[cfg(any(test, feature = "test-utils"))]
782    pub fn test_reads_awaiting_connection(&self) -> tokio::sync::watch::Receiver<usize> {
783        self.files.reads_awaiting_connection()
784    }
785
786    /// Read committed plaintext records still awaiting upload in application tests.
787    #[cfg(any(test, feature = "test-utils"))]
788    pub async fn test_queued_writes(
789        &self,
790    ) -> Result<Vec<coven_format::write::WriteRecord>, DbError> {
791        self.database.test_queued_writes().await
792    }
793}
794
795#[cfg(test)]
796impl CovenHandle {
797    /// Where the waiting upload of `file` sends its bytes, for tests that
798    /// fault that path.
799    pub(crate) async fn test_upload_location(&self, file: FileId) -> coven_database::FileLocation {
800        self.database
801            .upload_queue()
802            .await
803            .unwrap()
804            .uploads
805            .into_iter()
806            .find(|upload| upload.files.contains(&file))
807            .expect("an upload stores the file")
808            .location
809    }
810}
811
812#[cfg(test)]
813#[path = "handle_tests.rs"]
814mod tests;