armature-core 0.6.0

High-performance async HTTP framework core - routing, handlers, middleware
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
// Routing system for HTTP requests
//
// This module provides an optimized routing system that leverages:
// - Monomorphization: Handlers are specialized at compile time
// - Inline dispatch: Hot paths use #[inline(always)]
// - Zero-cost abstractions: Minimal runtime overhead

use crate::handler::{BoxedHandler, IntoHandler};
use crate::logging::{debug, trace};
use crate::route_constraint::RouteConstraints;
use crate::{Error, HttpMethod, HttpRequest, HttpResponse};
use smallvec::SmallVec;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

/// A route handler function type (legacy - for backwards compatibility)
///
/// **Deprecated**: Use `BoxedHandler` for better performance via monomorphization.
/// This type uses double dynamic dispatch (dyn Fn + Box<dyn Future>) which
/// prevents the compiler from inlining handler code.
///
/// Prefer using the optimized handler system:
/// ```ignore
/// use armature_core::handler::handler;
///
/// let h = handler(my_async_fn);
/// ```
pub type HandlerFn = Arc<
    dyn Fn(HttpRequest) -> Pin<Box<dyn Future<Output = Result<HttpResponse, Error>> + Send>>
        + Send
        + Sync,
>;

/// Optimized route handler that enables inlining via monomorphization.
///
/// This type wraps handlers in a way that allows the compiler to see through
/// to the actual handler implementation and inline it.
pub type OptimizedHandler = BoxedHandler;

/// Route definition with handler
#[derive(Clone)]
pub struct Route {
    pub method: HttpMethod,
    pub path: String,
    /// The route handler - uses optimized dispatch
    pub handler: BoxedHandler,
    /// Optional route constraints for parameter validation
    pub constraints: Option<RouteConstraints>,
}

impl Route {
    /// Create a new route with an optimized handler.
    ///
    /// This method accepts any handler type that implements `IntoHandler`,
    /// enabling compile-time specialization.
    #[inline]
    pub fn new<H, Args>(method: HttpMethod, path: impl Into<String>, handler: H) -> Self
    where
        H: IntoHandler<Args>,
    {
        Self {
            method,
            path: path.into(),
            handler: BoxedHandler::new(handler.into_handler()),
            constraints: None,
        }
    }

    /// Create a route from a legacy HandlerFn for backwards compatibility.
    #[inline]
    pub fn from_legacy(method: HttpMethod, path: impl Into<String>, handler: HandlerFn) -> Self {
        Self {
            method,
            path: path.into(),
            handler: crate::handler::from_legacy_handler(handler),
            constraints: None,
        }
    }

    /// Add route constraints.
    #[inline]
    pub fn with_constraints(mut self, constraints: RouteConstraints) -> Self {
        self.constraints = Some(constraints);
        self
    }
}

/// Router for managing routes and dispatching requests.
///
/// The router uses optimized handler dispatch that enables:
/// - Monomorphization of handler code
/// - Inlining of handler bodies
/// - Minimal allocation in the hot path
#[derive(Clone)]
pub struct Router {
    pub routes: Vec<Route>,
}

impl Router {
    /// Create a new empty router.
    #[inline]
    pub fn new() -> Self {
        Self { routes: Vec::new() }
    }

    /// Add a route to the router.
    #[inline]
    pub fn add_route(&mut self, route: Route) {
        self.routes.push(route);
    }

    /// Add a GET route with an optimized handler.
    #[inline]
    pub fn get<H, Args>(&mut self, path: impl Into<String>, handler: H) -> &mut Self
    where
        H: IntoHandler<Args>,
    {
        self.routes.push(Route::new(HttpMethod::GET, path, handler));
        self
    }

    /// Add a POST route with an optimized handler.
    #[inline]
    pub fn post<H, Args>(&mut self, path: impl Into<String>, handler: H) -> &mut Self
    where
        H: IntoHandler<Args>,
    {
        self.routes
            .push(Route::new(HttpMethod::POST, path, handler));
        self
    }

