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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! Middleware system for the Ignitia web framework.
//!
//! This module provides the core middleware infrastructure and built-in middleware implementations
//! for common HTTP server functionality. Middleware can intercept and modify requests and responses,
//! enabling cross-cutting concerns like logging, rate limiting, compression, and security.
//!
//! # Overview
//!
//! Middleware in Ignitia follows a chain-of-responsibility pattern where each middleware can:
//! - Inspect and modify incoming requests
//! - Pass control to the next middleware or handler in the chain
//! - Inspect and modify outgoing responses
//! - Short-circuit the chain by returning early
//!
//! # Core Components
//!
//! - [`Middleware`] - Trait for implementing custom middleware
//! - [`Next`] - Represents the next step in the middleware chain
//! - [`BoxFuture`] - Type alias for boxed async futures used internally
//!
//! # Built-in Middleware
//!
//! The framework provides several production-ready middleware implementations:
//!
//! - [`LoggerMiddleware`] - Request/response logging
//! - [`CorsMiddleware`] - Cross-Origin Resource Sharing (CORS)
//! - [`RateLimitingMiddleware`] - Rate limiting and throttling
//! - [`SecurityMiddleware`] - Security headers and protections
//! - [`CompressionMiddleware`] - Response compression (gzip, brotli)
//! - [`BodySizeLimitMiddleware`] - Request body size limits
//! - [`RequestIdMiddleware`] - Request ID generation and tracking
//!
//! # Examples
//!
//! ## Using Built-in Middleware
//!
//! ```
//! use ignitia::prelude::*;
//!
//! let router = Router::new()
//! .middleware(LoggerMiddleware::new())
//! .middleware(CorsMiddleware::permissive())
//! .middleware(RateLimitingMiddleware::per_minute(100))
//! .get("/", || async { "Hello, World!" });
//! ```
//!
//! ## Creating Custom Middleware
//!
//! ```
//! use ignitia::prelude::*;
//! use ignitia::middleware::{Middleware, Next};
//!
//! #[derive(Clone)]
//! struct AuthMiddleware {
//! api_key: String,
//! }
//!
//! #[async_trait::async_trait]
//! impl Middleware for AuthMiddleware {
//! async fn handle(&self, req: Request, next: Next) -> Response {
//! // Check for API key in headers
//! if let Some(key) = req.header("x-api-key") {
//! if key == self.api_key {
//! return next.run(req).await;
//! }
//! }
//!
//! // Return unauthorized if no valid key
//! Response::new(StatusCode::UNAUTHORIZED)
//! .with_body("Invalid API key")
//! }
//! }
//!
//! let router = Router::new()
//! .middleware(AuthMiddleware {
//! api_key: "secret123".to_string(),
//! })
//! .get("/protected", || async { "Protected resource" });
//! ```
//!
//! ## Conditional Middleware
//!
//! ```
//! use ignitia::prelude::*;
//! use ignitia::middleware::{Middleware, Next};
//!
//! #[derive(Clone)]
//! struct ConditionalLogger {
//! verbose: bool,
//! }
//!
//! #[async_trait::async_trait]
//! impl Middleware for ConditionalLogger {
//! async fn handle(&self, req: Request, next: Next) -> Response {
//! if self.verbose {
//! println!("Request: {} {}", req.method, req.uri.path());
//! }
//!
//! let response = next.run(req).await;
//!
//! if self.verbose {
//! println!("Response: {}", response.status);
//! }
//!
//! response
//! }
//! }
//! ```
//!
//! ## Middleware with State
//!
//! ```
//! use ignitia::prelude::*;
//! use ignitia::middleware::{Middleware, Next};
//! use std::sync::Arc;
//! use parking_lot::Mutex;
//!
//! #[derive(Clone)]
//! struct RequestCounterMiddleware {
//! counter: Arc<Mutex<u64>>,
//! }
//!
//! impl RequestCounterMiddleware {
//! fn new() -> Self {
//! Self {
//! counter: Arc::new(Mutex::new(0)),
//! }
//! }
//!
//! fn count(&self) -> u64 {
//! *self.counter.lock()
//! }
//! }
//!
//! #[async_trait::async_trait]
//! impl Middleware for RequestCounterMiddleware {
//! async fn handle(&self, req: Request, next: Next) -> Response {
//! let count = {
//! let mut counter = self.counter.lock();
//! *counter += 1;
//! *counter
//! };
//!
//! println!("Request #{}", count);
//! next.run(req).await
//! }
//! }
//! ```
use Future;
use Pin;
use Arc;
use crate::;
pub use ;
pub use CompressionMiddleware;
pub use Cors as CorsMiddleware;
pub use LoggerMiddleware;
pub use ;
pub use ;
pub use SecurityMiddleware;
// #[async_trait::async_trait]
// pub trait Middleware: Send + Sync {
// async fn before(&self, _req: &mut Request) -> Result<()> {
// Ok(())
// }
// async fn after(&self, _req: &Request, _res: &mut Response) -> Result<()> {
// Ok(())
// }
// }
/// Type alias for boxed async futures.
///
/// Used internally by the middleware system for async execution. This type represents
/// a pinned, boxed future that resolves to type `T` and can be sent across threads.
///
/// # Type Parameters
///
/// * `'a` - Lifetime of the future
/// * `T` - The type the future resolves to
pub type BoxFuture<'a, T> = ;
/// Represents the next step in the middleware chain.
///
/// `Next` is a continuation that encapsulates the remaining middleware and the final
/// handler. When called via `run()`, it executes the next middleware (or handler) in
/// the chain and returns the response.
///
/// # Cloning
///
/// `Next` is cheap to clone as it uses `Arc` internally for shared ownership.
///
/// # Examples
///
/// ## Basic Usage
///
/// ```
/// use ignitia::middleware::{Middleware, Next};
/// use ignitia::{Request, Response};
///
/// #[derive(Clone)]
/// struct LoggingMiddleware;
///
/// #[async_trait::async_trait]
/// impl Middleware for LoggingMiddleware {
/// async fn handle(&self, req: Request, next: Next) -> Response {
/// println!("Processing request...");
///
/// // Call next middleware/handler
/// let response = next.run(req).await;
///
/// println!("Request processed");
/// response
/// }
/// }
/// ```
///
/// ## Conditional Next Execution
///
/// ```
/// use ignitia::middleware::{Middleware, Next};
/// use ignitia::{Request, Response, StatusCode};
///
/// #[derive(Clone)]
/// struct AuthMiddleware;
///
/// #[async_trait::async_trait]
/// impl Middleware for AuthMiddleware {
/// async fn handle(&self, req: Request, next: Next) -> Response {
/// if req.header("authorization").is_some() {
/// // Authorized - continue chain
/// next.run(req).await
/// } else {
/// // Not authorized - don't call next
/// Response::new(StatusCode::UNAUTHORIZED)
/// }
/// }
/// }
/// ```
/// Core middleware trait for intercepting and modifying HTTP requests and responses.
///
/// Middleware implementations must be `Clone + Send + Sync` to support concurrent request
/// processing. The `handle` method receives a request and a [`Next`] continuation that
/// represents the rest of the middleware chain.
///
/// # Examples
///
/// ## Basic Middleware
///
/// ```
/// use ignitia::prelude::*;
/// use ignitia::middleware::{Middleware, Next};
///
/// #[derive(Clone)]
/// struct TimingMiddleware;
///
/// #[async_trait::async_trait]
/// impl Middleware for TimingMiddleware {
/// async fn handle(&self, req: Request, next: Next) -> Response {
/// let start = std::time::Instant::now();
/// let response = next.run(req).await;
/// let duration = start.elapsed();
///
/// println!("Request took {:?}", duration);
/// response
/// }
/// }
/// ```
///
/// ## Modifying Requests
///
/// ```
/// use ignitia::prelude::*;
/// use ignitia::middleware::{Middleware, Next};
///
/// #[derive(Clone)]
/// struct HeaderInjector;
///
/// #[async_trait::async_trait]
/// impl Middleware for HeaderInjector {
/// async fn handle(&self, mut req: Request, next: Next) -> Response {
/// // Add custom header to request
/// req.headers.insert(
/// http::header::HeaderName::from_static("x-custom-header"),
/// http::HeaderValue::from_static("custom-value"),
/// );
///
/// next.run(req).await
/// }
/// }
/// ```
///
/// ## Modifying Responses
///
/// ```
/// use ignitia::prelude::*;
/// use ignitia::middleware::{Middleware, Next};
///
/// #[derive(Clone)]
/// struct CacheHeaderMiddleware;
///
/// #[async_trait::async_trait]
/// impl Middleware for CacheHeaderMiddleware {
/// async fn handle(&self, req: Request, next: Next) -> Response {
/// let mut response = next.run(req).await;
///
/// // Add cache control header
/// response.headers.insert(
/// http::header::CACHE_CONTROL,
/// http::HeaderValue::from_static("public, max-age=3600"),
/// );
///
/// response
/// }
/// }
/// ```
///
/// ## Short-circuiting
///
/// ```
/// use ignitia::prelude::*;
/// use ignitia::middleware::{Middleware, Next};
///
/// #[derive(Clone)]
/// struct MaintenanceMode {
/// enabled: bool,
/// }
///
/// #[async_trait::async_trait]
/// impl Middleware for MaintenanceMode {
/// async fn handle(&self, req: Request, next: Next) -> Response {
/// if self.enabled {
/// // Short-circuit and return maintenance response
/// return Response::new(StatusCode::SERVICE_UNAVAILABLE)
/// .with_body("Site is under maintenance");
/// }
///
/// next.run(req).await
/// }
/// }
/// ```
/// Helper trait for function-based middleware
/// This allows any async function with signature `async fn(Request, Next) -> Response` to be middleware
/// Convenience function to create middleware from a closure.
///
/// This function allows creating simple middleware without implementing the [`Middleware`] trait.
/// It's useful for one-off middleware or prototyping.
///
/// # Type Parameters
///
/// * `F` - The closure type
/// * `Fut` - The future type returned by the closure
///
/// # Arguments
///
/// * `f` - Async closure that takes `(Request, Next)` and returns `Response`
///
/// # Returns
///
/// Returns an implementation of [`Middleware`].
///
/// # Examples
///
/// ```
/// use ignitia::prelude::*;
/// use ignitia::middleware::from_fn;
///
/// let logger = from_fn(|req, next| async move {
/// println!("Request: {} {}", req.method, req.uri.path());
/// next.run(req).await
/// });
///
/// let router = Router::new()
/// .middleware(logger)
/// .get("/", || async { "Hello" });
/// ```
/// Wrapper for function-based middleware that converts Result<Response, E> to Response