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