sadi 1.1.0

Semi-Automatic Dependency Injector
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Application container for bootstrapping and managing the dependency injection system.
//!
//! This module provides the [`Application`] struct, which serves as the main entry point
//! for configuring and initializing a dependency injection container with a modular structure.
//!
//! # Overview
//!
//! The `Application` manages:
//! - Root module registration
//! - Bootstrap process for loading modules and their dependencies
//! - Access to the root injector
//! - Hierarchical module loading with proper isolation
//!
//! # Thread Safety
//!
//! When the `thread-safe` feature is enabled, the [`Application`] requires the root module
//! to implement `Send + Sync`, allowing the application to be safely shared across threads.
//!
//! # Examples
//!
//! ```
//! use sadi::application::Application;
//! use sadi::module::Module;
//! use sadi::injector::Injector;
//!
//! struct AppModule;
//!
//! impl Module for AppModule {
//!     fn providers(&self, injector: &Injector) {
//!         // Register providers
//!     }
//! }
//!
//! let mut app = Application::new(AppModule);
//! app.bootstrap();
//!
//! let injector = app.injector();
//! // Use injector to resolve dependencies
//! ```

use crate::injector::Injector;
use crate::module::Module;
use crate::runtime::Shared;

#[cfg(feature = "tracing")]
use tracing::{debug, info};

/// The main application container for dependency injection.
///
/// `Application` manages the lifecycle of modules and provides access to the root
/// dependency injector. It handles the bootstrap process, which recursively loads
/// all modules and their imports, creating a hierarchical injector structure.
///
/// # Thread Safety
///
/// With the `thread-safe` feature enabled, the application requires modules to implement
/// `Send + Sync` to ensure they can be safely shared across threads. Without this feature,
/// modules have no additional thread-safety requirements.
///
/// # Lifecycle
///
/// 1. **Creation**: Create an application with a root module using [`new()`](Application::new)
/// 2. **Bootstrap**: Call [`bootstrap()`](Application::bootstrap) to load all modules
/// 3. **Usage**: Access the injector via [`injector()`](Application::injector) to resolve dependencies
///
/// # Examples
///
/// ```
/// use sadi::application::Application;
/// use sadi::module::Module;
/// use sadi::injector::Injector;
///
/// struct MyAppModule;
///
/// impl Module for MyAppModule {
///     fn providers(&self, injector: &Injector) {
///         // Configure your providers
///     }
/// }
///
/// let mut app = Application::new(MyAppModule);
/// assert!(!app.is_bootstrapped());
///
/// app.bootstrap();
/// assert!(app.is_bootstrapped());
///
/// let injector = app.injector();
/// // Use injector to get services
/// ```
pub struct Application {
    #[cfg(not(feature = "thread-safe"))]
    root: Option<Box<dyn Module>>,
    #[cfg(feature = "thread-safe")]
    root: Option<Box<dyn Module + Send + Sync>>,
    injector: Shared<Injector>,
}

#[cfg(feature = "debug")]
impl std::fmt::Debug for Application {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Application")
            .field("injector", &"...")
            .field("root", &"<dyn Module>")
            .finish()
    }
}

impl Application {
    /// Creates a new application with the given root module.
    ///
    /// The application is created in an un-bootstrapped state. You must call
    /// [`bootstrap()`](Application::bootstrap) to load the module and its dependencies.
    ///
    /// # Parameters
    ///
    /// - `root`: The root module that defines the application's dependency graph
    ///
    /// # Returns
    ///
    /// A new `Application` instance ready to be bootstrapped.
    ///
    /// # Examples
    ///
    /// ```
    /// use sadi::application::Application;
    /// use sadi::module::Module;
    /// use sadi::injector::Injector;
    ///
    /// struct RootModule;
    ///
    /// impl Module for RootModule {
    ///     fn providers(&self, injector: &Injector) {}
    /// }
    ///
    /// let app = Application::new(RootModule);
    /// assert!(!app.is_bootstrapped());
    /// ```
    pub fn new(root: impl Module + 'static) -> Self {
        #[cfg(feature = "tracing")]
        info!("Creating new Application instance with root module");

        Self {
            root: Some(Box::new(root)),
            injector: Shared::new(Injector::root()),
        }
    }

