mads-core 0.9.2

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
//! Integration tests for explicit application construction.

use std::any::TypeId;
use std::cell::Cell;
use std::sync::{Arc, Mutex};

use mads_core::{
    ApplicationContext, Catalog, ConstructionContext, ConstructionStep, DependencyDescriptor,
    ErasedProvider, LifecycleFuture, LifecycleHook, LifecycleState, MADS003, MADS008, Mads,
    ProviderDescriptor, ProviderFuture, ProviderKind, ProviderOrigin, ProviderState,
    ProviderVisibility, SourceLocation,
};

mod rooted {
    pub mod app {
        #[mads_core::module]
        pub struct AppModule;

        #[derive(Clone)]
        pub struct ReachableService;

        #[mads_core::provider]
        pub fn reachable_service() -> ReachableService {
            ReachableService
        }
    }

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

        #[derive(Clone)]
        pub struct UnreachableService;

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

struct Database;

impl Database {
    fn new() -> Self {
        Self
    }
}

struct Repository {
    database: Arc<Database>,
}

fn database_type_id() -> TypeId {
    TypeId::of::<Database>()
}

fn repository_type_id() -> TypeId {
    TypeId::of::<Repository>()
}

thread_local! {
    static DATABASE_CONSTRUCTIONS: Cell<usize> = const { Cell::new(0) };
}

fn reset_database_constructions() {
    DATABASE_CONSTRUCTIONS.set(0);
}

fn database_constructions() -> usize {
    DATABASE_CONSTRUCTIONS.get()
}

fn database_constructor<'a>(_: &'a ConstructionContext<'a>) -> ProviderFuture<'a> {
    Box::pin(async {
        DATABASE_CONSTRUCTIONS.set(DATABASE_CONSTRUCTIONS.get() + 1);
        Ok(Arc::new(Database::new()) as ErasedProvider)
    })
}

fn repository_constructor<'a>(context: &'a ConstructionContext<'a>) -> ProviderFuture<'a> {
    Box::pin(async move {
        let database = context.resolve::<Database>()?;
        Ok(Arc::new(Repository { database }) as ErasedProvider)
    })
}

static REPOSITORY_DEPENDENCIES: [DependencyDescriptor; 1] = [DependencyDescriptor::new(
    "builder::Database",
    database_type_id,
)];

inventory::submit! {
    ProviderDescriptor::new(
        ProviderKind::Provider,
        "builder::Database",
        database_type_id,
        &[],
        ProviderVisibility::Private,
        SourceLocation::new(file!(), line!(), column!()),
        database_constructor,
    )
}

inventory::submit! {
    ProviderDescriptor::new(
        ProviderKind::Repository,
        "builder::Repository",
        repository_type_id,
        &REPOSITORY_DEPENDENCIES,
        ProviderVisibility::Private,
        SourceLocation::new(file!(), line!(), column!()),
        repository_constructor,
    )
}

#[tokio::test]
async fn explicitly_constructs_a_provider_after_its_dependency_is_provided() {
    let mut builder = Mads::builder();
    builder
        .provide(Database::new())
        .expect("database insertion should work");
    builder
        .construct::<Repository>()
        .await
        .expect("explicit construction should work");
    let app = builder
        .build()
        .await
        .expect("the application graph should build");

    let repository = app
        .context()
        .resolve::<Repository>()
        .expect("repository should be available after explicit construction");
    let database = app
        .context()
        .resolve::<Database>()
        .expect("provided database should remain available");
    assert!(Arc::ptr_eq(&repository.database, &database));
}

#[tokio::test]
async fn construct_does_not_recursively_create_missing_dependencies() {
    let mut builder = Mads::builder();

    let Err(error) = builder.construct::<Repository>().await else {
        panic!("repository construction should require an explicit database");
    };

    assert_eq!(error.code(), MADS003);
    assert!(Catalog::provider_for::<Database>().is_ok());
}

#[test]
fn builder_analysis_is_repeatable_and_side_effect_free() {
    reset_database_constructions();
    let builder = Mads::builder();

    let first = builder.analyze();
    let second = builder.analyze();

    assert!(first.is_valid());
    assert!(second.is_valid());
    assert!(first.module_graph().is_none());
    assert!(second.module_graph().is_none());
    assert_eq!(database_constructions(), 0);
    assert_eq!(
        first
            .construction_plan()
            .unwrap()
            .steps()
            .iter()
            .map(ConstructionStep::type_name)
            .collect::<Vec<_>>(),
        second
            .construction_plan()
            .unwrap()
            .steps()
            .iter()
            .map(ConstructionStep::type_name)
            .collect::<Vec<_>>(),
    );
}

#[tokio::test]
async fn rooted_builder_constructs_only_the_selected_application() {
    use rooted::{
        app::{AppModule, ReachableService},
        unreachable::UnreachableService,
    };

    let mut builder = Mads::builder();
    builder.root::<AppModule>().unwrap();

    let analysis = builder.analyze();
    assert_eq!(
        analysis.module_graph().unwrap().root().type_name(),
        std::any::type_name::<AppModule>()
    );
    assert!(analysis.graph().provider::<ReachableService>().is_some());
    assert!(analysis.graph().provider::<UnreachableService>().is_none());

    let application = builder.build().await.unwrap();
    assert_eq!(
        application.module_graph().unwrap().root().type_name(),
        std::any::type_name::<AppModule>()
    );
    assert!(application.context().resolve::<ReachableService>().is_ok());
    assert!(
        application
            .context()
            .resolve::<UnreachableService>()
            .is_err()
    );
}

#[test]
fn root_can_be_selected_only_once() {
    use rooted::app::AppModule;

    let mut builder = Mads::builder();
    builder.root::<AppModule>().unwrap();
    let error = match builder.root::<AppModule>() {
        Ok(_) => panic!("a second root selection must fail"),
        Err(error) => error,
    };
    assert_eq!(error.code(), MADS008);
}

#[tokio::test]
async fn explicit_and_preconstructed_values_have_distinct_states() {
    let mut builder = Mads::builder();
    builder.provide(Database::new()).unwrap();
    builder.construct::<Repository>().await.unwrap();

    let analysis = builder.analyze();
    assert_eq!(
        analysis.graph().provider::<Database>().unwrap().state(),
        ProviderState::Provided
    );
    assert_eq!(
        analysis.graph().provider::<Repository>().unwrap().state(),
        ProviderState::Preconstructed
    );
    assert_eq!(
        analysis
            .construction_plan()
            .unwrap()
            .steps()
            .iter()
            .map(ConstructionStep::type_name)
            .collect::<Vec<_>>(),
        ["ReachableService", "UnreachableService"]
    );
}

#[tokio::test]
async fn build_constructs_the_complete_graph_in_dependency_order() {
    reset_database_constructions();
    let application = Mads::builder().build().await.unwrap();

    assert_eq!(database_constructions(), 1);
    assert!(application.context().resolve::<Database>().is_ok());
    assert!(application.context().resolve::<Repository>().is_ok());
    assert_eq!(
        application
            .construction_plan()
            .steps()
            .iter()
            .map(ConstructionStep::type_name)
            .collect::<Vec<_>>(),
        [
            "ReachableService",
            "UnreachableService",
            "builder::Database",
            "builder::Repository",
        ],
    );
}

#[tokio::test]
async fn supplied_values_suppress_matching_constructors() {
    reset_database_constructions();
    let mut builder = Mads::builder();
    builder.provide(Database::new()).unwrap();

    let application = builder.build().await.unwrap();

    assert_eq!(database_constructions(), 0);
    assert_eq!(
        application.graph().provider::<Database>().unwrap().origin(),
        ProviderOrigin::Provided
    );
    assert!(application.context().resolve::<Repository>().is_ok());
}

struct ApplicationHook(Arc<Mutex<Vec<&'static str>>>);

impl LifecycleHook for ApplicationHook {
    fn name(&self) -> &str {
        "application"
    }

    fn start<'a>(&'a self, _: &'a ApplicationContext) -> LifecycleFuture<'a> {
        Box::pin(async move {
            self.0
                .lock()
                .expect("event lock should not be poisoned")
                .push("start");
            Ok(())
        })
    }

    fn stop<'a>(&'a self, _: &'a ApplicationContext) -> LifecycleFuture<'a> {
        Box::pin(async move {
            self.0
                .lock()
                .expect("event lock should not be poisoned")
                .push("stop");
            Ok(())
        })
    }
}

struct NamedHook {
    name: &'static str,
    events: Arc<Mutex<Vec<String>>>,
}

impl NamedHook {
    fn new(name: &'static str, events: Arc<Mutex<Vec<String>>>) -> Self {
        Self { name, events }
    }
}

impl LifecycleHook for NamedHook {
    fn name(&self) -> &str {
        self.name
    }

    fn start<'a>(&'a self, _: &'a ApplicationContext) -> LifecycleFuture<'a> {
        Box::pin(async move {
            self.events
                .lock()
                .expect("event lock should not be poisoned")
                .push(format!("start:{}", self.name));
            Ok(())
        })
    }

    fn stop<'a>(&'a self, _: &'a ApplicationContext) -> LifecycleFuture<'a> {
        Box::pin(async move {
            self.events
                .lock()
                .expect("event lock should not be poisoned")
                .push(format!("stop:{}", self.name));
            Ok(())
        })
    }
}

#[tokio::test]
async fn built_application_owns_and_runs_registered_lifecycle_hooks() {
    reset_database_constructions();
    let events = Arc::new(Mutex::new(Vec::new()));
    let mut builder = Mads::builder();
    builder.lifecycle_hook(ApplicationHook(Arc::clone(&events)));
    let mut application = builder
        .build()
        .await
        .expect("the application graph should build");

    assert_eq!(database_constructions(), 1);
    assert!(
        events
            .lock()
            .expect("event lock should not be poisoned")
            .is_empty()
    );
    assert_eq!(application.state(), LifecycleState::Created);
    application.start().await.expect("application should start");
    assert_eq!(application.state(), LifecycleState::Running);
    application
        .shutdown()
        .await
        .expect("application should stop");

    assert_eq!(application.state(), LifecycleState::Stopped);
    assert_eq!(
        *events.lock().expect("event lock should not be poisoned"),
        ["start", "stop"]
    );
}

#[tokio::test]
async fn builder_groups_infrastructure_before_application_regardless_of_call_order() {
    let events = Arc::new(Mutex::new(Vec::new()));
    let mut builder = Mads::builder();
    builder.lifecycle_hook(NamedHook::new("application", Arc::clone(&events)));
    builder.__infrastructure_lifecycle_hook(
        "mads.test.infrastructure",
        NamedHook::new("infrastructure", Arc::clone(&events)),
    );
    let mut application = builder.build().await.unwrap();

    application.start().await.unwrap();
    application.shutdown().await.unwrap();

    assert_eq!(
        *events.lock().unwrap(),
        [
            "start:infrastructure",
            "start:application",
            "stop:application",
            "stop:infrastructure",
        ],
    );
}