    /// Add a PUT route with an optimized handler.
    #[inline]
    pub fn put<H, Args>(&mut self, path: impl Into<String>, handler: H) -> &mut Self
    where
        H: IntoHandler<Args>,
    {
        self.routes.push(Route::new(HttpMethod::PUT, path, handler));
        self
    }

    /// Add a DELETE route with an optimized handler.
    #[inline]
    pub fn delete<H, Args>(&mut self, path: impl Into<String>, handler: H) -> &mut Self
    where
        H: IntoHandler<Args>,
    {
        self.routes
            .push(Route::new(HttpMethod::DELETE, path, handler));
        self
    }

    /// Add a PATCH route with an optimized handler.
    #[inline]
    pub fn patch<H, Args>(&mut self, path: impl Into<String>, handler: H) -> &mut Self
    where
        H: IntoHandler<Args>,
    {
        self.routes
            .push(Route::new(HttpMethod::PATCH, path, handler));
        self
    }

    /// Add an OPTIONS route with an optimized handler.
    ///
    /// OPTIONS requests are typically used for CORS preflight checks.
    /// For automatic CORS handling, consider using the CORS middleware instead.
    #[inline]
    pub fn options<H, Args>(&mut self, path: impl Into<String>, handler: H) -> &mut Self
    where
        H: IntoHandler<Args>,
    {
        self.routes
            .push(Route::new(HttpMethod::OPTIONS, path, handler));
        self
    }

    /// Add a HEAD route with an optimized handler.
    ///
    /// HEAD requests are identical to GET but without the response body.
    /// Useful for checking resource existence or metadata.
    #[inline]
    pub fn head<H, Args>(&mut self, path: impl Into<String>, handler: H) -> &mut Self
    where
        H: IntoHandler<Args>,
    {
        self.routes
            .push(Route::new(HttpMethod::HEAD, path, handler));
        self
    }

    /// Add a QUERY route with an optimized handler.
    ///
    /// QUERY is a safe, idempotent method that carries the query in the
    /// request body (draft-ietf-httpbis-safe-method-w-body). Use it for
    /// queries too large or structured for a URL query string.
    #[inline]
    pub fn query<H, Args>(&mut self, path: impl Into<String>, handler: H) -> &mut Self
    where
        H: IntoHandler<Args>,
    {
        self.routes
            .push(Route::new(HttpMethod::QUERY, path, handler));
        self
    }

    /// Match a route without executing the handler.
    /// Returns the handler and path parameters if a route matches.
    /// Useful for route lookup benchmarking and inspection.
    #[inline]
    pub fn match_route(
        &self,
        method: &str,
        path: &str,
    ) -> Option<(BoxedHandler, HashMap<String, String>)> {
        // Strip query string if present
        let path = path.split('?').next().unwrap_or(path);

        // Split the request path once, up front, rather than per candidate route.
        let path_parts: SmallVec<[&str; 8]> = split_segments(path).collect();

        for route in &self.routes {
            if route.method.as_str() != method {
                continue;
            }

            if let Some(params) = match_path(&route.path, &path_parts) {
                return Some((route.handler.clone(), params));
            }
        }

        None
    }

    /// Find a route that matches the request and execute the handler.
    ///
    /// This is the main hot path for request handling. The handler dispatch
    /// is optimized via monomorphization - the actual handler code can be
    /// inlined by the compiler.
    #[inline]
    pub async fn route(&self, mut request: HttpRequest) -> Result<HttpResponse, Error> {
        debug!("Routing request: {} {}", request.method, request.path);

        // Parse query parameters from path
        let (path, query_string) = request
            .path
            .split_once('?')
            .map(|(p, q)| (p, Some(q)))
            .unwrap_or((&request.path, None));

        if let Some(query) = query_string {
            trace!("Parsing query string: {}", query);
            request.query_params = parse_query_string(query);
        }

        // Find matching route - this is the route matching hot path. The request
        // path is split once, up front, rather than per candidate route. The
        // `path_parts` borrow of `request.path` is confined to this block (which
        // drops the `SmallVec`) so `request` can be moved into the handler below;
        // we only carry out the matched index + params.
        let matched: Option<(usize, HashMap<String, String>)> = {
            let path_parts: SmallVec<[&str; 8]> = split_segments(path).collect();

            let mut found = None;
            for (idx, route) in self.routes.iter().enumerate() {
                if route.method.as_str() != request.method {
                    continue;
                }

                if let Some(params) = match_path(&route.path, &path_parts) {
                    debug!(
                        "Route matched: {} {} -> {}",
                        request.method, path, route.path
                    );
                    found = Some((idx, params));
                    break;
                }
            }
            found
        };

        if let Some((idx, params)) = matched {
            let route = &self.routes[idx];

            // Validate route constraints if present
            if let Some(constraints) = &route.constraints {
                trace!("Validating route constraints");
                constraints.validate(&params)?;
            }

            request.path_params = params;

            // Handler dispatch - the BoxedHandler.call() is optimized
            // to allow the compiler to inline the actual handler body
            trace!("Dispatching handler");
            return route.handler.call(request).await;
        }

        debug!("No route found for {} {}", request.method, path);
        Err(Error::RouteNotFound(format!("{} {}", request.method, path)))
    }
}

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

