reinhardt-di 0.2.2

Dependency injection system for Reinhardt, inspired by FastAPI
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
//! # Reinhardt Parameter Extraction
//!
//! FastAPI-inspired parameter extraction system.
//!
//! ## Features
//!
//! - **Path Parameters**: Extract from URL path
//! - **Query Parameters**: Extract from query string
//! - **Headers**: Extract from request headers
//! - **Cookies**: Extract from cookies
//! - **Body**: Extract from request body
//! - **Type-safe**: Full compile-time type checking
//!
//! ## Example
//!
//! ```rust,no_run
//! use reinhardt_di::params::{Path, Query, Json};
//! # use serde::Deserialize;
//! # #[derive(Deserialize)]
//! # struct UserFilter { page: i32 }
//! # #[derive(Deserialize)]
//! # struct UpdateUser { name: String }
//!
//! // Extract path parameter
//! let id = Path(42_i64);
//! let user_id: i64 = id.0; // or *id
//!
//! // Extract query parameters
//! # let filter_data = UserFilter { page: 1 };
//! let filter = Query(filter_data);
//! let page = filter.0.page;
//!
//! // Extract JSON body
//! # let user_data = UpdateUser { name: "Alice".to_string() };
//! let body = Json(user_data);
//! let name = &body.0.name;
//! ```

pub mod body;
pub mod cookie;
pub mod cookie_named;
pub(crate) mod cookie_util;
pub mod extract;
pub mod form;
pub mod has_inner;
pub mod header;
pub mod header_named;
pub mod json;
#[cfg(feature = "multipart")]
pub mod multipart;
pub mod path;
pub mod query;
pub mod validation;

use reinhardt_http::Error as CoreError;
use std::any::TypeId;
use std::collections::HashMap;
use std::sync::Mutex;
use thiserror::Error;

// Re-export Request from reinhardt-http and parameter error types from reinhardt-exception
pub use reinhardt_core::exception::{ParamErrorContext, ParamType};
pub use reinhardt_http::Request;

// Import helper functions for parameter error extraction
use reinhardt_core::exception::param_error::{
	extract_field_from_serde_error, extract_field_from_urlencoded_error,
};

pub use body::Body;
pub use cookie::{Cookie, CookieStruct};
pub use cookie_named::{CookieName, CookieNamed, CsrfToken, SessionId};
pub use extract::FromRequest;
pub use form::Form;
pub use has_inner::HasInner;
pub use header::{Header, HeaderStruct};
pub use header_named::{Authorization, ContentType, HeaderName, HeaderNamed};
pub use json::Json;
#[cfg(feature = "multipart")]
pub use multipart::Multipart;
pub use path::{Path, PathStruct};
pub use query::Query;
#[cfg(feature = "validation")]
pub use validation::Validated;
pub use validation::{
	ValidatedForm, ValidatedPath, ValidatedQuery, ValidationConstraints, WithValidation,
};

// Box wrappers to reduce enum size (clippy::result_large_err mitigation)
// ParamErrorContext contains multiple String fields which make the enum large
/// Errors that can occur during parameter extraction from HTTP requests.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ParamError {
	/// A required parameter was not provided.
	#[error("Missing required parameter: {0}")]
	MissingParameter(String),

	/// The parameter value is invalid.
	#[error("{}", .0.format_error())]
	InvalidParameter(Box<ParamErrorContext>),

	/// The parameter value could not be parsed to the expected type.
	#[error("{}", .0.format_error())]
	ParseError(Box<ParamErrorContext>),

	/// The parameter value could not be deserialized.
	#[error("{}", .0.format_error())]
	DeserializationError(Box<ParamErrorContext>),

	/// The URL-encoded parameter could not be decoded.
	#[error("{}", .0.format_error())]
	UrlEncodingError(Box<ParamErrorContext>),

	/// An error occurred while reading the request body.
	#[error("Request body error: {0}")]
	BodyError(String),

	/// The request payload exceeds the configured size limit.
	#[error("Payload too large: {0}")]
	PayloadTooLarge(String),

	/// The request lacks valid authentication for an extractor that
	/// requires it. Maps to `CoreError::Authentication` and therefore to
	/// HTTP 401 once propagated through the handler macro. Use this when
	/// an authenticated session, token, or identity is missing rather
	/// than when a request parameter is malformed (see #4446).
	#[error("Authentication required: {0}")]
	Authentication(String),

	/// The extractor failed for a reason that is neither a malformed
	/// request nor a missing identity (e.g. a misconfigured DI scope, a
	/// broken provider, or another infrastructure-level failure). Maps
	/// to `CoreError::Internal` so the handler returns HTTP 500 rather
	/// than masking the failure as a 4xx response.
	#[error("Internal extractor error: {0}")]
	Internal(String),

	/// The parameter failed validation constraints.
	#[cfg(feature = "validation")]
	#[error("{}", .0.format_error())]
	ValidationError(Box<ParamErrorContext>),

	/// Struct-level validation failed after successful extraction.
	///
	/// Contains structured per-field errors from `Validate::validate()`.
	/// Unlike `ValidationError` (which uses `ParamErrorContext` for single-field
	/// constraint violations), this variant carries a full `ValidationErrors`
	/// map for multi-field struct validation.
	#[cfg(feature = "validation")]
	#[error("Validation failed: {0:?}")]
	ValidationFailed(Box<reinhardt_core::validators::ValidationErrors>),
}