    /// Bootstraps the application by loading the root module and all its imports.
    ///
    /// This method recursively processes the module hierarchy:
    /// 1. Creates child injectors for each module
    /// 2. Loads all imported modules first
    /// 3. Registers the module's own providers
    ///
    /// # Panics
    ///
    /// Panics if called more than once on the same application instance.
    ///
    /// # Examples
    ///
    /// ```
    /// use sadi::application::Application;
    /// use sadi::module::Module;
    /// use sadi::injector::Injector;
    ///
    /// struct AppModule;
    ///
    /// impl Module for AppModule {
    ///     fn providers(&self, injector: &Injector) {
    ///         // Register providers
    ///     }
    /// }
    ///
    /// let mut app = Application::new(AppModule);
    /// app.bootstrap();
    /// assert!(app.is_bootstrapped());
    /// ```
    ///
    /// # Panics Example
    ///
    /// ```should_panic
    /// use sadi::application::Application;
    /// use sadi::module::Module;
    /// use sadi::injector::Injector;
    ///
    /// struct AppModule;
    /// impl Module for AppModule {
    ///     fn providers(&self, injector: &Injector) {}
    /// }
    ///
    /// let mut app = Application::new(AppModule);
    /// app.bootstrap();
    /// app.bootstrap(); // Panics: Application already bootstrapped
    /// ```
    pub fn bootstrap(&mut self) {
        let root = self.root.take().expect("Application already bootstrapped");

        #[cfg(feature = "tracing")]
        info!("Starting application bootstrap process");

        Self::load_module(self.injector.clone(), root);

        #[cfg(feature = "tracing")]
        info!("Application bootstrap completed successfully");
    }

    /// Returns a shared reference to the root injector.
    ///
    /// The injector can be used to resolve dependencies after the application
    /// has been bootstrapped. The returned reference can be cloned to share
    /// access to the injector.
    ///
    /// # Returns
    ///
    /// A shared reference to the root [`Injector`].
    ///
    /// # Examples
    ///
    /// ```
    /// use sadi::application::Application;
    /// use sadi::module::Module;
    /// use sadi::injector::Injector;
    ///
    /// struct AppModule;
    /// impl Module for AppModule {
    ///     fn providers(&self, injector: &Injector) {}
    /// }
    ///
    /// let mut app = Application::new(AppModule);
    /// app.bootstrap();
    ///
    /// let injector = app.injector();
    /// let another_ref = app.injector();
    /// // Both references point to the same injector
    /// ```
    pub fn injector(&self) -> Shared<Injector> {
        #[cfg(feature = "tracing")]
        debug!("Accessing root injector");

        #[cfg(feature = "tracing")]
        {
            if self.is_bootstrapped() {
                debug!("Injector is available and application is bootstrapped");
            } else {
                debug!("Injector is available but application is not bootstrapped yet");
            }
        }

        self.injector.clone()
    }

    /// Checks whether the application has been bootstrapped.
    ///
    /// Returns `true` if [`bootstrap()`](Application::bootstrap) has been called,
    /// `false` otherwise.
    ///
    /// # Returns
    ///
    /// - `true` if the application is bootstrapped
    /// - `false` if the application has not been bootstrapped yet
    ///
    /// # Examples
    ///
    /// ```
    /// use sadi::application::Application;
    /// use sadi::module::Module;
    /// use sadi::injector::Injector;
    ///
    /// struct AppModule;
    /// impl Module for AppModule {
    ///     fn providers(&self, injector: &Injector) {}
    /// }
    ///
    /// let mut app = Application::new(AppModule);
    /// assert!(!app.is_bootstrapped());
    ///
    /// app.bootstrap();
    /// assert!(app.is_bootstrapped());
    /// ```
    pub fn is_bootstrapped(&self) -> bool {
        let bootstrapped = self.root.is_none();

        #[cfg(feature = "tracing")]
        debug!("Checking application bootstrap state: {}", bootstrapped);

        bootstrapped
    }

