Skip to main content

mads_core/
builder.rs

1//! Explicit application construction and lifecycle ownership.
2
3use std::any::TypeId;
4use std::collections::VecDeque;
5
6use crate::auto_configuration::{
7    self, AutoConfigurationApplyContext, AutoConfigurationDescriptor, AutoConfigurationInputs,
8};
9use crate::{
10    ApplicationContext, ApplicationGraph, AutoConfigurationReport, Catalog, Config,
11    ConstructionContext, ConstructionPlan, ConstructionStep, Diagnostic, Error, GraphAnalysis,
12    LifecycleHook, LifecycleManager, LifecycleState, MADS006, MADS008, Module, ModuleGraph,
13    ProviderContribution, ProviderDescriptor, ProviderRegistry, Result,
14    graph::{
15        SatisfiedProvider, analyze_catalog, analyze_descriptors, build_module_graph,
16        select_focused_providers, select_scoped_providers, validate_module_catalog,
17    },
18};
19
20/// Builds an application by explicitly providing and constructing providers.
21pub struct MadsBuilder {
22    config: Config,
23    registry: ProviderRegistry,
24    satisfied: Vec<SatisfiedProvider>,
25    auto_configuration_inputs: AutoConfigurationInputs,
26    lifecycle: LifecycleManager,
27    root: Option<ModuleRoot>,
28    focus: Option<(TypeId, &'static str)>,
29    required_supplies: Vec<TypeId>,
30}
31
32impl MadsBuilder {
33    /// Creates a builder with configuration available to provider constructors and resolvers.
34    pub fn new(config: Config) -> Self {
35        let mut registry = ProviderRegistry::new();
36        registry
37            .insert(config.clone())
38            .expect("a new provider registry cannot already contain configuration");
39
40        Self {
41            config,
42            registry,
43            satisfied: vec![SatisfiedProvider::provided::<Config>()],
44            auto_configuration_inputs: AutoConfigurationInputs::default(),
45            lifecycle: LifecycleManager::new(),
46            root: None,
47            focus: None,
48            required_supplies: Vec::new(),
49        }
50    }
51
52    /// Selects the root module for scoped analysis and construction.
53    #[allow(clippy::result_large_err)]
54    pub fn root<M: Module>(&mut self) -> Result<&mut Self> {
55        if let Some((_, name)) = self.focus {
56            return Err(root_already_selected_error(
57                name,
58                std::any::type_name::<M>(),
59            ));
60        }
61        if let Some(root) = &self.root {
62            return Err(root_already_selected_error(
63                root.type_name,
64                std::any::type_name::<M>(),
65            ));
66        }
67        self.root = Some(ModuleRoot::of::<M>());
68        Ok(self)
69    }
70
71    /// Selects a registered dependency chain for an official test fixture.
72    #[doc(hidden)]
73    #[allow(clippy::result_large_err)]
74    pub fn __test_focus<T: Send + Sync + 'static>(&mut self) -> Result<&mut Self> {
75        if let Some(root) = &self.root {
76            return Err(root_already_selected_error(
77                root.type_name,
78                std::any::type_name::<T>(),
79            ));
80        }
81        if let Some((_, name)) = self.focus {
82            return Err(root_already_selected_error(
83                name,
84                std::any::type_name::<T>(),
85            ));
86        }
87        self.focus = Some((TypeId::of::<T>(), std::any::type_name::<T>()));
88        Ok(self)
89    }
90
91    /// Requires a fixture-owned value rather than a registered constructor.
92    #[doc(hidden)]
93    pub fn __test_require_provided<T: Send + Sync + 'static>(&mut self) -> &mut Self {
94        self.required_supplies.push(TypeId::of::<T>());
95        self
96    }
97
98    /// Provides a concrete application-scoped value.
99    #[allow(clippy::result_large_err)]
100    pub fn provide<T>(&mut self, value: T) -> Result<&mut Self>
101    where
102        T: Send + Sync + 'static,
103    {
104        self.registry.insert(value)?;
105        self.satisfied.push(SatisfiedProvider::provided::<T>());
106        Ok(self)
107    }
108
109    /// Constructs exactly one statically declared provider using currently provided dependencies.
110    #[allow(clippy::result_large_err)]
111    pub async fn construct<T>(&mut self) -> Result<&mut Self>
112    where
113        T: Send + Sync + 'static,
114    {
115        let descriptor = Catalog::provider_for::<T>()?;
116        let contribution = self.invoke_provider(descriptor).await?;
117        self.apply_provider_contribution(descriptor, contribution)?;
118        self.satisfied
119            .push(SatisfiedProvider::preconstructed::<T>());
120        Ok(self)
121    }
122
123    /// Analyzes the complete provider graph without invoking constructors.
124    pub fn analyze(&self) -> GraphAnalysis {
125        self.analyze_builder().public
126    }
127
128    /// Registers a private input for an official auto-configuration integration.
129    #[doc(hidden)]
130    pub fn __auto_configuration_input<T: Send + Sync + 'static>(
131        &mut self,
132        identifier: &'static str,
133        input: T,
134    ) -> bool {
135        self.auto_configuration_inputs.insert(identifier, input)
136    }
137
138    /// Registers a hook that runs when the completed application starts and stops.
139    pub fn lifecycle_hook<H>(&mut self, hook: H) -> &mut Self
140    where
141        H: LifecycleHook + 'static,
142    {
143        self.lifecycle.add_hook(hook);
144        self
145    }
146
147    /// Registers a framework-owned infrastructure lifecycle hook.
148    #[doc(hidden)]
149    pub fn __infrastructure_lifecycle_hook<H>(&mut self, owner: &'static str, hook: H) -> &mut Self
150    where
151        H: LifecycleHook + 'static,
152    {
153        self.lifecycle.add_infrastructure_hook(owner, hook);
154        self
155    }
156
157    /// Validates and automatically constructs the complete application graph.
158    #[allow(clippy::result_large_err)]
159    pub async fn build(mut self) -> Result<Mads> {
160        let BuilderAnalysis {
161            public,
162            selected,
163            failure,
164        } = self.analyze_builder();
165        if !public.is_valid() {
166            return Err(build_analysis_error(public, failure));
167        }
168        let (graph, construction_plan, auto_configurations, module_graph) =
169            public.into_valid_parts()?;
170
171        for descriptor in selected {
172            let context = AutoConfigurationApplyContext::new(
173                descriptor.identifier(),
174                &self.config,
175                &self.auto_configuration_inputs,
176                module_graph.as_ref(),
177            );
178            let contribution = (descriptor.applier())(&context)?;
179            let (provider, hooks) = contribution.into_parts();
180            self.registry.insert_erased(
181                descriptor.output_type_id(),
182                descriptor.output_type_name(),
183                provider,
184            )?;
185            for hook in hooks {
186                self.lifecycle
187                    .add_boxed_infrastructure_hook(descriptor.identifier(), hook);
188            }
189        }
190
191        for step in construction_plan.steps() {
192            let descriptor = step.descriptor();
193            let contribution = self
194                .invoke_provider(descriptor)
195                .await
196                .map_err(|source| provider_construction_error(step, &graph, source))?;
197            self.apply_provider_contribution(descriptor, contribution)?;
198        }
199
200        Ok(Mads {
201            context: ApplicationContext::new(self.registry, self.config),
202            lifecycle: self.lifecycle,
203            graph,
204            construction_plan,
205            auto_configurations,
206            module_graph,
207        })
208    }
209
210    fn analyze_builder(&self) -> BuilderAnalysis {
211        let providers = Catalog::providers();
212        if let Some((target, name)) = self.focus {
213            return self.analyze_focused(target, name, &providers);
214        }
215        let Some(root) = &self.root else {
216            return self.analyze_complete_catalog(&providers);
217        };
218
219        let modules = Catalog::modules();
220        let mut module_graph = match build_module_graph(root.type_id, &modules) {
221            Ok(module_graph) => module_graph,
222            Err(error) => {
223                return BuilderAnalysis {
224                    public: GraphAnalysis::invalid(error.diagnostics().to_vec()),
225                    selected: Vec::new(),
226                    failure: None,
227                };
228            }
229        };
230        let initial_scope = select_scoped_providers(&module_graph, &providers, &self.satisfied);
231        let auto_configuration = auto_configuration::analyze_parts(
232            &auto_configuration::descriptors(),
233            &initial_scope.descriptors,
234            &self.satisfied,
235            &self.config,
236            &self.auto_configuration_inputs,
237            Some(&module_graph),
238        );
239        let mut satisfied = self.satisfied.clone();
240        satisfied.extend(auto_configuration.virtual_satisfied);
241
242        let scoped = select_scoped_providers(&module_graph, &providers, &satisfied);
243        let mut covered_missing = auto_configuration.covered_missing;
244        for type_id in &scoped.covered_missing {
245            if !covered_missing.contains(type_id) {
246                covered_missing.push(*type_id);
247            }
248        }
249        let mut public = analyze_descriptors(&scoped.descriptors, &satisfied, &covered_missing);
250        public.prepend_diagnostics(scoped.diagnostics);
251        public.append_diagnostics(auto_configuration.diagnostics);
252        public.auto_configurations = auto_configuration.reports;
253        module_graph.set_provider_ownership(scoped.ownership);
254        public.set_module_graph(module_graph);
255
256        BuilderAnalysis {
257            public,
258            selected: auto_configuration.selected,
259            failure: auto_configuration.failure,
260        }
261    }
262
263    fn analyze_focused(
264        &self,
265        target: TypeId,
266        name: &'static str,
267        providers: &[&'static ProviderDescriptor],
268    ) -> BuilderAnalysis {
269        let initial = select_focused_providers(
270            target,
271            name,
272            providers,
273            &self.satisfied,
274            &self.required_supplies,
275            &[],
276        );
277        let selected_providers = providers
278            .iter()
279            .copied()
280            .filter(|descriptor| {
281                initial
282                    .graph()
283                    .providers
284                    .iter()
285                    .any(|node| node.type_id == descriptor.type_id())
286            })
287            .collect::<Vec<_>>();
288        let automatic = auto_configuration::descriptors()
289            .into_iter()
290            .filter(|descriptor| {
291                let output = descriptor.output_type_id();
292                !self.required_supplies.contains(&output)
293                    && initial.graph().providers.iter().any(|node| {
294                        node.type_id == output
295                            || node
296                                .declared_dependencies
297                                .iter()
298                                .any(|dependency| dependency.type_id() == output)
299                    })
300            })
301            .collect::<Vec<_>>();
302        let automatic = auto_configuration::analyze_parts(
303            &automatic,
304            &selected_providers,
305            &self.satisfied,
306            &self.config,
307            &self.auto_configuration_inputs,
308            None,
309        );
310        let mut satisfied = self.satisfied.clone();
311        satisfied.extend(automatic.virtual_satisfied);
312        let mut public = select_focused_providers(
313            target,
314            name,
315            providers,
316            &satisfied,
317            &self.required_supplies,
318            &automatic.covered_missing,
319        );
320        public.append_diagnostics(automatic.diagnostics);
321        public.auto_configurations = automatic.reports;
322        BuilderAnalysis {
323            public,
324            selected: automatic.selected,
325            failure: automatic.failure,
326        }
327    }
328
329    async fn invoke_provider(
330        &self,
331        descriptor: &'static ProviderDescriptor,
332    ) -> Result<ProviderContribution> {
333        let context = ConstructionContext::new(&self.registry, &self.config);
334        if let Some(constructor) = descriptor.lifecycle_constructor() {
335            constructor(&context).await
336        } else {
337            (descriptor.constructor())(&context)
338                .await
339                .map(ProviderContribution::from_provider)
340        }
341    }
342
343    fn apply_provider_contribution(
344        &mut self,
345        descriptor: &'static ProviderDescriptor,
346        contribution: ProviderContribution,
347    ) -> Result<()> {
348        let (provider, registrations) = contribution.into_parts();
349        self.registry
350            .insert_erased(descriptor.type_id(), descriptor.type_name(), provider)?;
351        for registration in registrations {
352            self.lifecycle.add_registration(registration);
353        }
354        Ok(())
355    }
356
357    fn analyze_complete_catalog(
358        &self,
359        providers: &[&'static crate::ProviderDescriptor],
360    ) -> BuilderAnalysis {
361        let module_diagnostics = validate_module_catalog(&Catalog::modules())
362            .err()
363            .map_or_else(Vec::new, |error| error.diagnostics().to_vec());
364        let auto_configuration = auto_configuration::analyze_parts(
365            &auto_configuration::descriptors(),
366            providers,
367            &self.satisfied,
368            &self.config,
369            &self.auto_configuration_inputs,
370            None,
371        );
372        let mut satisfied = self.satisfied.clone();
373        satisfied.extend(auto_configuration.virtual_satisfied);
374
375        let mut public = analyze_catalog(&satisfied, &auto_configuration.covered_missing);
376        public.prepend_diagnostics(module_diagnostics);
377        public.auto_configurations = auto_configuration.reports;
378        public.append_diagnostics(auto_configuration.diagnostics);
379
380        BuilderAnalysis {
381            public,
382            selected: auto_configuration.selected,
383            failure: auto_configuration.failure,
384        }
385    }
386}
387
388struct ModuleRoot {
389    type_id: TypeId,
390    type_name: &'static str,
391}
392
393impl ModuleRoot {
394    fn of<M: Module>() -> Self {
395        Self {
396            type_id: TypeId::of::<M>(),
397            type_name: std::any::type_name::<M>(),
398        }
399    }
400}
401
402struct BuilderAnalysis {
403    public: GraphAnalysis,
404    selected: Vec<&'static AutoConfigurationDescriptor>,
405    failure: Option<Error>,
406}
407
408/// An explicitly constructed application and its lifecycle state.
409pub struct Mads {
410    context: ApplicationContext,
411    lifecycle: LifecycleManager,
412    graph: ApplicationGraph,
413    construction_plan: ConstructionPlan,
414    auto_configurations: Vec<AutoConfigurationReport>,
415    module_graph: Option<ModuleGraph>,
416}
417
418impl Mads {
419    /// Creates a builder with empty configuration.
420    pub fn builder() -> MadsBuilder {
421        Self::builder_with_config(Config::empty())
422    }
423
424    /// Creates a builder with caller-supplied configuration.
425    pub fn builder_with_config(config: Config) -> MadsBuilder {
426        MadsBuilder::new(config)
427    }
428
429    /// Returns the application's current lifecycle state.
430    pub const fn state(&self) -> LifecycleState {
431        self.lifecycle.state()
432    }
433
434    /// Returns the immutable application context.
435    pub const fn context(&self) -> &ApplicationContext {
436        &self.context
437    }
438
439    /// Returns the immutable graph validated before construction.
440    pub const fn graph(&self) -> &ApplicationGraph {
441        &self.graph
442    }
443
444    /// Returns the deterministic provider construction plan that was executed.
445    pub const fn construction_plan(&self) -> &ConstructionPlan {
446        &self.construction_plan
447    }
448
449    /// Returns reports for official auto-configurations evaluated before the build.
450    pub fn auto_configurations(&self) -> &[AutoConfigurationReport] {
451        &self.auto_configurations
452    }
453
454    /// Returns the rooted module graph, or `None` for a complete-catalog build.
455    pub const fn module_graph(&self) -> Option<&ModuleGraph> {
456        self.module_graph.as_ref()
457    }
458
459    /// Starts registered lifecycle hooks.
460    #[allow(clippy::result_large_err)]
461    pub async fn start(&mut self) -> Result<()> {
462        self.lifecycle.start(&self.context).await
463    }
464
465    /// Stops registered lifecycle hooks in reverse registration order.
466    #[allow(clippy::result_large_err)]
467    pub async fn shutdown(&mut self) -> Result<()> {
468        self.lifecycle.shutdown(&self.context).await
469    }
470}
471
472fn root_already_selected_error(existing: &'static str, attempted: &'static str) -> Error {
473    Error::new(
474        Diagnostic::new(
475            MADS008,
476            "application root already selected",
477            format!("a builder already selected `{existing}` and cannot select another root"),
478        )
479        .with_subject(attempted),
480    )
481}
482
483fn build_analysis_error(public: GraphAnalysis, failure: Option<Error>) -> Error {
484    let GraphAnalysis { diagnostics, .. } = public;
485    if let Some(failure) = failure {
486        let primary = failure.diagnostic().clone();
487        let mut primary_removed = false;
488        let related = diagnostics.into_iter().filter(|diagnostic| {
489            if !primary_removed && *diagnostic == primary {
490                primary_removed = true;
491                false
492            } else {
493                true
494            }
495        });
496        return failure.with_related_diagnostics(related);
497    }
498
499    let mut diagnostics = diagnostics.into_iter();
500    let primary = diagnostics
501        .next()
502        .expect("invalid analysis has diagnostics");
503    Error::from_diagnostics(primary, diagnostics)
504}
505
506fn provider_construction_error(
507    step: &ConstructionStep,
508    graph: &ApplicationGraph,
509    source: Error,
510) -> Error {
511    let mut diagnostic = Diagnostic::new(
512        MADS006,
513        "provider construction failed",
514        "a provider constructor returned an error",
515    )
516    .with_subject(step.type_name())
517    .with_location(step.location());
518    if let Some(path) = consumer_path(graph, step) {
519        diagnostic = diagnostic.with_suggestion(format!("construction path: {path}"));
520    }
521    Error::with_source(diagnostic, source)
522}
523
524fn consumer_path(graph: &ApplicationGraph, failing_step: &ConstructionStep) -> Option<String> {
525    if !graph
526        .dependencies
527        .iter()
528        .any(|edge| edge.dependency_type_id == failing_step.type_id())
529    {
530        return None;
531    }
532
533    let mut roots = graph
534        .providers
535        .iter()
536        .enumerate()
537        .filter(|(_, provider)| {
538            !graph
539                .dependencies
540                .iter()
541                .any(|edge| edge.dependency_type_id == provider.type_id)
542        })
543        .map(|(index, _)| index)
544        .collect::<Vec<_>>();
545    roots.sort_by(|left, right| provider_order(graph, *left, *right));
546
547    let mut visited = vec![false; graph.providers.len()];
548    let mut queue = VecDeque::new();
549    for root in roots {
550        visited[root] = true;
551        queue.push_back(vec![root]);
552    }
553
554    while let Some(path) = queue.pop_front() {
555        let provider = *path.last().expect("paths are never empty");
556        if graph.providers[provider].type_id == failing_step.type_id() {
557            return Some(
558                path.iter()
559                    .map(|index| graph.providers[*index].type_name)
560                    .collect::<Vec<_>>()
561                    .join(" -> "),
562            );
563        }
564
565        let mut dependencies = graph
566            .dependencies
567            .iter()
568            .filter(|edge| edge.provider_type_id == graph.providers[provider].type_id)
569            .filter_map(|edge| {
570                graph
571                    .providers
572                    .iter()
573                    .position(|candidate| candidate.type_id == edge.dependency_type_id)
574            })
575            .collect::<Vec<_>>();
576        dependencies.sort_by(|left, right| provider_order(graph, *left, *right));
577        for dependency in dependencies {
578            if !visited[dependency] {
579                visited[dependency] = true;
580                let mut path = path.clone();
581                path.push(dependency);
582                queue.push_back(path);
583            }
584        }
585    }
586
587    None
588}
589
590fn provider_order(graph: &ApplicationGraph, left: usize, right: usize) -> std::cmp::Ordering {
591    let left = &graph.providers[left];
592    let right = &graph.providers[right];
593    left.type_name
594        .cmp(right.type_name)
595        .then_with(|| left.origin.cmp(&right.origin))
596        .then_with(|| match (left.location, right.location) {
597            (Some(left), Some(right)) => left
598                .file
599                .cmp(right.file)
600                .then_with(|| left.line.cmp(&right.line))
601                .then_with(|| left.column.cmp(&right.column)),
602            (None, Some(_)) => std::cmp::Ordering::Less,
603            (Some(_), None) => std::cmp::Ordering::Greater,
604            (None, None) => std::cmp::Ordering::Equal,
605        })
606}