mads-core 0.7.0

Framework-neutral dependency injection, configuration, and lifecycle core for MADS.rs
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
//! Integration tests for rooted provider selection and module boundaries.

use std::any::TypeId;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use mads_core::{
    Config, ConstructionContext, ErasedProvider, GraphAnalysis, MADS001, MADS002, MADS009, Mads,
    Module, ProviderDescriptor, ProviderFuture, ProviderKind, ProviderRegistry, ProviderVisibility,
    SourceLocation,
};

mod selected_scope {
    pub mod app {
        use super::unowned::RequiredUnownedUseCase;

        #[mads_core::module]
        pub struct AppModule;

        #[derive(Clone)]
        pub struct ReachableController;

        #[derive(Clone)]
        pub struct UnusedButOwnedService;

        pub mod providers {
            use super::{ReachableController, RequiredUnownedUseCase, UnusedButOwnedService};

            #[mads_core::provider]
            pub fn reachable_controller(_use_case: RequiredUnownedUseCase) -> ReachableController {
                ReachableController
            }

            #[mads_core::provider]
            pub fn unused_but_owned_service() -> UnusedButOwnedService {
                UnusedButOwnedService
            }
        }
    }

    pub mod unowned {
        #[derive(Clone)]
        pub struct RequiredUnownedUseCase;

        #[mads_core::provider]
        pub fn required_unowned_use_case() -> RequiredUnownedUseCase {
            RequiredUnownedUseCase
        }
    }

    pub mod unreachable {
        #[mads_core::module]
        pub struct UnreachableModule;

        #[derive(Clone)]
        pub struct UnreachableService;

        #[mads_core::provider]
        pub fn unreachable_service() -> UnreachableService {
            UnreachableService
        }
    }
}

mod direct_public {
    pub mod target {
        #[mads_core::module]
        pub struct TargetModule;

        #[derive(Clone)]
        pub struct PublicProvider;

        #[mads_core::provider]
        pub fn public_provider() -> PublicProvider {
            PublicProvider
        }
    }

    pub mod root {
        use super::target::{PublicProvider, TargetModule};

        #[mads_core::module(imports = [TargetModule])]
        pub struct DirectRoot;

        #[derive(Clone)]
        pub struct DirectConsumer;

        #[mads_core::provider]
        pub fn direct_consumer(_provider: PublicProvider) -> DirectConsumer {
            DirectConsumer
        }
    }
}

mod missing_import {
    pub mod target {
        #[mads_core::module]
        pub struct TargetModule;

        #[derive(Clone)]
        pub struct PublicProvider;

        #[mads_core::provider]
        pub fn public_provider() -> PublicProvider {
            PublicProvider
        }
    }

    pub mod root {
        use super::target::PublicProvider;

        #[mads_core::module]
        pub struct MissingImportRoot;

        #[derive(Clone)]
        pub struct MissingImportConsumer;

        #[mads_core::provider]
        pub fn missing_import_consumer(_provider: PublicProvider) -> MissingImportConsumer {
            MissingImportConsumer
        }
    }
}

mod transitive_only {
    pub mod third {
        #[mads_core::module]
        pub struct ThirdModule;

        #[derive(Clone)]
        pub struct ThirdProvider;

        #[mads_core::provider]
        pub fn third_provider() -> ThirdProvider {
            ThirdProvider
        }
    }

    pub mod middle {
        use super::third::ThirdModule;

        #[mads_core::module(imports = [ThirdModule])]
        pub struct MiddleModule;
    }

    pub mod root {
        use super::{middle::MiddleModule, third::ThirdProvider};

        #[mads_core::module(imports = [MiddleModule])]
        pub struct TransitiveRoot;

        #[derive(Clone)]
        pub struct TransitiveConsumer;

        #[mads_core::provider]
        pub fn transitive_consumer(_provider: ThirdProvider) -> TransitiveConsumer {
            TransitiveConsumer
        }
    }
}

mod restricted_crossing {
    pub mod target {
        #[mads_core::module]
        pub struct RestrictedTargetModule;

        #[derive(Clone)]
        pub(crate) struct RestrictedProvider;

        #[mads_core::provider]
        pub(crate) fn restricted_provider() -> RestrictedProvider {
            RestrictedProvider
        }
    }

    pub mod root {
        use super::target::{RestrictedProvider, RestrictedTargetModule};

        #[mads_core::module(imports = [RestrictedTargetModule])]
        pub struct RestrictedRoot;

        #[derive(Clone)]
        pub struct RestrictedConsumer;

        #[mads_core::provider]
        pub fn restricted_consumer(_provider: RestrictedProvider) -> RestrictedConsumer {
            RestrictedConsumer
        }
    }
}

mod unowned_bridge {
    pub mod target {
        #[mads_core::module]
        pub struct BridgeTargetModule;

        #[derive(Clone)]
        pub struct OwnedTarget;

        #[mads_core::provider]
        pub fn owned_target() -> OwnedTarget {
            OwnedTarget
        }
    }

