1use chrono::Local;
2
3#[derive(Clone)]
5pub struct AppState {
6 pub start_time: chrono::DateTime<Local>,
7 #[cfg(feature = "database")]
8 pub database: Option<crate::database::DatabasePool>,
9 #[cfg(feature = "redis")]
10 pub redis: Option<redis::aio::ConnectionManager>,
11 #[cfg(feature = "producer")]
12 pub message_producer: Option<crate::messaging::MessageProducerType>,
13 #[cfg(feature = "consumer")]
14 pub message_consumer: Option<crate::messaging::MessageConsumerType>,
15}
16
17impl AppState {
18 pub fn new() -> Self {
19 Self {
20 start_time: Local::now(),
21 #[cfg(feature = "database")]
22 database: None,
23 #[cfg(feature = "redis")]
24 redis: None,
25 #[cfg(feature = "producer")]
26 message_producer: None,
27 #[cfg(feature = "consumer")]
28 message_consumer: None,
29 }
30 }
31
32 #[cfg(feature = "database")]
34 pub fn with_database(mut self, pool: crate::database::DatabasePool) -> Self {
35 self.database = Some(pool);
36 self
37 }
38
39 #[cfg(feature = "redis")]
41 pub fn with_redis(mut self, conn: redis::aio::ConnectionManager) -> Self {
42 self.redis = Some(conn);
43 self
44 }
45
46 #[cfg(feature = "producer")]
48 pub fn with_message_producer(
49 mut self,
50 message_producer: crate::messaging::MessageProducerType,
51 ) -> Self {
52 self.message_producer = Some(message_producer);
53 self
54 }
55
56 #[cfg(feature = "consumer")]
58 pub fn with_message_consumer(
59 mut self,
60 message_consumer: crate::messaging::MessageConsumerType,
61 ) -> Self {
62 self.message_consumer = Some(message_consumer);
63 self
64 }
65
66 #[cfg(feature = "database")]
68 pub fn database(&self) -> Result<&crate::database::DatabasePool, crate::error::AppError> {
69 self.database
70 .as_ref()
71 .ok_or(crate::error::AppError::DatabaseNotInitialized)
72 }
73
74 #[cfg(feature = "redis")]
76 pub fn redis(&self) -> Result<redis::aio::ConnectionManager, crate::error::AppError> {
77 self.redis
78 .clone()
79 .ok_or(crate::error::AppError::RedisNotInitialized)
80 }
81
82 #[cfg(feature = "producer")]
84 pub fn message_producer(
85 &self,
86 ) -> Result<&crate::messaging::MessageProducerType, crate::error::AppError> {
87 self.message_producer.as_ref().ok_or_else(|| {
88 crate::error::AppError::Internal(anyhow::anyhow!("Kafka 消息生产者未初始化"))
89 })
90 }
91
92 #[cfg(feature = "consumer")]
94 pub fn message_consumer(
95 &self,
96 ) -> Result<&crate::messaging::MessageConsumerType, crate::error::AppError> {
97 self.message_consumer.as_ref().ok_or_else(|| {
98 crate::error::AppError::Internal(anyhow::anyhow!("Kafka 消息消费者未初始化"))
99 })
100 }
101}
102
103impl Default for AppState {
104 fn default() -> Self {
105 Self::new()
106 }
107}