Skip to main content

aequora_client/
sdk.rs

1//! High-level, misuse-resistant application client SDK.
2
3use 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/// Stable public error code, independent from error text and internal sources.
26#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
27#[non_exhaustive]
28pub enum AequoraErrorCode {
29    /// Durable storage failed.
30    StorageUnavailable,
31    /// A bounded transport exchange failed.
32    TransportUnavailable,
33    /// Authentication or credential acquisition failed.
34    AuthenticationRequired,
35    /// Authorization rejected the requested operation.
36    AuthorizationDenied,
37    /// A semantic conflict requires explicit handling.
38    Conflict,
39    /// Public input or configuration is invalid.
40    Validation,
41    /// A bounded resource limit rejected work.
42    Backpressure,
43    /// The configured runtime does not provide this optional capability.
44    UnsupportedCapability,
45    /// Client has begun or completed shutdown.
46    Closed,
47    /// An internal failure has no more specific stable category.
48    Internal,
49}
50
51impl AequoraErrorCode {
52    /// Stable machine-readable compatibility code.
53    #[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/// Stable retry classification for application policy and FFI consumers.
77#[derive(Clone, Copy, Debug, Eq, PartialEq)]
78pub enum RetryClass {
79    /// Retrying without replacing user intent may succeed.
80    Retryable,
81    /// User action or new semantic intent is required.
82    UserActionRequired,
83    /// Retrying the same request is not useful.
84    NonRetryable,
85}
86
87/// One top-level SDK error with semver-stable categories and codes.
88#[derive(Clone, Debug, Error, Eq, PartialEq)]
89#[non_exhaustive]
90pub enum AequoraError {
91    /// Stable adapter-boundary failure.
92    #[error("{code}: {source}")]
93    Adapter {
94        /// Stable public code.
95        code: AequoraErrorCode,
96        /// Redacted adapter source.
97        #[source]
98        source: AdapterError,
99    },
100    /// Application operation could not be encoded.
101    #[error("{code}: {source}")]
102    OperationEncoding {
103        /// Stable public code.
104        code: AequoraErrorCode,
105        /// Redacted operation encoder source.
106        #[source]
107        source: OperationEncodingError,
108    },
109    /// Builder is missing required configuration.
110    #[error("{code}: required client field `{field}` is missing")]
111    MissingConfiguration {
112        /// Stable public code.
113        code: AequoraErrorCode,
114        /// Missing semantic field.
115        field: &'static str,
116    },
117    /// Operation did not reach an authoritative terminal state within policy.
118    #[error("{code}: authoritative confirmation timed out")]
119    ConfirmationTimeout {
120        /// Stable public code.
121        code: AequoraErrorCode,
122    },
123    /// Runtime is closing or closed.
124    #[error("{code}: client is closed")]
125    Closed {
126        /// Stable public code.
127        code: AequoraErrorCode,
128    },
129    /// Another bounded synchronous attempt already owns the single-flight reservation.
130    #[error("{code}: a synchronization attempt is already running")]
131    SyncInProgress {
132        /// Stable public code.
133        code: AequoraErrorCode,
134    },
135}
136
137impl AequoraError {
138    /// Stable machine-readable code.
139    #[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    /// Stable retry classification.
152    #[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/// High-level current synchronization state. Internal planner phases are intentionally absent.
193#[derive(Clone, Copy, Debug, Eq, PartialEq)]
194#[non_exhaustive]
195pub enum SyncStatus {
196    /// Transport is currently unavailable.
197    Offline,
198    /// No durable work is pending.
199    Idle,
200    /// Durable operations await authoritative disposition.
201    Pending {
202        /// Number of pending operations.
203        operations: u64,
204    },
205    /// One bounded exchange is active.
206    Syncing,
207    /// At least one semantic conflict requires resolution.
208    Conflict,
209    /// Store requires a fresh snapshot bootstrap.
210    NeedsBootstrap,
211    /// New credentials or user authentication are required.
212    AuthenticationRequired,
213    /// Runtime compatibility requires an SDK/application upgrade.
214    UpgradeRequired,
215    /// Storage pressure currently rejects additional durable work.
216    StorageBlocked,
217    /// Client is shutting down or closed.
218    Closed,
219}
220
221/// Next safe action after a bounded synchronization attempt.
222#[derive(Clone, Copy, Debug, Eq, PartialEq)]
223#[non_exhaustive]
224pub enum SyncNextAction {
225    /// No immediate follow-up is required.
226    Idle,
227    /// Scheduler may retry after this lower bound.
228    RetryAfter(Duration),
229    /// A fresh snapshot bootstrap is required.
230    NeedsBootstrap,
231    /// A compatible application/SDK upgrade is required.
232    UpgradeRequired,
233    /// New credentials or user authentication are required.
234    AuthenticationRequired,
235}
236
237/// Stable summary of one bounded synchronization attempt.
238#[derive(Clone, Copy, Debug, Eq, PartialEq)]
239pub struct SyncResult {
240    /// Operations authoritatively disposed.
241    pub pushed: u64,
242    /// Authoritative changes applied locally.
243    pub pulled: u64,
244    /// Conflicts created during the attempt.
245    pub conflicts: u64,
246    /// Next safe scheduler/application action.
247    pub next_action: SyncNextAction,
248}
249
250/// Bounded scheduler hint. It cannot bypass admission or retry limits.
251#[derive(Clone, Copy, Debug, Eq, PartialEq)]
252#[non_exhaustive]
253pub enum SyncReason {
254    /// Explicit foreground user action.
255    UserInitiated,
256    /// Network availability changed.
257    ConnectivityChanged,
258    /// Application returned to an active lifecycle state.
259    AppResumed,
260    /// Advisory server hint suggested durable state may have changed.
261    ServerHint,
262}
263
264/// Redacted advisory data-change notification.
265#[derive(Clone, Copy, Debug, Eq, PartialEq)]
266pub struct DataChange {
267    /// Scope whose durable state may have changed.
268    pub scope_id: SyncScopeId,
269}
270
271/// Bounded bootstrap progress hint. Durable bootstrap state remains queryable.
272#[derive(Clone, Copy, Debug, Eq, PartialEq)]
273pub struct BootstrapProgress {
274    /// Completed bounded units.
275    pub completed: u64,
276    /// Total units when known.
277    pub total: Option<u64>,
278}
279
280/// Best-effort UI notification. Missing an event never loses durable state.
281#[derive(Clone, Debug, Eq, PartialEq)]
282#[non_exhaustive]
283pub enum SyncEvent {
284    /// High-level status changed.
285    StatusChanged(SyncStatus),
286    /// Durable data in one scope may have changed.
287    DataChanged(DataChange),
288    /// A semantic conflict was created.
289    ConflictCreated(ConflictId),
290    /// Operation lifecycle changed.
291    OperationUpdated(OperationUpdate),
292    /// Bootstrap made bounded progress.
293    BootstrapProgress(BootstrapProgress),
294    /// A scheduler hint was accepted.
295    SyncRequested(SyncReason),
296    /// Graceful shutdown completed.
297    Closed,
298}
299
300/// Event receiver with explicit best-effort lag semantics.
301pub struct EventStream {
302    receiver: broadcast::Receiver<SyncEvent>,
303}
304
305impl EventStream {
306    /// Waits for the next advisory event. Lagged messages are skipped because durable state is
307    /// available from [`AequoraClient::status`] and grouped handles.
308    #[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/// Bounded high-level client policy.
321#[derive(Clone, Copy, Debug)]
322pub struct ClientSdkConfig {
323    /// Advisory event queue capacity per client runtime.
324    pub event_capacity: usize,
325    /// Maximum conflicts returned by one list call.
326    pub conflict_page_size: usize,
327    /// Maximum time an authoritative wait helper may poll.
328    pub confirmation_timeout: Duration,
329    /// Delay between durable operation-state polls.
330    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/// Runtime-validated builder for the stable high-level client.
360#[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    /// Installs the cancellation-safe local adapter.
373    #[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    /// Installs a pre-shared local adapter handle.
380    #[must_use]
381    pub fn shared_store(mut self, store: Arc<dyn ClientStore>) -> Self {
382        self.store = Some(store);
383        self
384    }
385
386    /// Installs the bounded synchronization transport.
387    #[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    /// Installs a pre-shared transport handle.
394    #[must_use]
395    pub fn shared_transport(mut self, transport: Arc<dyn SyncTransport>) -> Self {
396        self.transport = Some(transport);
397        self
398    }
399
400    /// Installs a credential provider. Raw HTTP authorization headers are never exposed.
401    #[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    /// Installs a pre-shared credential provider.
408    #[must_use]
409    pub fn shared_credentials(mut self, provider: Arc<dyn CredentialProvider>) -> Self {
410        self.credentials = Some(provider);
411        self
412    }
413
414    /// Sets explicit tenant and device identity.
415    #[must_use]
416    pub const fn identity(mut self, identity: ClientIdentity) -> Self {
417        self.identity = Some(identity);
418        self
419    }
420
421    /// Sets the application registry/domain identity.
422    #[must_use]
423    pub fn domain(mut self, domain: DomainId) -> Self {
424        self.domain = Some(domain);
425        self
426    }
427
428    /// Installs a non-blocking observability hook.
429    #[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    /// Applies bounded SDK policy.
436    #[must_use]
437    pub const fn config(mut self, config: ClientSdkConfig) -> Self {
438        self.config = config;
439        self
440    }
441
442    /// Validates required semantic fields and creates one shared runtime.
443    ///
444    /// # Errors
445    ///
446    /// Returns a stable validation error naming the first missing or invalid field.
447    #[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/// Cheaply clonable reference to one client runtime.
508#[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    /// Starts a runtime-validated public SDK builder.
525    #[must_use]
526    pub fn builder() -> AequoraClientBuilder {
527        AequoraClientBuilder::default()
528    }
529
530    /// Durably commits application intent locally. The receipt never claims server acceptance.
531    ///
532    /// # Errors
533    ///
534    /// Returns a stable encoding, storage, resource, or lifecycle error.
535    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    /// Runs and awaits one bounded single-flight synchronization attempt.
562    ///
563    /// # Errors
564    ///
565    /// Returns a stable lifecycle, credential, transport, storage, or resource error.
566    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    /// Records a bounded scheduler hint without running work inline.
622    #[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    /// Queries current state from durable storage; event delivery is not required.
635    ///
636    /// # Errors
637    ///
638    /// Returns a stable storage or lifecycle error.
639    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    /// Subscribes to bounded best-effort UI events.
656    #[must_use]
657    pub fn events(&self) -> EventStream {
658        EventStream {
659            receiver: self.inner.events.subscribe(),
660        }
661    }
662
663    /// Groups operation inspection and confirmation helpers.
664    #[must_use]
665    pub fn operations(&self) -> OperationHandle {
666        OperationHandle {
667            inner: Arc::clone(&self.inner),
668        }
669    }
670
671    /// Groups semantic conflict APIs.
672    #[must_use]
673    pub fn conflicts(&self) -> ConflictHandle {
674        ConflictHandle {
675            inner: Arc::clone(&self.inner),
676        }
677    }
678
679    /// Groups partial-synchronization scope APIs.
680    #[must_use]
681    pub fn scopes(&self) -> ScopeHandle {
682        ScopeHandle {
683            inner: Arc::clone(&self.inner),
684        }
685    }
686
687    /// Groups optional high-level blob APIs.
688    #[must_use]
689    pub fn blobs(&self) -> BlobHandle {
690        BlobHandle {
691            inner: Arc::clone(&self.inner),
692        }
693    }
694
695    /// Groups bounded, redacted diagnostics APIs.
696    #[must_use]
697    pub fn diagnostics(&self) -> DiagnosticsHandle {
698        DiagnosticsHandle {
699            inner: Arc::clone(&self.inner),
700        }
701    }
702
703    /// Requests graceful shutdown of this shared runtime.
704    ///
705    /// # Errors
706    ///
707    /// Currently infallible; the `Result` permits future bounded shutdown providers without a
708    /// breaking signature change.
709    #[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/// Operation inspection namespace.
746#[derive(Clone)]
747pub struct OperationHandle {
748    inner: Arc<ClientInner>,
749}
750
751impl OperationHandle {
752    /// Queries one durable operation.
753    ///
754    /// # Errors
755    ///
756    /// Returns a stable storage or lifecycle error.
757    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/// One operation plus bounded authoritative-confirmation helper.
777#[derive(Clone)]
778pub struct OperationRef {
779    inner: Arc<ClientInner>,
780    snapshot: OperationSnapshot,
781}
782
783impl OperationRef {
784    /// Latest durable snapshot observed when this value was created.
785    #[must_use]
786    pub const fn snapshot(&self) -> OperationSnapshot {
787        self.snapshot
788    }
789
790    /// Waits until the operation reaches an authoritative terminal state or policy expires.
791    ///
792    /// # Errors
793    ///
794    /// Returns a stable storage, lifecycle, or timeout error.
795    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/// Semantic conflict namespace.
831#[derive(Clone)]
832pub struct ConflictHandle {
833    inner: Arc<ClientInner>,
834}
835
836impl ConflictHandle {
837    /// Lists a bounded page of unresolved conflicts.
838    ///
839    /// # Errors
840    ///
841    /// Returns a stable storage or lifecycle error.
842    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    /// Loads one unresolved conflict.
852    ///
853    /// # Errors
854    ///
855    /// Returns a stable storage or lifecycle error.
856    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    /// Persists semantic resolution intent without editing internal conflict or ledger rows.
866    ///
867    /// # Errors
868    ///
869    /// Returns a stable storage, validation, resource, or lifecycle error.
870    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/// Public result of a scope subscription request.
885#[derive(Clone, Copy, Debug, Eq, PartialEq)]
886#[non_exhaustive]
887pub enum ScopeSubscriptionState {
888    /// Durable request accepted and awaiting scheduler work.
889    Requested,
890    /// Snapshot/bootstrap work is active.
891    Bootstrapping,
892    /// Scope is active.
893    Active,
894}
895
896/// Partial-synchronization scope namespace.
897#[derive(Clone)]
898pub struct ScopeHandle {
899    inner: Arc<ClientInner>,
900}
901
902impl ScopeHandle {
903    /// Persists a semantic subscription request.
904    ///
905    /// # Errors
906    ///
907    /// Returns a stable storage, authorization, resource, or lifecycle error.
908    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    /// Persists semantic unsubscription without asserting domain deletion.
922    ///
923    /// # Errors
924    ///
925    /// Returns a stable storage, authorization, resource, or lifecycle error.
926    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/// Optional blob namespace. Raw storage handles are never exposed.
937#[derive(Clone)]
938pub struct BlobHandle {
939    inner: Arc<ClientInner>,
940}
941
942impl BlobHandle {
943    /// Imports a path through the configured blob capability.
944    ///
945    /// # Errors
946    ///
947    /// Returns [`AequoraErrorCode::UnsupportedCapability`] until a blob provider is installed.
948    #[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/// Bounded diagnostics namespace.
960#[derive(Clone)]
961pub struct DiagnosticsHandle {
962    inner: Arc<ClientInner>,
963}
964
965impl DiagnosticsHandle {
966    /// Returns a redacted bounded summary.
967    ///
968    /// # Errors
969    ///
970    /// Returns a stable storage or lifecycle error.
971    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}