/// Split a path into non-empty segments without allocating a `Vec`.
#[inline]
fn split_segments(path: &str) -> impl Iterator<Item = &str> {
    path.split('/').filter(|s| !s.is_empty())
}

/// Match a route path pattern against a request path that has already been
/// split into non-empty segments.
///
/// The pattern is compared segment-by-segment using a `split('/')` iterator,
/// so no `Vec` is allocated per candidate route. The `HashMap` of parameters is
/// only allocated once a route actually matches (and only sized for the number
/// of parameters the pattern declares).
fn match_path(pattern: &str, path_parts: &[&str]) -> Option<HashMap<String, String>> {
    // First pass: validate the segment count and static segments, and count
    // how many parameters the pattern declares. No allocation happens here.
    //
    // A `*name` segment is a catch-all: it consumes every remaining path
    // segment (zero or more) and, matching `CompiledRoute::matches`, ends
    // pattern validation right there (any pattern segments after a
    // catch-all are unreachable, same as the compiled matcher).
    let mut seen = 0usize;
    let mut param_count = 0usize;
    let mut catch_all_at: Option<usize> = None;
    for (i, pattern_part) in split_segments(pattern).enumerate() {
        if pattern_part.starts_with('*') {
            catch_all_at = Some(i);
            param_count += 1;
            break;
        }

        // Pattern has more segments than the request path
        let path_part = path_parts.get(i)?;
        if pattern_part.starts_with(':') {
            param_count += 1;
        } else if pattern_part != *path_part {
            // Static segment doesn't match
            return None;
        }
        seen = i + 1;
    }

    if let Some(idx) = catch_all_at {
        // Everything before the catch-all must already be present in the
        // request path; the catch-all itself may consume zero segments. The
        // per-segment loop above already validated this: for every `i < idx`
        // it early-returns `None` via `path_parts.get(i)?` if that index is
        // missing, so by the time we reach here `path_parts.len() >= idx`
        // always holds. Documented as an invariant rather than re-checked.
        debug_assert!(
            path_parts.len() >= idx,
            "catch-all index validated during first pass"
        );
    } else if seen != path_parts.len() {
        // Pattern must consume every request-path segment
        return None;
    }

    // Second pass: the route matched, so allocate the params map now.
    let mut params = HashMap::with_capacity(param_count);
    if param_count > 0 {
        for (i, pattern_part) in split_segments(pattern).enumerate() {
            if let Some(name) = pattern_part.strip_prefix('*') {
                // Catch-all: join all remaining path segments, matching
                // `CompiledRoute::extract_params`'s joining convention.
                let name = if name.is_empty() { "*" } else { name };
                params.insert(name.to_string(), path_parts[i..].join("/"));
                break;
            } else if let Some(param_name) = pattern_part.strip_prefix(':') {
                params.insert(param_name.to_string(), path_parts[i].to_string());
            }
        }
    }

    Some(params)
}

