fluxdi 1.1.0

FluxDI - 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
//! Module system for organizing dependency injection providers.
//!
//! This module defines the [`Module`] trait, which serves as the foundation for organizing
//! and configuring dependency injection in a modular, composable way.
//!
//! # Overview
//!
//! Modules allow you to:
//! - Group related providers together
//! - Import other modules to compose functionality
//! - Configure services within an injector
//!
//! # Thread Safety
//!
//! When the `thread-safe` feature is enabled, the [`Module`] trait requires implementors
//! to be `Send + Sync`, allowing modules to be safely shared across threads.
//!
//! # Examples
//!
//! ```
//! use fluxdi::module::Module;
//! use fluxdi::injector::Injector;
//!
//! struct DatabaseModule;
//!
//! impl Module for DatabaseModule {
//!     fn providers(&self, injector: &Injector) {
//!         // Register database-related providers
//!     }
//! }
//! ```
use crate::injector::Injector;
use crate::{Error, runtime::Shared};
use std::future::Future;
use std::pin::Pin;

#[cfg(not(feature = "thread-safe"))]
pub type ModuleLifecycleFuture = Pin<Box<dyn Future<Output = Result<(), Error>> + 'static>>;

#[cfg(feature = "thread-safe")]
pub type ModuleLifecycleFuture = Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'static>>;

/// Trait for defining a module in the dependency injection system.
///
/// A module encapsulates a set of providers and can import other modules to build
/// a hierarchical dependency injection configuration. Modules are the primary way
/// to organize and structure your application's services.
///
/// # Thread Safety
///
/// With the `thread-safe` feature enabled, modules must implement `Send + Sync` to
/// ensure they can be safely shared across threads. Without this feature, modules
/// have no additional thread-safety requirements.
///
/// # Required Methods
///
/// - None. Implement at least one of:
///   - [`configure`](Module::configure) (recommended)
///   - [`providers`](Module::providers) (legacy-compatible path)
///
/// # Optional Methods
///
/// - [`imports`](Module::imports): Returns other modules that this module depends on
/// - [`providers`](Module::providers): Legacy registration hook (sync)
/// - [`providers_async`](Module::providers_async): Async provider registration hook
/// - [`on_start`](Module::on_start): Async startup lifecycle hook
/// - [`on_stop`](Module::on_stop): Async shutdown lifecycle hook
///
/// # Examples
///
/// ## Basic Module
///
/// ```
/// use fluxdi::module::Module;
/// use fluxdi::injector::Injector;
///
/// struct LoggingModule;
///
/// impl Module for LoggingModule {
///     fn providers(&self, injector: &Injector) {
///         // Register logging providers
///     }
/// }
/// ```
///
/// ## Module with Imports
///
/// ```
/// use fluxdi::module::Module;
/// use fluxdi::injector::Injector;
///
/// struct DatabaseModule;
/// struct ConfigModule;
///
/// impl Module for DatabaseModule {
///     fn providers(&self, injector: &Injector) {
///         // Register database providers
///     }
/// }
///
/// impl Module for ConfigModule {
///     fn providers(&self, injector: &Injector) {
///         // Register config providers
///     }
/// }
///
/// struct AppModule;
///
/// impl Module for AppModule {
///     fn imports(&self) -> Vec<Box<dyn Module>> {
///         vec![
///             Box::new(DatabaseModule),
///             Box::new(ConfigModule),
///         ]
///     }
///
///     fn providers(&self, injector: &Injector) {
///         // Register app-level providers
///     }
/// }
/// ```
#[cfg(not(feature = "thread-safe"))]
pub trait Module {
    /// Returns the unique type identifier for this module.
    ///
    /// This method provides runtime type identification for modules, which can be useful
    /// for debugging, logging, or implementing module deduplication logic.
    ///
    /// # Returns
    ///
    /// A [`TypeId`](std::any::TypeId) that uniquely identifies the concrete type of this module.
    ///
    /// # Examples
    ///
    /// ```
    /// use fluxdi::module::Module;
    /// use fluxdi::injector::Injector;
    /// use std::any::TypeId;
    ///
    /// struct MyModule;
    /// impl Module for MyModule {
    ///     fn providers(&self, injector: &Injector) {}
    /// }
    ///
    /// let module = MyModule;
    /// let type_id = module.type_id();
    /// assert_eq!(type_id, TypeId::of::<MyModule>());
    /// ```
    fn type_id(&self) -> std::any::TypeId
    where
        Self: 'static,
    {
        std::any::TypeId::of::<Self>()
    }

