mads-core 0.8.1

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
//! Explicit application construction and lifecycle ownership.

use std::any::TypeId;
use std::collections::VecDeque;

use crate::auto_configuration::{
    self, AutoConfigurationApplyContext, AutoConfigurationDescriptor, AutoConfigurationInputs,
};
use crate::{
    ApplicationContext, ApplicationGraph, AutoConfigurationReport, Catalog, Config,
    ConstructionContext, ConstructionPlan, ConstructionStep, Diagnostic, Error, GraphAnalysis,
    LifecycleHook, LifecycleManager, LifecycleState, MADS006, MADS008, Module, ModuleGraph,
    ProviderRegistry, Result,
    graph::{
        SatisfiedProvider, analyze_catalog, analyze_descriptors, build_module_graph,
        select_scoped_providers, validate_module_catalog,
    },
};

/// Builds an application by explicitly providing and constructing providers.
pub struct MadsBuilder {
    config: Config,
    registry: ProviderRegistry,
    satisfied: Vec<SatisfiedProvider>,
    auto_configuration_inputs: AutoConfigurationInputs,
    lifecycle: LifecycleManager,
    root: Option<ModuleRoot>,
}

impl MadsBuilder {
    /// Creates a builder with configuration available to provider constructors and resolvers.
    pub fn new(config: Config) -> Self {
        let mut registry = ProviderRegistry::new();
        registry
            .insert(config.clone())
            .expect("a new provider registry cannot already contain configuration");

        Self {
            config,
            registry,
            satisfied: vec![SatisfiedProvider::provided::<Config>()],
            auto_configuration_inputs: AutoConfigurationInputs::default(),
            lifecycle: LifecycleManager::new(),
            root: None,
        }
    }

    /// Selects the root module for scoped analysis and construction.
    #[allow(clippy::result_large_err)]
    pub fn root<M: Module>(&mut self) -> Result<&mut Self> {
        if let Some(root) = &self.root {
            return Err(root_already_selected_error(
                root.type_name,
                std::any::type_name::<M>(),
            ));
        }
        self.root = Some(ModuleRoot::of::<M>());
        Ok(self)
    }

    /// Provides a concrete application-scoped value.
    #[allow(clippy::result_large_err)]
    pub fn provide<T>(&mut self, value: T) -> Result<&mut Self>
    where
        T: Send + Sync + 'static,
    {
        self.registry.insert(value)?;
        self.satisfied.push(SatisfiedProvider::provided::<T>());
        Ok(self)
    }

    /// Constructs exactly one statically declared provider using currently provided dependencies.
    #[allow(clippy::result_large_err)]
    pub async fn construct<T>(&mut self) -> Result<&mut Self>
    where
        T: Send + Sync + 'static,
    {
        let descriptor = Catalog::provider_for::<T>()?;
        let value = {
            let context = ConstructionContext::new(&self.registry, &self.config);
            (descriptor.constructor())(&context).await?
        };

        self.registry
            .insert_erased(descriptor.type_id(), descriptor.type_name(), value)?;
        self.satisfied
            .push(SatisfiedProvider::preconstructed::<T>());
        Ok(self)
    }

    /// Analyzes the complete provider graph without invoking constructors.
    pub fn analyze(&self) -> GraphAnalysis {
        self.analyze_builder().public
    }

