reinhardt-http 0.1.0-rc.2

HTTP primitives, request and response handling for Reinhardt
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
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
//! Middleware and handler traits for HTTP request processing.
//!
//! This module provides the core abstractions for handling HTTP requests
//! and composing middleware chains.
//!
//! ## Handler
//!
//! The `Handler` trait is the core abstraction for processing requests:
//!
//! ```rust
//! use reinhardt_http::{Handler, Request, Response};
//! use async_trait::async_trait;
//!
//! struct MyHandler;
//!
//! #[async_trait]
//! impl Handler for MyHandler {
//!     async fn handle(&self, request: Request) -> reinhardt_core::exception::Result<Response> {
//!         Ok(Response::ok().with_body("Hello!"))
//!     }
//! }
//! ```
//!
//! ## Middleware
//!
//! Middleware wraps handlers to add cross-cutting concerns:
//!
//! ```rust
//! use reinhardt_http::{Handler, Middleware, Request, Response};
//! use async_trait::async_trait;
//! use std::sync::Arc;
//!
//! struct LoggingMiddleware;
//!
//! #[async_trait]
//! impl Middleware for LoggingMiddleware {
//!     async fn process(&self, request: Request, next: Arc<dyn Handler>) -> reinhardt_core::exception::Result<Response> {
//!         println!("Request: {} {}", request.method, request.uri);
//!         next.handle(request).await
//!     }
//! }
//! ```

use async_trait::async_trait;
use reinhardt_core::exception::Result;
use std::sync::Arc;

use crate::{Request, Response};

/// Handler trait for processing requests.
///
/// This is the core abstraction - all request handlers implement this trait.
/// Handlers receive a request and produce a response or an error.
#[async_trait]
pub trait Handler: Send + Sync {
	/// Handles an HTTP request and produces a response.
	///
	/// # Errors
	///
	/// Returns an error if the request cannot be processed.
	async fn handle(&self, request: Request) -> Result<Response>;
}

/// Blanket implementation for `Arc<T>` where T: Handler.
///
/// This allows `Arc<dyn Handler>` to be used as a Handler,
/// enabling shared ownership of handlers across threads.
#[async_trait]
impl<T: Handler + ?Sized> Handler for Arc<T> {
	async fn handle(&self, request: Request) -> Result<Response> {
		(**self).handle(request).await
	}
}

/// Middleware trait for request/response processing.
///
/// Uses composition pattern instead of inheritance.
/// Middleware can modify requests before passing to the next handler,
/// or modify responses after the handler processes the request.
#[async_trait]
pub trait Middleware: Send + Sync {
	/// Processes a request through this middleware.
	///
	/// # Arguments
	///
	/// * `request` - The incoming HTTP request
	/// * `next` - The next handler in the chain to call
	///
	/// # Errors
	///
	/// Returns an error if the middleware or next handler fails.
	async fn process(&self, request: Request, next: Arc<dyn Handler>) -> Result<Response>;

	/// Determines whether this middleware should be executed for the given request.
	///
	/// This method enables conditional execution of middleware, allowing the middleware
	/// chain to skip unnecessary middleware based on request properties.
	///
	/// # Performance Benefits
	///
	/// By implementing this method, middleware chains can achieve O(k) complexity
	/// instead of O(n), where k is the number of middleware that should run,
	/// and k <= n (total middleware count).
	///
	/// # Common Use Cases
	///
	/// - Skip authentication middleware for public endpoints
	/// - Skip compression middleware for already compressed responses
	/// - Skip CORS middleware for same-origin requests
	/// - Skip rate limiting for internal/admin requests
	///
	/// # Default Implementation
	///
	/// By default, returns `true` (always execute), maintaining backward compatibility.
	fn should_continue(&self, _request: &Request) -> bool {
		true
	}
}

/// Middleware chain - composes multiple middleware into a single handler.
///
/// The chain processes requests through middleware in the order they were added,
/// with optimizations for conditional execution and early termination.
pub struct MiddlewareChain {
	middlewares: Vec<Arc<dyn Middleware>>,
	handler: Arc<dyn Handler>,
}

impl MiddlewareChain {
	/// Creates a new middleware chain with the given handler.
	///
	/// # Examples
	///
	/// ```rust
	/// use reinhardt_http::{MiddlewareChain, Handler, Request, Response};
	/// use std::sync::Arc;
	///
	/// struct MyHandler;
	///
	/// #[async_trait::async_trait]
	/// impl Handler for MyHandler {
	///     async fn handle(&self, _request: Request) -> reinhardt_core::exception::Result<Response> {
	///         Ok(Response::ok())
	///     }
	/// }
	///
	/// let handler = Arc::new(MyHandler);
	/// let chain = MiddlewareChain::new(handler);
	/// ```
	pub fn new(handler: Arc<dyn Handler>) -> Self {
		Self {
			middlewares: Vec::new(),
			handler,
		}
	}

