armature-core 0.2.3

High-performance async HTTP framework core - routing, handlers, middleware
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Lifecycle hook system for Armature framework.
//!
//! Provides lifecycle hooks for modules, controllers, and services similar to NestJS.
//!
//! ## Available Hooks
//!
//! - `OnModuleInit` - Called after module initialization
//! - `OnModuleDestroy` - Called before module destruction
//! - `OnApplicationBootstrap` - Called after full application bootstrap
//! - `OnApplicationShutdown` - Called during graceful shutdown
//!
//! ## Examples
//!
//! ```
//! use armature_core::lifecycle::{OnModuleInit, OnModuleDestroy};
//! use async_trait::async_trait;
//!
//! struct MyService {
//!     name: String,
//! }
//!
//! #[async_trait]
//! impl OnModuleInit for MyService {
//!     async fn on_module_init(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//!         println!("Service {} initialized!", self.name);
//!         Ok(())
//!     }
//! }
//!
//! #[async_trait]
//! impl OnModuleDestroy for MyService {
//!     async fn on_module_destroy(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//!         println!("Service {} destroyed!", self.name);
//!         Ok(())
//!     }
//! }
//! ```

use async_trait::async_trait;
use std::any::TypeId;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

/// Error type for lifecycle operations
pub type LifecycleResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;

/// Hook called after module dependencies are resolved
///
/// ## Example
///
/// ```
/// use armature_core::lifecycle::{OnModuleInit, LifecycleResult};
/// use async_trait::async_trait;
///
/// struct MyService;
///
/// #[async_trait]
/// impl OnModuleInit for MyService {
///     async fn on_module_init(&self) -> LifecycleResult {
///         println!("Service initialized!");
///         Ok(())
///     }
/// }
/// ```
#[async_trait]
pub trait OnModuleInit: Send + Sync {
    /// Called once the module has been initialized
    async fn on_module_init(&self) -> LifecycleResult;
}

/// Hook called before module is destroyed
#[async_trait]
pub trait OnModuleDestroy: Send + Sync {
    /// Called before the module is destroyed
    async fn on_module_destroy(&self) -> LifecycleResult;
}

/// Hook called after all modules have been initialized
#[async_trait]
pub trait OnApplicationBootstrap: Send + Sync {
    /// Called once the application has fully started
    async fn on_application_bootstrap(&self) -> LifecycleResult;
}

/// Hook called during application shutdown
#[async_trait]
pub trait OnApplicationShutdown: Send + Sync {
    /// Called when the application is shutting down
    async fn on_application_shutdown(&self, signal: Option<String>) -> LifecycleResult;
}

/// Hook called before module initialization
#[async_trait]
pub trait BeforeApplicationShutdown: Send + Sync {
    /// Called before application shutdown hooks
    async fn before_application_shutdown(&self, signal: Option<String>) -> LifecycleResult;
}

/// Manages lifecycle hooks for all registered components
///
/// ## Example
///
/// ```
/// use armature_core::lifecycle::{LifecycleManager, OnModuleInit, LifecycleResult};
/// use async_trait::async_trait;
/// use std::sync::Arc;
///
/// struct TestService;
///
/// #[async_trait]
/// impl OnModuleInit for TestService {
///     async fn on_module_init(&self) -> LifecycleResult {
///         Ok(())
///     }
/// }
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let manager = LifecycleManager::new();
/// let service = Arc::new(TestService);
///
/// manager.register_on_init("TestService".to_string(), service).await;
/// manager.call_module_init_hooks().await.unwrap();
/// # });
/// ```
#[allow(clippy::type_complexity)]
pub struct LifecycleManager {
    init_hooks: Arc<RwLock<Vec<(String, Arc<dyn OnModuleInit>)>>>,
    destroy_hooks: Arc<RwLock<Vec<(String, Arc<dyn OnModuleDestroy>)>>>,
    bootstrap_hooks: Arc<RwLock<Vec<(String, Arc<dyn OnApplicationBootstrap>)>>>,
    shutdown_hooks: Arc<RwLock<Vec<(String, Arc<dyn OnApplicationShutdown>)>>>,
    before_shutdown_hooks: Arc<RwLock<Vec<(String, Arc<dyn BeforeApplicationShutdown>)>>>,
    hook_registry: Arc<RwLock<HashMap<TypeId, String>>>,
}

