1#[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#[derive(Clone)]
63pub struct CovenHandle {
64 _scope: Arc<HandleScope>,
67 database: StoreDatabase,
68 files: coven_sync::Files,
69 steps: Arc<coven_sync::OperationSteps>,
71 waits: Arc<coven_sync::RetryWaits>,
72 state: Arc<coven_sync::SequenceState>,
73 codes: coven_sync::RestoreCodes,
75 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
84struct 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 pub fn store_id(&self) -> StoreId {
135 self.directory.id()
136 }
137
138 pub async fn store_name(&self) -> CovenResult<String> {
140 self.database.store_name().await.map_err(CovenError::from)
141 }
142
143 pub fn subscribe_store_name(&self) -> LiveQuery<String, CovenError> {
145 self.database.subscribe_store_name()
146 }
147
148 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 pub fn device_id(&self) -> DeviceId {
156 self.device
157 }
158
159 pub async fn storage_config(&self) -> Result<Option<StorageConfig>, SyncError> {
162 self.storage.storage_config().await
163 }
164
165 pub fn transfer_limits(&self) -> TransferLimits {
168 self.files.transfer_limits()
169 }
170 pub fn set_transfer_limits(&self, limits: TransferLimits) {
172 self.files.set_transfer_limits(limits);
173 }
174
175 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 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 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 pub async fn authenticate(&self, access: OAuthAccess) -> Result<(), StorageSetupError> {
219 self.storage.authenticate(access).await
220 }
221 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 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 pub fn cancel_storage_setup(&self) -> crate::storage::SetupCancellation {
252 self.storage.cancel_setup()
253 }
254 #[cfg(test)]
256 pub(crate) fn test_setup_hook(&self, hook: crate::storage::SetupHook) {
257 self.storage.test_setup_hook(hook);
258 }
259 pub async fn unlock_store_key(&self) -> Result<ConnectedStorage, StoreKeyUnlockError> {
261 self.storage.unlock().await
262 }
263 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 pub fn store_key_state(&self) -> Result<StoreKeyState, KeyError> {
273 self.storage.key_state()
274 }
275 pub async fn device_reset(&self) -> CovenResult<Option<DeviceReset>> {
278 self.database.device_reset().await.map_err(CovenError::from)
279 }
280
281 pub fn subscribe_device_reset(&self) -> LiveQuery<Option<DeviceReset>, CovenError> {
283 self.database.subscribe_device_reset()
284 }
285
286 pub async fn pending(&self) -> CovenResult<Vec<PendingRecord>> {
289 self.database.pending().await.map_err(CovenError::from)
290 }
291
292 pub async fn members(&self) -> CovenResult<Vec<MemberInfo>> {
294 self.database.members().await.map_err(CovenError::from)
295 }
296
297 pub fn subscribe_members(&self) -> LiveQuery<Vec<MemberInfo>, CovenError> {
299 self.database.subscribe_members()
300 }
301
302 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 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 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 pub async fn confirm_device_cut_off(&self, device: DeviceId) -> Result<(), SyncError> {
337 self.storage.confirm_device_cut_off(device).await
338 }
339 pub async fn holds_store(&self) -> Result<bool, SyncError> {
345 self.storage.holds_store().await
346 }
347 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 pub async fn guided_access_key(&self) -> Result<GuidedAccessKey, SyncError> {
381 self.storage.guided_access_key().await
382 }
383 pub async fn reload_from_snapshot(&self) -> Result<(), OperationError> {
385 Box::pin(self.storage.reload_from_snapshot()).await
389 }
390 pub async fn reset_store(&self) -> Result<(), SyncError> {
392 self.storage.reset(Audience::Store).await
393 }
394 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 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 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 #[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 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 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 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 pub fn circles(&self) -> Circles<'_> {
451 Circles::new(self)
452 }
453
454 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 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 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 pub async fn sqlite_settings(&self) -> Result<SqliteSettingsInEffect, DbError> {
496 self.database.sqlite_settings().await
497 }
498
499 pub async fn checkpoint(&self, mode: CheckpointMode) -> Result<WalCheckpoint, DbError> {
504 self.database.checkpoint(mode).await
505 }
506
507 pub async fn incremental_vacuum(&self, pages: IncrementalVacuum) -> Result<(), DbError> {
510 self.database.incremental_vacuum(pages).await
511 }
512
513 pub async fn release_memory(&self) -> Result<(), DbError> {
520 self.database.release_memory().await
521 }
522
523 pub async fn lost_values(&self) -> CovenResult<Vec<LostValue>> {
525 self.database.lost_values().await.map_err(CovenError::from)
526 }
527
528 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 pub fn subscribe_lost_values(&self) -> LiveQuery<Vec<LostValue>, CovenError> {
537 self.database.subscribe_lost_values()
538 }
539
540 pub async fn file_ref(&self, file: FileId) -> Result<FileRef, DbError> {
545 self.database.file_ref(file).await
546 }
547
548 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 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 pub async fn user_file(&self, file: FileId) -> Result<Option<UserFile>, DbError> {
575 self.database.user_file(file).await
576 }
577
578 pub async fn forget_store_keys(&self) -> Result<(), KeyError> {
581 self.storage.forget_store_keys().await
582 }
583
584 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 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 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 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 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 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 #[cfg(test)]
650 pub(crate) async fn applied_slot(&self) -> u64 {
651 self.database.applied_slot().await.unwrap()
652 }
653 #[cfg(test)]
655 pub(crate) async fn store_state(&self) -> coven_database::StoreState {
656 self.database.store_state().await.unwrap()
657 }
658 #[cfg(test)]
665 pub(crate) fn test_call_waits(&self) -> impl std::future::Future<Output = ()> {
666 self.storage.call_waits_from_now()
667 }
668 #[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 #[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 #[cfg(test)]
687 pub(crate) fn test_database(&self) -> &coven_database::StoreDatabase {
688 &self.database
689 }
690 #[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 #[cfg(test)]
699 pub(crate) fn test_pause_asked(&self) -> impl std::future::Future<Output = ()> {
700 self.storage.pause_asked_from_now()
701 }
702 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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;