	/// Adds a middleware to the chain using builder pattern.
	///
	/// # Examples
	///
	/// ```rust
	/// use reinhardt_http::{MiddlewareChain, Handler, Middleware, Request, Response};
	/// use std::sync::Arc;
	///
	/// # struct MyHandler;
	/// # struct MyMiddleware;
	/// # #[async_trait::async_trait]
	/// # impl Handler for MyHandler {
	/// #     async fn handle(&self, _request: Request) -> reinhardt_core::exception::Result<Response> {
	/// #         Ok(Response::ok())
	/// #     }
	/// # }
	/// # #[async_trait::async_trait]
	/// # impl Middleware for MyMiddleware {
	/// #     async fn process(&self, request: Request, next: Arc<dyn Handler>) -> reinhardt_core::exception::Result<Response> {
	/// #         next.handle(request).await
	/// #     }
	/// # }
	/// let handler = Arc::new(MyHandler);
	/// let middleware = Arc::new(MyMiddleware);
	/// let chain = MiddlewareChain::new(handler)
	///     .with_middleware(middleware);
	/// ```
	pub fn with_middleware(mut self, middleware: Arc<dyn Middleware>) -> Self {
		self.middlewares.push(middleware);
		self
	}

	/// Adds a middleware to the chain.
	///
	/// # Examples
	///
	/// ```rust
	/// use reinhardt_http::{MiddlewareChain, Handler, Middleware, Request, Response};
	/// use std::sync::Arc;
	///
	/// # struct MyHandler;
	/// # struct MyMiddleware;
	/// # #[async_trait::async_trait]
	/// # impl Handler for MyHandler {
	/// #     async fn handle(&self, _request: Request) -> reinhardt_core::exception::Result<Response> {
	/// #         Ok(Response::ok())
	/// #     }
	/// # }
	/// # #[async_trait::async_trait]
	/// # impl Middleware for MyMiddleware {
	/// #     async fn process(&self, request: Request, next: Arc<dyn Handler>) -> reinhardt_core::exception::Result<Response> {
	/// #         next.handle(request).await
	/// #     }
	/// # }
	/// let handler = Arc::new(MyHandler);
	/// let middleware = Arc::new(MyMiddleware);
	/// let mut chain = MiddlewareChain::new(handler);
	/// chain.add_middleware(middleware);
	/// ```
	pub fn add_middleware(&mut self, middleware: Arc<dyn Middleware>) {
		self.middlewares.push(middleware);
	}
}

#[async_trait]
impl Handler for MiddlewareChain {
	async fn handle(&self, request: Request) -> Result<Response> {
		if self.middlewares.is_empty() {
			return self.handler.handle(request).await;
		}

		// Build nested handler chain using composition with optimizations:
		// 1. Conditional execution (skip middleware based on should_continue)
		// 2. Short-circuiting (early return if response.should_stop_chain() is true)
		//
		// Performance improvements:
		// - Condition check: O(1) per middleware
		// - Skip unnecessary middleware: achieves O(k) where k <= n
		// - Early return: stops processing on first stop_chain=true response
		let mut current_handler = self.handler.clone();

		// Filter middleware based on should_continue condition
		// This achieves the O(k) optimization where k is the number of middleware that should run
		let active_middlewares: Vec<_> = self
			.middlewares
			.iter()
			.rev()
			.filter(|mw| mw.should_continue(&request))
			.collect();

		for middleware in active_middlewares {
			let mw = middleware.clone();
			let handler = current_handler.clone();

			current_handler = Arc::new(ConditionalComposedHandler {
				middleware: mw,
				next: handler,
			});
		}

		current_handler.handle(request).await
	}
}

/// Optimized internal handler that composes middleware with next handler.
///
/// Supports short-circuiting via `response.should_stop_chain()`.
struct ConditionalComposedHandler {
	middleware: Arc<dyn Middleware>,
	next: Arc<dyn Handler>,
}