impl ParamError {
	/// Create a deserialization error from serde_json::Error
	pub fn json_deserialization<T>(err: serde_json::Error, raw_value: Option<String>) -> Self {
		let field_name = extract_field_from_serde_error(&err);
		let mut ctx = ParamErrorContext::new(ParamType::Json, err.to_string())
			.with_expected_type::<T>()
			.with_source(Box::new(err));

		if let Some(field) = field_name {
			ctx = ctx.with_field(field);
		}

		if let Some(raw) = raw_value {
			ctx = ctx.with_raw_value(raw);
		}

		ParamError::DeserializationError(Box::new(ctx))
	}

	/// Create a URL encoding error
	pub fn url_encoding<T>(
		param_type: ParamType,
		err: serde_urlencoded::de::Error,
		raw_value: Option<String>,
	) -> Self {
		let field_name = extract_field_from_urlencoded_error(&err);
		let mut ctx = ParamErrorContext::new(param_type, err.to_string())
			.with_expected_type::<T>()
			.with_source(Box::new(err));

		if let Some(field) = field_name {
			ctx = ctx.with_field(field);
		}

		if let Some(raw) = raw_value {
			ctx = ctx.with_raw_value(raw);
		}

		ParamError::UrlEncodingError(Box::new(ctx))
	}

	/// Create an invalid parameter error
	pub fn invalid<T>(param_type: ParamType, message: impl Into<String>) -> Self {
		let ctx = ParamErrorContext::new(param_type, message).with_expected_type::<T>();
		ParamError::InvalidParameter(Box::new(ctx))
	}

	/// Create a parse error
	pub fn parse<T>(
		param_type: ParamType,
		message: impl Into<String>,
		source: Box<dyn std::error::Error + Send + Sync>,
	) -> Self {
		let ctx = ParamErrorContext::new(param_type, message)
			.with_expected_type::<T>()
			.with_source(source);
		ParamError::ParseError(Box::new(ctx))
	}

	/// Get the error context if available
	pub fn context(&self) -> Option<&ParamErrorContext> {
		match self {
			ParamError::InvalidParameter(ctx) => Some(ctx),
			ParamError::ParseError(ctx) => Some(ctx),
			ParamError::DeserializationError(ctx) => Some(ctx),
			ParamError::UrlEncodingError(ctx) => Some(ctx),
			#[cfg(feature = "validation")]
			ParamError::ValidationError(ctx) => Some(ctx),
			_ => None,
		}
	}

	/// Format the error as multiple lines for detailed logging
	pub fn format_multiline(&self, include_raw_value: bool) -> String {
		match self.context() {
			Some(ctx) => ctx.format_multiline(include_raw_value),
			None => format!("  {}", self),
		}
	}
}

impl From<ParamError> for CoreError {
	fn from(err: ParamError) -> Self {
		// Preserve authentication semantics: `Authentication` MUST surface
		// as `CoreError::Authentication` so the handler returns HTTP 401
		// rather than the 400 implied by `Validation`/`ParamValidation`.
		// `Internal` similarly MUST surface as `CoreError::Internal` so a
		// genuine misconfiguration (e.g. a corrupted DI scope) is not
		// masked as a 4xx response. See #4446.
		let err = match err {
			ParamError::Authentication(msg) => return CoreError::Authentication(msg),
			ParamError::Internal(msg) => return CoreError::Internal(msg),
			other => other,
		};
		// Use structured context if available, otherwise fall back to generic validation error
		match err.context() {
			Some(ctx) => CoreError::ParamValidation(Box::new(ctx.clone())),
			None => CoreError::Validation(err.to_string()),
		}
	}
}

/// A specialized `Result` type for parameter extraction operations.
pub type ParamResult<T> = std::result::Result<T, ParamError>;

/// Context for parameter extraction
pub struct ParamContext {
	/// Path parameters extracted from the URL.
	///
	/// Stored in URL pattern declaration order so that tuple extractors such
	/// as `Path<(T1, T2)>` can rely on positional ordering matching the URL
	/// pattern. See issue #4013.
	pub path_params: reinhardt_http::PathParams,
	/// Header name registry keyed by value type
	header_names: HashMap<TypeId, &'static str>,
	/// Cookie name registry keyed by value type
	cookie_names: HashMap<TypeId, &'static str>,
	/// Cached request body bytes. Populated on first call to
	/// [`read_body_cached`](Self::read_body_cached) so that multiple
	/// body-consuming extractors (e.g. two `Json<T>` factories in the same
	/// request, see #4645) can share a single read of the underlying
	/// stream instead of failing with "body already consumed" on the
	/// second call. The `Mutex` is held only briefly during init.
	body_cache: Mutex<Option<bytes::Bytes>>,
}

