Skip to main content

mads_core/
descriptor.rs

1//! Static metadata contracts emitted by provider and module declarations.
2
3use std::any::TypeId;
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::Arc;
7
8use crate::lifecycle::LifecycleRegistration;
9use crate::{ConstructionContext, ErasedProvider, LifecycleResource, Result, SourceLocation};
10
11/// Marker implemented by `#[module]` declarations.
12pub trait Module: Send + Sync + 'static {}
13
14/// One direct module import emitted by `#[module(imports = [ImportedModule])]`.
15pub struct ModuleImportDescriptor {
16    type_name: &'static str,
17    type_id: fn() -> TypeId,
18}
19
20impl ModuleImportDescriptor {
21    /// Creates an import descriptor from a stable type name and identifier factory.
22    pub const fn new(type_name: &'static str, type_id: fn() -> TypeId) -> Self {
23        Self { type_name, type_id }
24    }
25
26    /// Returns the imported module's authored type name.
27    pub const fn type_name(&self) -> &'static str {
28        self.type_name
29    }
30
31    /// Returns the imported module's runtime type identifier.
32    pub fn type_id(&self) -> TypeId {
33        (self.type_id)()
34    }
35}
36
37/// Categorizes the role a provider plays in an application.
38#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
39pub enum ProviderKind {
40    /// A provider implementing application service behavior.
41    Service,
42    /// A provider implementing persistence access behavior.
43    Repository,
44    /// A general-purpose provider.
45    Provider,
46}
47
48/// Describes whether a provider declaration is public outside its Rust module.
49#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
50pub enum ProviderVisibility {
51    /// The provider is public outside its Rust module.
52    Public,
53    /// The provider is private to its Rust module.
54    Private,
55}
56
57/// The asynchronous result of constructing an erased provider.
58pub type ProviderFuture<'a> = Pin<Box<dyn Future<Output = Result<ErasedProvider>> + Send + 'a>>;
59
60/// Constructs a provider using the dependencies and configuration available at startup.
61pub type ProviderConstructor = for<'a> fn(&'a ConstructionContext<'a>) -> ProviderFuture<'a>;
62
63/// A type-erased provider and lifecycle registrations produced together.
64#[doc(hidden)]
65pub struct ProviderContribution {
66    provider: ErasedProvider,
67    registrations: Vec<LifecycleRegistration>,
68}
69
70impl ProviderContribution {
71    /// Creates a contribution containing an ordinary provider and no hooks.
72    #[doc(hidden)]
73    pub fn from_provider(provider: ErasedProvider) -> Self {
74        Self {
75            provider,
76            registrations: Vec::new(),
77        }
78    }
79
80    /// Erases the native value while retaining its authored lifecycle hooks.
81    #[doc(hidden)]
82    pub fn from_resource<T>(resource: LifecycleResource<T>) -> Self
83    where
84        T: Send + Sync + 'static,
85    {
86        let (value, registrations) = resource.into_parts();
87        Self {
88            provider: Arc::new(value),
89            registrations,
90        }
91    }
92
93    pub(crate) fn into_parts(self) -> (ErasedProvider, Vec<LifecycleRegistration>) {
94        (self.provider, self.registrations)
95    }
96
97    /// Returns only the native provider, discarding unregistered hook metadata.
98    #[doc(hidden)]
99    pub fn into_provider(self) -> ErasedProvider {
100        self.into_parts().0
101    }
102}
103
104/// The asynchronous result of constructing a provider with lifecycle metadata.
105#[doc(hidden)]
106pub type LifecycleProviderFuture<'a> =
107    Pin<Box<dyn Future<Output = Result<ProviderContribution>> + Send + 'a>>;
108
109/// Constructs a provider and its lifecycle registrations together.
110#[doc(hidden)]
111pub type LifecycleProviderConstructor =
112    for<'a> fn(&'a ConstructionContext<'a>) -> LifecycleProviderFuture<'a>;
113
114/// Describes a provider dependency by its stable type metadata.
115pub struct DependencyDescriptor {
116    type_name: &'static str,
117    type_id: fn() -> TypeId,
118}
119
120impl DependencyDescriptor {
121    /// Creates a dependency descriptor from a stable type name and identifier factory.
122    pub const fn new(type_name: &'static str, type_id: fn() -> TypeId) -> Self {
123        Self { type_name, type_id }
124    }
125
126    /// Returns the dependency's stable type name.
127    pub const fn type_name(&self) -> &'static str {
128        self.type_name
129    }
130
131    /// Returns the dependency's runtime type identifier.
132    pub fn type_id(&self) -> TypeId {
133        (self.type_id)()
134    }
135}
136
137/// Describes a statically declared provider and its constructor.
138pub struct ProviderDescriptor {
139    kind: ProviderKind,
140    type_name: &'static str,
141    type_id: fn() -> TypeId,
142    runtime_type_name: Option<fn() -> &'static str>,
143    namespace: Option<&'static str>,
144    dependencies: &'static [DependencyDescriptor],
145    visibility: ProviderVisibility,
146    location: SourceLocation,
147    constructor: ProviderConstructor,
148    lifecycle_constructor: Option<LifecycleProviderConstructor>,
149}
150
151impl ProviderDescriptor {
152    /// Creates a provider descriptor from static declaration metadata.
153    pub const fn new(
154        kind: ProviderKind,
155        type_name: &'static str,
156        type_id: fn() -> TypeId,
157        dependencies: &'static [DependencyDescriptor],
158        visibility: ProviderVisibility,
159        location: SourceLocation,
160        constructor: ProviderConstructor,
161    ) -> Self {
162        Self {
163            kind,
164            type_name,
165            type_id,
166            runtime_type_name: None,
167            namespace: None,
168            dependencies,
169            visibility,
170            location,
171            constructor,
172            lifecycle_constructor: None,
173        }
174    }
175
176    /// Attaches the constructor that retains lifecycle registrations.
177    #[doc(hidden)]
178    #[must_use]
179    pub const fn with_lifecycle_constructor(
180        mut self,
181        constructor: LifecycleProviderConstructor,
182    ) -> Self {
183        self.lifecycle_constructor = Some(constructor);
184        self
185    }
186
187    /// Attaches the resolved Rust type name emitted by a provider macro.
188    ///
189    /// This document-hidden metadata lets catalog consumers compare types
190    /// across separately compiled crate instances while retaining `TypeId` as
191    /// the primary identity mechanism.
192    #[doc(hidden)]
193    pub const fn with_runtime_type_name(mut self, runtime_type_name: fn() -> &'static str) -> Self {
194        self.runtime_type_name = Some(runtime_type_name);
195        self
196    }
197
198    /// Attaches the Rust namespace containing this provider declaration.
199    #[must_use]
200    pub const fn with_namespace(mut self, namespace: &'static str) -> Self {
201        self.namespace = Some(namespace);
202        self
203    }
204
205    /// Returns the provider's role.
206    pub const fn kind(&self) -> ProviderKind {
207        self.kind
208    }
209
210    /// Returns the provider's stable output type name.
211    pub const fn type_name(&self) -> &'static str {
212        self.type_name
213    }
214
215    /// Returns the provider's runtime output type identifier.
216    pub fn type_id(&self) -> TypeId {
217        (self.type_id)()
218    }
219
220    /// Returns the resolved Rust output type name emitted by a provider macro.
221    #[doc(hidden)]
222    pub fn runtime_type_name(&self) -> Option<&'static str> {
223        self.runtime_type_name
224            .map(|runtime_type_name| runtime_type_name())
225    }
226
227    /// Returns the Rust namespace containing this provider declaration, when available.
228    pub const fn namespace(&self) -> Option<&'static str> {
229        self.namespace
230    }
231
232    /// Returns the static dependency descriptors required by this provider.
233    pub const fn dependencies(&self) -> &'static [DependencyDescriptor] {
234        self.dependencies
235    }
236
237    /// Returns the provider's declaration visibility metadata.
238    pub const fn visibility(&self) -> ProviderVisibility {
239        self.visibility
240    }
241
242    /// Returns the provider declaration's source location.
243    pub const fn location(&self) -> SourceLocation {
244        self.location
245    }
246
247    /// Returns the provider constructor.
248    pub const fn constructor(&self) -> ProviderConstructor {
249        self.constructor
250    }
251
252    /// Returns the lifecycle-aware constructor, when this provider has one.
253    #[doc(hidden)]
254    pub const fn lifecycle_constructor(&self) -> Option<LifecycleProviderConstructor> {
255        self.lifecycle_constructor
256    }
257}
258
259/// Describes a statically declared application module.
260pub struct ModuleDescriptor {
261    type_name: &'static str,
262    type_id: fn() -> TypeId,
263    namespace: Option<&'static str>,
264    imports: &'static [ModuleImportDescriptor],
265    global: bool,
266    location: SourceLocation,
267}
268
269impl ModuleDescriptor {
270    /// Creates a module descriptor from static declaration metadata.
271    pub const fn new(
272        type_name: &'static str,
273        type_id: fn() -> TypeId,
274        location: SourceLocation,
275    ) -> Self {
276        Self {
277            type_name,
278            type_id,
279            namespace: None,
280            imports: &[],
281            global: false,
282            location,
283        }
284    }
285
286    /// Attaches the Rust namespace containing this module declaration.
287    #[must_use]
288    pub const fn with_namespace(mut self, namespace: &'static str) -> Self {
289        self.namespace = Some(namespace);
290        self
291    }
292
293    /// Attaches the module's direct imports in authored declaration order.
294    #[must_use]
295    pub const fn with_imports(mut self, imports: &'static [ModuleImportDescriptor]) -> Self {
296        self.imports = imports;
297        self
298    }
299
300    /// Marks the module as global, allowing its providers to be accessed from any module.
301    #[must_use]
302    pub const fn with_global(mut self) -> Self {
303        self.global = true;
304        self
305    }
306
307    /// Returns the module's global declaration status.
308    pub const fn is_global(&self) -> bool {
309        self.global
310    }
311
312    /// Returns the module's stable type name.
313    pub const fn type_name(&self) -> &'static str {
314        self.type_name
315    }
316
317    /// Returns the module's runtime type identifier.
318    pub fn type_id(&self) -> TypeId {
319        (self.type_id)()
320    }
321
322    /// Returns the Rust namespace containing this module declaration, when available.
323    pub const fn namespace(&self) -> Option<&'static str> {
324        self.namespace
325    }
326
327    /// Returns the module's direct imports in authored declaration order.
328    pub const fn imports(&self) -> &'static [ModuleImportDescriptor] {
329        self.imports
330    }
331
332    /// Returns the module declaration's source location.
333    pub const fn location(&self) -> SourceLocation {
334        self.location
335    }
336}