    /// Registers a private input for an official auto-configuration integration.
    #[doc(hidden)]
    pub fn __auto_configuration_input<T: Send + Sync + 'static>(
        &mut self,
        identifier: &'static str,
        input: T,
    ) -> bool {
        self.auto_configuration_inputs.insert(identifier, input)
    }

    /// Registers a hook that runs when the completed application starts and stops.
    pub fn lifecycle_hook<H>(&mut self, hook: H) -> &mut Self
    where
        H: LifecycleHook + 'static,
    {
        self.lifecycle.add_hook(hook);
        self
    }

    /// Registers a framework-owned infrastructure lifecycle hook.
    #[doc(hidden)]
    pub fn __infrastructure_lifecycle_hook<H>(&mut self, owner: &'static str, hook: H) -> &mut Self
    where
        H: LifecycleHook + 'static,
    {
        self.lifecycle.add_infrastructure_hook(owner, hook);
        self
    }

    /// Validates and automatically constructs the complete application graph.
    #[allow(clippy::result_large_err)]
    pub async fn build(mut self) -> Result<Mads> {
        let BuilderAnalysis {
            public,
            selected,
            failure,
        } = self.analyze_builder();
        if !public.is_valid() {
            return Err(build_analysis_error(public, failure));
        }
        let (graph, construction_plan, auto_configurations, module_graph) =
            public.into_valid_parts()?;

        for descriptor in selected {
            let context = AutoConfigurationApplyContext::new(
                descriptor.identifier(),
                &self.config,
                &self.auto_configuration_inputs,
                module_graph.as_ref(),
            );
            let contribution = (descriptor.applier())(&context)?;
            let (provider, hooks) = contribution.into_parts();
            self.registry.insert_erased(
                descriptor.output_type_id(),
                descriptor.output_type_name(),
                provider,
            )?;
            for hook in hooks {
                self.lifecycle
                    .add_boxed_infrastructure_hook(descriptor.identifier(), hook);
            }
        }

        for step in construction_plan.steps() {
            let value = {
                let context = ConstructionContext::new(&self.registry, &self.config);
                (step.descriptor().constructor())(&context)
                    .await
                    .map_err(|source| provider_construction_error(step, &graph, source))?
            };
            self.registry
                .insert_erased(step.type_id(), step.type_name, value)?;
        }

        Ok(Mads {
            context: ApplicationContext::new(self.registry, self.config),
            lifecycle: self.lifecycle,
            graph,
            construction_plan,
            auto_configurations,
            module_graph,
        })
    }

    fn analyze_builder(&self) -> BuilderAnalysis {
        let providers = Catalog::providers();
        let Some(root) = &self.root else {
            return self.analyze_complete_catalog(&providers);
        };

        let modules = Catalog::modules();
        let mut module_graph = match build_module_graph(root.type_id, &modules) {
            Ok(module_graph) => module_graph,
            Err(error) => {
                return BuilderAnalysis {
                    public: GraphAnalysis::invalid(error.diagnostics().to_vec()),
                    selected: Vec::new(),
                    failure: None,
                };
            }
        };
        let initial_scope = select_scoped_providers(&module_graph, &providers, &self.satisfied);
        let auto_configuration = auto_configuration::analyze_parts(
            &auto_configuration::descriptors(),
            &initial_scope.descriptors,
            &self.satisfied,
            &self.config,
            &self.auto_configuration_inputs,
            Some(&module_graph),
        );
        let mut satisfied = self.satisfied.clone();
        satisfied.extend(auto_configuration.virtual_satisfied);

        let scoped = select_scoped_providers(&module_graph, &providers, &satisfied);
        let mut covered_missing = auto_configuration.covered_missing;
        for type_id in &scoped.covered_missing {
            if !covered_missing.contains(type_id) {
                covered_missing.push(*type_id);
            }
        }
        let mut public = analyze_descriptors(&scoped.descriptors, &satisfied, &covered_missing);
        public.prepend_diagnostics(scoped.diagnostics);
        public.append_diagnostics(auto_configuration.diagnostics);
        public.auto_configurations = auto_configuration.reports;
        module_graph.set_provider_ownership(scoped.ownership);
        public.set_module_graph(module_graph);

        BuilderAnalysis {
            public,
            selected: auto_configuration.selected,
            failure: auto_configuration.failure,
        }
    }

    fn analyze_complete_catalog(
        &self,
        providers: &[&'static crate::ProviderDescriptor],
    ) -> BuilderAnalysis {
        let module_diagnostics = validate_module_catalog(&Catalog::modules())
            .err()
            .map_or_else(Vec::new, |error| error.diagnostics().to_vec());
        let auto_configuration = auto_configuration::analyze_parts(
            &auto_configuration::descriptors(),
            providers,
            &self.satisfied,
            &self.config,
            &self.auto_configuration_inputs,
            None,
        );
        let mut satisfied = self.satisfied.clone();
        satisfied.extend(auto_configuration.virtual_satisfied);

        let mut public = analyze_catalog(&satisfied, &auto_configuration.covered_missing);
        public.prepend_diagnostics(module_diagnostics);
        public.auto_configurations = auto_configuration.reports;
        public.append_diagnostics(auto_configuration.diagnostics);

        BuilderAnalysis {
            public,
            selected: auto_configuration.selected,
            failure: auto_configuration.failure,
        }
    }
}

struct ModuleRoot {
    type_id: TypeId,
    type_name: &'static str,
}

impl ModuleRoot {
    fn of<M: Module>() -> Self {
        Self {
            type_id: TypeId::of::<M>(),
            type_name: std::any::type_name::<M>(),
        }
    }
}

struct BuilderAnalysis {
    public: GraphAnalysis,
    selected: Vec<&'static AutoConfigurationDescriptor>,
    failure: Option<Error>,
}

/// An explicitly constructed application and its lifecycle state.
pub struct Mads {
    context: ApplicationContext,
    lifecycle: LifecycleManager,
    graph: ApplicationGraph,
    construction_plan: ConstructionPlan,
    auto_configurations: Vec<AutoConfigurationReport>,
    module_graph: Option<ModuleGraph>,
}

impl Mads {
    /// Creates a builder with empty configuration.
    pub fn builder() -> MadsBuilder {
        Self::builder_with_config(Config::empty())
    }

    /// Creates a builder with caller-supplied configuration.
    pub fn builder_with_config(config: Config) -> MadsBuilder {
        MadsBuilder::new(config)
    }

    /// Returns the application's current lifecycle state.
    pub const fn state(&self) -> LifecycleState {
        self.lifecycle.state()
    }

    /// Returns the immutable application context.
    pub const fn context(&self) -> &ApplicationContext {
        &self.context
    }

    /// Returns the immutable graph validated before construction.
    pub const fn graph(&self) -> &ApplicationGraph {
        &self.graph
    }

    /// Returns the deterministic provider construction plan that was executed.
    pub const fn construction_plan(&self) -> &ConstructionPlan {
        &self.construction_plan
    }

    /// Returns reports for official auto-configurations evaluated before the build.
    pub fn auto_configurations(&self) -> &[AutoConfigurationReport] {
        &self.auto_configurations
    }

    /// Returns the rooted module graph, or `None` for a complete-catalog build.
    pub const fn module_graph(&self) -> Option<&ModuleGraph> {
        self.module_graph.as_ref()
    }

    /// Starts registered lifecycle hooks.
    #[allow(clippy::result_large_err)]
    pub async fn start(&mut self) -> Result<()> {
        self.lifecycle.start(&self.context).await
    }

    /// Stops registered lifecycle hooks in reverse registration order.
    #[allow(clippy::result_large_err)]
    pub async fn shutdown(&mut self) -> Result<()> {
        self.lifecycle.shutdown(&self.context).await
    }
}

fn root_already_selected_error(existing: &'static str, attempted: &'static str) -> Error {
    Error::new(
        Diagnostic::new(
            MADS008,
            "application root already selected",
            format!("a builder already selected `{existing}` and cannot select another root"),
        )
        .with_subject(attempted),
    )
}

fn build_analysis_error(public: GraphAnalysis, failure: Option<Error>) -> Error {
    let GraphAnalysis { diagnostics, .. } = public;
    if let Some(failure) = failure {
        let primary = failure.diagnostic().clone();
        let mut primary_removed = false;
        let related = diagnostics.into_iter().filter(|diagnostic| {
            if !primary_removed && *diagnostic == primary {
                primary_removed = true;
                false
            } else {
                true
            }
        });
        return failure.with_related_diagnostics(related);
    }

    let mut diagnostics = diagnostics.into_iter();
    let primary = diagnostics
        .next()
        .expect("invalid analysis has diagnostics");
    Error::from_diagnostics(primary, diagnostics)
}

fn provider_construction_error(
    step: &ConstructionStep,
    graph: &ApplicationGraph,
    source: Error,
) -> Error {
    let mut diagnostic = Diagnostic::new(
        MADS006,
        "provider construction failed",
        "a provider constructor returned an error",
    )
    .with_subject(step.type_name())
    .with_location(step.location());
    if let Some(path) = consumer_path(graph, step) {
        diagnostic = diagnostic.with_suggestion(format!("construction path: {path}"));
    }
    Error::with_source(diagnostic, source)
}

fn consumer_path(graph: &ApplicationGraph, failing_step: &ConstructionStep) -> Option<String> {
    if !graph
        .dependencies
        .iter()
        .any(|edge| edge.dependency_type_id == failing_step.type_id())
    {
        return None;
    }

    let mut roots = graph
        .providers
        .iter()
        .enumerate()
        .filter(|(_, provider)| {
            !graph
                .dependencies
                .iter()
                .any(|edge| edge.dependency_type_id == provider.type_id)
        })
        .map(|(index, _)| index)
        .collect::<Vec<_>>();
    roots.sort_by(|left, right| provider_order(graph, *left, *right));

    let mut visited = vec![false; graph.providers.len()];
    let mut queue = VecDeque::new();
    for root in roots {
        visited[root] = true;
        queue.push_back(vec![root]);
    }

    while let Some(path) = queue.pop_front() {
        let provider = *path.last().expect("paths are never empty");
        if graph.providers[provider].type_id == failing_step.type_id() {
            return Some(
                path.iter()
                    .map(|index| graph.providers[*index].type_name)
                    .collect::<Vec<_>>()
                    .join(" -> "),
            );
        }

        let mut dependencies = graph
            .dependencies
            .iter()
            .filter(|edge| edge.provider_type_id == graph.providers[provider].type_id)
            .filter_map(|edge| {
                graph
                    .providers
                    .iter()
                    .position(|candidate| candidate.type_id == edge.dependency_type_id)
            })
            .collect::<Vec<_>>();
        dependencies.sort_by(|left, right| provider_order(graph, *left, *right));
        for dependency in dependencies {
            if !visited[dependency] {
                visited[dependency] = true;
                let mut path = path.clone();
                path.push(dependency);
                queue.push_back(path);
            }
        }
    }

    None
}

fn provider_order(graph: &ApplicationGraph, left: usize, right: usize) -> std::cmp::Ordering {
    let left = &graph.providers[left];
    let right = &graph.providers[right];
    left.type_name
        .cmp(right.type_name)
        .then_with(|| left.origin.cmp(&right.origin))
        .then_with(|| match (left.location, right.location) {
            (Some(left), Some(right)) => left
                .file
                .cmp(right.file)
                .then_with(|| left.line.cmp(&right.line))
                .then_with(|| left.column.cmp(&right.column)),
            (None, Some(_)) => std::cmp::Ordering::Less,
            (Some(_), None) => std::cmp::Ordering::Greater,
            (None, None) => std::cmp::Ordering::Equal,
        })
}