/// Parse a query string into a map of parameters
///
/// Uses SIMD-optimized byte searching via memchr for faster parsing.
/// Values are percent-decoded (and `+` decoded as space) so handlers
/// receive the actual parameter values, not their encoded form.
#[inline]
fn parse_query_string(query: &str) -> HashMap<String, String> {
    // Use the SIMD-optimized decoding parser
    crate::simd_parser::parse_query_string_decoded(query)
}

#[cfg(test)]
mod tests {
    use super::*;

    // Test helper handler
    async fn test_handler(_req: HttpRequest) -> Result<HttpResponse, Error> {
        Ok(HttpResponse::ok())
    }

    // Test helper: split a raw path and run match_path, mirroring how the
    // router pre-splits the request path before the route loop.
    fn match_path_str(pattern: &str, path: &str) -> Option<HashMap<String, String>> {
        let parts: Vec<&str> = super::split_segments(path).collect();
        match_path(pattern, &parts)
    }

    #[test]
    fn test_match_path_static() {
        let pattern = "/users";
        let path = "/users";
        let result = match_path_str(pattern, path);
        assert!(result.is_some());
        assert_eq!(result.unwrap().len(), 0);
    }

    #[test]
    fn test_match_path_with_param() {
        let pattern = "/users/:id";
        let path = "/users/123";
        let result = match_path_str(pattern, path);
        assert!(result.is_some());
        let params = result.unwrap();
        assert_eq!(params.get("id"), Some(&"123".to_string()));
    }

