mecha10-core 0.8.2

Mecha10 core runtime and foundational types
Documentation
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! Service Manager for Lifecycle Management
//!
//! This module provides centralized management of Service lifecycles, including
//! registration, startup, shutdown, and health monitoring.
//!
//! # Architecture
//!
//! ```text
//! ┌────────────────────────────────────────────────────────────┐
//! │                    ServiceManager                           │
//! ├────────────────────────────────────────────────────────────┤
//! │                                                            │
//! │  1. Register services (init phase)                         │
//! │     ├─ HTTP API Service                                    │
//! │     ├─ Database Service                                    │
//! │     └─ Job Processor Service                               │
//! │                                                            │
//! │  2. Start all services (in registration order)             │
//! │     └─ Spawn background tasks                              │
//! │                                                            │
//! │  3. Monitor health                                         │
//! │     └─ Periodic health checks                              │
//! │                                                            │
//! │  4. Stop all services (reverse order)                      │
//! │     └─ Graceful shutdown                                   │
//! │                                                            │
//! └────────────────────────────────────────────────────────────┘
//! ```
//!
//! # Example
//!
//! ```rust
//! use mecha10_core::prelude::*;
//! use mecha10_core::service::Service;
//! use mecha10_core::service_manager::ServiceManager;
//!
//! # async fn example() -> Result<()> {
//! // Create service manager
//! let mut service_manager = ServiceManager::new();
//!
//! # let http_config = HttpConfig;
//! # let db_config = DbConfig;
//! // Register services
//! service_manager.register::<HttpApiService>(http_config).await?;
//! service_manager.register::<DatabaseService>(db_config).await?;
//!
//! // Start all services
//! service_manager.start_all().await?;
//!
//! // ... application runs ...
//!
//! // Wait for shutdown signal
//! tokio::signal::ctrl_c().await?;
//!
//! // Stop all services (in reverse order)
//! service_manager.stop_all().await?;
//! # Ok(())
//! # }
//! # #[derive(Debug)] struct HttpApiService;
//! # #[derive(Debug)] struct DatabaseService;
//! # #[derive(Debug, serde::Deserialize)] struct HttpConfig;
//! # #[derive(Debug, serde::Deserialize)] struct DbConfig;
//! # #[async_trait::async_trait]
//! # impl Service for HttpApiService {
//! #     type Config = HttpConfig;
//! #     async fn init(_: Self::Config) -> Result<Self> { Ok(Self) }
//! #     async fn start(&mut self) -> Result<()> { Ok(()) }
//! #     async fn stop(&mut self) -> Result<()> { Ok(()) }
//! #     fn name(&self) -> &str { "http" }
//! # }
//! # #[async_trait::async_trait]
//! # impl Service for DatabaseService {
//! #     type Config = DbConfig;
//! #     async fn init(_: Self::Config) -> Result<Self> { Ok(Self) }
//! #     async fn start(&mut self) -> Result<()> { Ok(()) }
//! #     async fn stop(&mut self) -> Result<()> { Ok(()) }
//! #     fn name(&self) -> &str { "db" }
//! # }
//! ```

use crate::service::Service;
use crate::{HealthStatus, Result};
use async_trait::async_trait;
use tokio::sync::broadcast;
use tracing::{debug, error, info};

#[async_trait]
trait ServiceWrapper: Send + Sync {
    async fn start(&mut self) -> Result<()>;
    async fn stop(&mut self) -> Result<()>;
    async fn health_check(&self) -> HealthStatus;
    fn name(&self) -> &str;
}

struct ServiceBox<S: Service> {
    service: S,
}

#[async_trait]
impl<S: Service> ServiceWrapper for ServiceBox<S> {
    async fn start(&mut self) -> Result<()> {
        self.service.start().await
    }

    async fn stop(&mut self) -> Result<()> {
        self.service.stop().await
    }

    async fn health_check(&self) -> HealthStatus {
        self.service.health_check().await
    }

    fn name(&self) -> &str {
        self.service.name()
    }
}

pub struct ServiceManager {
    services: Vec<Box<dyn ServiceWrapper>>,

    shutdown_tx: broadcast::Sender<()>,
}

impl ServiceManager {
    /// Create a new ServiceManager.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use mecha10_core::service_manager::ServiceManager;
    /// let manager = ServiceManager::new();
    /// ```
    pub fn new() -> Self {
        let (shutdown_tx, _) = broadcast::channel(1);
        Self {
            services: Vec::new(),
            shutdown_tx,
        }
    }