impl LifecycleManager {
    /// Create a new lifecycle manager
    ///
    /// ## Example
    ///
    /// ```
    /// use armature_core::lifecycle::LifecycleManager;
    ///
    /// let manager = LifecycleManager::new();
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let counts = manager.hook_counts().await;
    /// assert_eq!(counts.init, 0);
    /// # });
    /// ```
    pub fn new() -> Self {
        Self {
            init_hooks: Arc::new(RwLock::new(Vec::new())),
            destroy_hooks: Arc::new(RwLock::new(Vec::new())),
            bootstrap_hooks: Arc::new(RwLock::new(Vec::new())),
            shutdown_hooks: Arc::new(RwLock::new(Vec::new())),
            before_shutdown_hooks: Arc::new(RwLock::new(Vec::new())),
            hook_registry: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Register a type name for tracking purposes
    pub async fn register_type(&self, type_id: TypeId, name: String) {
        let mut registry = self.hook_registry.write().await;
        registry.insert(type_id, name);
    }

    /// Get the registered name for a type
    pub async fn get_type_name(&self, type_id: TypeId) -> Option<String> {
        let registry = self.hook_registry.read().await;
        registry.get(&type_id).cloned()
    }

    /// Register an OnModuleInit hook
    pub async fn register_on_init(&self, name: String, hook: Arc<dyn OnModuleInit>) {
        let mut hooks = self.init_hooks.write().await;
        hooks.push((name, hook));
    }

    /// Register an OnModuleDestroy hook
    pub async fn register_on_destroy(&self, name: String, hook: Arc<dyn OnModuleDestroy>) {
        let mut hooks = self.destroy_hooks.write().await;
        hooks.push((name, hook));
    }

    /// Register an OnApplicationBootstrap hook
    pub async fn register_on_bootstrap(&self, name: String, hook: Arc<dyn OnApplicationBootstrap>) {
        let mut hooks = self.bootstrap_hooks.write().await;
        hooks.push((name, hook));
    }

    /// Register an OnApplicationShutdown hook
    pub async fn register_on_shutdown(&self, name: String, hook: Arc<dyn OnApplicationShutdown>) {
        let mut hooks = self.shutdown_hooks.write().await;
        hooks.push((name, hook));
    }

    /// Register a BeforeApplicationShutdown hook
    pub async fn register_before_shutdown(
        &self,
        name: String,
        hook: Arc<dyn BeforeApplicationShutdown>,
    ) {
        let mut hooks = self.before_shutdown_hooks.write().await;
        hooks.push((name, hook));
    }

    /// Execute all OnModuleInit hooks
    pub async fn call_module_init_hooks(
        &self,
    ) -> Result<(), Vec<(String, Box<dyn std::error::Error + Send + Sync>)>> {
        println!("🔄 Calling module initialization hooks...");
        let hooks = self.init_hooks.read().await;
        let mut errors = Vec::new();

        for (name, hook) in hooks.iter() {
            match hook.on_module_init().await {
                Ok(_) => {
                    println!("{}: onModuleInit() completed", name);
                }
                Err(e) => {
                    eprintln!("{}: onModuleInit() failed: {}", name, e);
                    errors.push((name.clone(), e));
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Execute all OnModuleDestroy hooks
    pub async fn call_module_destroy_hooks(
        &self,
    ) -> Result<(), Vec<(String, Box<dyn std::error::Error + Send + Sync>)>> {
        println!("🔄 Calling module destruction hooks...");
        let hooks = self.destroy_hooks.read().await;
        let mut errors = Vec::new();

        // Call in reverse order (LIFO)
        for (name, hook) in hooks.iter().rev() {
            match hook.on_module_destroy().await {
                Ok(_) => {
                    println!("{}: onModuleDestroy() completed", name);
                }
                Err(e) => {
                    eprintln!("{}: onModuleDestroy() failed: {}", name, e);
                    errors.push((name.clone(), e));
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Execute all OnApplicationBootstrap hooks
    pub async fn call_bootstrap_hooks(
        &self,
    ) -> Result<(), Vec<(String, Box<dyn std::error::Error + Send + Sync>)>> {
        println!("🚀 Calling application bootstrap hooks...");
        let hooks = self.bootstrap_hooks.read().await;
        let mut errors = Vec::new();

        for (name, hook) in hooks.iter() {
            match hook.on_application_bootstrap().await {
                Ok(_) => {
                    println!("{}: onApplicationBootstrap() completed", name);
                }
                Err(e) => {
                    eprintln!("{}: onApplicationBootstrap() failed: {}", name, e);
                    errors.push((name.clone(), e));
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Execute BeforeApplicationShutdown hooks
    pub async fn call_before_shutdown_hooks(
        &self,
        signal: Option<String>,
    ) -> Result<(), Vec<(String, Box<dyn std::error::Error + Send + Sync>)>> {
        println!("⚠️  Calling before shutdown hooks...");
        let hooks = self.before_shutdown_hooks.read().await;
        let mut errors = Vec::new();

        for (name, hook) in hooks.iter() {
            match hook.before_application_shutdown(signal.clone()).await {
                Ok(_) => {
                    println!("{}: beforeApplicationShutdown() completed", name);
                }
                Err(e) => {
                    eprintln!("{}: beforeApplicationShutdown() failed: {}", name, e);
                    errors.push((name.clone(), e));
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Execute all OnApplicationShutdown hooks
    ///
    /// ## Example
    ///
    /// ```
    /// use armature_core::lifecycle::{LifecycleManager, OnApplicationShutdown, LifecycleResult};
    /// use async_trait::async_trait;
    /// use std::sync::Arc;
    ///
    /// struct ShutdownService;
    ///
    /// #[async_trait]
    /// impl OnApplicationShutdown for ShutdownService {
    ///     async fn on_application_shutdown(&self, signal: Option<String>) -> LifecycleResult {
    ///         println!("Shutting down with signal: {:?}", signal);
    ///         Ok(())
    ///     }
    /// }
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let manager = LifecycleManager::new();
    /// let service = Arc::new(ShutdownService);
    ///
    /// manager.register_on_shutdown("ShutdownService".to_string(), service).await;
    /// manager.call_shutdown_hooks(Some("SIGTERM".to_string())).await.unwrap();
    /// # });
    /// ```
    pub async fn call_shutdown_hooks(
        &self,
        signal: Option<String>,
    ) -> Result<(), Vec<(String, Box<dyn std::error::Error + Send + Sync>)>> {
        println!("🛑 Calling application shutdown hooks...");
        let hooks = self.shutdown_hooks.read().await;
        let mut errors = Vec::new();

        // Call in reverse order (LIFO)
        for (name, hook) in hooks.iter().rev() {
            match hook.on_application_shutdown(signal.clone()).await {
                Ok(_) => {
                    println!("{}: onApplicationShutdown() completed", name);
                }
                Err(e) => {
                    eprintln!("{}: onApplicationShutdown() failed: {}", name, e);
                    errors.push((name.clone(), e));
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Get the number of registered hooks of each type
    pub async fn hook_counts(&self) -> LifecycleHookCounts {
        LifecycleHookCounts {
            init: self.init_hooks.read().await.len(),
            destroy: self.destroy_hooks.read().await.len(),
            bootstrap: self.bootstrap_hooks.read().await.len(),
            shutdown: self.shutdown_hooks.read().await.len(),
            before_shutdown: self.before_shutdown_hooks.read().await.len(),
        }
    }

    /// Clear all registered hooks
    pub async fn clear(&self) {
        self.init_hooks.write().await.clear();
        self.destroy_hooks.write().await.clear();
        self.bootstrap_hooks.write().await.clear();
        self.shutdown_hooks.write().await.clear();
        self.before_shutdown_hooks.write().await.clear();
        self.hook_registry.write().await.clear();
    }
}

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

/// Statistics about registered lifecycle hooks
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LifecycleHookCounts {
    pub init: usize,
    pub destroy: usize,
    pub bootstrap: usize,
    pub shutdown: usize,
    pub before_shutdown: usize,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[allow(dead_code)]
    struct TestService {
        name: String,
        init_called: Arc<RwLock<bool>>,
        destroy_called: Arc<RwLock<bool>>,
    }

    #[async_trait]
    impl OnModuleInit for TestService {
        async fn on_module_init(&self) -> LifecycleResult {
            *self.init_called.write().await = true;
            Ok(())
        }
    }

    #[async_trait]
    impl OnModuleDestroy for TestService {
        async fn on_module_destroy(&self) -> LifecycleResult {
            *self.destroy_called.write().await = true;
            Ok(())
        }
    }

    #[tokio::test]
    async fn test_lifecycle_manager_registration() {
        let manager = LifecycleManager::new();
        let init_called = Arc::new(RwLock::new(false));
        let destroy_called = Arc::new(RwLock::new(false));

        let service = Arc::new(TestService {
            name: "TestService".to_string(),
            init_called: init_called.clone(),
            destroy_called: destroy_called.clone(),
        });

        manager
            .register_on_init("TestService".to_string(), service.clone())
            .await;
        manager
            .register_on_destroy("TestService".to_string(), service.clone())
            .await;

        let counts = manager.hook_counts().await;
        assert_eq!(counts.init, 1);
        assert_eq!(counts.destroy, 1);
    }

    #[tokio::test]
    async fn test_lifecycle_hooks_execution() {
        let manager = LifecycleManager::new();
        let init_called = Arc::new(RwLock::new(false));
        let destroy_called = Arc::new(RwLock::new(false));

        let service = Arc::new(TestService {
            name: "TestService".to_string(),
            init_called: init_called.clone(),
            destroy_called: destroy_called.clone(),
        });

        manager
            .register_on_init("TestService".to_string(), service.clone())
            .await;
        manager
            .register_on_destroy("TestService".to_string(), service.clone())
            .await;

        // Execute init hooks
        manager.call_module_init_hooks().await.unwrap();
        assert!(*init_called.read().await);

        // Execute destroy hooks
        manager.call_module_destroy_hooks().await.unwrap();
        assert!(*destroy_called.read().await);
    }

    #[tokio::test]
    async fn test_lifecycle_hook_order() {
        let manager = LifecycleManager::new();
        let order = Arc::new(RwLock::new(Vec::new()));

        struct OrderService {
            id: usize,
            order: Arc<RwLock<Vec<usize>>>,
        }

        #[async_trait]
        impl OnModuleInit for OrderService {
            async fn on_module_init(&self) -> LifecycleResult {
                self.order.write().await.push(self.id);
                Ok(())
            }
        }

        for i in 1..=3 {
            let service = Arc::new(OrderService {
                id: i,
                order: order.clone(),
            });
            manager
                .register_on_init(format!("Service{}", i), service)
                .await;
        }

        manager.call_module_init_hooks().await.unwrap();

        let execution_order = order.read().await.clone();
        assert_eq!(execution_order, vec![1, 2, 3]);
    }
}