Skip to main content

xecute/
lib.rs

1//! Application architecture tools, macros, and a dependency-injection runtime for Axum.
2//!
3//! `Container` owns application providers while `ModuleGraph` verifies module
4//! boundaries before the application starts. The older [`Injector`] API is
5//! retained for applications migrating from the first preview release.
6
7use std::{
8    any::{Any, TypeId, type_name},
9    cell::RefCell,
10    collections::{HashMap, HashSet},
11    fmt,
12    sync::{Arc, Mutex, OnceLock},
13};
14
15pub use xmacros::*;
16
17/// HTTP middleware and application pipeline composition.
18pub mod middleware;
19pub use middleware::Application;
20
21/// Executable application, module, controller, and route guards.
22pub mod guards;
23
24/// JWT bearer authentication, verified principals, and role/permission policies.
25#[cfg(feature = "auth")]
26pub mod auth;
27
28/// Streaming multipart uploads with private local and optional S3 storage.
29#[cfg(feature = "upload")]
30pub mod upload;
31
32/// In-process HTTP tests and isolated provider overrides.
33#[cfg(feature = "testing")]
34pub mod testing;
35
36/// Typed command/query dispatch, event fan-out, and shared CQRS pipelines.
37#[cfg(feature = "cqrs")]
38pub mod cqrs;
39
40/// Bounded process-local background jobs and interval scheduling.
41#[cfg(feature = "jobs")]
42pub mod jobs;
43
44/// Explicit TTL caching with memory and optional Redis backends.
45#[cfg(feature = "cache")]
46pub mod cache;
47
48/// Optional SQLx PostgreSQL pools, migrations, and lifecycle integration.
49#[cfg(feature = "postgres")]
50pub mod database;
51
52/// Typed configuration readers and redacted validation errors.
53pub mod config;
54
55mod lifecycle;
56
57mod scoped;
58pub use scoped::{Inject, with_container};
59
60/// Safe HTTP error envelopes, normalization, and request correlation.
61pub mod exceptions;
62
63mod http;
64mod openapi;
65/// Explicit route version groups and per-version OpenAPI metadata.
66pub mod versioning;
67pub use http::{ApiOperation, ApiResponse, HttpError, HttpStatus, ValidatedJson, ValidatedQuery};
68pub use openapi::{DocumentationError, json_schema, openapi_document};
69pub use versioning::{ApiVersion, ApiVersions, VersionError};
70
71/// Common controller types and macros.
72pub mod prelude {
73    pub use crate::{
74        Application, HttpError, HttpStatus, Inject, Injectable, controller, middleware, routes,
75    };
76    pub use axum::{
77        Json, Router,
78        response::{IntoResponse, Response},
79    };
80}
81
82type DynValue = dyn Any + Send + Sync;
83type Cache = Mutex<HashMap<ProviderKey, Arc<OnceLock<Result<Arc<DynValue>, InjectError>>>>>;
84type Factory = dyn Fn(&Container) -> Result<Arc<DynValue>, InjectError> + Send + Sync;
85
86/// The lifecycle of a provider instance.
87#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
88pub enum Scope {
89    #[default]
90    /// Reuse one instance for the container lifetime.
91    Singleton,
92    /// Construct a new instance for each resolution.
93    Transient,
94    /// Reuse an instance within one request-local container.
95    Request,
96}
97
98/// A type-safe key used to identify a provider.
99#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
100pub struct ProviderKey {
101    type_id: TypeId,
102    name: &'static str,
103}
104impl ProviderKey {
105    #[must_use]
106    /// Identify a provider by its concrete Rust type.
107    pub fn of<T: 'static>() -> Self {
108        Self {
109            type_id: TypeId::of::<T>(),
110            name: type_name::<T>(),
111        }
112    }
113    #[must_use]
114    /// Return the diagnostic type name.
115    pub const fn name(self) -> &'static str {
116        self.name
117    }
118}
119
120/// Errors discovered while constructing or validating an application.
121#[derive(Debug, Clone, Eq, PartialEq)]
122pub enum InjectError {
123    /// A required provider was not registered.
124    Missing(&'static str),
125    /// More than one module definition uses the same module name.
126    DuplicateModule(&'static str),
127    /// More than one registration uses the same provider key.
128    DuplicateProvider(&'static str),
129    /// An importing module requested a provider that was not exported.
130    PrivateProviderAccess {
131        /// Provider type involved in the validation failure.
132        provider: &'static str,
133        /// Module owning the invalid relationship.
134        module: &'static str,
135    },
136    /// A module exported a provider it does not own.
137    InvalidExport {
138        /// Provider type involved in the validation failure.
139        provider: &'static str,
140        /// Module owning the invalid relationship.
141        module: &'static str,
142    },
143    /// A referenced module was not present in the module graph.
144    InvalidImport {
145        /// Module owning the invalid relationship.
146        module: &'static str,
147        /// Referenced imported module.
148        import: &'static str,
149    },
150    /// Dependency resolution encountered a cycle.
151    Circular(Vec<&'static str>),
152    /// A provider depends on a shorter-lived provider.
153    InvalidScopeDependency {
154        /// Provider that owns the dependency relationship.
155        owner: &'static str,
156        /// Dependency with an incompatible scope.
157        dependency: &'static str,
158    },
159    /// A request-scoped provider was resolved without an active request.
160    RequestScopeRequired(&'static str),
161    /// A factory resolved a dependency not declared in its metadata.
162    UndeclaredDependency {
163        /// Factory performing the resolution.
164        owner: &'static str,
165        /// Dependency missing from the factory metadata.
166        dependency: &'static str,
167    },
168    /// A factory returned a value of the wrong concrete type.
169    Downcast(&'static str),
170    /// A provider could not be constructed; the static message must not contain secrets.
171    ConstructionFailed(&'static str),
172    /// A synchronization lock was poisoned by a panic.
173    Poisoned,
174    /// Async construction or lifecycle hooks require initialize_async before serving.
175    AsyncInitializationRequired(&'static str),
176    /// Lifecycle hooks are supported only on singleton providers.
177    InvalidLifecycleScope(&'static str),
178    /// Initialization or shutdown was cancelled, or the container has stopped.
179    LifecycleStopped,
180}
181impl fmt::Display for InjectError {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        match self {
184            Self::Missing(n) => write!(f, "missing provider: {n}"),
185            Self::DuplicateModule(n) => write!(f, "duplicate module: {n}"),
186            Self::DuplicateProvider(n) => write!(f, "duplicate provider: {n}"),
187            Self::PrivateProviderAccess { provider, module } => write!(
188                f,
189                "private provider {provider} is not visible to module {module}"
190            ),
191            Self::InvalidExport { provider, module } => write!(
192                f,
193                "module {module} exports unregistered provider {provider}"
194            ),
195            Self::InvalidImport { module, import } => {
196                write!(f, "module {module} imports unknown module {import}")
197            }
198            Self::Circular(chain) => write!(f, "circular dependency:\n{}", chain.join("\n  -> ")),
199            Self::InvalidScopeDependency { owner, dependency } => write!(
200                f,
201                "invalid scope dependency: singleton {owner} depends on request-scoped {dependency}"
202            ),
203            Self::RequestScopeRequired(n) => write!(f, "request scope required for provider: {n}"),
204            Self::UndeclaredDependency { owner, dependency } => write!(
205                f,
206                "provider {owner} resolved undeclared dependency {dependency}"
207            ),
208            Self::Downcast(n) => write!(f, "provider {n} returned an incompatible value"),
209            Self::ConstructionFailed(reason) => write!(f, "provider construction failed: {reason}"),
210            Self::AsyncInitializationRequired(n) => {
211                write!(f, "provider {n} requires initialize_async")
212            }
213            Self::InvalidLifecycleScope(n) => {
214                write!(f, "lifecycle hooks require singleton scope: {n}")
215            }
216            Self::LifecycleStopped => write!(f, "container lifecycle stopped or interrupted"),
217            Self::Poisoned => write!(f, "container lock was poisoned"),
218        }
219    }
220}
221impl std::error::Error for InjectError {}
222
223/// A provider registration. Dependencies are metadata used for startup validation.
224pub struct ProviderDefinition {
225    key: ProviderKey,
226    scope: Scope,
227    dependencies: Vec<ProviderKey>,
228    optional_dependencies: Vec<ProviderKey>,
229    factory: Arc<Factory>,
230    async_factory: Option<Arc<lifecycle::AsyncFactory>>,
231    init_hook: Option<Arc<lifecycle::Hook>>,
232    shutdown_hook: Option<Arc<lifecycle::Hook>>,
233}
234impl fmt::Debug for ProviderDefinition {
235    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236        f.debug_struct("ProviderDefinition")
237            .field("key", &self.key)
238            .field("scope", &self.scope)
239            .field("dependencies", &self.dependencies)
240            .finish()
241    }
242}
243impl ProviderDefinition {
244    #[must_use]
245    /// Create a new instance from the supplied definition inputs.
246    pub fn new<T, F>(scope: Scope, dependencies: Vec<ProviderKey>, factory: F) -> Self
247    where
248        T: Send + Sync + 'static,
249        F: Fn(&Container) -> Result<T, InjectError> + Send + Sync + 'static,
250    {
251        Self {
252            key: ProviderKey::of::<T>(),
253            scope,
254            dependencies,
255            optional_dependencies: Vec::new(),
256            factory: Arc::new(move |c| factory(c).map(|v| Arc::new(v) as Arc<DynValue>)),
257            async_factory: None,
258            init_hook: None,
259            shutdown_hook: None,
260        }
261    }
262    #[must_use]
263    /// Register a factory whose result is cached for the container lifetime.
264    pub fn singleton<T, F>(dependencies: Vec<ProviderKey>, factory: F) -> Self
265    where
266        T: Send + Sync + 'static,
267        F: Fn(&Container) -> Result<T, InjectError> + Send + Sync + 'static,
268    {
269        Self::new(Scope::Singleton, dependencies, factory)
270    }
271    #[must_use]
272    /// Register a factory reused within each independent request context.
273    pub fn request<T, F>(dependencies: Vec<ProviderKey>, factory: F) -> Self
274    where
275        T: Send + Sync + 'static,
276        F: Fn(&Container) -> Result<T, InjectError> + Send + Sync + 'static,
277    {
278        Self::new(Scope::Request, dependencies, factory)
279    }
280    #[must_use]
281    /// Register a factory constructing a fresh instance on every resolution.
282    pub fn transient<T, F>(dependencies: Vec<ProviderKey>, factory: F) -> Self
283    where
284        T: Send + Sync + 'static,
285        F: Fn(&Container) -> Result<T, InjectError> + Send + Sync + 'static,
286    {
287        Self::new(Scope::Transient, dependencies, factory)
288    }
289    #[must_use]
290    /// Register one preconstructed value, useful for application settings and test doubles.
291    pub fn value<T: Send + Sync + 'static>(value: T) -> Self {
292        let value: Arc<DynValue> = Arc::new(value);
293        Self {
294            key: ProviderKey::of::<T>(),
295            scope: Scope::Singleton,
296            dependencies: Vec::new(),
297            optional_dependencies: Vec::new(),
298            factory: Arc::new(move |_| Ok(value.clone())),
299            async_factory: None,
300            init_hook: None,
301            shutdown_hook: None,
302        }
303    }
304    #[must_use]
305    /// Mark one declared dependency as optional for startup registration validation.
306    pub fn optional_dependency<T: 'static>(mut self) -> Self {
307        self.optional_dependencies.push(ProviderKey::of::<T>());
308        self
309    }
310    #[must_use]
311    /// Return the type key identifying this provider.
312    pub fn key(&self) -> ProviderKey {
313        self.key
314    }
315    #[must_use]
316    /// Return the lifetime used when resolving this provider.
317    pub fn scope(&self) -> Scope {
318        self.scope
319    }
320    #[must_use]
321    /// List the provider keys required by this factory.
322    pub fn dependencies(&self) -> &[ProviderKey] {
323        &self.dependencies
324    }
325}
326
327/// Types generated by `#[injectable]` can register themselves with a container.
328pub trait Provider: Send + Sync + 'static {
329    /// Return the lifetime used when resolving this provider.
330    fn scope() -> Scope {
331        Scope::Singleton
332    }
333    /// List the provider keys required by this factory.
334    fn dependencies() -> Vec<ProviderKey> {
335        Vec::new()
336    }
337    /// Optional dependency keys which may be absent at startup.
338    fn optional_dependencies() -> Vec<ProviderKey> {
339        Vec::new()
340    }
341    /// Construct a provider using dependencies from the container.
342    fn provide(container: &Container) -> Result<Self, InjectError>
343    where
344        Self: Sized;
345    /// Build registration metadata for this provider.
346    fn definition() -> ProviderDefinition
347    where
348        Self: Sized,
349    {
350        let mut definition =
351            ProviderDefinition::new(Self::scope(), Self::dependencies(), Self::provide);
352        definition.optional_dependencies = Self::optional_dependencies();
353        definition
354    }
355}
356
357/// Thread-safe provider container with shared singleton and isolated request caches.
358#[derive(Clone, Default)]
359pub struct Container {
360    providers: Arc<HashMap<ProviderKey, ProviderDefinition>>,
361    singletons: Arc<Cache>,
362    request_values: Option<Arc<Cache>>,
363    lifecycle: Arc<lifecycle::Lifecycle>,
364    async_owner: Option<ProviderKey>,
365}
366
367thread_local! {
368    static RESOLVING: RefCell<Vec<(usize, ProviderKey)>> = const { RefCell::new(Vec::new()) };
369}
370struct ResolutionGuard;
371impl Drop for ResolutionGuard {
372    fn drop(&mut self) {
373        RESOLVING.with(|path| {
374            path.borrow_mut().pop();
375        });
376    }
377}
378impl Container {
379    #[must_use]
380    /// Start constructing and validating a dependency container.
381    pub fn builder() -> ContainerBuilder {
382        ContainerBuilder::default()
383    }
384    /// Resolve a provider; request providers require a request context.
385    pub fn resolve<T: Send + Sync + 'static>(&self) -> Result<Arc<T>, InjectError> {
386        self.resolve_key(ProviderKey::of::<T>())?
387            .downcast::<T>()
388            .map_err(|_| InjectError::Downcast(type_name::<T>()))
389    }
390    /// Return None only for an unregistered optional provider; propagate factory failures.
391    pub fn resolve_optional<T: Send + Sync + 'static>(
392        &self,
393    ) -> Result<Option<Arc<T>>, InjectError> {
394        if !self.providers.contains_key(&ProviderKey::of::<T>()) {
395            return Ok(None);
396        }
397        self.resolve().map(Some)
398    }
399    fn resolve_key(&self, key: ProviderKey) -> Result<Arc<DynValue>, InjectError> {
400        let definition = self
401            .providers
402            .get(&key)
403            .ok_or(InjectError::Missing(key.name))?;
404        // Fail before entering a synchronous OnceLock factory, so an early resolve
405        // cannot permanently cache AsyncInitializationRequired in its dependents.
406        self.ensure_async_dependencies(key, &mut HashSet::new())?;
407        let identity = Arc::as_ptr(&self.providers) as usize;
408        RESOLVING.with(|path| {
409            let mut path = path.borrow_mut();
410            if !path.iter().any(|(id, _)| *id == identity)
411                && let Some(owner) = self.async_owner
412                && !self.providers[&owner].dependencies.contains(&key)
413            {
414                return Err(InjectError::UndeclaredDependency {
415                    owner: owner.name,
416                    dependency: key.name,
417                });
418            }
419            if let Some(index) = path.iter().position(|entry| *entry == (identity, key)) {
420                let mut chain = path[index..]
421                    .iter()
422                    .map(|entry| entry.1.name)
423                    .collect::<Vec<_>>();
424                chain.push(key.name);
425                return Err(InjectError::Circular(chain));
426            }
427            if let Some((id, parent)) = path.last()
428                && *id == identity
429                && !self.providers[parent].dependencies.contains(&key)
430            {
431                return Err(InjectError::UndeclaredDependency {
432                    owner: parent.name,
433                    dependency: key.name,
434                });
435            }
436            path.push((identity, key));
437            Ok(())
438        })?;
439        let _guard = ResolutionGuard;
440        let cache = match definition.scope {
441            Scope::Transient => return (definition.factory)(self),
442            Scope::Singleton => &self.singletons,
443            Scope::Request => self
444                .request_values
445                .as_ref()
446                .ok_or(InjectError::RequestScopeRequired(key.name))?,
447        };
448        // Lock only to obtain the per-provider slot. Factories can resolve other slots.
449        let slot = cache
450            .lock()
451            .map_err(|_| InjectError::Poisoned)?
452            .entry(key)
453            .or_default()
454            .clone();
455        // Successful instances and construction errors are deterministic within the scope.
456        // OnceLock serializes concurrent initialization without holding the cache lock.
457        if definition.async_factory.is_some() {
458            return slot
459                .get()
460                .cloned()
461                .unwrap_or(Err(InjectError::AsyncInitializationRequired(key.name)));
462        }
463        slot.get_or_init(|| {
464            if definition.scope == Scope::Singleton {
465                // Singletons must never retain the first HTTP request's resolution context.
466                let root = Self {
467                    providers: self.providers.clone(),
468                    singletons: self.singletons.clone(),
469                    request_values: None,
470                    lifecycle: self.lifecycle.clone(),
471                    async_owner: None,
472                };
473                (definition.factory)(&root)
474            } else {
475                (definition.factory)(self)
476            }
477        })
478        .clone()
479    }
480    #[must_use]
481    /// Start an independent request cache while sharing application singletons.
482    pub fn request(&self) -> RequestScope {
483        RequestScope {
484            container: Self {
485                providers: self.providers.clone(),
486                singletons: self.singletons.clone(),
487                request_values: Some(Arc::default()),
488                lifecycle: self.lifecycle.clone(),
489                async_owner: self.async_owner,
490            },
491        }
492    }
493    /// Eagerly construct singletons so factory failures are reported before listening.
494    /// Request and transient factories are constructed only when resolved.
495    pub fn initialize(&self) -> Result<(), InjectError> {
496        if !self
497            .lifecycle
498            .ready
499            .load(std::sync::atomic::Ordering::Acquire)
500            && let Some(definition) = self.providers.values().find(|p| {
501                p.async_factory.is_some() || p.init_hook.is_some() || p.shutdown_hook.is_some()
502            })
503        {
504            return Err(InjectError::AsyncInitializationRequired(
505                definition.key.name,
506            ));
507        }
508        for definition in self
509            .providers
510            .values()
511            .filter(|definition| definition.scope == Scope::Singleton)
512        {
513            self.resolve_key(definition.key)?;
514        }
515        Ok(())
516    }
517}
518
519/// Builds a validated [`Container`].
520#[derive(Default)]
521pub struct ContainerBuilder {
522    providers: Vec<ProviderDefinition>,
523    overrides: Vec<ProviderDefinition>,
524}
525impl ContainerBuilder {
526    #[must_use]
527    /// Append a provider registration to this definition.
528    pub fn provider(mut self, provider: ProviderDefinition) -> Self {
529        self.providers.push(provider);
530        self
531    }
532    #[must_use]
533    /// Register a type implementing the provider factory contract.
534    pub fn injectable<T: Provider>(self) -> Self {
535        self.provider(T::definition())
536    }
537    /// Replace an existing provider for an isolated test container.
538    #[must_use]
539    pub fn override_provider(mut self, provider: ProviderDefinition) -> Self {
540        self.overrides.push(provider);
541        self
542    }
543    /// Register a preconstructed value such as a trait adapter or test double.
544    #[must_use]
545    pub fn value<T: Send + Sync + 'static>(self, value: T) -> Self {
546        self.provider(ProviderDefinition::value(value))
547    }
548    #[cfg(feature = "testing")]
549    pub(crate) fn into_definitions(self) -> Vec<ProviderDefinition> {
550        self.providers
551    }
552    /// Validate registrations and dependency relationships before constructing the container.
553    pub fn build(self) -> Result<Container, InjectError> {
554        let mut providers = HashMap::new();
555        for provider in self.providers {
556            let key = provider.key;
557            if providers.insert(key, provider).is_some() {
558                return Err(InjectError::DuplicateProvider(key.name));
559            }
560        }
561        let mut overrides = HashSet::new();
562        for replacement in self.overrides {
563            let key = replacement.key;
564            if !overrides.insert(key) {
565                return Err(InjectError::DuplicateProvider(key.name));
566            }
567            if !providers.contains_key(&key) {
568                return Err(InjectError::Missing(key.name));
569            }
570            providers.insert(key, replacement);
571        }
572        for provider in providers.values() {
573            for dependency in &provider.dependencies {
574                if !providers.contains_key(dependency)
575                    && !provider.optional_dependencies.contains(dependency)
576                {
577                    return Err(InjectError::Missing(dependency.name));
578                }
579            }
580        }
581        for provider in providers.values() {
582            if provider.scope != Scope::Singleton
583                && (provider.init_hook.is_some() || provider.shutdown_hook.is_some())
584            {
585                return Err(InjectError::InvalidLifecycleScope(provider.key.name));
586            }
587        }
588        validate_provider_scopes(&providers)?;
589        validate_provider_cycles(&providers)?;
590        Ok(Container {
591            providers: Arc::new(providers),
592            singletons: Arc::default(),
593            request_values: None,
594            lifecycle: Arc::default(),
595            async_owner: None,
596        })
597    }
598}
599
600fn validate_provider_cycles(
601    providers: &HashMap<ProviderKey, ProviderDefinition>,
602) -> Result<(), InjectError> {
603    fn visit(
604        key: ProviderKey,
605        providers: &HashMap<ProviderKey, ProviderDefinition>,
606        visiting: &mut Vec<ProviderKey>,
607        visited: &mut HashSet<ProviderKey>,
608    ) -> Result<(), InjectError> {
609        if let Some(index) = visiting.iter().position(|entry| *entry == key) {
610            let mut chain = visiting[index..]
611                .iter()
612                .map(|entry| entry.name)
613                .collect::<Vec<_>>();
614            chain.push(key.name);
615            return Err(InjectError::Circular(chain));
616        }
617        if !visited.insert(key) {
618            return Ok(());
619        }
620        visiting.push(key);
621        if let Some(provider) = providers.get(&key) {
622            for dependency in &provider.dependencies {
623                if providers.contains_key(dependency) {
624                    visit(*dependency, providers, visiting, visited)?;
625                }
626            }
627        }
628        visiting.pop();
629        Ok(())
630    }
631    let mut visiting = Vec::new();
632    let mut visited = HashSet::new();
633    for key in providers.keys().copied() {
634        visit(key, providers, &mut visiting, &mut visited)?;
635    }
636    Ok(())
637}
638fn validate_provider_scopes(
639    providers: &HashMap<ProviderKey, ProviderDefinition>,
640) -> Result<(), InjectError> {
641    for provider in providers
642        .values()
643        .filter(|provider| provider.scope == Scope::Singleton)
644    {
645        let mut pending = provider.dependencies.clone();
646        let mut visited = HashSet::new();
647        while let Some(key) = pending.pop() {
648            if !visited.insert(key) {
649                continue;
650            }
651            if let Some(dependency) = providers.get(&key) {
652                if dependency.scope == Scope::Request {
653                    return Err(InjectError::InvalidScopeDependency {
654                        owner: provider.key.name,
655                        dependency: key.name,
656                    });
657                }
658                pending.extend_from_slice(&dependency.dependencies);
659            }
660        }
661    }
662    Ok(())
663}
664
665/// Owned request-local provider cache. Clones share only this request's values.
666/// Returned Arcs can outlive the HTTP request if retained by application code.
667#[derive(Clone)]
668pub struct RequestScope {
669    container: Container,
670}
671impl RequestScope {
672    pub(crate) fn belongs_to(&self, container: &Container) -> bool {
673        Arc::ptr_eq(&self.container.providers, &container.providers)
674    }
675    /// Resolve nested request, transient, and singleton dependencies in this request.
676    pub fn resolve<T: Send + Sync + 'static>(&self) -> Result<Arc<T>, InjectError> {
677        self.container.resolve()
678    }
679    /// Resolve an optional provider without hiding factory failures.
680    pub fn resolve_optional<T: Send + Sync + 'static>(
681        &self,
682    ) -> Result<Option<Arc<T>>, InjectError> {
683        self.container.resolve_optional()
684    }
685}
686
687/// Compatibility name for the owned request scope; the lifetime no longer restricts ownership.
688/// Existing `RequestContainer<'a>` type annotations continue to compile.
689pub type RequestContainer<'a> = RequestScope;
690
691/// Declarative module metadata, used to validate imports and exports.
692#[derive(Debug)]
693pub struct ModuleDefinition {
694    /// Unique module type name.
695    pub name: &'static str,
696    /// Provider registrations owned by this module.
697    pub providers: Vec<ProviderDefinition>,
698    /// Module names whose exports this module can access.
699    pub imports: Vec<&'static str>,
700    /// Provider keys available to importing modules.
701    pub exports: Vec<ProviderKey>,
702    /// Whether exports are visible throughout the module graph.
703    pub global: bool,
704}
705impl ModuleDefinition {
706    #[must_use]
707    /// Create a new instance from the supplied definition inputs.
708    pub fn new(name: &'static str) -> Self {
709        Self {
710            name,
711            providers: Vec::new(),
712            imports: Vec::new(),
713            exports: Vec::new(),
714            global: false,
715        }
716    }
717    #[must_use]
718    /// Append a provider registration to this definition.
719    pub fn provider(mut self, provider: ProviderDefinition) -> Self {
720        self.providers.push(provider);
721        self
722    }
723    #[must_use]
724    /// Import providers exported by the named module.
725    pub fn import(mut self, module: &'static str) -> Self {
726        self.imports.push(module);
727        self
728    }
729    #[must_use]
730    /// Make the specified provider visible to importing modules.
731    pub fn export<T: 'static>(mut self) -> Self {
732        self.exports.push(ProviderKey::of::<T>());
733        self
734    }
735    #[must_use]
736    /// Make this module’s exports visible to all modules.
737    pub fn global(mut self) -> Self {
738        self.global = true;
739        self
740    }
741}
742
743/// Validates module metadata and flattens modules into a container.
744pub struct ModuleGraph {
745    modules: Vec<ModuleDefinition>,
746}
747impl ModuleGraph {
748    #[must_use]
749    /// Create a new instance from the supplied definition inputs.
750    pub fn new(modules: Vec<ModuleDefinition>) -> Self {
751        Self { modules }
752    }
753    /// Validate registrations and dependency relationships before constructing the container.
754    pub fn build(self) -> Result<Container, InjectError> {
755        self.build_with_overrides(Vec::new())
756    }
757    /// Validate module metadata and replace selected provider factories for tests.
758    pub fn build_with_overrides(
759        self,
760        overrides: Vec<ProviderDefinition>,
761    ) -> Result<Container, InjectError> {
762        let mut modules = HashMap::new();
763        for module in self.modules {
764            let name = module.name;
765            if modules.insert(name, module).is_some() {
766                return Err(InjectError::DuplicateModule(name));
767            }
768        }
769        for module in modules.values() {
770            let owned: HashSet<_> = module
771                .providers
772                .iter()
773                .map(ProviderDefinition::key)
774                .collect();
775            for export in &module.exports {
776                if !owned.contains(export) {
777                    return Err(InjectError::InvalidExport {
778                        provider: export.name,
779                        module: module.name,
780                    });
781                }
782            }
783            for import in &module.imports {
784                if !modules.contains_key(import) {
785                    return Err(InjectError::InvalidImport {
786                        module: module.name,
787                        import,
788                    });
789                }
790            }
791        }
792        for module in modules.values() {
793            let mut visible: HashSet<_> = module
794                .providers
795                .iter()
796                .map(ProviderDefinition::key)
797                .collect();
798            for imported in modules
799                .values()
800                .filter(|candidate| candidate.global || module.imports.contains(&candidate.name))
801            {
802                visible.extend(imported.exports.iter().copied());
803            }
804            for provider in &module.providers {
805                for dependency in &provider.dependencies {
806                    let registered = modules.values().any(|candidate| {
807                        candidate
808                            .providers
809                            .iter()
810                            .any(|provider| provider.key == *dependency)
811                    });
812                    if registered && !visible.contains(dependency) {
813                        return Err(InjectError::PrivateProviderAccess {
814                            provider: dependency.name,
815                            module: module.name,
816                        });
817                    }
818                }
819            }
820        }
821        let mut builder = Container::builder();
822        for module in modules.into_values() {
823            for provider in module.providers {
824                builder = builder.provider(provider);
825            }
826        }
827        for replacement in overrides {
828            builder = builder.override_provider(replacement);
829        }
830        builder.build()
831    }
832}
833
834// Compatibility API for the initial local migration.
835/// Compatibility construction contract for applications using the original injector.
836pub trait Injectable: Sized {
837    /// Construct a value through the compatibility injector.
838    fn inject(injector: &Injector) -> Result<Self, InjectError>;
839}
840impl<T: Injectable + 'static> Injectable for Arc<T> {
841    /// Construct a value through the compatibility injector.
842    fn inject(injector: &Injector) -> Result<Self, InjectError> {
843        injector.resolve::<T>().map(Arc::new)
844    }
845}
846/// Compatibility injector storing cloneable application values.
847pub struct Injector {
848    values: HashMap<TypeId, Box<dyn Any>>,
849}
850thread_local! { static PATH: RefCell<Vec<&'static str>> = const { RefCell::new(Vec::new()) }; }
851impl Injector {
852    #[must_use]
853    /// Create a new instance from the supplied definition inputs.
854    pub fn new() -> Self {
855        Self {
856            values: HashMap::new(),
857        }
858    }
859    #[must_use]
860    /// Register a cloneable value for compatibility injection.
861    pub fn value<T: Clone + 'static>(mut self, value: T) -> Self {
862        self.values.insert(TypeId::of::<T>(), Box::new(value));
863        self
864    }
865    /// Resolve a dependency, applying its configured lifecycle.
866    pub fn resolve<T: Injectable + 'static>(&self) -> Result<T, InjectError> {
867        let name = type_name::<T>();
868        PATH.with(|path| {
869            let mut path = path.borrow_mut();
870            if let Some(index) = path.iter().position(|entry| *entry == name) {
871                let mut chain = path[index..].to_vec();
872                chain.push(name);
873                return Err(InjectError::Circular(chain));
874            }
875            path.push(name);
876            drop(path);
877            let result = T::inject(self);
878            PATH.with(|path| {
879                path.borrow_mut().pop();
880            });
881            result
882        })
883    }
884    /// Read a registered cloneable value or return a missing-provider error.
885    pub fn value_of<T: Clone + 'static>(&self) -> Result<T, InjectError> {
886        self.values
887            .get(&TypeId::of::<T>())
888            .and_then(|value| value.downcast_ref::<T>())
889            .cloned()
890            .ok_or(InjectError::Missing(type_name::<T>()))
891    }
892}
893impl Default for Injector {
894    fn default() -> Self {
895        Self::new()
896    }
897}
898
899#[cfg(test)]
900mod tests {
901    use super::*;
902    struct A;
903    impl Provider for A {
904        /// Construct a provider using dependencies from the container.
905        fn provide(_: &Container) -> Result<Self, InjectError> {
906            Ok(Self)
907        }
908    }
909    #[test]
910    fn singleton_is_cached() {
911        let c = Container::builder().injectable::<A>().build().unwrap();
912        assert!(Arc::ptr_eq(
913            &c.resolve::<A>().unwrap(),
914            &c.resolve::<A>().unwrap()
915        ));
916    }
917}