Skip to main content

reinhardt_di/
lib.rs

1//! # Reinhardt Dependency Injection
2//!
3//! FastAPI-inspired dependency injection system for Reinhardt.
4//!
5//! ## Features
6//!
7//! - **Type-safe**: Full compile-time type checking
8//! - **Async-first**: Built for async/await
9//! - **Scoped**: Request-scoped and singleton dependencies
10//! - **Composable**: Dependencies can depend on other dependencies
11//! - **Cache**: Automatic caching within request scope
12//! - **Circular Dependency Detection**: Automatic runtime detection with optimized performance
13//!
14//! ## Development Tools (dev-tools feature)
15//!
16//! When the `dev-tools` feature is enabled, additional debugging and profiling tools are available:
17//!
18//! - **Visualization**: Generate dependency graphs in DOT format for Graphviz
19//! - **Profiling**: Track dependency resolution performance and identify bottlenecks
20//! - **Advanced Caching**: LRU and TTL-based caching strategies
21//!
22//! ## Generator Support (generator feature) ✅
23//!
24//! Generator-based dependency resolution for lazy, streaming dependency injection.
25//!
26//! **Note**: Uses `genawaiter` crate as a workaround for unstable native async yield.
27//! Will be migrated to native syntax when Rust stabilizes async generators.
28//!
29//! ```rust,no_run
30//! # #[cfg(feature = "generator")]
31//! # use reinhardt_di::generator::DependencyGenerator;
32//! # #[cfg(feature = "generator")]
33//! # async fn example() {
34//! // let gen = DependencyGenerator::new(|co| async move {
35//! //     let db = resolve_database().await;
36//! //     co.yield_(db).await;
37//! //
38//! //     let cache = resolve_cache().await;
39//! //     co.yield_(cache).await;
40//! // });
41//! # }
42//! ```
43//!
44//! ## Example
45//!
46//! ```rust,no_run
47//! # use reinhardt_di::{Depends, Injectable};
48//! # #[tokio::main]
49//! # async fn main() {
50//! // Define a dependency
51//! // struct Database {
52//! //     pool: DbPool,
53//! // }
54//! //
55//! // #[async_trait]
56//! // impl Injectable for Database {
57//! //     async fn inject(ctx: &InjectionContext) -> Result<Self> {
58//! //         Ok(Database {
59//! //             pool: get_pool().await?,
60//! //         })
61//! //     }
62//! // }
63//! //
64//! // Use in endpoint
65//! // #[endpoint(GET "/users")]
66//! // async fn list_users(
67//! //     db: Depends<Database>,
68//! // ) -> Result<Vec<User>> {
69//! //     db.query("SELECT * FROM users").await
70//! // }
71//! # }
72//! ```
73//!
74//! ## InjectionContext Construction
75//!
76//! InjectionContext is constructed using the builder pattern with a required singleton scope:
77//!
78//! ```rust
79//! use reinhardt_di::{InjectionContext, SingletonScope};
80//! use std::sync::Arc;
81//!
82//! // Create singleton scope
83//! let singleton = Arc::new(SingletonScope::new());
84//!
85//! // Build injection context with singleton scope
86//! let ctx = InjectionContext::builder(singleton).build();
87//! ```
88//!
89//! Optional request and param context can be added:
90//!
91//! ```ignore
92//! use reinhardt_di::{InjectionContext, SingletonScope};
93//! use reinhardt_http::Request;
94//! use std::sync::Arc;
95//!
96//! let singleton = Arc::new(SingletonScope::new());
97//!
98//! // Create a dummy request for demonstration
99//! let request = Request::builder()
100//!     .method(hyper::Method::GET)
101//!     .uri("/")
102//!     .version(hyper::Version::HTTP_11)
103//!     .headers(hyper::HeaderMap::new())
104//!     .body(bytes::Bytes::new())
105//!     .build()
106//!     .unwrap();
107//!
108//! let ctx = InjectionContext::builder(singleton)
109//!     .with_request(request)
110//!     .build();
111//! ```
112//!
113//! ## Circular Dependency Detection
114//!
115//! The DI system automatically detects circular dependencies at runtime using an optimized
116//! thread-local mechanism:
117//!
118//! ```ignore
119//! # use reinhardt_di::{Injectable, InjectionContext, SingletonScope, DiResult};
120//! # use async_trait::async_trait;
121//! # use std::sync::Arc;
122//! #[derive(Clone)]
123//! struct ServiceA {
124//!     b: Arc<ServiceB>,
125//! }
126//!
127//! #[derive(Clone)]
128//! struct ServiceB {
129//!     a: Arc<ServiceA>,  // Circular dependency!
130//! }
131//!
132//! #[async_trait]
133//! impl Injectable for ServiceA {
134//!     async fn inject(ctx: &InjectionContext) -> DiResult<Self> {
135//!         let b = ctx.resolve::<ServiceB>().await?;
136//!         Ok(ServiceA { b })
137//!     }
138//! }
139//!
140//! #[async_trait]
141//! impl Injectable for ServiceB {
142//!     async fn inject(ctx: &InjectionContext) -> DiResult<Self> {
143//!         let a = ctx.resolve::<ServiceA>().await?;
144//!         Ok(ServiceB { a })
145//!     }
146//! }
147//!
148//! let singleton = Arc::new(SingletonScope::new());
149//! let ctx = InjectionContext::builder(singleton).build();
150//!
151//! // This will return Err with DiError::CircularDependency
152//! let result = ctx.resolve::<ServiceA>().await;
153//! assert!(result.is_err());
154//! ```
155//!
156//! ### Performance Characteristics
157//!
158//! - **Cache Hit**: < 5% overhead (cycle detection completely skipped)
159//! - **Cache Miss**: 10-20% overhead (O(1) detection using HashSet)
160//! - **Deep Chains**: Sampling reduces linear cost (checks every 10th at depth 50+)
161//! - **Thread Safety**: Thread-local storage eliminates lock contention
162//!
163//! ## Development Tools Example
164//!
165//! ```ignore
166//! # #[cfg(feature = "dev-tools")]
167//! # use reinhardt_di::{visualization::DependencyGraph, profiling::DependencyProfiler};
168//! # #[cfg(feature = "dev-tools")]
169//! # fn main() {
170//! // fn visualize_dependencies() {
171//! //     let mut graph = DependencyGraph::new();
172//! //     graph.add_node("Database", "singleton");
173//! //     graph.add_node("UserService", "request");
174//! //     graph.add_dependency("UserService", "Database");
175//! //
176//! //     println!("{}", graph.to_dot());
177//! // }
178//! //
179//! // fn profile_resolution() {
180//! //     let mut profiler = DependencyProfiler::new();
181//! //     profiler.start_resolve("Database");
182//! //     // ... perform resolution ...
183//! //     profiler.end_resolve("Database");
184//! //
185//! //     let report = profiler.generate_report();
186//! //     println!("{}", report.to_string());
187//! // }
188//! # }
189//! ```
190
191pub mod params;
192
193pub mod context;
194pub mod cycle_detection;
195pub mod depends;
196pub mod function_handle;
197pub mod graph;
198pub mod injectable;
199pub mod injected;
200pub mod override_registry;
201pub mod provider;
202pub mod registry;
203pub mod scope;
204
205use thiserror::Error;
206
207pub use context::{InjectionContext, InjectionContextBuilder, RequestContext};
208pub use cycle_detection::{
209	CycleError, ResolutionGuard, begin_resolution, register_type_name, with_cycle_detection_scope,
210};
211pub use function_handle::FunctionHandle;
212pub use override_registry::OverrideRegistry;
213
214#[cfg(feature = "params")]
215pub use context::{ParamContext, Request};
216pub use depends::{Depends, DependsBuilder};
217pub use injectable::Injectable;
218pub use injected::{
219	DependencyScope as InjectedScope, Injected, InjectionMetadata, OptionalInjected,
220};
221pub use provider::{Provider, ProviderFn};
222pub use registry::{
223	DependencyRegistration, DependencyRegistry, DependencyScope, FactoryTrait, global_registry,
224};
225pub use scope::{RequestScope, Scope, SingletonScope};
226
227// Re-export inventory for macro use
228pub use inventory;
229
230// Re-export macros
231#[cfg(feature = "macros")]
232pub use reinhardt_di_macros::{injectable, injectable_factory};
233
234#[derive(Debug, Error)]
235pub enum DiError {
236	#[error("Dependency not found: {0}")]
237	NotFound(String),
238
239	#[error("Circular dependency detected: {0}")]
240	CircularDependency(String),
241
242	#[error("Provider error: {0}")]
243	ProviderError(String),
244
245	#[error("Type mismatch: expected {expected}, got {actual}")]
246	TypeMismatch { expected: String, actual: String },
247
248	#[error("Scope error: {0}")]
249	ScopeError(String),
250
251	#[error("Type '{type_name}' not registered. {hint}")]
252	NotRegistered { type_name: String, hint: String },
253
254	#[error("Dependency not registered: {type_name}")]
255	DependencyNotRegistered { type_name: String },
256
257	#[error("Internal error: {message}")]
258	Internal { message: String },
259}
260
261impl From<DiError> for reinhardt_core::exception::Error {
262	fn from(err: DiError) -> Self {
263		reinhardt_core::exception::Error::Internal(format!("Dependency injection error: {}", err))
264	}
265}
266
267pub type DiResult<T> = std::result::Result<T, DiError>;
268
269// Generator support
270#[cfg(feature = "generator")]
271pub mod generator;
272
273// Development tools
274#[cfg(feature = "dev-tools")]
275pub mod visualization;
276
277#[cfg(feature = "dev-tools")]
278pub mod profiling;
279
280#[cfg(feature = "dev-tools")]
281pub mod advanced_cache;