    /// Returns the type name of this module as a string.
    ///
    /// This method provides a human-readable representation of the module's type,
    /// which is particularly useful for debugging, logging, and error messages.
    ///
    /// # Returns
    ///
    /// A static string slice containing the fully-qualified type name of this module.
    ///
    /// # Examples
    ///
    /// ```
    /// use fluxdi::module::Module;
    /// use fluxdi::injector::Injector;
    ///
    /// struct DatabaseModule;
    /// impl Module for DatabaseModule {
    ///     fn providers(&self, injector: &Injector) {}
    /// }
    ///
    /// let module = DatabaseModule;
    /// let name = module.type_name();
    /// // The exact format depends on the module path
    /// assert!(name.contains("DatabaseModule"));
    /// ```
    fn type_name(&self) -> &'static str
    where
        Self: 'static,
    {
        std::any::type_name::<Self>()
    }

    /// Returns a list of modules that this module imports.
    ///
    /// Imported modules have their providers registered before this module's providers.
    /// This allows a module to build upon functionality provided by other modules.
    ///
    /// # Default Implementation
    ///
    /// By default, returns an empty vector (no imports).
    ///
    /// # Returns
    ///
    /// A vector of boxed `Module` trait objects representing the imported modules.
    ///
    /// # Examples
    ///
    /// ```
    /// use fluxdi::module::Module;
    /// use fluxdi::injector::Injector;
    ///
    /// struct CoreModule;
    /// impl Module for CoreModule {
    ///     fn providers(&self, injector: &Injector) {}
    /// }
    ///
    /// struct FeatureModule;
    /// impl Module for FeatureModule {
    ///     fn imports(&self) -> Vec<Box<dyn Module>> {
    ///         vec![Box::new(CoreModule)]
    ///     }
    ///
    ///     fn providers(&self, injector: &Injector) {}
    /// }
    /// ```
    fn imports(&self) -> Vec<Box<dyn Module>> {
        vec![]
    }

    /// Configures providers for this module.
    ///
    /// This is the preferred registration hook used by `Application` bootstrap flows.
    /// The default implementation delegates to [`providers`](Module::providers) for
    /// backward compatibility.
    fn configure(&self, injector: &Injector) -> Result<(), Error> {
        self.providers(injector);
        Ok(())
    }

    /// Registers providers with the given injector.
    ///
    /// This method is called to configure the dependency injection container with
    /// the services that this module provides. Use the injector to register
    /// factories, values, and other providers.
    ///
    /// # Parameters
    ///
    /// - `injector`: The injector instance to register providers with
    ///
    /// # Examples
    ///
    /// ```
    /// use fluxdi::module::Module;
    /// use fluxdi::injector::Injector;
    ///
    /// struct MyModule;
    ///
    /// impl Module for MyModule {
    ///     fn providers(&self, injector: &Injector) {
    ///         // Register providers here
    ///         // injector.register<...>(...)
    ///     }
    /// }
    /// ```
    fn providers(&self, _injector: &Injector) {}

    /// Async variant of provider registration.
    ///
    /// Default behavior calls [`providers`](Module::providers) synchronously.
    fn providers_async(&self, injector: Shared<Injector>) -> ModuleLifecycleFuture {
        let result = self.configure(&injector);
        Box::pin(async move { result })
    }

    /// Lifecycle hook executed after this module and its imports finish registration.
    fn on_start(&self, _injector: Shared<Injector>) -> ModuleLifecycleFuture {
        Box::pin(async { Ok(()) })
    }

    /// Lifecycle hook executed during application shutdown in reverse module order.
    fn on_stop(&self, _injector: Shared<Injector>) -> ModuleLifecycleFuture {
        Box::pin(async { Ok(()) })
    }
}

