1use aequora_adapter_sdk::{
4 AdapterError, AdapterErrorKind, ClientIdentity, ClientStore, ConflictId, ConflictResolution,
5 ConflictSummary, CredentialProvider, DomainId, DurableClientStatus, ExchangeContext,
6 NoopObservationSink, ObservationSink, OperationSnapshot, SyncTransport,
7};
8use aequora_operation::{
9 EncodedOperation, MutationReceipt, Operation, OperationEncodingError, OperationState,
10 OperationUpdate,
11};
12use aequora_types::{OperationId, SyncScopeId};
13use std::{
14 fmt,
15 path::{Path, PathBuf},
16 sync::{
17 Arc,
18 atomic::{AtomicBool, Ordering},
19 },
20 time::{Duration, Instant},
21};
22use thiserror::Error;
23use tokio::sync::broadcast;
24
25#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
27#[non_exhaustive]
28pub enum AequoraErrorCode {
29 StorageUnavailable,
31 TransportUnavailable,
33 AuthenticationRequired,
35 AuthorizationDenied,
37 Conflict,
39 Validation,
41 Backpressure,
43 UnsupportedCapability,
45 Closed,
47 Internal,
49}
50
51impl AequoraErrorCode {
52 #[must_use]
54 pub const fn as_str(self) -> &'static str {
55 match self {
56 Self::StorageUnavailable => "AEQ-SDK-STORAGE-001",
57 Self::TransportUnavailable => "AEQ-SDK-TRANSPORT-001",
58 Self::AuthenticationRequired => "AEQ-SDK-AUTHN-001",
59 Self::AuthorizationDenied => "AEQ-SDK-AUTHZ-001",
60 Self::Conflict => "AEQ-SDK-CONFLICT-001",
61 Self::Validation => "AEQ-SDK-VALIDATION-001",
62 Self::Backpressure => "AEQ-SDK-RESOURCE-001",
63 Self::UnsupportedCapability => "AEQ-SDK-CAPABILITY-001",
64 Self::Closed => "AEQ-SDK-CLOSED-001",
65 Self::Internal => "AEQ-SDK-INTERNAL-001",
66 }
67 }
68}
69
70impl fmt::Display for AequoraErrorCode {
71 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
72 formatter.write_str(self.as_str())
73 }
74}
75
76#[derive(Clone, Copy, Debug, Eq, PartialEq)]
78pub enum RetryClass {
79 Retryable,
81 UserActionRequired,
83 NonRetryable,
85}
86
87#[derive(Clone, Debug, Error, Eq, PartialEq)]
89#[non_exhaustive]
90pub enum AequoraError {
91 #[error("{code}: {source}")]
93 Adapter {
94 code: AequoraErrorCode,
96 #[source]
98 source: AdapterError,
99 },
100 #[error("{code}: {source}")]
102 OperationEncoding {
103 code: AequoraErrorCode,
105 #[source]
107 source: OperationEncodingError,
108 },
109 #[error("{code}: required client field `{field}` is missing")]
111 MissingConfiguration {
112 code: AequoraErrorCode,
114 field: &'static str,
116 },
117 #[error("{code}: authoritative confirmation timed out")]
119 ConfirmationTimeout {
120 code: AequoraErrorCode,
122 },
123 #[error("{code}: client is closed")]
125 Closed {
126 code: AequoraErrorCode,
128 },
129 #[error("{code}: a synchronization attempt is already running")]
131 SyncInProgress {
132 code: AequoraErrorCode,
134 },
135}
136
137impl AequoraError {
138 #[must_use]
140 pub const fn code(&self) -> AequoraErrorCode {
141 match self {
142 Self::Adapter { code, .. }
143 | Self::OperationEncoding { code, .. }
144 | Self::MissingConfiguration { code, .. }
145 | Self::ConfirmationTimeout { code }
146 | Self::Closed { code }
147 | Self::SyncInProgress { code } => *code,
148 }
149 }
150
151 #[must_use]
153 pub const fn retry_class(&self) -> RetryClass {
154 match self.code() {
155 AequoraErrorCode::StorageUnavailable
156 | AequoraErrorCode::TransportUnavailable
157 | AequoraErrorCode::Backpressure
158 | AequoraErrorCode::Internal => RetryClass::Retryable,
159 AequoraErrorCode::AuthenticationRequired
160 | AequoraErrorCode::AuthorizationDenied
161 | AequoraErrorCode::Conflict => RetryClass::UserActionRequired,
162 AequoraErrorCode::Validation
163 | AequoraErrorCode::UnsupportedCapability
164 | AequoraErrorCode::Closed => RetryClass::NonRetryable,
165 }
166 }
167
168 fn from_adapter(error: AdapterError) -> Self {
169 let code = match error.kind() {
170 AdapterErrorKind::Storage => AequoraErrorCode::StorageUnavailable,
171 AdapterErrorKind::Transport => AequoraErrorCode::TransportUnavailable,
172 AdapterErrorKind::Authentication => AequoraErrorCode::AuthenticationRequired,
173 AdapterErrorKind::Validation => AequoraErrorCode::Validation,
174 AdapterErrorKind::Backpressure => AequoraErrorCode::Backpressure,
175 AdapterErrorKind::UnsupportedCapability => AequoraErrorCode::UnsupportedCapability,
176 _ => AequoraErrorCode::Internal,
177 };
178 Self::Adapter {
179 code,
180 source: error,
181 }
182 }
183
184 const fn missing(field: &'static str) -> Self {
185 Self::MissingConfiguration {
186 code: AequoraErrorCode::Validation,
187 field,
188 }
189 }
190}
191
192#[derive(Clone, Copy, Debug, Eq, PartialEq)]
194#[non_exhaustive]
195pub enum SyncStatus {
196 Offline,
198 Idle,
200 Pending {
202 operations: u64,
204 },
205 Syncing,
207 Conflict,
209 NeedsBootstrap,
211 AuthenticationRequired,
213 UpgradeRequired,
215 StorageBlocked,
217 Closed,
219}
220
221#[derive(Clone, Copy, Debug, Eq, PartialEq)]
223#[non_exhaustive]
224pub enum SyncNextAction {
225 Idle,
227 RetryAfter(Duration),
229 NeedsBootstrap,
231 UpgradeRequired,
233 AuthenticationRequired,
235}
236
237#[derive(Clone, Copy, Debug, Eq, PartialEq)]
239pub struct SyncResult {
240 pub pushed: u64,
242 pub pulled: u64,
244 pub conflicts: u64,
246 pub next_action: SyncNextAction,
248}
249
250#[derive(Clone, Copy, Debug, Eq, PartialEq)]
252#[non_exhaustive]
253pub enum SyncReason {
254 UserInitiated,
256 ConnectivityChanged,
258 AppResumed,
260 ServerHint,
262}
263
264#[derive(Clone, Copy, Debug, Eq, PartialEq)]
266pub struct DataChange {
267 pub scope_id: SyncScopeId,
269}
270
271#[derive(Clone, Copy, Debug, Eq, PartialEq)]
273pub struct BootstrapProgress {
274 pub completed: u64,
276 pub total: Option<u64>,
278}
279
280#[derive(Clone, Debug, Eq, PartialEq)]
282#[non_exhaustive]
283pub enum SyncEvent {
284 StatusChanged(SyncStatus),
286 DataChanged(DataChange),
288 ConflictCreated(ConflictId),
290 OperationUpdated(OperationUpdate),
292 BootstrapProgress(BootstrapProgress),
294 SyncRequested(SyncReason),
296 Closed,
298}
299
300pub struct EventStream {
302 receiver: broadcast::Receiver<SyncEvent>,
303}
304
305impl EventStream {
306 #[must_use]
309 pub async fn next(&mut self) -> Option<SyncEvent> {
310 loop {
311 match self.receiver.recv().await {
312 Ok(event) => return Some(event),
313 Err(broadcast::error::RecvError::Lagged(_)) => {}
314 Err(broadcast::error::RecvError::Closed) => return None,
315 }
316 }
317 }
318}
319
320#[derive(Clone, Copy, Debug)]
322pub struct ClientSdkConfig {
323 pub event_capacity: usize,
325 pub conflict_page_size: usize,
327 pub confirmation_timeout: Duration,
329 pub confirmation_poll_interval: Duration,
331}
332
333impl Default for ClientSdkConfig {
334 fn default() -> Self {
335 Self {
336 event_capacity: 64,
337 conflict_page_size: 100,
338 confirmation_timeout: Duration::from_secs(30),
339 confirmation_poll_interval: Duration::from_millis(250),
340 }
341 }
342}
343
344impl ClientSdkConfig {
345 fn validate(self) -> Result<Self, AequoraError> {
346 if self.event_capacity == 0 {
347 return Err(AequoraError::missing("config.event_capacity"));
348 }
349 if self.conflict_page_size == 0 {
350 return Err(AequoraError::missing("config.conflict_page_size"));
351 }
352 if self.confirmation_timeout.is_zero() || self.confirmation_poll_interval.is_zero() {
353 return Err(AequoraError::missing("config.confirmation_timeout"));
354 }
355 Ok(self)
356 }
357}
358
359#[derive(Default)]
361pub struct AequoraClientBuilder {
362 store: Option<Arc<dyn ClientStore>>,
363 transport: Option<Arc<dyn SyncTransport>>,
364 credentials: Option<Arc<dyn CredentialProvider>>,
365 identity: Option<ClientIdentity>,
366 domain: Option<DomainId>,
367 observer: Option<Arc<dyn ObservationSink>>,
368 config: ClientSdkConfig,
369}
370
371impl AequoraClientBuilder {
372 #[must_use]
374 pub fn store(mut self, store: impl ClientStore + 'static) -> Self {
375 self.store = Some(Arc::new(store));
376 self
377 }
378
379 #[must_use]
381 pub fn shared_store(mut self, store: Arc<dyn ClientStore>) -> Self {
382 self.store = Some(store);
383 self
384 }
385
386 #[must_use]
388 pub fn transport(mut self, transport: impl SyncTransport + 'static) -> Self {
389 self.transport = Some(Arc::new(transport));
390 self
391 }
392
393 #[must_use]
395 pub fn shared_transport(mut self, transport: Arc<dyn SyncTransport>) -> Self {
396 self.transport = Some(transport);
397 self
398 }
399
400 #[must_use]
402 pub fn credentials(mut self, provider: impl CredentialProvider + 'static) -> Self {
403 self.credentials = Some(Arc::new(provider));
404 self
405 }
406
407 #[must_use]
409 pub fn shared_credentials(mut self, provider: Arc<dyn CredentialProvider>) -> Self {
410 self.credentials = Some(provider);
411 self
412 }
413
414 #[must_use]
416 pub const fn identity(mut self, identity: ClientIdentity) -> Self {
417 self.identity = Some(identity);
418 self
419 }
420
421 #[must_use]
423 pub fn domain(mut self, domain: DomainId) -> Self {
424 self.domain = Some(domain);
425 self
426 }
427
428 #[must_use]
430 pub fn observer(mut self, observer: impl ObservationSink + 'static) -> Self {
431 self.observer = Some(Arc::new(observer));
432 self
433 }
434
435 #[must_use]
437 pub const fn config(mut self, config: ClientSdkConfig) -> Self {
438 self.config = config;
439 self
440 }
441
442 #[allow(clippy::unused_async)]
448 pub async fn build(self) -> Result<AequoraClient, AequoraError> {
449 let config = self.config.validate()?;
450 let (events, _) = broadcast::channel(config.event_capacity);
451 Ok(AequoraClient {
452 inner: Arc::new(ClientInner {
453 store: self.store.ok_or_else(|| AequoraError::missing("store"))?,
454 transport: self
455 .transport
456 .ok_or_else(|| AequoraError::missing("transport"))?,
457 credentials: self
458 .credentials
459 .ok_or_else(|| AequoraError::missing("credentials"))?,
460 identity: self
461 .identity
462 .ok_or_else(|| AequoraError::missing("identity"))?,
463 domain: self.domain.ok_or_else(|| AequoraError::missing("domain"))?,
464 observer: self
465 .observer
466 .unwrap_or_else(|| Arc::new(NoopObservationSink)),
467 events,
468 syncing: AtomicBool::new(false),
469 closed: AtomicBool::new(false),
470 sync_requested: AtomicBool::new(false),
471 config,
472 }),
473 })
474 }
475}
476
477struct ClientInner {
478 store: Arc<dyn ClientStore>,
479 transport: Arc<dyn SyncTransport>,
480 credentials: Arc<dyn CredentialProvider>,
481 identity: ClientIdentity,
482 domain: DomainId,
483 observer: Arc<dyn ObservationSink>,
484 events: broadcast::Sender<SyncEvent>,
485 syncing: AtomicBool,
486 closed: AtomicBool,
487 sync_requested: AtomicBool,
488 config: ClientSdkConfig,
489}
490
491impl ClientInner {
492 fn ensure_open(&self) -> Result<(), AequoraError> {
493 if self.closed.load(Ordering::Acquire) {
494 Err(AequoraError::Closed {
495 code: AequoraErrorCode::Closed,
496 })
497 } else {
498 Ok(())
499 }
500 }
501
502 fn notify(&self, event: SyncEvent) {
503 let _ignored = self.events.send(event);
504 }
505}
506
507#[derive(Clone)]
509pub struct AequoraClient {
510 inner: Arc<ClientInner>,
511}
512
513impl fmt::Debug for AequoraClient {
514 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
515 formatter
516 .debug_struct("AequoraClient")
517 .field("domain", &self.inner.domain)
518 .field("closed", &self.inner.closed.load(Ordering::Relaxed))
519 .finish_non_exhaustive()
520 }
521}
522
523impl AequoraClient {
524 #[must_use]
526 pub fn builder() -> AequoraClientBuilder {
527 AequoraClientBuilder::default()
528 }
529
530 pub async fn mutate<O: Operation>(
536 &self,
537 operation: O,
538 ) -> Result<MutationReceipt, AequoraError> {
539 self.inner.ensure_open()?;
540 let encoded = EncodedOperation::from_operation(&operation).map_err(|source| {
541 AequoraError::OperationEncoding {
542 code: AequoraErrorCode::Validation,
543 source,
544 }
545 })?;
546 let operation_id = encoded.operation_id();
547 let local_status = self
548 .inner
549 .store
550 .commit_operation(encoded)
551 .await
552 .map_err(AequoraError::from_adapter)?;
553 self.inner
554 .notify(SyncEvent::OperationUpdated(OperationUpdate {
555 operation_id,
556 state: OperationState::Pending,
557 }));
558 Ok(MutationReceipt::new(operation_id, local_status))
559 }
560
561 pub async fn sync_now(&self) -> Result<SyncResult, AequoraError> {
567 self.inner.ensure_open()?;
568 if self
569 .inner
570 .syncing
571 .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
572 .is_err()
573 {
574 return Err(AequoraError::SyncInProgress {
575 code: AequoraErrorCode::Backpressure,
576 });
577 }
578 let _reservation = SyncReservation(&self.inner.syncing);
579 self.inner.sync_requested.store(false, Ordering::Release);
580 self.inner.observer.on_status("syncing");
581 self.inner
582 .notify(SyncEvent::StatusChanged(SyncStatus::Syncing));
583
584 let credential = self
585 .inner
586 .credentials
587 .credential()
588 .await
589 .map_err(AequoraError::from_adapter)?;
590 let summary = self
591 .inner
592 .transport
593 .exchange(ExchangeContext {
594 identity: self.inner.identity,
595 domain: &self.inner.domain,
596 credential: &credential,
597 })
598 .await
599 .map_err(AequoraError::from_adapter)?;
600 let next_action = if summary.upgrade_required {
601 SyncNextAction::UpgradeRequired
602 } else if summary.needs_bootstrap {
603 SyncNextAction::NeedsBootstrap
604 } else if let Some(delay) = summary.retry_after {
605 SyncNextAction::RetryAfter(delay)
606 } else {
607 SyncNextAction::Idle
608 };
609 let result = SyncResult {
610 pushed: summary.pushed,
611 pulled: summary.pulled,
612 conflicts: summary.conflicts,
613 next_action,
614 };
615 let status = self.status().await?;
616 self.inner.observer.on_status("idle");
617 self.inner.notify(SyncEvent::StatusChanged(status));
618 Ok(result)
619 }
620
621 #[must_use]
623 pub fn request_sync(&self, reason: SyncReason) -> bool {
624 if self.inner.closed.load(Ordering::Acquire) {
625 return false;
626 }
627 let newly_requested = !self.inner.sync_requested.swap(true, Ordering::AcqRel);
628 if newly_requested {
629 self.inner.notify(SyncEvent::SyncRequested(reason));
630 }
631 newly_requested
632 }
633
634 pub async fn status(&self) -> Result<SyncStatus, AequoraError> {
640 if self.inner.closed.load(Ordering::Acquire) {
641 return Ok(SyncStatus::Closed);
642 }
643 if self.inner.syncing.load(Ordering::Acquire) {
644 return Ok(SyncStatus::Syncing);
645 }
646 let durable = self
647 .inner
648 .store
649 .status()
650 .await
651 .map_err(AequoraError::from_adapter)?;
652 Ok(status_from_durable(durable))
653 }
654
655 #[must_use]
657 pub fn events(&self) -> EventStream {
658 EventStream {
659 receiver: self.inner.events.subscribe(),
660 }
661 }
662
663 #[must_use]
665 pub fn operations(&self) -> OperationHandle {
666 OperationHandle {
667 inner: Arc::clone(&self.inner),
668 }
669 }
670
671 #[must_use]
673 pub fn conflicts(&self) -> ConflictHandle {
674 ConflictHandle {
675 inner: Arc::clone(&self.inner),
676 }
677 }
678
679 #[must_use]
681 pub fn scopes(&self) -> ScopeHandle {
682 ScopeHandle {
683 inner: Arc::clone(&self.inner),
684 }
685 }
686
687 #[must_use]
689 pub fn blobs(&self) -> BlobHandle {
690 BlobHandle {
691 inner: Arc::clone(&self.inner),
692 }
693 }
694
695 #[must_use]
697 pub fn diagnostics(&self) -> DiagnosticsHandle {
698 DiagnosticsHandle {
699 inner: Arc::clone(&self.inner),
700 }
701 }
702
703 #[allow(clippy::unused_async)]
710 pub async fn shutdown(&self) -> Result<(), AequoraError> {
711 if !self.inner.closed.swap(true, Ordering::AcqRel) {
712 self.inner
713 .notify(SyncEvent::StatusChanged(SyncStatus::Closed));
714 self.inner.notify(SyncEvent::Closed);
715 self.inner.observer.on_status("closed");
716 }
717 Ok(())
718 }
719}
720
721struct SyncReservation<'a>(&'a AtomicBool);
722
723impl Drop for SyncReservation<'_> {
724 fn drop(&mut self) {
725 self.0.store(false, Ordering::Release);
726 }
727}
728
729const fn status_from_durable(status: DurableClientStatus) -> SyncStatus {
730 if status.storage_blocked {
731 SyncStatus::StorageBlocked
732 } else if status.needs_bootstrap {
733 SyncStatus::NeedsBootstrap
734 } else if status.conflicts > 0 {
735 SyncStatus::Conflict
736 } else if status.pending_operations > 0 {
737 SyncStatus::Pending {
738 operations: status.pending_operations,
739 }
740 } else {
741 SyncStatus::Idle
742 }
743}
744
745#[derive(Clone)]
747pub struct OperationHandle {
748 inner: Arc<ClientInner>,
749}
750
751impl OperationHandle {
752 pub async fn get(
758 &self,
759 operation_id: OperationId,
760 ) -> Result<Option<OperationRef>, AequoraError> {
761 self.inner.ensure_open()?;
762 self.inner
763 .store
764 .operation(operation_id)
765 .await
766 .map(|snapshot| {
767 snapshot.map(|snapshot| OperationRef {
768 inner: Arc::clone(&self.inner),
769 snapshot,
770 })
771 })
772 .map_err(AequoraError::from_adapter)
773 }
774}
775
776#[derive(Clone)]
778pub struct OperationRef {
779 inner: Arc<ClientInner>,
780 snapshot: OperationSnapshot,
781}
782
783impl OperationRef {
784 #[must_use]
786 pub const fn snapshot(&self) -> OperationSnapshot {
787 self.snapshot
788 }
789
790 pub async fn await_authoritative(self) -> Result<OperationSnapshot, AequoraError> {
796 let started = Instant::now();
797 loop {
798 self.inner.ensure_open()?;
799 let snapshot = self
800 .inner
801 .store
802 .operation(self.snapshot.operation_id)
803 .await
804 .map_err(AequoraError::from_adapter)?
805 .ok_or_else(|| {
806 AequoraError::from_adapter(AdapterError::new(
807 AdapterErrorKind::Storage,
808 "durable operation disappeared",
809 ))
810 })?;
811 if matches!(
812 snapshot.state,
813 OperationState::AuthoritativeAccepted
814 | OperationState::Rejected
815 | OperationState::Conflict
816 | OperationState::Superseded
817 ) {
818 return Ok(snapshot);
819 }
820 if started.elapsed() >= self.inner.config.confirmation_timeout {
821 return Err(AequoraError::ConfirmationTimeout {
822 code: AequoraErrorCode::TransportUnavailable,
823 });
824 }
825 tokio::time::sleep(self.inner.config.confirmation_poll_interval).await;
826 }
827 }
828}
829
830#[derive(Clone)]
832pub struct ConflictHandle {
833 inner: Arc<ClientInner>,
834}
835
836impl ConflictHandle {
837 pub async fn list(&self) -> Result<Vec<ConflictSummary>, AequoraError> {
843 self.inner.ensure_open()?;
844 self.inner
845 .store
846 .conflicts(self.inner.config.conflict_page_size)
847 .await
848 .map_err(AequoraError::from_adapter)
849 }
850
851 pub async fn get(&self, id: ConflictId) -> Result<Option<ConflictSummary>, AequoraError> {
857 self.inner.ensure_open()?;
858 self.inner
859 .store
860 .conflict(id)
861 .await
862 .map_err(AequoraError::from_adapter)
863 }
864
865 pub async fn resolve(
871 &self,
872 id: ConflictId,
873 resolution: ConflictResolution,
874 ) -> Result<OperationId, AequoraError> {
875 self.inner.ensure_open()?;
876 self.inner
877 .store
878 .resolve_conflict(id, resolution)
879 .await
880 .map_err(AequoraError::from_adapter)
881 }
882}
883
884#[derive(Clone, Copy, Debug, Eq, PartialEq)]
886#[non_exhaustive]
887pub enum ScopeSubscriptionState {
888 Requested,
890 Bootstrapping,
892 Active,
894}
895
896#[derive(Clone)]
898pub struct ScopeHandle {
899 inner: Arc<ClientInner>,
900}
901
902impl ScopeHandle {
903 pub async fn subscribe(
909 &self,
910 scope: SyncScopeId,
911 ) -> Result<ScopeSubscriptionState, AequoraError> {
912 self.inner.ensure_open()?;
913 self.inner
914 .store
915 .subscribe_scope(scope)
916 .await
917 .map_err(AequoraError::from_adapter)?;
918 Ok(ScopeSubscriptionState::Requested)
919 }
920
921 pub async fn unsubscribe(&self, scope: SyncScopeId) -> Result<(), AequoraError> {
927 self.inner.ensure_open()?;
928 self.inner
929 .store
930 .unsubscribe_scope(scope)
931 .await
932 .map_err(AequoraError::from_adapter)
933 }
934}
935
936#[derive(Clone)]
938pub struct BlobHandle {
939 inner: Arc<ClientInner>,
940}
941
942impl BlobHandle {
943 #[allow(clippy::unused_async)]
949 pub async fn import(&self, path: impl AsRef<Path>) -> Result<PathBuf, AequoraError> {
950 self.inner.ensure_open()?;
951 let _path = path.as_ref();
952 Err(AequoraError::from_adapter(AdapterError::new(
953 AdapterErrorKind::UnsupportedCapability,
954 "blob provider is not configured",
955 )))
956 }
957}
958
959#[derive(Clone)]
961pub struct DiagnosticsHandle {
962 inner: Arc<ClientInner>,
963}
964
965impl DiagnosticsHandle {
966 pub async fn summary(&self) -> Result<Arc<str>, AequoraError> {
972 self.inner.ensure_open()?;
973 self.inner
974 .store
975 .diagnostic_summary()
976 .await
977 .map_err(AequoraError::from_adapter)
978 }
979}
980
981#[cfg(test)]
982mod tests {
983 use super::*;
984 use aequora_adapter_sdk::{Credential, ExchangeSummary};
985 use aequora_operation::{LocalCommitStatus, OperationKind, OperationSchemaVersion};
986 use aequora_types::{DeviceId, TenantId};
987 use async_trait::async_trait;
988 use std::{collections::BTreeMap, sync::Mutex};
989
990 #[derive(Default)]
991 struct MemoryStore {
992 operations: Mutex<BTreeMap<OperationId, OperationState>>,
993 }
994
995 #[async_trait]
996 impl ClientStore for MemoryStore {
997 async fn commit_operation(
998 &self,
999 operation: EncodedOperation,
1000 ) -> Result<LocalCommitStatus, AdapterError> {
1001 self.operations
1002 .lock()
1003 .unwrap_or_else(std::sync::PoisonError::into_inner)
1004 .insert(operation.operation_id(), OperationState::Pending);
1005 Ok(LocalCommitStatus::SavedLocally)
1006 }
1007
1008 async fn operation(
1009 &self,
1010 operation_id: OperationId,
1011 ) -> Result<Option<OperationSnapshot>, AdapterError> {
1012 Ok(self
1013 .operations
1014 .lock()
1015 .unwrap_or_else(std::sync::PoisonError::into_inner)
1016 .get(&operation_id)
1017 .copied()
1018 .map(|state| OperationSnapshot {
1019 operation_id,
1020 state,
1021 }))
1022 }
1023
1024 async fn status(&self) -> Result<DurableClientStatus, AdapterError> {
1025 Ok(DurableClientStatus {
1026 pending_operations: self
1027 .operations
1028 .lock()
1029 .unwrap_or_else(std::sync::PoisonError::into_inner)
1030 .len() as u64,
1031 ..DurableClientStatus::default()
1032 })
1033 }
1034
1035 async fn conflicts(&self, _limit: usize) -> Result<Vec<ConflictSummary>, AdapterError> {
1036 Ok(Vec::new())
1037 }
1038
1039 async fn conflict(
1040 &self,
1041 _conflict_id: ConflictId,
1042 ) -> Result<Option<ConflictSummary>, AdapterError> {
1043 Ok(None)
1044 }
1045
1046 async fn resolve_conflict(
1047 &self,
1048 _conflict_id: ConflictId,
1049 _resolution: ConflictResolution,
1050 ) -> Result<OperationId, AdapterError> {
1051 Err(AdapterError::new(
1052 AdapterErrorKind::UnsupportedCapability,
1053 "no conflicts",
1054 ))
1055 }
1056
1057 async fn subscribe_scope(&self, _scope: SyncScopeId) -> Result<(), AdapterError> {
1058 Ok(())
1059 }
1060
1061 async fn unsubscribe_scope(&self, _scope: SyncScopeId) -> Result<(), AdapterError> {
1062 Ok(())
1063 }
1064
1065 async fn diagnostic_summary(&self) -> Result<Arc<str>, AdapterError> {
1066 Ok(Arc::from("healthy"))
1067 }
1068 }
1069
1070 struct Transport;
1071
1072 #[async_trait]
1073 impl SyncTransport for Transport {
1074 async fn exchange(
1075 &self,
1076 _context: ExchangeContext<'_>,
1077 ) -> Result<ExchangeSummary, AdapterError> {
1078 Ok(ExchangeSummary::default())
1079 }
1080 }
1081
1082 struct Credentials;
1083
1084 #[async_trait]
1085 impl CredentialProvider for Credentials {
1086 async fn credential(&self) -> Result<Credential, AdapterError> {
1087 Ok(Credential::new("test-only"))
1088 }
1089 }
1090
1091 struct CreateStudent;
1092
1093 impl Operation for CreateStudent {
1094 type Outcome = ();
1095
1096 const KIND: OperationKind = OperationKind::from_static(1001);
1097 const SCHEMA_VERSION: OperationSchemaVersion = OperationSchemaVersion::from_static(1);
1098
1099 fn encode(&self) -> Result<Vec<u8>, OperationEncodingError> {
1100 Ok(vec![1])
1101 }
1102 }
1103
1104 async fn client() -> AequoraClient {
1105 AequoraClient::builder()
1106 .store(MemoryStore::default())
1107 .transport(Transport)
1108 .credentials(Credentials)
1109 .identity(ClientIdentity {
1110 tenant_id: TenantId::new(),
1111 device_id: DeviceId::new(),
1112 })
1113 .domain(DomainId::new("school").unwrap_or_else(|error| {
1114 panic!("domain should be valid: {error}");
1115 }))
1116 .build()
1117 .await
1118 .unwrap_or_else(|error| panic!("client should build: {error}"))
1119 }
1120
1121 #[tokio::test]
1122 async fn mutation_receipt_is_local_only_and_state_remains_queryable() {
1123 let client = client().await;
1124 let mut events = client.events();
1125 let receipt = client
1126 .mutate(CreateStudent)
1127 .await
1128 .unwrap_or_else(|error| panic!("mutation should persist: {error}"));
1129 assert_eq!(receipt.local_status(), LocalCommitStatus::SavedLocally);
1130 assert_eq!(
1131 client.status().await,
1132 Ok(SyncStatus::Pending { operations: 1 })
1133 );
1134 assert!(matches!(
1135 events.next().await,
1136 Some(SyncEvent::OperationUpdated(_))
1137 ));
1138 }
1139
1140 #[tokio::test]
1141 async fn cloned_handle_shares_runtime_and_shutdown_is_explicit() {
1142 let client = client().await;
1143 let clone = client.clone();
1144 clone
1145 .shutdown()
1146 .await
1147 .unwrap_or_else(|error| panic!("shutdown should succeed: {error}"));
1148 assert_eq!(client.status().await, Ok(SyncStatus::Closed));
1149 assert!(matches!(
1150 client.mutate(CreateStudent).await,
1151 Err(AequoraError::Closed { .. })
1152 ));
1153 }
1154}