Skip to main content

aequora_server/
sdk.rs

1//! High-level server SDK independent from Axum and physical database types.
2
3use aequora_adapter_sdk::{
4    AdapterError, Authenticator, AuthorityService, Credential, DomainContext, DomainHandler,
5    DomainOutcome,
6};
7use aequora_operation::{EncodedOperation, OperationKind};
8use std::{
9    collections::{BTreeMap, btree_map::Entry},
10    fmt,
11    sync::Arc,
12};
13use thiserror::Error;
14
15/// Domain handler registration failure detected before traffic is served.
16#[derive(Clone, Debug, Error, Eq, PartialEq)]
17#[non_exhaustive]
18pub enum DomainRegistrationError {
19    /// More than one handler claimed an operation kind.
20    #[error("operation kind {kind} is registered more than once")]
21    DuplicateKind {
22        /// Duplicated stable kind.
23        kind: OperationKind,
24    },
25    /// Handler did not declare a certified consistency profile.
26    #[error("operation kind {kind} has no consistency profile")]
27    MissingProfile {
28        /// Operation kind missing its profile.
29        kind: OperationKind,
30    },
31    /// Handler declared schema version zero.
32    #[error("operation kind {kind} has reserved schema version zero")]
33    MissingSchema {
34        /// Operation kind missing a usable schema version.
35        kind: OperationKind,
36    },
37}
38
39/// Immutable, validated domain-handler registry.
40#[derive(Clone)]
41pub struct DomainRegistry {
42    handlers: Arc<BTreeMap<OperationKind, Arc<dyn DomainHandler>>>,
43}
44
45impl fmt::Debug for DomainRegistry {
46    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47        formatter
48            .debug_struct("DomainRegistry")
49            .field("operation_kinds", &self.handlers.keys().collect::<Vec<_>>())
50            .finish()
51    }
52}
53
54impl DomainRegistry {
55    /// Starts an empty registry builder.
56    #[must_use]
57    pub fn builder() -> DomainRegistryBuilder {
58        DomainRegistryBuilder::default()
59    }
60
61    fn handler(&self, kind: OperationKind) -> Option<&Arc<dyn DomainHandler>> {
62        self.handlers.get(&kind)
63    }
64}
65
66/// Validating domain registry builder.
67#[derive(Default)]
68pub struct DomainRegistryBuilder {
69    handlers: BTreeMap<OperationKind, Arc<dyn DomainHandler>>,
70    error: Option<DomainRegistrationError>,
71}
72
73impl DomainRegistryBuilder {
74    /// Registers one explicitly profiled domain handler.
75    #[must_use]
76    pub fn register(mut self, handler: impl DomainHandler + 'static) -> Self {
77        let kind = handler.operation_kind();
78        if self.error.is_some() {
79            return self;
80        }
81        if handler.profile().is_none() {
82            self.error = Some(DomainRegistrationError::MissingProfile { kind });
83        } else if handler.schema_version() == 0 {
84            self.error = Some(DomainRegistrationError::MissingSchema { kind });
85        } else {
86            match self.handlers.entry(kind) {
87                Entry::Vacant(entry) => {
88                    entry.insert(Arc::new(handler));
89                }
90                Entry::Occupied(_) => {
91                    self.error = Some(DomainRegistrationError::DuplicateKind { kind });
92                }
93            }
94        }
95        self
96    }
97
98    /// Freezes the registry after validating duplicate ownership, schema, and profile metadata.
99    ///
100    /// # Errors
101    ///
102    /// Returns the first deterministic registration error.
103    pub fn build(self) -> Result<DomainRegistry, DomainRegistrationError> {
104        if let Some(error) = self.error {
105            Err(error)
106        } else {
107            Ok(DomainRegistry {
108                handlers: Arc::new(self.handlers),
109            })
110        }
111    }
112}
113
114/// Stable server-side operation outcome. Business rejection is not a system failure.
115#[derive(Clone, Debug, Eq, PartialEq)]
116#[non_exhaustive]
117pub enum ServerOperationOutcome {
118    /// Authority committed the accepted handler result.
119    Accepted(Vec<u8>),
120    /// Domain business rules rejected the intent.
121    BusinessRejected {
122        /// Stable application-defined code.
123        code: Arc<str>,
124    },
125    /// Domain requested explicit conflict resolution.
126    Conflict {
127        /// Stable application-defined reason.
128        reason: Arc<str>,
129    },
130}
131
132/// Stable high-level server error.
133#[derive(Clone, Debug, Error, Eq, PartialEq)]
134#[non_exhaustive]
135pub enum StableServerError {
136    /// Required builder field is absent.
137    #[error("required server field `{field}` is missing")]
138    MissingConfiguration {
139        /// Missing semantic field.
140        field: &'static str,
141    },
142    /// Operation kind is not registered.
143    #[error("operation kind {kind} is not registered")]
144    UnknownOperation {
145        /// Unknown stable operation kind.
146        kind: OperationKind,
147    },
148    /// Operation schema is incompatible with its registered handler.
149    #[error("operation kind {kind} schema {received} does not match registered schema {expected}")]
150    SchemaMismatch {
151        /// Stable operation kind.
152        kind: OperationKind,
153        /// Received schema version.
154        received: u16,
155        /// Registered schema version.
156        expected: u16,
157    },
158    /// Authentication, handler, or authority adapter failed.
159    #[error(transparent)]
160    Adapter(#[from] AdapterError),
161    /// A newer handler outcome is not understood by this server release.
162    #[error("domain handler returned an unsupported outcome variant")]
163    UnsupportedOutcome,
164}
165
166/// Runtime-validated server builder.
167#[derive(Default)]
168pub struct AequoraServerBuilder {
169    authority: Option<Arc<dyn AuthorityService>>,
170    registry: Option<DomainRegistry>,
171    authenticator: Option<Arc<dyn Authenticator>>,
172}
173
174impl AequoraServerBuilder {
175    /// Installs the authoritative commit service.
176    #[must_use]
177    pub fn authority_store(mut self, authority: impl AuthorityService + 'static) -> Self {
178        self.authority = Some(Arc::new(authority));
179        self
180    }
181
182    /// Installs a pre-shared authoritative commit service.
183    #[must_use]
184    pub fn shared_authority_store(mut self, authority: Arc<dyn AuthorityService>) -> Self {
185        self.authority = Some(authority);
186        self
187    }
188
189    /// Installs the validated application domain registry.
190    #[must_use]
191    pub fn registry(mut self, registry: DomainRegistry) -> Self {
192        self.registry = Some(registry);
193        self
194    }
195
196    /// Alias matching domain-oriented examples.
197    #[must_use]
198    pub fn domain(self, registry: DomainRegistry) -> Self {
199        self.registry(registry)
200    }
201
202    /// Installs the authentication provider.
203    #[must_use]
204    pub fn authenticator(mut self, authenticator: impl Authenticator + 'static) -> Self {
205        self.authenticator = Some(Arc::new(authenticator));
206        self
207    }
208
209    /// Installs a pre-shared authentication provider.
210    #[must_use]
211    pub fn shared_authenticator(mut self, authenticator: Arc<dyn Authenticator>) -> Self {
212        self.authenticator = Some(authenticator);
213        self
214    }
215
216    /// Validates required fields before any request traffic is accepted.
217    ///
218    /// # Errors
219    ///
220    /// Returns a stable validation error naming the first missing field.
221    pub fn build(self) -> Result<AequoraServer, StableServerError> {
222        Ok(AequoraServer {
223            inner: Arc::new(ServerInner {
224                authority: self
225                    .authority
226                    .ok_or(StableServerError::MissingConfiguration {
227                        field: "authority_store",
228                    })?,
229                registry: self
230                    .registry
231                    .ok_or(StableServerError::MissingConfiguration { field: "registry" })?,
232                authenticator: self.authenticator.ok_or(
233                    StableServerError::MissingConfiguration {
234                        field: "authenticator",
235                    },
236                )?,
237            }),
238        })
239    }
240}
241
242struct ServerInner {
243    authority: Arc<dyn AuthorityService>,
244    registry: DomainRegistry,
245    authenticator: Arc<dyn Authenticator>,
246}
247
248/// Cheaply clonable high-level server core. Transport integration belongs in `aequora-axum` or
249/// another adapter crate.
250#[derive(Clone)]
251pub struct AequoraServer {
252    inner: Arc<ServerInner>,
253}
254
255impl fmt::Debug for AequoraServer {
256    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
257        formatter
258            .debug_struct("AequoraServer")
259            .field("registry", &self.inner.registry)
260            .finish_non_exhaustive()
261    }
262}
263
264impl AequoraServer {
265    /// Starts a runtime-validated high-level server builder.
266    #[must_use]
267    pub fn builder() -> AequoraServerBuilder {
268        AequoraServerBuilder::default()
269    }
270
271    /// Authenticates, dispatches, and authoritatively commits one semantic operation.
272    ///
273    /// # Errors
274    ///
275    /// Returns a stable authentication, registry, handler, schema, or authority failure.
276    pub async fn execute(
277        &self,
278        credential: &Credential,
279        operation: EncodedOperation,
280    ) -> Result<ServerOperationOutcome, StableServerError> {
281        let identity = self.inner.authenticator.authenticate(credential).await?;
282        let kind = operation.kind();
283        let handler = self
284            .inner
285            .registry
286            .handler(kind)
287            .ok_or(StableServerError::UnknownOperation { kind })?;
288        let expected = handler.schema_version();
289        let received = operation.schema_version().get();
290        if received != expected {
291            return Err(StableServerError::SchemaMismatch {
292                kind,
293                received,
294                expected,
295            });
296        }
297        let context = DomainContext {
298            identity,
299            operation_id: operation.operation_id(),
300        };
301        match handler.handle(context, operation.payload()).await? {
302            DomainOutcome::Accepted(outcome) => self
303                .inner
304                .authority
305                .commit(identity, operation, outcome)
306                .await
307                .map(ServerOperationOutcome::Accepted)
308                .map_err(StableServerError::from),
309            DomainOutcome::BusinessRejected { code } => {
310                Ok(ServerOperationOutcome::BusinessRejected { code })
311            }
312            DomainOutcome::Conflict { reason } => Ok(ServerOperationOutcome::Conflict { reason }),
313            _ => Err(StableServerError::UnsupportedOutcome),
314        }
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321    use aequora_adapter_sdk::{AdapterErrorKind, ClientIdentity, DomainContext};
322    use aequora_operation::{Operation, OperationEncodingError, OperationSchemaVersion};
323    use aequora_types::{DeviceId, TenantId};
324    use async_trait::async_trait;
325
326    struct Handler;
327
328    #[async_trait]
329    impl DomainHandler for Handler {
330        fn operation_kind(&self) -> OperationKind {
331            OperationKind::new(77).unwrap_or_else(|error| panic!("kind is valid: {error}"))
332        }
333
334        fn schema_version(&self) -> u16 {
335            1
336        }
337
338        fn profile(&self) -> Option<&'static str> {
339            Some("strong-aggregate")
340        }
341
342        async fn handle(
343            &self,
344            _context: DomainContext,
345            payload: &[u8],
346        ) -> Result<DomainOutcome, AdapterError> {
347            Ok(DomainOutcome::Accepted(payload.to_vec()))
348        }
349    }
350
351    struct Auth;
352
353    #[async_trait]
354    impl Authenticator for Auth {
355        async fn authenticate(
356            &self,
357            _credential: &Credential,
358        ) -> Result<ClientIdentity, AdapterError> {
359            Ok(ClientIdentity {
360                tenant_id: TenantId::new(),
361                device_id: DeviceId::new(),
362            })
363        }
364    }
365
366    struct Authority;
367
368    #[async_trait]
369    impl AuthorityService for Authority {
370        async fn commit(
371            &self,
372            _identity: ClientIdentity,
373            _operation: EncodedOperation,
374            outcome: Vec<u8>,
375        ) -> Result<Vec<u8>, AdapterError> {
376            Ok(outcome)
377        }
378    }
379
380    struct TestOperation;
381
382    impl Operation for TestOperation {
383        type Outcome = ();
384
385        const KIND: OperationKind = OperationKind::from_static(77);
386        const SCHEMA_VERSION: OperationSchemaVersion = OperationSchemaVersion::from_static(1);
387
388        fn encode(&self) -> Result<Vec<u8>, OperationEncodingError> {
389            Ok(vec![7])
390        }
391    }
392
393    #[test]
394    fn duplicate_registration_fails_before_runtime_traffic() {
395        let result = DomainRegistry::builder()
396            .register(Handler)
397            .register(Handler)
398            .build();
399        assert!(matches!(
400            result,
401            Err(DomainRegistrationError::DuplicateKind { .. })
402        ));
403    }
404
405    #[tokio::test]
406    async fn server_dispatches_without_http_or_database_types() {
407        let registry = DomainRegistry::builder()
408            .register(Handler)
409            .build()
410            .unwrap_or_else(|error| panic!("registry should build: {error}"));
411        let server = AequoraServer::builder()
412            .authority_store(Authority)
413            .registry(registry)
414            .authenticator(Auth)
415            .build()
416            .unwrap_or_else(|error| panic!("server should build: {error}"));
417        let operation = EncodedOperation::from_operation(&TestOperation)
418            .unwrap_or_else(|error| panic!("operation should encode: {error}"));
419        assert_eq!(
420            server.execute(&Credential::new("test"), operation).await,
421            Ok(ServerOperationOutcome::Accepted(vec![7]))
422        );
423    }
424
425    #[test]
426    fn adapter_errors_remain_system_failures() {
427        let error = AdapterError::new(AdapterErrorKind::Internal, "redacted");
428        assert!(matches!(
429            StableServerError::from(error),
430            StableServerError::Adapter(_)
431        ));
432    }
433}