mads-core 0.9.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
//! Immutable records used to inspect a provider graph.

use std::any::TypeId;

use crate::{
    AutoConfigurationReport, DependencyDescriptor, Diagnostic, ProviderDescriptor, ProviderKind,
    ProviderVisibility, SourceLocation,
};

use super::module::ModuleGraph;

/// Describes how a provider enters an application graph.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum ProviderOrigin {
    /// A value supplied directly by the application.
    Provided,
    /// A value supplied by an official auto-configuration integration.
    AutoConfiguration,
    /// A service declaration.
    Service,
    /// A repository declaration.
    Repository,
    /// A general provider declaration.
    Provider,
}

impl From<ProviderKind> for ProviderOrigin {
    fn from(kind: ProviderKind) -> Self {
        match kind {
            ProviderKind::Service => Self::Service,
            ProviderKind::Repository => Self::Repository,
            ProviderKind::Provider => Self::Provider,
        }
    }
}

/// Describes how a provider value is satisfied for a specific build.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ProviderState {
    /// A value supplied directly by the application.
    Provided,
    /// A value manually constructed before automatic construction.
    Preconstructed,
    /// A value selected from an official auto-configuration integration.
    AutoConfigured,
    /// A statically declared provider awaiting construction.
    Planned,
}

#[allow(dead_code)]
#[derive(Clone, Copy)]
pub(crate) struct SatisfiedProvider {
    pub(crate) type_id: TypeId,
    pub(crate) type_name: &'static str,
    pub(crate) state: ProviderState,
}

#[allow(dead_code)]
impl SatisfiedProvider {
    pub(crate) fn provided<T>() -> Self
    where
        T: Send + Sync + 'static,
    {
        Self {
            type_id: TypeId::of::<T>(),
            type_name: std::any::type_name::<T>(),
            state: ProviderState::Provided,
        }
    }

    pub(crate) fn preconstructed<T>() -> Self
    where
        T: Send + Sync + 'static,
    {
        Self {
            type_id: TypeId::of::<T>(),
            type_name: std::any::type_name::<T>(),
            state: ProviderState::Preconstructed,
        }
    }

    pub(crate) fn auto_configured(type_id: TypeId, type_name: &'static str) -> Self {
        Self {
            type_id,
            type_name,
            state: ProviderState::AutoConfigured,
        }
    }
}

/// Immutable metadata for one provider in an application graph.
pub struct ProviderNode {
    pub(crate) type_id: TypeId,
    pub(crate) type_name: &'static str,
    pub(crate) origin: ProviderOrigin,
    pub(crate) visibility: ProviderVisibility,
    pub(crate) state: ProviderState,
    pub(crate) location: Option<SourceLocation>,
    pub(crate) declared_dependencies: &'static [DependencyDescriptor],
}

impl ProviderNode {
    /// Returns the provider's stable output type name.
    pub const fn type_name(&self) -> &str {
        self.type_name
    }

    /// Returns how the provider enters the application graph.
    pub const fn origin(&self) -> ProviderOrigin {
        self.origin
    }

    /// Returns the provider declaration's visibility metadata.
    pub const fn visibility(&self) -> ProviderVisibility {
        self.visibility
    }

    /// Returns the provider's current satisfaction state.
    pub const fn state(&self) -> ProviderState {
        self.state
    }

    /// Returns the provider declaration location when it is statically declared.
    pub const fn location(&self) -> Option<SourceLocation> {
        self.location
    }

    /// Returns the provider's declared dependencies in source declaration order.
    pub const fn declared_dependencies(&self) -> &[DependencyDescriptor] {
        self.declared_dependencies
    }
}

/// A resolved dependency from one provider to a required type.
pub struct DependencyEdge {
    #[allow(dead_code)]
    pub(crate) provider_type_id: TypeId,
    pub(crate) provider_type_name: &'static str,
    #[allow(dead_code)]
    pub(crate) dependency_type_id: TypeId,
    pub(crate) dependency_type_name: &'static str,
}

impl DependencyEdge {
    /// Returns the stable type name of the provider declaring the dependency.
    pub const fn provider_type_name(&self) -> &str {
        self.provider_type_name
    }