    pub mod bridge {
        use super::target::OwnedTarget;

        #[derive(Clone)]
        pub struct UnownedBridge;

        #[mads_core::provider]
        pub fn unowned_bridge(_target: OwnedTarget) -> UnownedBridge {
            UnownedBridge
        }
    }

    pub mod root {
        use super::bridge::UnownedBridge;

        #[mads_core::module]
        pub struct BridgeRoot;

        #[derive(Clone)]
        pub struct BridgeConsumer;

        #[mads_core::provider]
        pub fn bridge_consumer(_bridge: UnownedBridge) -> BridgeConsumer {
            BridgeConsumer
        }
    }
}

mod diamond {
    use super::{AtomicUsize, Ordering};

    pub static CONSTRUCTIONS: AtomicUsize = AtomicUsize::new(0);

    pub mod shared {
        use super::{CONSTRUCTIONS, Ordering};

        #[mads_core::module]
        pub struct SharedModule;

        pub struct SharedProvider;

        #[mads_core::provider]
        pub fn shared_provider() -> SharedProvider {
            CONSTRUCTIONS.fetch_add(1, Ordering::SeqCst);
            SharedProvider
        }
    }

    pub mod left {
        use super::shared::SharedModule;

        #[mads_core::module(imports = [SharedModule])]
        pub struct LeftModule;
    }

    pub mod right {
        use super::shared::SharedModule;

        #[mads_core::module(imports = [SharedModule])]
        pub struct RightModule;
    }

    pub mod root {
        use super::{left::LeftModule, right::RightModule};

        #[mads_core::module(imports = [LeftModule, RightModule])]
        pub struct DiamondRoot;
    }
}

mod duplicate_reachable {
    use super::{
        Arc, ConstructionContext, ErasedProvider, ProviderDescriptor, ProviderFuture, ProviderKind,
        ProviderVisibility, SourceLocation, TypeId,
    };

    #[mads_core::module]
    pub struct DuplicateRoot;

    pub struct DuplicateProvider;

    fn duplicate_type_id() -> TypeId {
        TypeId::of::<DuplicateProvider>()
    }

    fn duplicate_constructor<'a>(_: &'a ConstructionContext<'a>) -> ProviderFuture<'a> {
        Box::pin(async { Ok(Arc::new(DuplicateProvider) as ErasedProvider) })
    }

    mads_core::__private::inventory::submit! {
        ProviderDescriptor::new(
            ProviderKind::Provider,
            "DuplicateProvider",
            duplicate_type_id,
            &[],
            ProviderVisibility::Public,
            SourceLocation::new("duplicate_reachable.rs", 1, 1),
            duplicate_constructor,
        )
        .with_namespace(module_path!())
    }

    mads_core::__private::inventory::submit! {
        ProviderDescriptor::new(
            ProviderKind::Provider,
            "DuplicateProvider",
            duplicate_type_id,
            &[],
            ProviderVisibility::Public,
            SourceLocation::new("duplicate_reachable.rs", 1, 1),
            duplicate_constructor,
        )
        .with_namespace(module_path!())
    }
}

mod ambiguous_dependency {
    #[derive(Clone)]
    pub struct SharedDependency;

    pub mod app {
        use super::SharedDependency;

        #[mads_core::module]
        pub struct AmbiguousDependencyRoot;

        pub struct Consumer;

        #[mads_core::provider]
        pub fn consumer(_dependency: SharedDependency) -> Consumer {
            Consumer
        }
    }

    pub mod constructors {
        use super::SharedDependency;

        #[mads_core::provider]
        pub fn first_shared_dependency() -> SharedDependency {
            SharedDependency
        }

        #[mads_core::provider]
        pub fn second_shared_dependency() -> SharedDependency {
            SharedDependency
        }
    }
}

mod mixed_dependency_scope {
    #[derive(Clone)]
    pub struct SharedDependency;

    pub mod allowed {
        use super::SharedDependency;

        #[mads_core::module]
        pub struct AllowedModule;

        #[mads_core::provider]
        pub fn allowed_dependency() -> SharedDependency {
            SharedDependency
        }
    }

    pub mod foreign {
        use super::SharedDependency;

        #[mads_core::module]
        pub struct ForeignModule;

        #[mads_core::provider]
        pub fn foreign_dependency() -> SharedDependency {
            SharedDependency
        }
    }

    pub mod app {
        use super::{SharedDependency, allowed::AllowedModule};

        #[mads_core::module(imports = [AllowedModule])]
        pub struct MixedDependencyRoot;

        pub struct Consumer;

        #[mads_core::provider]
        pub fn consumer(_dependency: SharedDependency) -> Consumer {
            Consumer
        }
    }
}

fn rooted_analysis<M: Module>() -> GraphAnalysis {
    let mut builder = Mads::builder();
    builder
        .root::<M>()
        .expect("module graph metadata should be valid");
    builder.analyze()
}

