elif_core/foundation/
traits.rs

1use std::any::TypeId;
2use std::fmt;
3
4/// Core trait for framework components that can be registered and managed
5pub trait FrameworkComponent: Send + Sync + 'static {
6    /// Get the type name of this component
7    fn type_name(&self) -> &'static str {
8        std::any::type_name::<Self>()
9    }
10
11    /// Get the TypeId of this component
12    fn type_id(&self) -> TypeId {
13        TypeId::of::<Self>()
14    }
15}
16
17/// Trait for components that require initialization
18#[allow(async_fn_in_trait)]
19pub trait Initializable {
20    type Config;
21    type Error: std::error::Error + Send + Sync + 'static;
22
23    /// Initialize the component with given configuration
24    async fn initialize(&mut self, config: Self::Config) -> Result<(), Self::Error>;
25
26    /// Check if the component is initialized
27    fn is_initialized(&self) -> bool;
28}
29
30/// Trait for components that need cleanup
31#[allow(async_fn_in_trait)]
32pub trait Finalizable {
33    type Error: std::error::Error + Send + Sync + 'static;
34
35    /// Perform cleanup operations
36    async fn finalize(&mut self) -> Result<(), Self::Error>;
37}
38
39/// Trait for components that can be validated
40pub trait Validatable {
41    type Error: std::error::Error + Send + Sync + 'static;
42
43    /// Validate the component's current state
44    fn validate(&self) -> Result<(), Self::Error>;
45}
46
47/// Trait for components that can be cloned safely
48pub trait CloneableComponent: FrameworkComponent + Clone {}
49
50impl<T> CloneableComponent for T where T: FrameworkComponent + Clone {}
51
52/// Service trait for dependency injection
53pub trait Service: FrameworkComponent {
54    /// Service identifier - usually the type name
55    fn service_id(&self) -> String {
56        self.type_name().to_string()
57    }
58}
59
60/// Factory trait for creating services
61#[allow(async_fn_in_trait)]
62pub trait ServiceFactory: Send + Sync + 'static {
63    type Service: Service;
64    type Config;
65    type Error: std::error::Error + Send + Sync + 'static;
66
67    /// Create a new service instance
68    async fn create_service(&self, config: Self::Config) -> Result<Self::Service, Self::Error>;
69}
70
71/// Marker trait for singleton services
72pub trait Singleton: Service {}
73
74/// Marker trait for transient services
75pub trait Transient: Service {}
76
77impl fmt::Debug for dyn FrameworkComponent {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        f.debug_struct("FrameworkComponent")
80            .field("type_name", &self.type_name())
81            .field("type_id", &self.type_id())
82            .finish()
83    }
84}
85
86impl fmt::Debug for dyn Service {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        f.debug_struct("Service")
89            .field("service_id", &self.service_id())
90            .field("type_name", &self.type_name())
91            .finish()
92    }
93}