use aequora_adapter_sdk::{
AdapterError, Authenticator, AuthorityService, Credential, DomainContext, DomainHandler,
DomainOutcome,
};
use aequora_operation::{EncodedOperation, OperationKind};
use std::{
collections::{BTreeMap, btree_map::Entry},
fmt,
sync::Arc,
};
use thiserror::Error;
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[non_exhaustive]
pub enum DomainRegistrationError {
#[error("operation kind {kind} is registered more than once")]
DuplicateKind {
kind: OperationKind,
},
#[error("operation kind {kind} has no consistency profile")]
MissingProfile {
kind: OperationKind,
},
#[error("operation kind {kind} has reserved schema version zero")]
MissingSchema {
kind: OperationKind,
},
}
#[derive(Clone)]
pub struct DomainRegistry {
handlers: Arc<BTreeMap<OperationKind, Arc<dyn DomainHandler>>>,
}
impl fmt::Debug for DomainRegistry {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("DomainRegistry")
.field("operation_kinds", &self.handlers.keys().collect::<Vec<_>>())
.finish()
}
}
impl DomainRegistry {
#[must_use]
pub fn builder() -> DomainRegistryBuilder {
DomainRegistryBuilder::default()
}
fn handler(&self, kind: OperationKind) -> Option<&Arc<dyn DomainHandler>> {
self.handlers.get(&kind)
}
}
#[derive(Default)]
pub struct DomainRegistryBuilder {
handlers: BTreeMap<OperationKind, Arc<dyn DomainHandler>>,
error: Option<DomainRegistrationError>,
}
impl DomainRegistryBuilder {
#[must_use]
pub fn register(mut self, handler: impl DomainHandler + 'static) -> Self {
let kind = handler.operation_kind();
if self.error.is_some() {
return self;
}
if handler.profile().is_none() {
self.error = Some(DomainRegistrationError::MissingProfile { kind });
} else if handler.schema_version() == 0 {
self.error = Some(DomainRegistrationError::MissingSchema { kind });
} else {
match self.handlers.entry(kind) {
Entry::Vacant(entry) => {
entry.insert(Arc::new(handler));
}
Entry::Occupied(_) => {
self.error = Some(DomainRegistrationError::DuplicateKind { kind });
}
}
}
self
}
pub fn build(self) -> Result<DomainRegistry, DomainRegistrationError> {
if let Some(error) = self.error {
Err(error)
} else {
Ok(DomainRegistry {
handlers: Arc::new(self.handlers),
})
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ServerOperationOutcome {
Accepted(Vec<u8>),
BusinessRejected {
code: Arc<str>,
},
Conflict {
reason: Arc<str>,
},
}
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[non_exhaustive]
pub enum StableServerError {
#[error("required server field `{field}` is missing")]
MissingConfiguration {
field: &'static str,
},
#[error("operation kind {kind} is not registered")]
UnknownOperation {
kind: OperationKind,
},
#[error("operation kind {kind} schema {received} does not match registered schema {expected}")]
SchemaMismatch {
kind: OperationKind,
received: u16,
expected: u16,
},
#[error(transparent)]
Adapter(#[from] AdapterError),
#[error("domain handler returned an unsupported outcome variant")]
UnsupportedOutcome,
}
#[derive(Default)]
pub struct AequoraServerBuilder {
authority: Option<Arc<dyn AuthorityService>>,
registry: Option<DomainRegistry>,
authenticator: Option<Arc<dyn Authenticator>>,
}
impl AequoraServerBuilder {
#[must_use]
pub fn authority_store(mut self, authority: impl AuthorityService + 'static) -> Self {
self.authority = Some(Arc::new(authority));
self
}
#[must_use]
pub fn shared_authority_store(mut self, authority: Arc<dyn AuthorityService>) -> Self {
self.authority = Some(authority);
self
}
#[must_use]
pub fn registry(mut self, registry: DomainRegistry) -> Self {
self.registry = Some(registry);
self
}
#[must_use]
pub fn domain(self, registry: DomainRegistry) -> Self {
self.registry(registry)
}
#[must_use]
pub fn authenticator(mut self, authenticator: impl Authenticator + 'static) -> Self {
self.authenticator = Some(Arc::new(authenticator));
self
}
#[must_use]
pub fn shared_authenticator(mut self, authenticator: Arc<dyn Authenticator>) -> Self {
self.authenticator = Some(authenticator);
self
}
pub fn build(self) -> Result<AequoraServer, StableServerError> {
Ok(AequoraServer {
inner: Arc::new(ServerInner {
authority: self
.authority
.ok_or(StableServerError::MissingConfiguration {
field: "authority_store",
})?,
registry: self
.registry
.ok_or(StableServerError::MissingConfiguration { field: "registry" })?,
authenticator: self.authenticator.ok_or(
StableServerError::MissingConfiguration {
field: "authenticator",
},
)?,
}),
})
}
}
struct ServerInner {
authority: Arc<dyn AuthorityService>,
registry: DomainRegistry,
authenticator: Arc<dyn Authenticator>,
}
#[derive(Clone)]
pub struct AequoraServer {
inner: Arc<ServerInner>,
}
impl fmt::Debug for AequoraServer {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("AequoraServer")
.field("registry", &self.inner.registry)
.finish_non_exhaustive()
}
}
impl AequoraServer {
#[must_use]
pub fn builder() -> AequoraServerBuilder {
AequoraServerBuilder::default()
}
pub async fn execute(
&self,
credential: &Credential,
operation: EncodedOperation,
) -> Result<ServerOperationOutcome, StableServerError> {
let identity = self.inner.authenticator.authenticate(credential).await?;
let kind = operation.kind();
let handler = self
.inner
.registry
.handler(kind)
.ok_or(StableServerError::UnknownOperation { kind })?;
let expected = handler.schema_version();
let received = operation.schema_version().get();
if received != expected {
return Err(StableServerError::SchemaMismatch {
kind,
received,
expected,
});
}
let context = DomainContext {
identity,
operation_id: operation.operation_id(),
};
match handler.handle(context, operation.payload()).await? {
DomainOutcome::Accepted(outcome) => self
.inner
.authority
.commit(identity, operation, outcome)
.await
.map(ServerOperationOutcome::Accepted)
.map_err(StableServerError::from),
DomainOutcome::BusinessRejected { code } => {
Ok(ServerOperationOutcome::BusinessRejected { code })
}
DomainOutcome::Conflict { reason } => Ok(ServerOperationOutcome::Conflict { reason }),
_ => Err(StableServerError::UnsupportedOutcome),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use aequora_adapter_sdk::{AdapterErrorKind, ClientIdentity, DomainContext};
use aequora_operation::{Operation, OperationEncodingError, OperationSchemaVersion};
use aequora_types::{DeviceId, TenantId};
use async_trait::async_trait;
struct Handler;
#[async_trait]
impl DomainHandler for Handler {
fn operation_kind(&self) -> OperationKind {
OperationKind::new(77).unwrap_or_else(|error| panic!("kind is valid: {error}"))
}
fn schema_version(&self) -> u16 {
1
}
fn profile(&self) -> Option<&'static str> {
Some("strong-aggregate")
}
async fn handle(
&self,
_context: DomainContext,
payload: &[u8],
) -> Result<DomainOutcome, AdapterError> {
Ok(DomainOutcome::Accepted(payload.to_vec()))
}
}
struct Auth;
#[async_trait]
impl Authenticator for Auth {
async fn authenticate(
&self,
_credential: &Credential,
) -> Result<ClientIdentity, AdapterError> {
Ok(ClientIdentity {
tenant_id: TenantId::new(),
device_id: DeviceId::new(),
})
}
}
struct Authority;
#[async_trait]
impl AuthorityService for Authority {
async fn commit(
&self,
_identity: ClientIdentity,
_operation: EncodedOperation,
outcome: Vec<u8>,
) -> Result<Vec<u8>, AdapterError> {
Ok(outcome)
}
}
struct TestOperation;
impl Operation for TestOperation {
type Outcome = ();
const KIND: OperationKind = OperationKind::from_static(77);
const SCHEMA_VERSION: OperationSchemaVersion = OperationSchemaVersion::from_static(1);
fn encode(&self) -> Result<Vec<u8>, OperationEncodingError> {
Ok(vec![7])
}
}
#[test]
fn duplicate_registration_fails_before_runtime_traffic() {
let result = DomainRegistry::builder()
.register(Handler)
.register(Handler)
.build();
assert!(matches!(
result,
Err(DomainRegistrationError::DuplicateKind { .. })
));
}
#[tokio::test]
async fn server_dispatches_without_http_or_database_types() {
let registry = DomainRegistry::builder()
.register(Handler)
.build()
.unwrap_or_else(|error| panic!("registry should build: {error}"));
let server = AequoraServer::builder()
.authority_store(Authority)
.registry(registry)
.authenticator(Auth)
.build()
.unwrap_or_else(|error| panic!("server should build: {error}"));
let operation = EncodedOperation::from_operation(&TestOperation)
.unwrap_or_else(|error| panic!("operation should encode: {error}"));
assert_eq!(
server.execute(&Credential::new("test"), operation).await,
Ok(ServerOperationOutcome::Accepted(vec![7]))
);
}
#[test]
fn adapter_errors_remain_system_failures() {
let error = AdapterError::new(AdapterErrorKind::Internal, "redacted");
assert!(matches!(
StableServerError::from(error),
StableServerError::Adapter(_)
));
}
}