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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! # Reinhardt Dependency Injection
//!
//! FastAPI-inspired dependency injection system for Reinhardt.
//!
//! ## Features
//!
//! - **Type-safe**: Full compile-time type checking
//! - **Async-first**: Built for async/await
//! - **Scoped**: Request-scoped and singleton dependencies
//! - **Composable**: Dependencies can depend on other dependencies
//! - **Cache**: Automatic caching within request scope
//! - **Circular Dependency Detection**: Automatic runtime detection with optimized performance
//!
//! ## Cargo features
//!
//! - `testing` — exposes [`DependencyRegistry::register_override`] and
//! [`testing::OverrideGuard`] for use by `reinhardt-testkit` and other
//! test harnesses. When operating on a per-context registry (via
//! `InjectionContextBuilder::with_registry`), `#[serial(di_registry)]`
//! is not required. Direct mutations of the global registry still
//! require `#[serial(di_registry)]`.
//!
//! ## Development Tools (dev-tools feature)
//!
//! When the `dev-tools` feature is enabled, additional debugging and profiling tools are available:
//!
//! - **Visualization**: Generate dependency graphs in DOT format for Graphviz
//! - **Profiling**: Track dependency resolution performance and identify bottlenecks
//! - **Advanced Caching**: LRU and TTL-based caching strategies
//!
//! ## Generator Support (generator feature) ✅
//!
//! Generator-based dependency resolution for lazy, streaming dependency injection.
//!
//! **Note**: Uses `genawaiter` crate as a workaround for unstable native async yield.
//! Will be migrated to native syntax when Rust stabilizes async generators.
//!
//! ```rust,no_run
//! # #[cfg(feature = "generator")]
//! # use reinhardt_di::generator::DependencyGenerator;
//! # #[cfg(feature = "generator")]
//! # async fn example() {
//! // let gen = DependencyGenerator::new(|co| async move {
//! // let db = resolve_database().await;
//! // co.yield_(db).await;
//! //
//! // let cache = resolve_cache().await;
//! // co.yield_(cache).await;
//! // });
//! # }
//! ```
//!
//! ## Example
//!
//! ```rust,no_run
//! # use reinhardt_di::{Depends, Injectable};
//! # #[tokio::main]
//! # async fn main() {
//! // Define a dependency
//! // struct Database {
//! // pool: DbPool,
//! // }
//! //
//! // #[async_trait]
//! // impl Injectable for Database {
//! // async fn inject(ctx: &InjectionContext) -> Result<Self> {
//! // Ok(Database {
//! // pool: get_pool().await?,
//! // })
//! // }
//! // }
//! //
//! // Use in endpoint
//! // #[endpoint(GET "/users")]
//! // async fn list_users(
//! // db: Depends<Database>,
//! // ) -> Result<Vec<User>> {
//! // db.query("SELECT * FROM users").await
//! // }
//! # }
//! ```
//!
//! ## InjectionContext Construction
//!
//! InjectionContext is constructed using the builder pattern with a required singleton scope:
//!
//! ```rust
//! use reinhardt_di::{InjectionContext, SingletonScope};
//! use std::sync::Arc;
//!
//! // Create singleton scope
//! let singleton = Arc::new(SingletonScope::new());
//!
//! // Build injection context with singleton scope
//! let ctx = InjectionContext::builder(singleton).build();
//! ```
//!
//! Optional request and param context can be added:
//!
//! ```no_run
//! use reinhardt_di::{InjectionContext, SingletonScope};
//! use reinhardt_http::Request;
//! use std::sync::Arc;
//!
//! let singleton = Arc::new(SingletonScope::new());
//!
//! // Create a dummy request for demonstration
//! let request = Request::builder()
//! .method(hyper::Method::GET)
//! .uri("/")
//! .version(hyper::Version::HTTP_11)
//! .headers(hyper::HeaderMap::new())
//! .body(bytes::Bytes::new())
//! .build()
//! .unwrap();
//!
//! let ctx = InjectionContext::builder(singleton)
//! .with_request(request)
//! .build();
//! ```
//!
//! ## Resolve Context
//!
//! The [`get_di_context`] function provides access to the active
//! [`InjectionContext`] within `#[injectable_factory]` and `#[injectable]`
//! function bodies, without requiring `#[inject]`.
//!
//! This enables factories to access the DI context for purposes like
//! passing it to downstream consumers:
//!
//! ```rust,ignore
//! use reinhardt_di::{ContextLevel, Depends, get_di_context};
//!
//! #[injectable_factory(scope = "transient")]
//! async fn make_router(
//! #[inject] config: Depends<AppConfig>,
//! ) -> Router {
//! let di_ctx = get_di_context(ContextLevel::Current);
//! Router::new().with_di_context(di_ctx)
//! }
//! ```
//!
//! [`ContextLevel::Root`] returns the application-level context, while
//! [`ContextLevel::Current`] returns the currently active context
//! (which may be a request-scoped fork).
//!
//! Use [`try_get_di_context`] for a non-panicking variant that returns
//! `None` when called outside of a DI resolution context.
//!
//! ## Circular Dependency Detection
//!
//! The DI system automatically detects circular dependencies at runtime using an optimized
//! thread-local mechanism:
//!
//! ```ignore
//! # use reinhardt_di::{Injectable, InjectionContext, SingletonScope, DiResult};
//! # use async_trait::async_trait;
//! # use std::sync::Arc;
//! #[derive(Clone)]
//! struct ServiceA {
//! b: Arc<ServiceB>,
//! }
//!
//! #[derive(Clone)]
//! struct ServiceB {
//! a: Arc<ServiceA>, // Circular dependency!
//! }
//!
//! #[async_trait]
//! impl Injectable for ServiceA {
//! async fn inject(ctx: &InjectionContext) -> DiResult<Self> {
//! let b = ctx.resolve::<ServiceB>().await?;
//! Ok(ServiceA { b })
//! }
//! }
//!
//! #[async_trait]
//! impl Injectable for ServiceB {
//! async fn inject(ctx: &InjectionContext) -> DiResult<Self> {
//! let a = ctx.resolve::<ServiceA>().await?;
//! Ok(ServiceB { a })
//! }
//! }
//!
//! let singleton = Arc::new(SingletonScope::new());
//! let ctx = InjectionContext::builder(singleton).build();
//!
//! // This will return Err with DiError::CircularDependency
//! let result = ctx.resolve::<ServiceA>().await;
//! assert!(result.is_err());
//! ```
//!
//! ### Performance Characteristics
//!
//! - **Cache Hit**: < 5% overhead (cycle detection completely skipped)
//! - **Cache Miss**: 10-20% overhead (O(1) detection using HashSet)
//! - **Deep Chains**: Sampling reduces linear cost (checks every 10th at depth 50+)
//! - **Thread Safety**: Thread-local storage eliminates lock contention
//!
//! ## Development Tools Example
//!
//! ```no_run
//! # #[cfg(feature = "dev-tools")]
//! # use reinhardt_di::{visualization::DependencyGraph, profiling::DependencyProfiler};
//! # #[cfg(feature = "dev-tools")]
//! # fn main() {
//! // fn visualize_dependencies() {
//! // let mut graph = DependencyGraph::new();
//! // graph.add_node("Database", "singleton");
//! // graph.add_node("UserService", "request");
//! // graph.add_dependency("UserService", "Database");
//! //
//! // println!("{}", graph.to_dot());
//! // }
//! //
//! // fn profile_resolution() {
//! // let mut profiler = DependencyProfiler::new();
//! // profiler.start_resolve("Database");
//! // // ... perform resolution ...
//! // profiler.end_resolve("Database");
//! //
//! // let report = profiler.generate_report();
//! // println!("{}", report.to_string());
//! // }
//! # }
//! ```
//!
//! ## Auth Extractor DI Context Requirements
//!
//! The `reinhardt-auth` crate provides injectable auth extractors that depend on
//! specific DI context configuration. Understanding these requirements is essential
//! for proper authentication integration.
//!
//! ### `CurrentUser<U>` (recommended)
//!
//! Loads the full user model from the database. Requires:
//!
//! - **`DatabaseConnection`** registered as a singleton in `InjectionContext`
//! - **`AuthState`** present in request extensions (set by authentication middleware)
//! - Feature `params` enabled on `reinhardt-auth`
//!
//! Returns an injection error if any requirement is missing (fail-fast behavior).
//!
//! ```ignore
//! use reinhardt_auth::CurrentUser;
//! use reinhardt_auth::DefaultUser;
//!
//! #[get("/profile/")]
//! pub async fn profile(
//! #[inject] CurrentUser(user): CurrentUser<DefaultUser>,
//! ) -> ViewResult<Response> {
//! let username = user.get_username();
//! // ...
//! }
//! ```
//!
//! ### `AuthInfo` (lightweight alternative)
//!
//! Extracts authentication metadata without a database query. Requires:
//!
//! - **`AuthState`** present in request extensions (set by authentication middleware)
//! - No `DatabaseConnection` needed
//!
//! ### `AuthUser<U>` (deprecated)
//!
//! Deprecated in favor of `CurrentUser<U>` and scheduled for removal in 0.3.
//! It retains the same fail-fast behavior as `CurrentUser<U>` for 0.2
//! compatibility.
//!
//! ### Startup Validation
//!
//! Call `reinhardt_auth::validate_auth_extractors()` during application startup
//! to verify that required dependencies (e.g., `DatabaseConnection`) are registered
//! before the first request arrives.
use Error;
pub use ;
pub use ;
pub use FunctionHandle;
pub use OverrideRegistry;
pub use ;
pub use ;
pub use Injectable;
pub use ;
pub use ;
pub use DiRegistrationList;
pub use ;
pub use ;
pub use ;
pub use OverrideGuard;
pub use ;
// Re-export inventory and async_trait for macro use
pub use async_trait;
pub use inventory;
// Re-export macros
pub use ;
/// Errors that can occur during dependency injection resolution.
/// A specialized `Result` type for dependency injection operations.
pub type DiResult<T> = Result;
// Generator support
// Development tools