rustapi-core 0.1.450

The core engine of the RustAPI framework. Provides the hyper-based HTTP server, router, extraction logic, and foundational traits.
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
623
624
625
626
//! Tower Layer integration for RustAPI middleware
//!
//! This module provides the infrastructure for applying Tower-compatible layers
//! to the RustAPI request/response pipeline.

use crate::request::Request;
use crate::response::Response;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use tower_service::Service;

/// A boxed middleware function type
#[allow(dead_code)]
pub type BoxedMiddleware = Arc<
    dyn Fn(Request, BoxedNext) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>>
        + Send
        + Sync,
>;

/// A boxed next function for middleware chains
pub type BoxedNext =
    Arc<dyn Fn(Request) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>> + Send + Sync>;

/// Trait for middleware that can be applied to RustAPI
///
/// This trait allows both Tower layers and custom middleware to be used
/// with the `.layer()` method.
///
/// # Example: Implementing a custom simple logger middleware
///
/// ```rust
/// use rustapi_core::middleware::{MiddlewareLayer, BoxedNext};
/// use rustapi_core::{Request, Response};
/// use std::pin::Pin;
/// use std::future::Future;
///
/// #[derive(Clone)]
/// struct SimpleLogger;
///
/// impl MiddlewareLayer for SimpleLogger {
///     fn call(
///         &self,
///         req: Request,
///         next: BoxedNext,
///     ) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>> {
///         Box::pin(async move {
///             println!("Incoming request: {} {}", req.method(), req.uri());
///             let response = next(req).await;
///             println!("Response status: {}", response.status());
///             response
///         })
///     }
///
///     fn clone_box(&self) -> Box<dyn MiddlewareLayer> {
///         Box::new(self.clone())
///     }
/// }
/// ```
pub trait MiddlewareLayer: Send + Sync + 'static {
    /// Apply this middleware to a request, calling `next` to continue the chain
    fn call(
        &self,
        req: Request,
        next: BoxedNext,
    ) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>>;

    /// Clone this middleware into a boxed trait object
    fn clone_box(&self) -> Box<dyn MiddlewareLayer>;
}

impl Clone for Box<dyn MiddlewareLayer> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}

/// A stack of middleware layers
#[derive(Clone, Default)]
pub struct LayerStack {
    layers: Vec<Box<dyn MiddlewareLayer>>,
}

impl LayerStack {
    /// Create a new empty layer stack
    pub fn new() -> Self {
        Self { layers: Vec::new() }
    }

    /// Add a middleware layer to the stack
    ///
    /// Layers are executed in the order they are added (outermost first).
    pub fn push(&mut self, layer: Box<dyn MiddlewareLayer>) {
        self.layers.push(layer);
    }

    /// Add a middleware layer to the beginning of the stack
    ///
    /// This layer will be executed first (outermost).
    pub fn prepend(&mut self, layer: Box<dyn MiddlewareLayer>) {
        self.layers.insert(0, layer);
    }

    /// Check if the stack is empty
    pub fn is_empty(&self) -> bool {
        self.layers.is_empty()
    }

    /// Get the number of layers
    pub fn len(&self) -> usize {
        self.layers.len()
    }

    /// Execute the middleware stack with a final handler
    pub fn execute(
        &self,
        req: Request,
        handler: BoxedNext,
    ) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>> {
        if self.layers.is_empty() {
            return handler(req);
        }

        // Build the chain from inside out
        // The last layer added should be the outermost (first to execute)
        let mut next = handler;

        for layer in self.layers.iter().rev() {
            let layer = layer.clone_box();
            let current_next = next;
            next = Arc::new(move |req: Request| {
                let layer = layer.clone_box();
                let next = current_next.clone();
                Box::pin(async move { layer.call(req, next).await })
                    as Pin<Box<dyn Future<Output = Response> + Send + 'static>>
            });
        }

        next(req)
    }
}

impl IntoIterator for LayerStack {
    type Item = Box<dyn MiddlewareLayer>;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.layers.into_iter()
    }
}

impl Extend<Box<dyn MiddlewareLayer>> for LayerStack {
    fn extend<T: IntoIterator<Item = Box<dyn MiddlewareLayer>>>(&mut self, iter: T) {
        self.layers.extend(iter);
    }
}

/// Wrapper to adapt a Tower Layer to RustAPI's middleware system
#[allow(dead_code)]
pub struct TowerLayerAdapter<L> {
    layer: L,
}

impl<L> TowerLayerAdapter<L>
where
    L: Clone + Send + Sync + 'static,
{
    /// Create a new adapter from a Tower layer
    #[allow(dead_code)]
    pub fn new(layer: L) -> Self {
        Self { layer }
    }
}