    /// Returns the stable type name of the required dependency.
    pub const fn dependency_type_name(&self) -> &str {
        self.dependency_type_name
    }
}

/// An immutable ordered provider graph.
pub struct ApplicationGraph {
    pub(crate) providers: Vec<ProviderNode>,
    pub(crate) dependencies: Vec<DependencyEdge>,
}

impl ApplicationGraph {
    /// Returns providers in deterministic graph order.
    pub fn providers(&self) -> &[ProviderNode] {
        &self.providers
    }

    /// Returns resolved dependency edges in deterministic graph order.
    pub fn dependencies(&self) -> &[DependencyEdge] {
        &self.dependencies
    }

    /// Returns the provider node for `T`, if the graph contains one.
    pub fn provider<T>(&self) -> Option<&ProviderNode>
    where
        T: Send + Sync + 'static,
    {
        let type_id = TypeId::of::<T>();
        self.providers
            .iter()
            .find(|provider| provider.type_id == type_id)
    }
}

/// One statically declared provider in construction order.
pub struct ConstructionStep {
    #[allow(dead_code)]
    pub(crate) type_id: TypeId,
    pub(crate) type_name: &'static str,
    pub(crate) origin: ProviderOrigin,
    pub(crate) location: SourceLocation,
    #[allow(dead_code)]
    pub(crate) descriptor: &'static ProviderDescriptor,
}

impl ConstructionStep {
    pub(crate) const fn type_id(&self) -> TypeId {
        self.type_id
    }

    pub(crate) const fn descriptor(&self) -> &'static ProviderDescriptor {
        self.descriptor
    }

    /// Returns the underlying descriptor for framework integration and testing.
    #[doc(hidden)]
    pub const fn __descriptor(&self) -> &'static ProviderDescriptor {
        self.descriptor
    }

    /// Returns the stable output type name of the provider to construct.
    pub const fn type_name(&self) -> &str {
        self.type_name
    }

    /// Returns how the provider enters the application graph.
    pub const fn origin(&self) -> ProviderOrigin {
        self.origin
    }

    /// Returns the source location of the provider declaration.
    pub const fn location(&self) -> SourceLocation {
        self.location
    }
}

/// A deterministic sequence of providers to construct.
pub struct ConstructionPlan {
    pub(crate) steps: Vec<ConstructionStep>,
}

impl ConstructionPlan {
    /// Returns construction steps in deterministic execution order.
    pub fn steps(&self) -> &[ConstructionStep] {
        &self.steps
    }
}

/// The result of graph inspection and validation.
pub struct GraphAnalysis {
    pub(crate) graph: ApplicationGraph,
    pub(crate) diagnostics: Vec<Diagnostic>,
    pub(crate) construction_plan: Option<ConstructionPlan>,
    pub(crate) auto_configurations: Vec<AutoConfigurationReport>,
    pub(crate) module_graph: Option<ModuleGraph>,
}

impl GraphAnalysis {
    /// Returns the immutable provider graph.
    pub const fn graph(&self) -> &ApplicationGraph {
        &self.graph
    }

    /// Returns diagnostics emitted while analyzing the graph.
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

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

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

    /// Returns the deterministic construction plan when the graph is valid.
    pub const fn construction_plan(&self) -> Option<&ConstructionPlan> {
        self.construction_plan.as_ref()
    }

    /// Reports whether analysis produced a construction plan without diagnostics.
    pub fn is_valid(&self) -> bool {
        self.diagnostics.is_empty() && self.construction_plan.is_some()
    }

    pub(crate) fn prepend_diagnostics(&mut self, mut diagnostics: Vec<Diagnostic>) {
        if diagnostics.is_empty() {
            return;
        }
        self.construction_plan = None;
        diagnostics.append(&mut self.diagnostics);
        self.diagnostics = diagnostics;
    }

    pub(crate) fn append_diagnostics(&mut self, diagnostics: Vec<Diagnostic>) {
        if diagnostics.is_empty() {
            return;
        }
        self.construction_plan = None;
        self.diagnostics.extend(diagnostics);
    }