impl ParamContext {
	/// Create a new empty ParamContext
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::params::ParamContext;
	///
	/// let ctx = ParamContext::new();
	/// assert_eq!(ctx.path_params.len(), 0);
	/// ```
	pub fn new() -> Self {
		Self {
			path_params: reinhardt_http::PathParams::new(),
			header_names: HashMap::new(),
			cookie_names: HashMap::new(),
			body_cache: Mutex::new(None),
		}
	}
	/// Create a ParamContext with pre-populated path parameters.
	///
	/// Accepts anything convertible into [`reinhardt_http::PathParams`],
	/// including a `HashMap<String, String>` (note: converting from a
	/// `HashMap` does not preserve ordering — supply a
	/// `Vec<(String, String)>` or a `PathParams` directly when ordering
	/// matters, as it does for tuple extractors). See issue #4013.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::params::ParamContext;
	/// use reinhardt_http::PathParams;
	///
	/// let mut params = PathParams::new();
	/// params.insert("id", "42");
	/// params.insert("name", "test");
	///
	/// let ctx = ParamContext::with_path_params(params);
	/// assert_eq!(ctx.get_path_param("id"), Some("42"));
	/// assert_eq!(ctx.get_path_param("name"), Some("test"));
	/// ```
	pub fn with_path_params(path_params: impl Into<reinhardt_http::PathParams>) -> Self {
		Self {
			path_params: path_params.into(),
			header_names: HashMap::new(),
			cookie_names: HashMap::new(),
			body_cache: Mutex::new(None),
		}
	}
	/// Get a path parameter by name
	///
	/// Returns `None` if the parameter doesn't exist.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_di::params::ParamContext;
	/// use std::collections::HashMap;
	///
	/// let mut params = HashMap::new();
	/// params.insert("user_id".to_string(), "123".to_string());
	///
	/// let ctx = ParamContext::with_path_params(params);
	/// assert_eq!(ctx.get_path_param("user_id"), Some("123"));
	/// assert_eq!(ctx.get_path_param("missing"), None);
	/// ```
	pub fn get_path_param(&self, name: &str) -> Option<&str> {
		self.path_params.get(name).map(|s| s.as_str())
	}

	/// Register a header name for the given value type `T`
	pub fn set_header_name<T: 'static>(&mut self, name: &'static str) {
		self.header_names.insert(TypeId::of::<T>(), name);
	}

	/// Get a registered header name for value type `T`
	pub fn get_header_name<T: 'static>(&self) -> Option<&'static str> {
		self.header_names.get(&TypeId::of::<T>()).copied()
	}

	/// Register a cookie name for the given value type `T`
	pub fn set_cookie_name<T: 'static>(&mut self, name: &'static str) {
		self.cookie_names.insert(TypeId::of::<T>(), name);
	}

	/// Get a registered cookie name for value type `T`
	pub fn get_cookie_name<T: 'static>(&self) -> Option<&'static str> {
		self.cookie_names.get(&TypeId::of::<T>()).copied()
	}

	/// Read the request body, caching the bytes on first call.
	///
	/// `Request::read_body()` is one-shot: it flips an internal
	/// `body_consumed` flag and refuses subsequent calls. That is fine for
	/// a single handler, but breaks down once multiple request-scoped
	/// extractors (e.g. two `Json<T>` factories within one
	/// `#[injectable_factory]` resolution chain — see #4645) want to read
	/// the same body. This method consumes the body exactly once per
	/// request and caches the resulting [`bytes::Bytes`] in
	/// `ParamContext`; subsequent callers receive a cheap `Bytes::clone`
	/// (refcount bump, no copy).
	///
	/// Returns `ParamError::BodyError` if the underlying read fails or
	/// the body was previously consumed through some path that bypassed
	/// this cache.
	pub fn read_body_cached(&self, request: &reinhardt_http::Request) -> ParamResult<bytes::Bytes> {
		// Brief critical section: short-lived sync mutex is acceptable
		// because the cached bytes never block on I/O — the only work
		// done inside the lock is the (sync) `request.read_body()` call,
		// which is itself just an `AtomicBool` swap + `Bytes::clone()`.
		let mut guard = self
			.body_cache
			.lock()
			.expect("ParamContext body_cache mutex poisoned");
		if let Some(bytes) = guard.as_ref() {
			return Ok(bytes.clone());
		}
		let bytes = request
			.read_body()
			.map_err(|e| ParamError::BodyError(format!("Failed to read body: {}", e)))?;
		*guard = Some(bytes.clone());
		Ok(bytes)
	}
}

impl Default for ParamContext {
	fn default() -> Self {
		Self::new()
	}
}