impl<L> Clone for TowerLayerAdapter<L>
where
    L: Clone,
{
    fn clone(&self) -> Self {
        Self {
            layer: self.layer.clone(),
        }
    }
}

/// A simple service wrapper for the next handler in the chain
#[allow(dead_code)]
pub struct NextService {
    next: BoxedNext,
}

impl NextService {
    #[allow(dead_code)]
    pub fn new(next: BoxedNext) -> Self {
        Self { next }
    }
}

impl Clone for NextService {
    fn clone(&self) -> Self {
        Self {
            next: self.next.clone(),
        }
    }
}

impl Service<Request> for NextService {
    type Response = Response;
    type Error = std::convert::Infallible;
    type Future = Pin<Box<dyn Future<Output = Result<Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: Request) -> Self::Future {
        let next = self.next.clone();
        Box::pin(async move { Ok(next(req).await) })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::path_params::PathParams;
    use crate::request::Request;
    use crate::response::Response;
    use bytes::Bytes;
    use http::{Extensions, Method, StatusCode};
    use proptest::prelude::*;
    use proptest::test_runner::TestCaseError;

    /// Create a test request with the given method and path
    fn create_test_request(method: Method, path: &str) -> Request {
        let uri: http::Uri = path.parse().unwrap();
        let builder = http::Request::builder().method(method).uri(uri);

        let req = builder.body(()).unwrap();
        let (parts, _) = req.into_parts();

        Request::new(
            parts,
            crate::request::BodyVariant::Buffered(Bytes::new()),
            Arc::new(Extensions::new()),
            PathParams::new(),
        )
    }

    /// A simple test middleware that tracks execution order
    #[derive(Clone)]
    struct OrderTrackingMiddleware {
        id: usize,
        order: Arc<std::sync::Mutex<Vec<(usize, &'static str)>>>,
    }

    impl OrderTrackingMiddleware {
        fn new(id: usize, order: Arc<std::sync::Mutex<Vec<(usize, &'static str)>>>) -> Self {
            Self { id, order }
        }
    }

    impl MiddlewareLayer for OrderTrackingMiddleware {
        fn call(
            &self,
            req: Request,
            next: BoxedNext,
        ) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>> {
            let id = self.id;
            let order = self.order.clone();

            Box::pin(async move {
                // Record pre-handler execution
                order.lock().unwrap().push((id, "pre"));

                // Call next
                let response = next(req).await;

                // Record post-handler execution
                order.lock().unwrap().push((id, "post"));

                response
            })
        }

        fn clone_box(&self) -> Box<dyn MiddlewareLayer> {
            Box::new(self.clone())
        }
    }

    /// A middleware that modifies the response status
    #[derive(Clone)]
    #[allow(dead_code)]
    struct StatusModifyingMiddleware {
        status: StatusCode,
    }

    #[allow(dead_code)]
    impl StatusModifyingMiddleware {
        fn new(status: StatusCode) -> Self {
            Self { status }
        }
    }

    impl MiddlewareLayer for StatusModifyingMiddleware {
        fn call(
            &self,
            req: Request,
            next: BoxedNext,
        ) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>> {
            let status = self.status;

            Box::pin(async move {
                let mut response = next(req).await;
                *response.status_mut() = status;
                response
            })
        }

        fn clone_box(&self) -> Box<dyn MiddlewareLayer> {
            Box::new(self.clone())
        }
    }

    // **Feature: phase3-batteries-included, Property 1: Layer application preserves handler behavior**
    //
    // For any Tower-compatible layer L and handler H, applying L via `.layer(L)` SHALL result
    // in requests being processed by L before reaching H, and responses being processed by L
    // after leaving H.
    //
    // **Validates: Requirements 1.1**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_layer_application_preserves_handler_behavior(
            handler_status in 200u16..600u16,
        ) {
            let rt = tokio::runtime::Runtime::new().unwrap();
            let result: Result<(), TestCaseError> = rt.block_on(async {
                let order = Arc::new(std::sync::Mutex::new(Vec::new()));

                // Create a layer stack with one middleware
                let mut stack = LayerStack::new();
                stack.push(Box::new(OrderTrackingMiddleware::new(1, order.clone())));

                // Create a handler that returns the specified status
                let handler_status = StatusCode::from_u16(handler_status).unwrap_or(StatusCode::OK);
                let handler: BoxedNext = Arc::new(move |_req: Request| {
                    let status = handler_status;
                    Box::pin(async move {
                        http::Response::builder()
                            .status(status)
                            .body(crate::response::Body::from("test"))
                            .unwrap()
                    }) as Pin<Box<dyn Future<Output = Response> + Send + 'static>>
                });

                // Execute through the stack
                let request = create_test_request(Method::GET, "/test");
                let response = stack.execute(request, handler).await;

                // Verify the handler was called (response has expected status)
                prop_assert_eq!(response.status(), handler_status);

                // Verify middleware executed in correct order (pre before post)
                let execution_order = order.lock().unwrap();
                prop_assert_eq!(execution_order.len(), 2);
                prop_assert_eq!(execution_order[0], (1, "pre"));
                prop_assert_eq!(execution_order[1], (1, "post"));

                Ok(())
            });
            result?;
        }
    }

    #[test]
    fn test_empty_layer_stack_calls_handler_directly() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let stack = LayerStack::new();

            let handler: BoxedNext = Arc::new(|_req: Request| {
                Box::pin(async {
                    http::Response::builder()
                        .status(StatusCode::OK)
                        .body(crate::response::Body::from("direct"))
                        .unwrap()
                }) as Pin<Box<dyn Future<Output = Response> + Send + 'static>>
            });

            let request = create_test_request(Method::GET, "/test");
            let response = stack.execute(request, handler).await;

            assert_eq!(response.status(), StatusCode::OK);
        });
    }

    // **Feature: phase3-batteries-included, Property 2: Middleware execution order**
    //
    // For any sequence of layers [L1, L2, ..., Ln] added via `.layer()`, requests SHALL pass
    // through layers in the order L1 → L2 → ... → Ln → Handler → Ln → ... → L2 → L1
    // (outermost first on request, innermost first on response).
    //
    // **Validates: Requirements 1.2**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_middleware_execution_order(
            num_layers in 1usize..10usize,
        ) {
            let rt = tokio::runtime::Runtime::new().unwrap();
            let result: Result<(), TestCaseError> = rt.block_on(async {
                let order = Arc::new(std::sync::Mutex::new(Vec::new()));

                // Create a layer stack with multiple middleware
                let mut stack = LayerStack::new();
                for i in 0..num_layers {
                    stack.push(Box::new(OrderTrackingMiddleware::new(i, order.clone())));
                }

                // Create a simple handler
                let handler: BoxedNext = Arc::new(|_req: Request| {
                    Box::pin(async {
                        http::Response::builder()
                            .status(StatusCode::OK)
                            .body(crate::response::Body::from("test"))
                            .unwrap()
                    }) as Pin<Box<dyn Future<Output = Response> + Send + 'static>>
                });

                // Execute through the stack
                let request = create_test_request(Method::GET, "/test");
                let _response = stack.execute(request, handler).await;

                // Verify execution order
                let execution_order = order.lock().unwrap();

                // Should have 2 * num_layers entries (pre and post for each)
                prop_assert_eq!(execution_order.len(), num_layers * 2);

                // First half should be "pre" in order 0, 1, 2, ... (outermost first)
                for i in 0..num_layers {
                    prop_assert_eq!(execution_order[i], (i, "pre"),
                        "Pre-handler order mismatch at index {}", i);
                }

                // Second half should be "post" in reverse order n-1, n-2, ..., 0 (innermost first)
                for i in 0..num_layers {
                    let expected_id = num_layers - 1 - i;
                    prop_assert_eq!(execution_order[num_layers + i], (expected_id, "post"),
                        "Post-handler order mismatch at index {}", i);
                }

                Ok(())
            });
            result?;
        }
    }

    /// A middleware that short-circuits with an error response without calling next
    #[derive(Clone)]
    struct ShortCircuitMiddleware {
        error_status: StatusCode,
        should_short_circuit: bool,
    }

    impl ShortCircuitMiddleware {
        fn new(error_status: StatusCode, should_short_circuit: bool) -> Self {
            Self {
                error_status,
                should_short_circuit,
            }
        }
    }

    impl MiddlewareLayer for ShortCircuitMiddleware {
        fn call(
            &self,
            req: Request,
            next: BoxedNext,
        ) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>> {
            let error_status = self.error_status;
            let should_short_circuit = self.should_short_circuit;

            Box::pin(async move {
                if should_short_circuit {
                    // Return error response without calling next (short-circuit)
                    http::Response::builder()
                        .status(error_status)
                        .body(crate::response::Body::from("error"))
                        .unwrap()
                } else {
                    // Continue to next middleware/handler
                    next(req).await
                }
            })
        }

        fn clone_box(&self) -> Box<dyn MiddlewareLayer> {
            Box::new(self.clone())
        }
    }

    // **Feature: phase3-batteries-included, Property 4: Middleware short-circuit on error**
    //
    // For any middleware that returns an error response, the handler SHALL NOT be invoked,
    // and the error response SHALL be returned directly to the client.
    //
    // **Validates: Requirements 1.5**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_middleware_short_circuit_on_error(
            error_status in 400u16..600u16,
            num_middleware_before in 0usize..5usize,
            num_middleware_after in 0usize..5usize,
        ) {
            let rt = tokio::runtime::Runtime::new().unwrap();
            let result: Result<(), TestCaseError> = rt.block_on(async {
                let order = Arc::new(std::sync::Mutex::new(Vec::new()));
                let handler_called = Arc::new(std::sync::atomic::AtomicBool::new(false));

                // Create a layer stack with middleware before the short-circuit
                let mut stack = LayerStack::new();

                // Add middleware before the short-circuit middleware
                for i in 0..num_middleware_before {
                    stack.push(Box::new(OrderTrackingMiddleware::new(i, order.clone())));
                }

                // Add the short-circuit middleware
                let error_status = StatusCode::from_u16(error_status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
                stack.push(Box::new(ShortCircuitMiddleware::new(error_status, true)));

                // Add middleware after the short-circuit middleware (these should NOT execute pre)
                for i in 0..num_middleware_after {
                    stack.push(Box::new(OrderTrackingMiddleware::new(100 + i, order.clone())));
                }

                // Create a handler that tracks if it was called
                let handler_called_clone = handler_called.clone();
                let handler: BoxedNext = Arc::new(move |_req: Request| {
                    let handler_called = handler_called_clone.clone();
                    Box::pin(async move {
                        handler_called.store(true, std::sync::atomic::Ordering::SeqCst);
                        http::Response::builder()
                            .status(StatusCode::OK)
                            .body(crate::response::Body::from("handler"))
                            .unwrap()
                    }) as Pin<Box<dyn Future<Output = Response> + Send + 'static>>
                });

                // Execute through the stack
                let request = create_test_request(Method::GET, "/test");
                let response = stack.execute(request, handler).await;

                // Verify the error response was returned
                prop_assert_eq!(response.status(), error_status,
                    "Response should have the error status from short-circuit middleware");

                // Verify the handler was NOT called
                prop_assert!(!handler_called.load(std::sync::atomic::Ordering::SeqCst),
                    "Handler should NOT be called when middleware short-circuits");

                // Verify execution order:
                // - Middleware before short-circuit should have "pre" recorded
                // - Middleware after short-circuit should NOT have "pre" recorded (never reached)
                // - All middleware before short-circuit should have "post" recorded (unwinding)
                let execution_order = order.lock().unwrap();

                // Count pre and post for middleware before short-circuit
                let pre_count = execution_order.iter().filter(|(id, phase)| *id < 100 && *phase == "pre").count();
                let post_count = execution_order.iter().filter(|(id, phase)| *id < 100 && *phase == "post").count();

                prop_assert_eq!(pre_count, num_middleware_before,
                    "All middleware before short-circuit should have pre recorded");
                prop_assert_eq!(post_count, num_middleware_before,
                    "All middleware before short-circuit should have post recorded (unwinding)");

                // Middleware after short-circuit should NOT have any entries
                let after_entries = execution_order.iter().filter(|(id, _)| *id >= 100).count();
                prop_assert_eq!(after_entries, 0,
                    "Middleware after short-circuit should NOT be executed");

                Ok(())
            });
            result?;
        }
    }

    #[test]
    fn test_short_circuit_returns_error_response() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let mut stack = LayerStack::new();
            stack.push(Box::new(ShortCircuitMiddleware::new(
                StatusCode::UNAUTHORIZED,
                true,
            )));

            let handler_called = Arc::new(std::sync::atomic::AtomicBool::new(false));
            let handler_called_clone = handler_called.clone();

            let handler: BoxedNext = Arc::new(move |_req: Request| {
                let handler_called = handler_called_clone.clone();
                Box::pin(async move {
                    handler_called.store(true, std::sync::atomic::Ordering::SeqCst);
                    http::Response::builder()
                        .status(StatusCode::OK)
                        .body(crate::response::Body::from("handler"))
                        .unwrap()
                }) as Pin<Box<dyn Future<Output = Response> + Send + 'static>>
            });

            let request = create_test_request(Method::GET, "/test");
            let response = stack.execute(request, handler).await;

            assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
            assert!(!handler_called.load(std::sync::atomic::Ordering::SeqCst));
        });
    }
}