    pub(crate) fn set_module_graph(&mut self, module_graph: ModuleGraph) {
        self.module_graph = Some(module_graph);
    }

    pub(crate) fn invalid(diagnostics: Vec<Diagnostic>) -> Self {
        Self {
            graph: ApplicationGraph {
                providers: Vec::new(),
                dependencies: Vec::new(),
            },
            diagnostics,
            construction_plan: None,
            auto_configurations: Vec::new(),
            module_graph: None,
        }
    }

    pub(crate) fn into_valid_parts(
        self,
    ) -> crate::Result<(
        ApplicationGraph,
        ConstructionPlan,
        Vec<AutoConfigurationReport>,
        Option<ModuleGraph>,
    )> {
        match (self.diagnostics.is_empty(), self.construction_plan) {
            (true, Some(plan)) => Ok((
                self.graph,
                plan,
                self.auto_configurations,
                self.module_graph,
            )),
            (false, _) => {
                let mut diagnostics = self.diagnostics.into_iter();
                let primary = diagnostics
                    .next()
                    .expect("invalid analysis has diagnostics");
                Err(crate::Error::from_diagnostics(primary, diagnostics))
            }
            (true, None) => unreachable!("valid analysis always has a plan"),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::any::TypeId;
    use std::sync::Arc;

    use crate::{
        ConstructionContext, ErasedProvider, ProviderDescriptor, ProviderFuture, ProviderKind,
        ProviderVisibility, SourceLocation,
    };

    use super::*;

    struct Database;
    struct Repository;

    #[test]
    fn immutable_graph_types_expose_stable_metadata() {
        let database = ProviderNode {
            type_id: TypeId::of::<Database>(),
            type_name: "graph::Database",
            origin: ProviderOrigin::Provided,
            visibility: ProviderVisibility::Public,
            state: ProviderState::Provided,
            location: None,
            declared_dependencies: &[],
        };
        let graph = ApplicationGraph {
            providers: vec![database],
            dependencies: Vec::new(),
        };
        let analysis = GraphAnalysis {
            graph,
            diagnostics: Vec::new(),
            construction_plan: Some(ConstructionPlan { steps: Vec::new() }),
            auto_configurations: Vec::new(),
            module_graph: None,
        };

        assert!(analysis.is_valid());
        assert_eq!(analysis.graph().providers().len(), 1);
        assert_eq!(
            analysis.graph().provider::<Database>().unwrap().origin(),
            ProviderOrigin::Provided,
        );
        assert_eq!(
            analysis
                .graph()
                .provider::<Database>()
                .unwrap()
                .visibility(),
            ProviderVisibility::Public,
        );
        assert!(analysis.construction_plan().unwrap().steps().is_empty());
    }

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

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

    static REPOSITORY_DESCRIPTOR: ProviderDescriptor = ProviderDescriptor::new(
        ProviderKind::Repository,
        "graph::Repository",
        repository_type_id,
        &[],
        ProviderVisibility::Private,
        SourceLocation::new("repository.rs", 3, 1),
        repository_constructor,
    );

    #[test]
    fn edges_and_steps_expose_stable_metadata() {
        let edge = DependencyEdge {
            provider_type_id: TypeId::of::<Repository>(),
            provider_type_name: "graph::Repository",
            dependency_type_id: TypeId::of::<Database>(),
            dependency_type_name: "graph::Database",
        };
        let step = ConstructionStep {
            type_id: TypeId::of::<Repository>(),
            type_name: "graph::Repository",
            origin: ProviderOrigin::Repository,
            location: SourceLocation::new("repository.rs", 3, 1),
            descriptor: &REPOSITORY_DESCRIPTOR,
        };

        assert_eq!(edge.provider_type_name(), "graph::Repository");
        assert_eq!(edge.dependency_type_name(), "graph::Database");
        assert_eq!(step.type_name(), "graph::Repository");
        assert_eq!(step.origin(), ProviderOrigin::Repository);
        assert_eq!(step.location(), SourceLocation::new("repository.rs", 3, 1));
    }
}