#[cfg(feature = "thread-safe")]
pub trait Module: Send + Sync {
    /// Returns the unique type identifier for this module.
    ///
    /// This method provides runtime type identification for modules, which can be useful
    /// for debugging, logging, or implementing module deduplication logic.
    ///
    /// # Returns
    ///
    /// A [`TypeId`](std::any::TypeId) that uniquely identifies the concrete type of this module.
    ///
    /// # Examples
    ///
    /// ```
    /// use fluxdi::module::Module;
    /// use fluxdi::injector::Injector;
    /// use std::any::TypeId;
    ///
    /// struct MyModule;
    /// impl Module for MyModule {
    ///     fn providers(&self, injector: &Injector) {}
    /// }
    ///
    /// let module = MyModule;
    /// let type_id = module.type_id();
    /// assert_eq!(type_id, TypeId::of::<MyModule>());
    /// ```
    fn type_id(&self) -> std::any::TypeId
    where
        Self: 'static,
    {
        std::any::TypeId::of::<Self>()
    }

    /// Returns the type name of this module as a string.
    ///
    /// This method provides a human-readable representation of the module's type,
    /// which is particularly useful for debugging, logging, and error messages.
    ///
    /// # Returns
    ///
    /// A static string slice containing the fully-qualified type name of this module.
    ///
    /// # Examples
    ///
    /// ```
    /// use fluxdi::module::Module;
    /// use fluxdi::injector::Injector;
    ///
    /// struct DatabaseModule;
    /// impl Module for DatabaseModule {
    ///     fn providers(&self, injector: &Injector) {}
    /// }
    ///
    /// let module = DatabaseModule;
    /// let name = module.type_name();
    /// // The exact format depends on the module path
    /// assert!(name.contains("DatabaseModule"));
    /// ```
    fn type_name(&self) -> &'static str
    where
        Self: 'static,
    {
        std::any::type_name::<Self>()
    }

    /// Returns a list of modules that this module imports.
    ///
    /// Imported modules have their providers registered before this module's providers.
    /// This allows a module to build upon functionality provided by other modules.
    ///
    /// # Default Implementation
    ///
    /// By default, returns an empty vector (no imports).
    ///
    /// # Returns
    ///
    /// A vector of boxed `Module` trait objects representing the imported modules.
    ///
    /// # Examples
    ///
    /// ```
    /// use fluxdi::module::Module;
    /// use fluxdi::injector::Injector;
    ///
    /// struct CoreModule;
    /// impl Module for CoreModule {
    ///     fn providers(&self, injector: &Injector) {}
    /// }
    ///
    /// struct FeatureModule;
    /// impl Module for FeatureModule {
    ///     fn imports(&self) -> Vec<Box<dyn Module>> {
    ///         vec![Box::new(CoreModule)]
    ///     }
    ///
    ///     fn providers(&self, injector: &Injector) {}
    /// }
    /// ```
    fn imports(&self) -> Vec<Box<dyn Module>> {
        vec![]
    }

    /// Configures providers for this module.
    ///
    /// This is the preferred registration hook used by `Application` bootstrap flows.
    /// The default implementation delegates to [`providers`](Module::providers) for
    /// backward compatibility.
    fn configure(&self, injector: &Injector) -> Result<(), Error> {
        self.providers(injector);
        Ok(())
    }

    /// Registers providers with the given injector.
    ///
    /// This method is called to configure the dependency injection container with
    /// the services that this module provides. Use the injector to register
    /// factories, values, and other providers.
    ///
    /// # Parameters
    ///
    /// - `injector`: The injector instance to register providers with
    ///
    /// # Examples
    ///
    /// ```
    /// use fluxdi::module::Module;
    /// use fluxdi::injector::Injector;
    ///
    /// struct MyModule;
    ///
    /// impl Module for MyModule {
    ///     fn providers(&self, injector: &Injector) {
    ///         // Register providers here
    ///         // injector.register<...>(...)
    ///     }
    /// }
    /// ```
    fn providers(&self, _injector: &Injector) {}

    /// Async variant of provider registration.
    ///
    /// Default behavior calls [`providers`](Module::providers) synchronously.
    fn providers_async(&self, injector: Shared<Injector>) -> ModuleLifecycleFuture {
        let result = self.configure(&injector);
        Box::pin(async move { result })
    }