#[test]
fn rooted_scope_includes_owned_roots_and_required_unowned_closure_only() {
    use selected_scope::{
        app::{AppModule, ReachableController, UnusedButOwnedService},
        unowned::RequiredUnownedUseCase,
        unreachable::UnreachableService,
    };

    let analysis = rooted_analysis::<AppModule>();
    assert!(analysis.is_valid());
    assert!(analysis.graph().provider::<ReachableController>().is_some());
    assert!(
        analysis
            .graph()
            .provider::<UnusedButOwnedService>()
            .is_some()
    );
    assert!(analysis.graph().provider::<UnreachableService>().is_none());
    assert!(
        analysis
            .graph()
            .provider::<RequiredUnownedUseCase>()
            .is_some()
    );
}

#[test]
fn rooted_scope_reports_duplicate_reachable_provider_declarations() {
    let analysis = rooted_analysis::<duplicate_reachable::DuplicateRoot>();

    assert_eq!(analysis.diagnostics()[0].code(), MADS001);
    assert!(analysis.construction_plan().is_none());
}

#[test]
fn rooted_scope_reports_ambiguous_unowned_dependency_constructors() {
    let analysis = rooted_analysis::<ambiguous_dependency::app::AmbiguousDependencyRoot>();

    assert_eq!(analysis.diagnostics()[0].code(), MADS002);
    assert!(analysis.construction_plan().is_none());
}

#[test]
fn externally_satisfied_dependency_skips_ambiguous_static_constructors() {
    let mut builder = Mads::builder();
    builder
        .root::<ambiguous_dependency::app::AmbiguousDependencyRoot>()
        .unwrap()
        .provide(ambiguous_dependency::SharedDependency)
        .unwrap();

    let analysis = builder.analyze();
    assert!(analysis.is_valid(), "{:?}", analysis.diagnostics());
    assert!(
        analysis
            .graph()
            .provider::<ambiguous_dependency::SharedDependency>()
            .is_some()
    );
}

#[test]
fn accessible_dependency_ignores_a_constructor_outside_the_rooted_scope() {
    let analysis = rooted_analysis::<mixed_dependency_scope::app::MixedDependencyRoot>();

    assert!(analysis.is_valid(), "{:?}", analysis.diagnostics());
    assert!(
        analysis
            .graph()
            .provider::<mixed_dependency_scope::SharedDependency>()
            .is_some()
    );
}

#[test]
fn direct_import_allows_an_unrestricted_public_provider() {
    let analysis = rooted_analysis::<direct_public::root::DirectRoot>();
    assert!(analysis.is_valid());
}

#[test]
fn missing_direct_import_reports_module_boundary_diagnostic() {
    let analysis = rooted_analysis::<missing_import::root::MissingImportRoot>();
    assert_eq!(analysis.diagnostics()[0].code(), MADS009);
    assert!(
        analysis.diagnostics()[0]
            .to_string()
            .contains("direct import")
    );
    assert!(analysis.construction_plan().is_none());
}

#[test]
fn transitive_import_does_not_reexport_a_provider() {
    let analysis = rooted_analysis::<transitive_only::root::TransitiveRoot>();
    assert_eq!(analysis.diagnostics()[0].code(), MADS009);
    assert!(
        analysis.diagnostics()[0]
            .to_string()
            .contains("direct import")
    );
}

#[test]
fn restricted_provider_cannot_cross_a_module_boundary() {
    let analysis = rooted_analysis::<restricted_crossing::root::RestrictedRoot>();
    assert_eq!(analysis.diagnostics()[0].code(), MADS009);
    assert!(
        analysis.diagnostics()[0]
            .to_string()
            .contains("unrestricted `pub`")
    );
}

#[test]
fn unowned_bridge_carries_the_requesting_module_context() {
    let analysis = rooted_analysis::<unowned_bridge::root::BridgeRoot>();
    assert_eq!(analysis.diagnostics()[0].code(), MADS009);
    assert!(
        analysis.diagnostics()[0]
            .to_string()
            .contains("direct import")
    );
}

#[tokio::test]
async fn diamond_scope_plans_and_constructs_the_shared_provider_once() {
    use diamond::{CONSTRUCTIONS, root::DiamondRoot, shared::SharedProvider};

    CONSTRUCTIONS.store(0, Ordering::SeqCst);
    let analysis = rooted_analysis::<DiamondRoot>();
    let plan = analysis
        .construction_plan()
        .expect("diamond scope should have a construction plan");
    assert_eq!(
        plan.steps()
            .iter()
            .filter(|step| step.type_name() == "SharedProvider")
            .count(),
        1
    );

    let registry = ProviderRegistry::new();
    let config = Config::empty();
    let context = ConstructionContext::new(&registry, &config);
    for step in plan.steps() {
        let _ = (step.__descriptor().constructor())(&context)
            .await
            .expect("planned constructor should succeed");
    }
    assert!(analysis.graph().provider::<SharedProvider>().is_some());
    assert_eq!(CONSTRUCTIONS.load(Ordering::SeqCst), 1);
}