#[async_trait]
impl Handler for ConditionalComposedHandler {
	async fn handle(&self, request: Request) -> Result<Response> {
		// Process the request through this middleware
		let response = self.middleware.process(request, self.next.clone()).await?;

		// Short-circuit: if response indicates chain should stop, return immediately
		// This prevents further middleware/handlers from executing
		if response.should_stop_chain() {
			return Ok(response);
		}

		Ok(response)
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use bytes::Bytes;
	use hyper::{HeaderMap, Method, Version};

	// Mock handler for testing
	struct MockHandler {
		response_body: String,
	}

	#[async_trait]
	impl Handler for MockHandler {
		async fn handle(&self, _request: Request) -> Result<Response> {
			Ok(Response::ok().with_body(self.response_body.clone()))
		}
	}

	// Mock middleware for testing
	struct MockMiddleware {
		prefix: String,
	}

	#[async_trait]
	impl Middleware for MockMiddleware {
		async fn process(&self, request: Request, next: Arc<dyn Handler>) -> Result<Response> {
			// Call the next handler
			let response = next.handle(request).await?;

			// Modify the response
			let current_body = String::from_utf8(response.body.to_vec()).unwrap_or_default();
			let new_body = format!("{}{}", self.prefix, current_body);

			Ok(Response::ok().with_body(new_body))
		}
	}

	fn create_test_request() -> Request {
		Request::builder()
			.method(Method::GET)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap()
	}

	#[tokio::test]
	async fn test_handler_basic() {
		let handler = MockHandler {
			response_body: "Hello".to_string(),
		};

		let request = create_test_request();
		let response = handler.handle(request).await.unwrap();

		let body = String::from_utf8(response.body.to_vec()).unwrap();
		assert_eq!(body, "Hello");
	}

	#[tokio::test]
	async fn test_middleware_basic() {
		let handler = Arc::new(MockHandler {
			response_body: "World".to_string(),
		});

		let middleware = MockMiddleware {
			prefix: "Hello, ".to_string(),
		};

		let request = create_test_request();
		let response = middleware.process(request, handler).await.unwrap();

		let body = String::from_utf8(response.body.to_vec()).unwrap();
		assert_eq!(body, "Hello, World");
	}

	#[tokio::test]
	async fn test_middleware_chain_empty() {
		let handler = Arc::new(MockHandler {
			response_body: "Test".to_string(),
		});

		let chain = MiddlewareChain::new(handler);

		let request = create_test_request();
		let response = chain.handle(request).await.unwrap();

		let body = String::from_utf8(response.body.to_vec()).unwrap();
		assert_eq!(body, "Test");
	}

	#[tokio::test]
	async fn test_middleware_chain_single() {
		let handler = Arc::new(MockHandler {
			response_body: "Handler".to_string(),
		});

		let middleware1 = Arc::new(MockMiddleware {
			prefix: "MW1:".to_string(),
		});

		let chain = MiddlewareChain::new(handler).with_middleware(middleware1);

		let request = create_test_request();
		let response = chain.handle(request).await.unwrap();

		let body = String::from_utf8(response.body.to_vec()).unwrap();
		assert_eq!(body, "MW1:Handler");
	}

	#[tokio::test]
	async fn test_middleware_chain_multiple() {
		let handler = Arc::new(MockHandler {
			response_body: "Data".to_string(),
		});

		let middleware1 = Arc::new(MockMiddleware {
			prefix: "M1:".to_string(),
		});

		let middleware2 = Arc::new(MockMiddleware {
			prefix: "M2:".to_string(),
		});

		let chain = MiddlewareChain::new(handler)
			.with_middleware(middleware1)
			.with_middleware(middleware2);

		let request = create_test_request();
		let response = chain.handle(request).await.unwrap();

		let body = String::from_utf8(response.body.to_vec()).unwrap();
		// Middleware are applied in the order they were added
		assert_eq!(body, "M1:M2:Data");
	}

	#[tokio::test]
	async fn test_middleware_chain_add_middleware() {
		let handler = Arc::new(MockHandler {
			response_body: "Result".to_string(),
		});

		let middleware = Arc::new(MockMiddleware {
			prefix: "Prefix:".to_string(),
		});

		let mut chain = MiddlewareChain::new(handler);
		chain.add_middleware(middleware);

		let request = create_test_request();
		let response = chain.handle(request).await.unwrap();

		let body = String::from_utf8(response.body.to_vec()).unwrap();
		assert_eq!(body, "Prefix:Result");
	}

	// Conditional middleware that only runs for /api/* paths
	struct ConditionalMiddleware {
		prefix: String,
	}

	#[async_trait]
	impl Middleware for ConditionalMiddleware {
		async fn process(&self, request: Request, next: Arc<dyn Handler>) -> Result<Response> {
			let response = next.handle(request).await?;
			let current_body = String::from_utf8(response.body.to_vec()).unwrap_or_default();
			let new_body = format!("{}{}", self.prefix, current_body);
			Ok(Response::ok().with_body(new_body))
		}

		fn should_continue(&self, request: &Request) -> bool {
			request.uri.path().starts_with("/api/")
		}
	}

	#[tokio::test]
	async fn test_middleware_conditional_skip() {
		let handler = Arc::new(MockHandler {
			response_body: "Response".to_string(),
		});

		let conditional_mw = Arc::new(ConditionalMiddleware {
			prefix: "API:".to_string(),
		});

		let chain = MiddlewareChain::new(handler).with_middleware(conditional_mw);

		// Test with /api/ path - middleware should run
		let api_request = Request::builder()
			.method(Method::GET)
			.uri("/api/users")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();
		let response = chain.handle(api_request).await.unwrap();
		let body = String::from_utf8(response.body.to_vec()).unwrap();
		assert_eq!(body, "API:Response");

		// Test with non-/api/ path - middleware should be skipped
		let non_api_request = Request::builder()
			.method(Method::GET)
			.uri("/public")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();
		let response = chain.handle(non_api_request).await.unwrap();
		let body = String::from_utf8(response.body.to_vec()).unwrap();
		assert_eq!(body, "Response"); // No prefix because middleware was skipped
	}

	// Middleware that returns early with stop_chain=true
	struct ShortCircuitMiddleware {
		should_stop: bool,
	}

	#[async_trait]
	impl Middleware for ShortCircuitMiddleware {
		async fn process(&self, request: Request, next: Arc<dyn Handler>) -> Result<Response> {
			if self.should_stop {
				// Return early without calling next
				return Ok(Response::unauthorized()
					.with_body("Auth required")
					.with_stop_chain(true));
			}
			next.handle(request).await
		}
	}

	#[tokio::test]
	async fn test_middleware_short_circuit() {
		let handler = Arc::new(MockHandler {
			response_body: "Handler Response".to_string(),
		});

		let short_circuit_mw = Arc::new(ShortCircuitMiddleware { should_stop: true });
		let normal_mw = Arc::new(MockMiddleware {
			prefix: "Normal:".to_string(),
		});

		let chain = MiddlewareChain::new(handler)
			.with_middleware(short_circuit_mw)
			.with_middleware(normal_mw);

		let request = create_test_request();
		let response = chain.handle(request).await.unwrap();

		// Should get unauthorized response, not the handler response
		assert_eq!(response.status, hyper::StatusCode::UNAUTHORIZED);
		let body = String::from_utf8(response.body.to_vec()).unwrap();
		assert_eq!(body, "Auth required");
	}

	#[tokio::test]
	async fn test_middleware_no_short_circuit() {
		let handler = Arc::new(MockHandler {
			response_body: "Handler Response".to_string(),
		});

		let short_circuit_mw = Arc::new(ShortCircuitMiddleware { should_stop: false });
		let normal_mw = Arc::new(MockMiddleware {
			prefix: "Normal:".to_string(),
		});

		let chain = MiddlewareChain::new(handler)
			.with_middleware(short_circuit_mw)
			.with_middleware(normal_mw);

		let request = create_test_request();
		let response = chain.handle(request).await.unwrap();

		// Should pass through to handler and apply normal middleware
		assert_eq!(response.status, hyper::StatusCode::OK);
		let body = String::from_utf8(response.body.to_vec()).unwrap();
		assert_eq!(body, "Normal:Handler Response");
	}

	#[tokio::test]
	async fn test_middleware_multiple_conditions() {
		let handler = Arc::new(MockHandler {
			response_body: "Base".to_string(),
		});

		// Only runs for /api/* paths
		let api_mw = Arc::new(ConditionalMiddleware {
			prefix: "API:".to_string(),
		});

		// Always runs
		let always_mw = Arc::new(MockMiddleware {
			prefix: "Always:".to_string(),
		});

		let chain = MiddlewareChain::new(handler)
			.with_middleware(api_mw)
			.with_middleware(always_mw);

		// Test with /api/ path - both middleware should run
		let api_request = Request::builder()
			.method(Method::GET)
			.uri("/api/test")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();
		let response = chain.handle(api_request).await.unwrap();
		let body = String::from_utf8(response.body.to_vec()).unwrap();
		assert_eq!(body, "API:Always:Base");

		// Test with non-/api/ path - only always_mw should run
		let non_api_request = Request::builder()
			.method(Method::GET)
			.uri("/public")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();
		let response = chain.handle(non_api_request).await.unwrap();
		let body = String::from_utf8(response.body.to_vec()).unwrap();
		assert_eq!(body, "Always:Base"); // Only always_mw prefix
	}

	#[tokio::test]
	async fn test_response_should_stop_chain() {
		let response = Response::ok();
		assert!(!response.should_stop_chain());

		let stopping_response = Response::unauthorized().with_stop_chain(true);
		assert!(stopping_response.should_stop_chain());
	}
}