    /// Lifecycle hook executed after this module and its imports finish registration.
    fn on_start(&self, _injector: Shared<Injector>) -> ModuleLifecycleFuture {
        Box::pin(async { Ok(()) })
    }

    /// Lifecycle hook executed during application shutdown in reverse module order.
    fn on_stop(&self, _injector: Shared<Injector>) -> ModuleLifecycleFuture {
        Box::pin(async { Ok(()) })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::runtime::Shared;
    use futures::executor::block_on;

    struct EmptyModule;

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

    struct ModuleWithImports {
        import_count: usize,
    }

    impl Module for ModuleWithImports {
        fn imports(&self) -> Vec<Box<dyn Module>> {
            (0..self.import_count)
                .map(|_| Box::new(EmptyModule) as Box<dyn Module>)
                .collect()
        }

        fn providers(&self, _injector: &Injector) {}
    }

    #[test]
    fn test_default_imports_returns_empty_vec() {
        let module = EmptyModule;
        let imports = module.imports();
        assert!(imports.is_empty(), "Default imports should be empty");
    }

    #[test]
    fn test_module_can_have_imports() {
        let module = ModuleWithImports { import_count: 3 };
        let imports = module.imports();
        assert_eq!(imports.len(), 3, "Should have 3 imports");
    }

    #[test]
    fn test_module_providers_can_be_called() {
        let module = EmptyModule;
        let injector = Injector::root();

        // Should not panic
        module.providers(&injector);
        assert!(module.configure(&injector).is_ok());
    }

    #[test]
    fn test_module_trait_object() {
        let module: Box<dyn Module> = Box::new(EmptyModule);
        let injector = Injector::root();

        // Test that trait object works correctly
        let imports = module.imports();
        assert!(imports.is_empty());

        module.providers(&injector);
    }

    #[test]
    fn test_multiple_modules() {
        let modules: Vec<Box<dyn Module>> = vec![
            Box::new(EmptyModule),
            Box::new(EmptyModule),
            Box::new(ModuleWithImports { import_count: 2 }),
        ];

        assert_eq!(modules.len(), 3, "Should have 3 modules");

        let injector = Injector::root();
        for module in modules {
            module.providers(&injector);
            assert!(module.configure(&injector).is_ok());
        }
    }

    #[test]
    fn test_default_async_lifecycle_hooks_are_noop() {
        let module = EmptyModule;
        let injector = Shared::new(Injector::root());

        assert!(block_on(module.providers_async(injector.clone())).is_ok());
        assert!(block_on(module.on_start(injector.clone())).is_ok());
        assert!(block_on(module.on_stop(injector)).is_ok());
    }

    #[test]
    fn test_nested_imports() {
        let module = ModuleWithImports { import_count: 2 };
        let imports = module.imports();

        // Each import should also be callable
        let injector = Injector::root();
        for import in imports {
            import.providers(&injector);
            assert!(
                import.imports().is_empty(),
                "Nested imports should be empty for EmptyModule"
            );
        }
    }

    // Note: CountingModule uses RefCell which is not Send, so it's only available
    // when thread-safe feature is disabled
    #[cfg(not(feature = "thread-safe"))]
    struct CountingModule {
        call_count: std::cell::RefCell<usize>,
    }

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

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

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

    #[test]
    fn test_providers_can_have_side_effects() {
        #[cfg(not(feature = "thread-safe"))]
        let module = CountingModule {
            call_count: std::cell::RefCell::new(0),
        };

        #[cfg(feature = "thread-safe")]
        let module = CountingModule {
            call_count: std::sync::Mutex::new(0),
        };

        let injector = Injector::root();

        #[cfg(not(feature = "thread-safe"))]
        {
            assert_eq!(*module.call_count.borrow(), 0);
            module.providers(&injector);
            assert_eq!(*module.call_count.borrow(), 1);
            module.providers(&injector);
            assert_eq!(*module.call_count.borrow(), 2);
        }

        #[cfg(feature = "thread-safe")]
        {
            assert_eq!(*module.call_count.lock().unwrap(), 0);
            module.providers(&injector);
            assert_eq!(*module.call_count.lock().unwrap(), 1);
            module.providers(&injector);
            assert_eq!(*module.call_count.lock().unwrap(), 2);
        }
    }
}