    /// Register a service with configuration.
    ///
    /// Calls `Service::init()` to initialize the service, then stores it
    /// for later startup. Services are started in the order they are registered.
    ///
    /// # Arguments
    ///
    /// * `config` - Service-specific configuration
    ///
    /// # Returns
    ///
    /// * `Ok(())` - Service registered successfully
    /// * `Err(_)` - Service initialization failed
    ///
    /// # Example
    ///
    /// ```rust
    /// # use mecha10_core::prelude::*;
    /// # use mecha10_core::service::Service;
    /// # use mecha10_core::service_manager::ServiceManager;
    /// # async fn example() -> Result<()> {
    /// let mut manager = ServiceManager::new();
    ///
    /// // Register HTTP API
    /// manager.register::<HttpApiService>(HttpApiConfig {
    ///     host: "0.0.0.0".to_string(),
    ///     port: 8080,
    /// }).await?;
    ///
    /// // Register database
    /// manager.register::<DatabaseService>(DatabaseConfig {
    ///     url: "postgresql://localhost/mecha10".to_string(),
    ///     max_connections: 20,
    /// }).await?;
    /// # Ok(())
    /// # }
    /// # #[derive(Debug)] struct HttpApiService;
    /// # #[derive(Debug)] struct DatabaseService;
    /// # #[derive(Debug, serde::Deserialize)] struct HttpApiConfig { host: String, port: u16 }
    /// # #[derive(Debug, serde::Deserialize)] struct DatabaseConfig { url: String, max_connections: u32 }
    /// # #[async_trait::async_trait]
    /// # impl Service for HttpApiService {
    /// #     type Config = HttpApiConfig;
    /// #     async fn init(_: Self::Config) -> Result<Self> { Ok(Self) }
    /// #     async fn start(&mut self) -> Result<()> { Ok(()) }
    /// #     async fn stop(&mut self) -> Result<()> { Ok(()) }
    /// #     fn name(&self) -> &str { "http_api" }
    /// # }
    /// # #[async_trait::async_trait]
    /// # impl Service for DatabaseService {
    /// #     type Config = DatabaseConfig;
    /// #     async fn init(_: Self::Config) -> Result<Self> { Ok(Self) }
    /// #     async fn start(&mut self) -> Result<()> { Ok(()) }
    /// #     async fn stop(&mut self) -> Result<()> { Ok(()) }
    /// #     fn name(&self) -> &str { "database" }
    /// # }
    /// ```
    pub async fn register<S>(&mut self, config: S::Config) -> Result<()>
    where
        S: Service + 'static,
    {
        debug!("Registering service: {}", std::any::type_name::<S>());

        let service = S::init(config).await?;
        let name = service.name().to_string();

        let boxed = Box::new(ServiceBox { service });

        self.services.push(boxed);

        info!("Registered service: {}", name);
        Ok(())
    }

    /// Start all registered services.
    ///
    /// Services are started in the order they were registered. If any service
    /// fails to start, the error is returned and remaining services are not started.
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All services started successfully
    /// * `Err(_)` - A service failed to start
    ///
    /// # Example
    ///
    /// ```rust
    /// # use mecha10_core::prelude::*;
    /// # use mecha10_core::service_manager::ServiceManager;
    /// # async fn example() -> Result<()> {
    /// let mut manager = ServiceManager::new();
    /// // ... register services ...
    ///
    /// // Start all services
    /// manager.start_all().await?;
    ///
    /// info!("All services started successfully");
    /// # Ok(())
    /// # }
    /// ```
    pub async fn start_all(&mut self) -> Result<()> {
        info!("Starting {} services", self.services.len());

        for service in &mut self.services {
            let name = service.name().to_string();
            debug!("Starting service: {}", name);

            if let Err(e) = service.start().await {
                error!("Failed to start service '{}': {}", name, e);
                return Err(e);
            }

            info!("Started service: {}", name);
        }

        info!("All services started successfully");
        Ok(())
    }

    /// Stop all services gracefully.
    ///
    /// Services are stopped in **reverse order** of registration. This ensures
    /// that dependent services are stopped first (e.g., stop API server before database).
    ///
    /// Each service's `stop()` method is called, even if previous services failed
    /// to stop. All errors are logged, and the first error encountered is returned.
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All services stopped successfully
    /// * `Err(_)` - At least one service failed to stop
    ///
    /// # Example
    ///
    /// ```rust
    /// # use mecha10_core::prelude::*;
    /// # use mecha10_core::service_manager::ServiceManager;
    /// # async fn example() -> Result<()> {
    /// # let mut manager = ServiceManager::new();
    /// // ... services running ...
    ///
    /// // Graceful shutdown
    /// tokio::signal::ctrl_c().await?;
    /// manager.stop_all().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn stop_all(&mut self) -> Result<()> {
        info!("Stopping {} services (in reverse order)", self.services.len());