    /// Recursively loads a module and its imports into the injector hierarchy.
    ///
    /// Creates a child injector for the module, loads all imported modules first,
    /// then registers the module's own providers. This ensures proper dependency
    /// resolution order.
    ///
    /// # Parameters
    ///
    /// - `parent`: The parent injector to create a child from
    /// - `module`: The module to load
    fn load_module(parent: Shared<Injector>, module: Box<dyn Module>) {
        #[cfg(feature = "tracing")]
        debug!("Loading module into injector hierarchy");

        let module_injector = Shared::new(Injector::child(parent.clone()));

        #[cfg(feature = "tracing")]
        debug!("Created child injector for module");

        let imports = module.imports();
        #[cfg(feature = "tracing")]
        if !imports.is_empty() {
            debug!("Module has {} imports, loading them first", imports.len());
        }

        #[allow(unused_variables)]
        for (index, import) in imports.into_iter().enumerate() {
            #[cfg(feature = "tracing")]
            debug!("Loading import {}", index + 1);

            Self::load_module(module_injector.clone(), import);
        }

        #[cfg(feature = "tracing")]
        debug!("Registering module providers");

        module.providers(&module_injector);

        #[cfg(feature = "tracing")]
        debug!("Module loaded successfully");
    }
}

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

    #[cfg(not(feature = "thread-safe"))]
    use std::cell::RefCell;
    #[cfg(not(feature = "thread-safe"))]
    use std::rc::Rc;

    #[cfg(feature = "thread-safe")]
    use std::sync::{Arc, Mutex};

    struct EmptyModule;

    impl Module for EmptyModule {
        fn providers(&self, _injector: &Injector) {}
    }

    // CountingModule with conditional thread safety
    #[cfg(not(feature = "thread-safe"))]
    struct CountingModule {
        counter: Rc<RefCell<usize>>,
    }

    #[cfg(not(feature = "thread-safe"))]
    impl Module for CountingModule {
        fn providers(&self, _injector: &Injector) {
            *self.counter.borrow_mut() += 1;
        }
    }

    #[cfg(feature = "thread-safe")]
    struct CountingModule {
        counter: Arc<Mutex<usize>>,
    }

    #[cfg(feature = "thread-safe")]
    impl Module for CountingModule {
        fn providers(&self, _injector: &Injector) {
            *self.counter.lock().unwrap() += 1;
        }
    }

    // ModuleWithImports with conditional thread safety
    #[cfg(not(feature = "thread-safe"))]
    struct ModuleWithImports {
        counter: Rc<RefCell<usize>>,
    }

    #[cfg(not(feature = "thread-safe"))]
    impl Module for ModuleWithImports {
        fn imports(&self) -> Vec<Box<dyn Module>> {
            vec![
                Box::new(CountingModule {
                    counter: self.counter.clone(),
                }),
                Box::new(CountingModule {
                    counter: self.counter.clone(),
                }),
            ]
        }

        fn providers(&self, _injector: &Injector) {
            *self.counter.borrow_mut() += 1;
        }
    }

    #[cfg(feature = "thread-safe")]
    struct ModuleWithImports {
        counter: Arc<Mutex<usize>>,
    }

    #[cfg(feature = "thread-safe")]
    impl Module for ModuleWithImports {
        fn imports(&self) -> Vec<Box<dyn Module>> {
            vec![
                Box::new(CountingModule {
                    counter: self.counter.clone(),
                }),
                Box::new(CountingModule {
                    counter: self.counter.clone(),
                }),
            ]
        }

        fn providers(&self, _injector: &Injector) {
            *self.counter.lock().unwrap() += 1;
        }
    }

    #[test]
    fn test_new_creates_unbootstrapped_application() {
        let app = Application::new(EmptyModule);
        assert!(
            !app.is_bootstrapped(),
            "New application should not be bootstrapped"
        );
    }

    #[test]
    fn test_bootstrap_changes_state() {
        let mut app = Application::new(EmptyModule);
        assert!(!app.is_bootstrapped());

        app.bootstrap();
        assert!(
            app.is_bootstrapped(),
            "Application should be bootstrapped after bootstrap()"
        );
    }

    #[test]
    #[should_panic(expected = "Application already bootstrapped")]
    fn test_bootstrap_twice_panics() {
        let mut app = Application::new(EmptyModule);
        app.bootstrap();
        app.bootstrap(); // Should panic
    }

    #[test]
    fn test_injector_returns_shared_reference() {
        let mut app = Application::new(EmptyModule);
        app.bootstrap();

        let injector1 = app.injector();
        let _injector2 = app.injector();

        // Both should reference the same underlying injector
        #[cfg(feature = "thread-safe")]
        assert_eq!(std::sync::Arc::strong_count(&injector1), 3); // app + injector1 + injector2

        #[cfg(not(feature = "thread-safe"))]
        assert_eq!(std::rc::Rc::strong_count(&injector1), 3); // app + injector1 + injector2
    }

    #[test]
    fn test_bootstrap_calls_module_providers() {
        #[cfg(not(feature = "thread-safe"))]
        let counter = Rc::new(RefCell::new(0));
        #[cfg(feature = "thread-safe")]
        let counter = Arc::new(Mutex::new(0));

        let module = CountingModule {
            counter: counter.clone(),
        };

        let mut app = Application::new(module);

        #[cfg(not(feature = "thread-safe"))]
        assert_eq!(*counter.borrow(), 0);
        #[cfg(feature = "thread-safe")]
        assert_eq!(*counter.lock().unwrap(), 0);

        app.bootstrap();

        #[cfg(not(feature = "thread-safe"))]
        assert_eq!(
            *counter.borrow(),
            1,
            "Module providers should be called during bootstrap"
        );
        #[cfg(feature = "thread-safe")]
        assert_eq!(
            *counter.lock().unwrap(),
            1,
            "Module providers should be called during bootstrap"
        );
    }

    #[test]
    fn test_bootstrap_loads_imports_first() {
        #[cfg(not(feature = "thread-safe"))]
        let counter = Rc::new(RefCell::new(0));
        #[cfg(feature = "thread-safe")]
        let counter = Arc::new(Mutex::new(0));

        let module = ModuleWithImports {
            counter: counter.clone(),
        };

        let mut app = Application::new(module);
        app.bootstrap();

        // 2 imports + 1 root module = 3 calls
        #[cfg(not(feature = "thread-safe"))]
        assert_eq!(*counter.borrow(), 3, "All modules should be loaded");
        #[cfg(feature = "thread-safe")]
        assert_eq!(*counter.lock().unwrap(), 3, "All modules should be loaded");
    }

    #[test]
    fn test_application_can_be_created_with_different_modules() {
        let _app1 = Application::new(EmptyModule);

        #[cfg(not(feature = "thread-safe"))]
        let _app2 = Application::new(CountingModule {
            counter: Rc::new(RefCell::new(0)),
        });
        #[cfg(feature = "thread-safe")]
        let _app2 = Application::new(CountingModule {
            counter: Arc::new(Mutex::new(0)),
        });

        // Should compile and work with different module types
    }

    #[test]
    fn test_injector_accessible_before_bootstrap() {
        let app = Application::new(EmptyModule);
        let _injector = app.injector();
        // Should not panic - injector is available even before bootstrap
    }

    #[test]
    fn test_multiple_injector_clones() {
        let mut app = Application::new(EmptyModule);
        app.bootstrap();

        let injectors: Vec<_> = (0..5).map(|_| app.injector()).collect();
        assert_eq!(injectors.len(), 5);

        #[cfg(feature = "thread-safe")]
        assert_eq!(std::sync::Arc::strong_count(&injectors[0]), 6); // app + 5 in vec

        #[cfg(not(feature = "thread-safe"))]
        assert_eq!(std::rc::Rc::strong_count(&injectors[0]), 6); // app + 5 in vec
    }

    #[cfg(feature = "debug")]
    #[test]
    fn test_debug_implementation() {
        let app = Application::new(EmptyModule);
        let debug_str = format!("{:?}", app);
        assert!(
            debug_str.contains("Application"),
            "Debug output should contain 'Application'"
        );
    }

    // NestedImportModule with conditional thread safety
    #[cfg(not(feature = "thread-safe"))]
    struct NestedImportModule {
        counter: Rc<RefCell<usize>>,
        depth: usize,
    }

    #[cfg(not(feature = "thread-safe"))]
    impl Module for NestedImportModule {
        fn imports(&self) -> Vec<Box<dyn Module>> {
            if self.depth > 0 {
                vec![Box::new(NestedImportModule {
                    counter: self.counter.clone(),
                    depth: self.depth - 1,
                })]
            } else {
                vec![]
            }
        }

        fn providers(&self, _injector: &Injector) {
            *self.counter.borrow_mut() += 1;
        }
    }

    #[cfg(feature = "thread-safe")]
    struct NestedImportModule {
        counter: Arc<Mutex<usize>>,
        depth: usize,
    }

    #[cfg(feature = "thread-safe")]
    impl Module for NestedImportModule {
        fn imports(&self) -> Vec<Box<dyn Module>> {
            if self.depth > 0 {
                vec![Box::new(NestedImportModule {
                    counter: self.counter.clone(),
                    depth: self.depth - 1,
                })]
            } else {
                vec![]
            }
        }

        fn providers(&self, _injector: &Injector) {
            *self.counter.lock().unwrap() += 1;
        }
    }

    #[test]
    fn test_deeply_nested_modules() {
        #[cfg(not(feature = "thread-safe"))]
        let counter = Rc::new(RefCell::new(0));
        #[cfg(feature = "thread-safe")]
        let counter = Arc::new(Mutex::new(0));

        let module = NestedImportModule {
            counter: counter.clone(),
            depth: 5,
        };

        let mut app = Application::new(module);
        app.bootstrap();

        // depth 5, 4, 3, 2, 1, 0 = 6 modules total
        #[cfg(not(feature = "thread-safe"))]
        assert_eq!(*counter.borrow(), 6, "All nested modules should be loaded");
        #[cfg(feature = "thread-safe")]
        assert_eq!(
            *counter.lock().unwrap(),
            6,
            "All nested modules should be loaded"
        );
    }
}