1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//! Domain Service Trait
//!
//! Base trait for all domain services in the Backbone Framework.
//! Domain services encapsulate business logic that doesn't naturally
//! belong to a single entity.
//!
//! # Example
//!
//! ```ignore
//! use backbone_core::DomainService;
//!
//! pub struct PaymentService {
//! // dependencies
//! }
//!
//! #[async_trait::async_trait]
//! impl DomainService for PaymentService {
//! fn service_id(&self) -> &'static str {
//! "payment.payment_service"
//! }
//!
//! async fn health_check(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//! // Check payment gateway connectivity
//! Ok(())
//! }
//! }
//! ```
use async_trait::async_trait;
/// Base trait for all domain services.
///
/// Domain services are stateless operations that coordinate between
/// multiple entities or handle complex business logic.
#[async_trait]
pub trait DomainService: Send + Sync {
/// Unique identifier for this service.
///
/// Format: `{module}.{service_name}`
/// Example: `"corpus.organization_service"`
fn service_id(&self) -> &'static str;
/// Perform a health check for this service.
///
/// Returns `Ok(())` if the service is healthy,
/// or an error describing the issue.
async fn health_check(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
Ok(())
}
/// Get the service name (derived from service_id).
fn service_name(&self) -> &'static str {
self.service_id()
.split('.')
.next_back()
.unwrap_or(self.service_id())
}
/// Get the module name (derived from service_id).
fn module_name(&self) -> &'static str {
self.service_id()
.split('.')
.next()
.unwrap_or("unknown")
}
}
/// Marker trait for domain services that support transactions.
#[async_trait]
pub trait TransactionalDomainService: DomainService {
/// Execute an operation within a transaction context.
async fn with_transaction<F, R, E>(&self, operation: F) -> Result<R, E>
where
F: FnOnce() -> Result<R, E> + Send,
R: Send,
E: Send;
}
#[cfg(test)]
mod tests {
use super::*;
struct TestService;
#[async_trait]
impl DomainService for TestService {
fn service_id(&self) -> &'static str {
"test.test_service"
}
}
#[test]
fn test_service_name_extraction() {
let service = TestService;
assert_eq!(service.service_name(), "test_service");
assert_eq!(service.module_name(), "test");
}
}