    #[test]
    fn test_match_path_no_match() {
        let pattern = "/users/:id";
        let path = "/posts/123";
        let result = match_path_str(pattern, path);
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_query_string() {
        let query = "name=john&age=30";
        let params = parse_query_string(query);
        assert_eq!(params.get("name"), Some(&"john".to_string()));
        assert_eq!(params.get("age"), Some(&"30".to_string()));
    }

    #[test]
    fn test_parse_query_string_decodes_values() {
        let query = "name=john%20doe&x=a%26b";
        let params = parse_query_string(query);
        assert_eq!(params.get("name"), Some(&"john doe".to_string()));
        assert_eq!(params.get("x"), Some(&"a&b".to_string()));
    }

    #[test]
    fn test_query_method_round_trip() {
        assert_eq!(HttpMethod::from_str("QUERY"), Some(HttpMethod::QUERY));
        assert_eq!(HttpMethod::from_str("query"), Some(HttpMethod::QUERY));
        assert_eq!(HttpMethod::QUERY.as_str(), "QUERY");
    }

    #[tokio::test]
    async fn test_query_route_dispatch() {
        async fn echo_body(req: HttpRequest) -> Result<HttpResponse, Error> {
            Ok(HttpResponse::ok().with_body(req.body.clone()))
        }

        let mut router = Router::new();
        router.query("/search", echo_body);

        let mut request = HttpRequest::new("QUERY".to_string(), "/search".to_string());
        request.body = b"name=john".to_vec();
        let response = router.route(request).await.unwrap();
        assert_eq!(response.status, 200);
        assert_eq!(response.into_body_bytes().as_ref(), b"name=john");

        // A GET to the same path must not hit the QUERY handler
        let request = HttpRequest::new("GET".to_string(), "/search".to_string());
        assert!(router.route(request).await.is_err());
    }

    #[test]
    fn test_match_path_multiple_params() {
        let pattern = "/users/:user_id/posts/:post_id";
        let path = "/users/123/posts/456";
        let result = match_path_str(pattern, path);
        assert!(result.is_some());
        let params = result.unwrap();
        assert_eq!(params.get("user_id"), Some(&"123".to_string()));
        assert_eq!(params.get("post_id"), Some(&"456".to_string()));
    }

    #[test]
    fn test_match_path_trailing_slash() {
        let pattern = "/users";
        let path = "/users/";
        let result = match_path_str(pattern, path);
        // Should handle trailing slash gracefully
        assert!(result.is_some() || result.is_none());
    }

    #[test]
    fn test_match_path_nested() {
        let pattern = "/api/v1/users/:id";
        let path = "/api/v1/users/123";
        let result = match_path_str(pattern, path);
        assert!(result.is_some());
        let params = result.unwrap();
        assert_eq!(params.get("id"), Some(&"123".to_string()));
    }

    #[test]
    fn test_match_path_empty() {
        let pattern = "/";
        let path = "/";
        let result = match_path_str(pattern, path);
        assert!(result.is_some());
    }

    #[test]
    fn test_parse_query_string_empty() {
        let query = "";
        let params = parse_query_string(query);
        // Empty string may return one empty entry, which is fine
        assert!(params.is_empty() || params.len() == 1);
    }

    #[test]
    fn test_parse_query_string_special_chars() {
        let query = "name=john%20doe&email=test%40example.com";
        let params = parse_query_string(query);
        assert!(params.contains_key("name"));
        assert!(params.contains_key("email"));
    }

    #[test]
    fn test_parse_query_string_no_value() {
        let query = "flag&debug=true";
        let params = parse_query_string(query);
        assert!(params.contains_key("debug"));
        assert_eq!(params.get("debug"), Some(&"true".to_string()));
    }

    #[test]
    fn test_match_path_catch_all() {
        // Mirrors route_cache.rs's `test_compiled_route_catch_all`, but
        // exercises the linear `Router`'s own matcher directly.
        let pattern = "/files/*path";

        assert!(match_path_str(pattern, "/files/docs").is_some());

        let result = match_path_str(pattern, "/files/docs/readme.md");
        assert!(result.is_some());
        let params = result.unwrap();
        assert_eq!(params.get("path"), Some(&"docs/readme.md".to_string()));

        // An exact prefix match (no trailing segments) should still match,
        // with the catch-all param extracted as an empty string.
        let result = match_path_str(pattern, "/files");
        assert!(result.is_some());
        assert_eq!(result.unwrap().get("path"), Some(&String::new()));

        // A path that doesn't even reach the static prefix must not match.
        assert!(match_path_str(pattern, "/other").is_none());
    }

    #[test]
    fn test_match_path_catch_all_with_preceding_param() {
        // A catch-all preceded by a named `:param` segment must extract both
        // the param and the catch-all correctly.
        let pattern = "/users/:id/files/*path";
        let result = match_path_str(pattern, "/users/42/files/a/b");
        assert!(result.is_some());
        let params = result.unwrap();
        assert_eq!(params.get("id"), Some(&"42".to_string()));
        assert_eq!(params.get("path"), Some(&"a/b".to_string()));

        // A bare, unnamed catch-all (`*` with no name) stores its captured
        // value under the literal key `"*"` (see the `name.is_empty()`
        // fallback in `match_path`).
        let pattern = "/files/*";
        let result = match_path_str(pattern, "/files/a/b/c");
        assert!(result.is_some());
        let params = result.unwrap();
        assert_eq!(params.get("*"), Some(&"a/b/c".to_string()));
    }

    #[tokio::test]
    async fn test_router_route_catch_all() {
        // Mirrors route_cache.rs's `test_from_router_catch_all`, but calls
        // `Router::route` directly instead of going through
        // `OptimizedRouter`, to make sure the linear router's own catch-all
        // handling (not just the compiled fast path) works end to end.
        async fn echo_path(req: HttpRequest) -> Result<HttpResponse, Error> {
            let p = req.path_params.get("path").cloned().unwrap_or_default();
            Ok(HttpResponse::ok().with_body(p.into_bytes()))
        }

        let mut router = Router::new();
        router.get("/files/*path", echo_path);

        let req = HttpRequest::new("GET".to_string(), "/files/docs/readme.md".to_string());
        let response = router.route(req).await.unwrap();
        assert_eq!(response.status, 200);
        assert_eq!(response.into_body_bytes().as_ref(), b"docs/readme.md");

        // `match_route` (used for lookup without dispatch) must agree.
        let (_, params) = router
            .match_route("GET", "/files/docs/readme.md")
            .expect("catch-all route should match via match_route");
        assert_eq!(params.get("path"), Some(&"docs/readme.md".to_string()));
    }

    #[test]
    fn test_match_path_param_with_special_chars() {
        let pattern = "/users/:id";
        let path = "/users/abc-123";
        let result = match_path_str(pattern, path);
        assert!(result.is_some());
        let params = result.unwrap();
        assert_eq!(params.get("id"), Some(&"abc-123".to_string()));
    }

    #[test]
    fn test_route_creation_optimized() {
        // Test the new optimized route creation
        let route = Route::new(HttpMethod::GET, "/users", test_handler);
        assert_eq!(route.method, HttpMethod::GET);
        assert_eq!(route.path, "/users");
    }

    #[test]
    fn test_route_creation_legacy() {
        // Test legacy handler compatibility
        let legacy_handler: HandlerFn =
            Arc::new(|_req| Box::pin(async move { Ok(HttpResponse::ok()) }));
        let route = Route::from_legacy(HttpMethod::GET, "/users", legacy_handler);
        assert_eq!(route.method, HttpMethod::GET);
        assert_eq!(route.path, "/users");
    }

    #[test]
    fn test_router_fluent_api() {
        let mut router = Router::new();
        router
            .get("/users", test_handler)
            .post("/users", test_handler)
            .put("/users/:id", test_handler)
            .delete("/users/:id", test_handler)
            .patch("/users/:id", test_handler)
            .options("/users", test_handler)
            .head("/users/:id", test_handler);

        assert_eq!(router.routes.len(), 7);
    }

    #[test]
    fn test_router_options_route() {
        let mut router = Router::new();
        router.options("/api/resource", test_handler);

        assert_eq!(router.routes.len(), 1);
        assert_eq!(router.routes[0].method, HttpMethod::OPTIONS);
        assert_eq!(router.routes[0].path, "/api/resource");
    }

    #[test]
    fn test_router_head_route() {
        let mut router = Router::new();
        router.head("/api/resource/:id", test_handler);

        assert_eq!(router.routes.len(), 1);
        assert_eq!(router.routes[0].method, HttpMethod::HEAD);
        assert_eq!(router.routes[0].path, "/api/resource/:id");
    }

    #[test]
    fn test_router_add_route() {
        let mut router = Router::new();
        let route = Route::new(HttpMethod::GET, "/test", test_handler);
        router.add_route(route);
        assert_eq!(router.routes.len(), 1);
    }

    #[test]
    fn test_router_multiple_routes() {
        let mut router = Router::new();

        for i in 0..5 {
            router.get(format!("/test{}", i), test_handler);
        }

        assert_eq!(router.routes.len(), 5);
    }

    #[test]
    fn test_parse_query_string_multiple_same_key() {
        let query = "tag=rust&tag=web&tag=framework";
        let params = parse_query_string(query);
        // Should contain at least one tag
        assert!(params.contains_key("tag"));
    }

    #[test]
    fn test_route_with_constraints() {
        let constraints =
            RouteConstraints::new().add("id", Box::new(crate::route_constraint::IntConstraint));

        let route =
            Route::new(HttpMethod::GET, "/users/:id", test_handler).with_constraints(constraints);

        assert!(route.constraints.is_some());
    }

    #[tokio::test]
    async fn test_router_dispatch() {
        let mut router = Router::new();
        router.get("/test", test_handler);

        let req = HttpRequest::new("GET".to_string(), "/test".to_string());
        let response = router.route(req).await.unwrap();
        assert_eq!(response.status, 200);
    }

    #[tokio::test]
    async fn test_router_dispatch_with_params() {
        async fn param_handler(req: HttpRequest) -> Result<HttpResponse, Error> {
            let id = req.param("id").unwrap();
            Ok(HttpResponse::ok().with_body(id.as_bytes().to_vec()))
        }

        let mut router = Router::new();
        router.get("/users/:id", param_handler);

        let req = HttpRequest::new("GET".to_string(), "/users/123".to_string());
        let response = router.route(req).await.unwrap();
        assert_eq!(response.status, 200);
        assert_eq!(String::from_utf8(response.body).unwrap(), "123");
    }

    #[tokio::test]
    async fn test_router_404() {
        let router = Router::new();
        let req = HttpRequest::new("GET".to_string(), "/nonexistent".to_string());
        let result = router.route(req).await;
        assert!(matches!(result, Err(Error::RouteNotFound(_))));
    }
}