        let mut first_error = None;

        for service in self.services.iter_mut().rev() {
            let name = service.name().to_string();
            debug!("Stopping service: {}", name);

            match service.stop().await {
                Ok(()) => {
                    info!("Stopped service: {}", name);
                }
                Err(e) => {
                    error!("Failed to stop service '{}': {}", name, e);
                    if first_error.is_none() {
                        first_error = Some(e);
                    }
                }
            }
        }

        if let Some(err) = first_error {
            error!("Service manager stopped with errors");
            Err(err)
        } else {
            info!("All services stopped successfully");
            Ok(())
        }
    }

    /// Check health of all services.
    ///
    /// Calls `health_check()` on each registered service and returns a vector
    /// of (name, status) tuples.
    ///
    /// # Returns
    ///
    /// * `Vec<(String, HealthStatus)>` - Health status for each service
    ///
    /// # Example
    ///
    /// ```rust
    /// # use mecha10_core::prelude::*;
    /// # use mecha10_core::service_manager::ServiceManager;
    /// # async fn example() -> Result<()> {
    /// # let manager = ServiceManager::new();
    /// let health = manager.health_check_all().await;
    ///
    /// for (name, status) in health {
    ///     if !status.healthy {
    ///         warn!("Service '{}' is unhealthy: {:?}", name, status.message);
    ///     } else {
    ///         info!("Service '{}' is healthy", name);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn health_check_all(&self) -> Vec<(String, HealthStatus)> {
        let mut results = Vec::new();

        for service in &self.services {
            let name = service.name().to_string();
            let status = service.health_check().await;

            debug!("Health check for '{}': healthy={}", name, status.healthy);
            results.push((name, status));
        }

        results
    }

    /// Get a broadcast receiver for shutdown signals.
    ///
    /// Services can use this to listen for shutdown signals and stop gracefully.
    ///
    /// # Returns
    ///
    /// * `broadcast::Receiver<()>` - Shutdown signal receiver
    ///
    /// # Example
    ///
    /// ```rust
    /// # use mecha10_core::service_manager::ServiceManager;
    /// # async fn example() {
    /// let manager = ServiceManager::new();
    /// let mut shutdown_rx = manager.shutdown_signal();
    ///
    /// tokio::spawn(async move {
    ///     shutdown_rx.recv().await.ok();
    ///     // Service cleanup...
    /// });
    /// # }
    /// ```
    pub fn shutdown_signal(&self) -> broadcast::Receiver<()> {
        self.shutdown_tx.subscribe()
    }

    /// Trigger shutdown by broadcasting to all listeners.
    ///
    /// This sends a signal to all `shutdown_signal()` receivers. Services
    /// should listen to this signal to stop gracefully.
    ///
    /// Note: This does NOT call `stop_all()`. You must call `stop_all()`
    /// separately to actually stop services.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use mecha10_core::service_manager::ServiceManager;
    /// # async fn example() {
    /// let mut manager = ServiceManager::new();
    ///
    /// // Trigger shutdown signal
    /// manager.shutdown();
    ///
    /// // Then stop all services
    /// manager.stop_all().await.ok();
    /// # }
    /// ```
    pub fn shutdown(&self) {
        info!("Broadcasting shutdown signal");
        let _ = self.shutdown_tx.send(());
    }

    /// Get the number of registered services.
    ///
    /// # Returns
    ///
    /// * `usize` - Number of services
    ///
    /// # Example
    ///
    /// ```rust
    /// # use mecha10_core::service_manager::ServiceManager;
    /// # let manager = ServiceManager::new();
    /// println!("Services registered: {}", manager.service_count());
    /// ```
    pub fn service_count(&self) -> usize {
        self.services.len()
    }

    /// Get names of all registered services.
    ///
    /// # Returns
    ///
    /// * `Vec<String>` - Service names
    ///
    /// # Example
    ///
    /// ```rust
    /// # use mecha10_core::service_manager::ServiceManager;
    /// # let manager = ServiceManager::new();
    /// let names = manager.service_names();
    /// println!("Services: {}", names.join(", "));
    /// ```
    pub fn service_names(&self) -> Vec<String> {
        self.services.iter().map(|s| s.name().to_string()).collect()
    }
}

impl Default for ServiceManager {
    fn default() -> Self {
        Self::new()
    }
}