-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrouter.rs
More file actions
3420 lines (2972 loc) · 123 KB
/
router.rs
File metadata and controls
3420 lines (2972 loc) · 123 KB
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Router implementation using radix tree (matchit)
//!
//! This module provides HTTP routing functionality for RustAPI. Routes are
//! registered using path patterns and HTTP method handlers.
//!
//! # Path Patterns
//!
//! Routes support dynamic path parameters using `{param}` syntax:
//!
//! - `/users` - Static path
//! - `/users/{id}` - Single parameter
//! - `/users/{user_id}/posts/{post_id}` - Multiple parameters
//!
//! # Example
//!
//! ```rust,ignore
//! use rustapi_core::{Router, get, post, put, delete};
//!
//! async fn list_users() -> &'static str { "List users" }
//! async fn get_user() -> &'static str { "Get user" }
//! async fn create_user() -> &'static str { "Create user" }
//! async fn update_user() -> &'static str { "Update user" }
//! async fn delete_user() -> &'static str { "Delete user" }
//!
//! let router = Router::new()
//! .route("/users", get(list_users).post(create_user))
//! .route("/users/{id}", get(get_user).put(update_user).delete(delete_user));
//! ```
//!
//! # Method Chaining
//!
//! Multiple HTTP methods can be registered for the same path using method chaining:
//!
//! ```rust,ignore
//! .route("/users", get(list).post(create))
//! .route("/users/{id}", get(show).put(update).delete(destroy))
//! ```
//!
//! # Route Conflict Detection
//!
//! The router detects conflicting routes at registration time and provides
//! helpful error messages with resolution guidance.
use crate::handler::{into_boxed_handler, BoxedHandler, Handler};
use crate::path_params::PathParams;
use crate::typed_path::TypedPath;
use http::{Extensions, Method};
use matchit::Router as MatchitRouter;
use rustapi_openapi::Operation;
use std::collections::HashMap;
use std::sync::Arc;
/// Information about a registered route for conflict detection
#[derive(Debug, Clone)]
pub struct RouteInfo {
/// The original path pattern (e.g., "/users/{id}")
pub path: String,
/// The HTTP methods registered for this path
pub methods: Vec<Method>,
}
/// Error returned when a route conflict is detected
#[derive(Debug, Clone)]
pub struct RouteConflictError {
/// The path that was being registered
pub new_path: String,
/// The HTTP method that conflicts
pub method: Option<Method>,
/// The existing path that conflicts
pub existing_path: String,
/// Detailed error message from the underlying router
pub details: String,
}
impl std::fmt::Display for RouteConflictError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(
f,
"\n╭─────────────────────────────────────────────────────────────╮"
)?;
writeln!(
f,
"│ ROUTE CONFLICT DETECTED │"
)?;
writeln!(
f,
"╰─────────────────────────────────────────────────────────────╯"
)?;
writeln!(f)?;
writeln!(f, " Conflicting routes:")?;
writeln!(f, " → Existing: {}", self.existing_path)?;
writeln!(f, " → New: {}", self.new_path)?;
writeln!(f)?;
if let Some(ref method) = self.method {
writeln!(f, " HTTP Method: {}", method)?;
writeln!(f)?;
}
writeln!(f, " Details: {}", self.details)?;
writeln!(f)?;
writeln!(f, " How to resolve:")?;
writeln!(f, " 1. Use different path patterns for each route")?;
writeln!(
f,
" 2. If paths must be similar, ensure parameter names differ"
)?;
writeln!(
f,
" 3. Consider using different HTTP methods if appropriate"
)?;
writeln!(f)?;
writeln!(f, " Example:")?;
writeln!(f, " Instead of:")?;
writeln!(f, " .route(\"/users/{{id}}\", get(handler1))")?;
writeln!(f, " .route(\"/users/{{user_id}}\", get(handler2))")?;
writeln!(f)?;
writeln!(f, " Use:")?;
writeln!(f, " .route(\"/users/{{id}}\", get(handler1))")?;
writeln!(f, " .route(\"/users/{{id}}/profile\", get(handler2))")?;
Ok(())
}
}
impl std::error::Error for RouteConflictError {}
/// HTTP method router for a single path
pub struct MethodRouter {
handlers: HashMap<Method, BoxedHandler>,
pub(crate) operations: HashMap<Method, Operation>,
pub(crate) component_registrars: Vec<fn(&mut rustapi_openapi::OpenApiSpec)>,
}
impl Clone for MethodRouter {
fn clone(&self) -> Self {
Self {
handlers: self.handlers.clone(),
operations: self.operations.clone(),
component_registrars: self.component_registrars.clone(),
}
}
}
impl MethodRouter {
/// Create a new empty method router
pub fn new() -> Self {
Self {
handlers: HashMap::new(),
operations: HashMap::new(),
component_registrars: Vec::new(),
}
}
/// Add a handler for a specific method
fn on(
mut self,
method: Method,
handler: BoxedHandler,
operation: Operation,
component_registrar: fn(&mut rustapi_openapi::OpenApiSpec),
) -> Self {
self.handlers.insert(method.clone(), handler);
self.operations.insert(method, operation);
self.component_registrars.push(component_registrar);
self
}
/// Get handler for a method
pub(crate) fn get_handler(&self, method: &Method) -> Option<&BoxedHandler> {
self.handlers.get(method)
}
/// Get allowed methods for 405 response
pub(crate) fn allowed_methods(&self) -> Vec<Method> {
self.handlers.keys().cloned().collect()
}
/// Create from pre-boxed handlers (internal use)
pub(crate) fn from_boxed(handlers: HashMap<Method, BoxedHandler>) -> Self {
Self {
handlers,
operations: HashMap::new(), // Operations lost when using raw boxed handlers for now
component_registrars: Vec::new(),
}
}
/// Insert a pre-boxed handler and its OpenAPI operation (internal use).
///
/// Panics if the same method is inserted twice for the same path.
pub(crate) fn insert_boxed_with_operation(
&mut self,
method: Method,
handler: BoxedHandler,
operation: Operation,
component_registrar: fn(&mut rustapi_openapi::OpenApiSpec),
) {
if self.handlers.contains_key(&method) {
panic!(
"Duplicate handler for method {} on the same path",
method.as_str()
);
}
self.handlers.insert(method.clone(), handler);
self.operations.insert(method, operation);
self.component_registrars.push(component_registrar);
}
/// Add a GET handler
pub fn get<H, T>(self, handler: H) -> Self
where
H: Handler<T>,
T: 'static,
{
let mut op = Operation::new();
H::update_operation(&mut op);
self.on(
Method::GET,
into_boxed_handler(handler),
op,
<H as Handler<T>>::register_components,
)
}
/// Add a POST handler
pub fn post<H, T>(self, handler: H) -> Self
where
H: Handler<T>,
T: 'static,
{
let mut op = Operation::new();
H::update_operation(&mut op);
self.on(
Method::POST,
into_boxed_handler(handler),
op,
<H as Handler<T>>::register_components,
)
}
/// Add a PUT handler
pub fn put<H, T>(self, handler: H) -> Self
where
H: Handler<T>,
T: 'static,
{
let mut op = Operation::new();
H::update_operation(&mut op);
self.on(
Method::PUT,
into_boxed_handler(handler),
op,
<H as Handler<T>>::register_components,
)
}
/// Add a PATCH handler
pub fn patch<H, T>(self, handler: H) -> Self
where
H: Handler<T>,
T: 'static,
{
let mut op = Operation::new();
H::update_operation(&mut op);
self.on(
Method::PATCH,
into_boxed_handler(handler),
op,
<H as Handler<T>>::register_components,
)
}
/// Add a DELETE handler
pub fn delete<H, T>(self, handler: H) -> Self
where
H: Handler<T>,
T: 'static,
{
let mut op = Operation::new();
H::update_operation(&mut op);
self.on(
Method::DELETE,
into_boxed_handler(handler),
op,
<H as Handler<T>>::register_components,
)
}
}
impl Default for MethodRouter {
fn default() -> Self {
Self::new()
}
}
/// Create a GET route handler
pub fn get<H, T>(handler: H) -> MethodRouter
where
H: Handler<T>,
T: 'static,
{
let mut op = Operation::new();
H::update_operation(&mut op);
MethodRouter::new().on(
Method::GET,
into_boxed_handler(handler),
op,
<H as Handler<T>>::register_components,
)
}
/// Create a POST route handler
pub fn post<H, T>(handler: H) -> MethodRouter
where
H: Handler<T>,
T: 'static,
{
let mut op = Operation::new();
H::update_operation(&mut op);
MethodRouter::new().on(
Method::POST,
into_boxed_handler(handler),
op,
<H as Handler<T>>::register_components,
)
}
/// Create a PUT route handler
pub fn put<H, T>(handler: H) -> MethodRouter
where
H: Handler<T>,
T: 'static,
{
let mut op = Operation::new();
H::update_operation(&mut op);
MethodRouter::new().on(
Method::PUT,
into_boxed_handler(handler),
op,
<H as Handler<T>>::register_components,
)
}
/// Create a PATCH route handler
pub fn patch<H, T>(handler: H) -> MethodRouter
where
H: Handler<T>,
T: 'static,
{
let mut op = Operation::new();
H::update_operation(&mut op);
MethodRouter::new().on(
Method::PATCH,
into_boxed_handler(handler),
op,
<H as Handler<T>>::register_components,
)
}
/// Create a DELETE route handler
pub fn delete<H, T>(handler: H) -> MethodRouter
where
H: Handler<T>,
T: 'static,
{
let mut op = Operation::new();
H::update_operation(&mut op);
MethodRouter::new().on(
Method::DELETE,
into_boxed_handler(handler),
op,
<H as Handler<T>>::register_components,
)
}
/// Main router
pub struct Router {
inner: MatchitRouter<MethodRouter>,
state: Arc<Extensions>,
/// Track registered routes for conflict detection
registered_routes: HashMap<String, RouteInfo>,
/// Store MethodRouters for nesting support (keyed by matchit path)
method_routers: HashMap<String, MethodRouter>,
/// Track state type IDs for merging (type name -> whether it's set)
/// This is a workaround since Extensions doesn't support iteration
state_type_ids: Vec<std::any::TypeId>,
}
impl Router {
/// Create a new router
pub fn new() -> Self {
Self {
inner: MatchitRouter::new(),
state: Arc::new(Extensions::new()),
registered_routes: HashMap::new(),
method_routers: HashMap::new(),
state_type_ids: Vec::new(),
}
}
/// Add a typed route using a TypedPath
pub fn typed<P: TypedPath>(self, method_router: MethodRouter) -> Self {
self.route(P::PATH, method_router)
}
/// Add a route
pub fn route(mut self, path: &str, method_router: MethodRouter) -> Self {
// Convert {param} style to :param for matchit
let matchit_path = convert_path_params(path);
// Get the methods being registered
let methods: Vec<Method> = method_router.handlers.keys().cloned().collect();
// Store a clone of the MethodRouter for nesting support
self.method_routers
.insert(matchit_path.clone(), method_router.clone());
match self.inner.insert(matchit_path.clone(), method_router) {
Ok(_) => {
// Track the registered route
self.registered_routes.insert(
matchit_path.clone(),
RouteInfo {
path: path.to_string(),
methods,
},
);
}
Err(e) => {
// Remove the method_router we just added since registration failed
self.method_routers.remove(&matchit_path);
// Find the existing conflicting route
let existing_path = self
.find_conflicting_route(&matchit_path)
.map(|info| info.path.clone())
.unwrap_or_else(|| "<unknown>".to_string());
let conflict_error = RouteConflictError {
new_path: path.to_string(),
method: methods.first().cloned(),
existing_path,
details: e.to_string(),
};
panic!("{}", conflict_error);
}
}
self
}
/// Find a conflicting route by checking registered routes
fn find_conflicting_route(&self, matchit_path: &str) -> Option<&RouteInfo> {
// Try to find an exact match first
if let Some(info) = self.registered_routes.get(matchit_path) {
return Some(info);
}
// Try to find a route that would conflict (same structure but different param names)
let normalized_new = normalize_path_for_comparison(matchit_path);
for (registered_path, info) in &self.registered_routes {
let normalized_existing = normalize_path_for_comparison(registered_path);
if normalized_new == normalized_existing {
return Some(info);
}
}
None
}
/// Add application state
pub fn state<S: Clone + Send + Sync + 'static>(mut self, state: S) -> Self {
let type_id = std::any::TypeId::of::<S>();
let extensions = Arc::make_mut(&mut self.state);
extensions.insert(state);
if !self.state_type_ids.contains(&type_id) {
self.state_type_ids.push(type_id);
}
self
}
/// Check if state of a given type exists
pub fn has_state<S: 'static>(&self) -> bool {
self.state_type_ids.contains(&std::any::TypeId::of::<S>())
}
/// Get state type IDs (for testing and debugging)
pub fn state_type_ids(&self) -> &[std::any::TypeId] {
&self.state_type_ids
}
/// Nest another router under a prefix
///
/// All routes from the nested router will be registered with the prefix
/// prepended to their paths. State from the nested router is merged into
/// the parent router (parent state takes precedence for type conflicts).
///
/// # State Merging
///
/// When nesting routers with state:
/// - If the parent router has state of type T, it is preserved (parent wins)
/// - If only the nested router has state of type T, it is added to the parent
/// - State type tracking is merged to enable proper conflict detection
///
/// Note: Due to limitations of `http::Extensions`, automatic state merging
/// requires using the `merge_state` method for specific types.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::{Router, get};
///
/// async fn list_users() -> &'static str { "List users" }
/// async fn get_user() -> &'static str { "Get user" }
///
/// let users_router = Router::new()
/// .route("/", get(list_users))
/// .route("/{id}", get(get_user));
///
/// let app = Router::new()
/// .nest("/api/users", users_router);
///
/// // Routes are now:
/// // GET /api/users/
/// // GET /api/users/{id}
/// ```
///
/// # Nesting with State
///
/// The `nest` method automatically tracks state types from the nested router to prevent
/// conflicts, but it does NOT automatically merge the state values instance by instance.
/// You should distinctively add state to the parent, or use `merge_state` if you want
/// to pull a specific state object from the child.
///
/// ```rust,ignore
/// use rustapi_core::Router;
/// use std::sync::Arc;
///
/// #[derive(Clone)]
/// struct Database { /* ... */ }
///
/// let db = Database { /* ... */ };
///
/// // Option 1: Add state to the parent (Recommended)
/// let api = Router::new()
/// .nest("/v1", Router::new()
/// .route("/users", get(list_users))) // Needs Database
/// .state(db);
///
/// // Option 2: Define specific state in sub-router and merge explicitly
/// let sub_router = Router::new()
/// .state(Database { /* ... */ })
/// .route("/items", get(list_items));
///
/// let app = Router::new()
/// .merge_state::<Database>(&sub_router) // Pulls Database from sub_router
/// .nest("/api", sub_router);
/// ```
pub fn nest(mut self, prefix: &str, router: Router) -> Self {
// 1. Normalize the prefix
let normalized_prefix = normalize_prefix(prefix);
// 2. Merge state type IDs from nested router
// Parent state takes precedence - we only track types, actual values
// are handled by merge_state calls or by the user adding state to parent
for type_id in &router.state_type_ids {
if !self.state_type_ids.contains(type_id) {
self.state_type_ids.push(*type_id);
}
}
// 3. Collect routes from the nested router before consuming it
// We need to iterate over registered_routes and get the corresponding MethodRouters
let nested_routes: Vec<(String, RouteInfo, MethodRouter)> = router
.registered_routes
.into_iter()
.filter_map(|(matchit_path, route_info)| {
router
.method_routers
.get(&matchit_path)
.map(|mr| (matchit_path, route_info, mr.clone()))
})
.collect();
// 4. Register each nested route with the prefix
for (matchit_path, route_info, method_router) in nested_routes {
// Build the prefixed path
// The matchit_path already has the :param format
// The route_info.path has the {param} format
let prefixed_matchit_path = if matchit_path == "/" {
normalized_prefix.clone()
} else {
format!("{}{}", normalized_prefix, matchit_path)
};
let prefixed_display_path = if route_info.path == "/" {
normalized_prefix.clone()
} else {
format!("{}{}", normalized_prefix, route_info.path)
};
// Store the MethodRouter for future nesting
self.method_routers
.insert(prefixed_matchit_path.clone(), method_router.clone());
// Try to insert into the matchit router
match self
.inner
.insert(prefixed_matchit_path.clone(), method_router)
{
Ok(_) => {
// Track the registered route
self.registered_routes.insert(
prefixed_matchit_path,
RouteInfo {
path: prefixed_display_path,
methods: route_info.methods,
},
);
}
Err(e) => {
// Remove the method_router we just added since registration failed
self.method_routers.remove(&prefixed_matchit_path);
// Find the existing conflicting route
let existing_path = self
.find_conflicting_route(&prefixed_matchit_path)
.map(|info| info.path.clone())
.unwrap_or_else(|| "<unknown>".to_string());
let conflict_error = RouteConflictError {
new_path: prefixed_display_path,
method: route_info.methods.first().cloned(),
existing_path,
details: e.to_string(),
};
panic!("{}", conflict_error);
}
}
}
self
}
/// Merge state from another router into this one
///
/// This method allows explicit state merging when nesting routers.
/// Parent state takes precedence - if the parent already has state of type S,
/// the nested state is ignored.
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Clone)]
/// struct DbPool(String);
///
/// let nested = Router::new().state(DbPool("nested".to_string()));
/// let parent = Router::new()
/// .merge_state::<DbPool>(&nested); // Adds DbPool from nested
/// ```
pub fn merge_state<S: Clone + Send + Sync + 'static>(mut self, other: &Router) -> Self {
let type_id = std::any::TypeId::of::<S>();
// Parent wins - only merge if parent doesn't have this state type
if !self.state_type_ids.contains(&type_id) {
// Try to get the state from the other router
if let Some(state) = other.state.get::<S>() {
let extensions = Arc::make_mut(&mut self.state);
extensions.insert(state.clone());
self.state_type_ids.push(type_id);
}
}
self
}
/// Match a request and return the handler + params
pub fn match_route(&self, path: &str, method: &Method) -> RouteMatch<'_> {
match self.inner.at(path) {
Ok(matched) => {
let method_router = matched.value;
if let Some(handler) = method_router.get_handler(method) {
// Use stack-optimized PathParams (avoids heap allocation for ≤4 params)
let params: PathParams = matched
.params
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
RouteMatch::Found { handler, params }
} else {
RouteMatch::MethodNotAllowed {
allowed: method_router.allowed_methods(),
}
}
}
Err(_) => RouteMatch::NotFound,
}
}
/// Get shared state
pub fn state_ref(&self) -> Arc<Extensions> {
self.state.clone()
}
/// Get registered routes (for testing and debugging)
pub fn registered_routes(&self) -> &HashMap<String, RouteInfo> {
&self.registered_routes
}
/// Get method routers (for OpenAPI integration during nesting)
pub fn method_routers(&self) -> &HashMap<String, MethodRouter> {
&self.method_routers
}
}
impl Default for Router {
fn default() -> Self {
Self::new()
}
}
/// Result of route matching
pub enum RouteMatch<'a> {
Found {
handler: &'a BoxedHandler,
params: PathParams,
},
NotFound,
MethodNotAllowed {
allowed: Vec<Method>,
},
}
/// Convert {param} style to :param for matchit
fn convert_path_params(path: &str) -> String {
let mut result = String::with_capacity(path.len());
for ch in path.chars() {
match ch {
'{' => {
result.push(':');
}
'}' => {
// Skip closing brace
}
_ => {
result.push(ch);
}
}
}
result
}
/// Normalize a path for conflict comparison by replacing parameter names with a placeholder
fn normalize_path_for_comparison(path: &str) -> String {
let mut result = String::with_capacity(path.len());
let mut in_param = false;
for ch in path.chars() {
match ch {
':' => {
in_param = true;
result.push_str(":_");
}
'/' => {
in_param = false;
result.push('/');
}
_ if in_param => {
// Skip parameter name characters
}
_ => {
result.push(ch);
}
}
}
result
}
/// Normalize a prefix for router nesting.
///
/// Ensures the prefix:
/// - Starts with exactly one leading slash
/// - Has no trailing slash (unless it's just "/")
/// - Has no double slashes
///
/// # Examples
///
/// ```ignore
/// assert_eq!(normalize_prefix("api"), "/api");
/// assert_eq!(normalize_prefix("/api"), "/api");
/// assert_eq!(normalize_prefix("/api/"), "/api");
/// assert_eq!(normalize_prefix("//api//"), "/api");
/// assert_eq!(normalize_prefix(""), "/");
/// ```
pub(crate) fn normalize_prefix(prefix: &str) -> String {
// Handle empty string
if prefix.is_empty() {
return "/".to_string();
}
// Split by slashes and filter out empty segments (handles multiple slashes)
let segments: Vec<&str> = prefix.split('/').filter(|s| !s.is_empty()).collect();
// If no segments after filtering, return root
if segments.is_empty() {
return "/".to_string();
}
// Build the normalized prefix with leading slash
let mut result = String::with_capacity(prefix.len() + 1);
for segment in segments {
result.push('/');
result.push_str(segment);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_convert_path_params() {
assert_eq!(convert_path_params("/users/{id}"), "/users/:id");
assert_eq!(
convert_path_params("/users/{user_id}/posts/{post_id}"),
"/users/:user_id/posts/:post_id"
);
assert_eq!(convert_path_params("/static/path"), "/static/path");
}
#[test]
fn test_normalize_path_for_comparison() {
assert_eq!(normalize_path_for_comparison("/users/:id"), "/users/:_");
assert_eq!(
normalize_path_for_comparison("/users/:user_id"),
"/users/:_"
);
assert_eq!(
normalize_path_for_comparison("/users/:id/posts/:post_id"),
"/users/:_/posts/:_"
);
assert_eq!(
normalize_path_for_comparison("/static/path"),
"/static/path"
);
}
#[test]
fn test_normalize_prefix() {
// Basic cases
assert_eq!(normalize_prefix("api"), "/api");
assert_eq!(normalize_prefix("/api"), "/api");
assert_eq!(normalize_prefix("/api/"), "/api");
assert_eq!(normalize_prefix("api/"), "/api");
// Multiple segments
assert_eq!(normalize_prefix("api/v1"), "/api/v1");
assert_eq!(normalize_prefix("/api/v1"), "/api/v1");
assert_eq!(normalize_prefix("/api/v1/"), "/api/v1");
// Edge cases: empty and root
assert_eq!(normalize_prefix(""), "/");
assert_eq!(normalize_prefix("/"), "/");
// Multiple slashes
assert_eq!(normalize_prefix("//api"), "/api");
assert_eq!(normalize_prefix("api//v1"), "/api/v1");
assert_eq!(normalize_prefix("//api//v1//"), "/api/v1");
assert_eq!(normalize_prefix("///"), "/");
}
#[test]
#[should_panic(expected = "ROUTE CONFLICT DETECTED")]
fn test_route_conflict_detection() {
async fn handler1() -> &'static str {
"handler1"
}
async fn handler2() -> &'static str {
"handler2"
}
let _router = Router::new()
.route("/users/{id}", get(handler1))
.route("/users/{user_id}", get(handler2)); // This should panic
}
#[test]
fn test_no_conflict_different_paths() {
async fn handler1() -> &'static str {
"handler1"
}
async fn handler2() -> &'static str {
"handler2"
}
let router = Router::new()
.route("/users/{id}", get(handler1))
.route("/users/{id}/profile", get(handler2));
assert_eq!(router.registered_routes().len(), 2);
}
#[test]
fn test_route_info_tracking() {
async fn handler() -> &'static str {
"handler"
}
let router = Router::new().route("/users/{id}", get(handler));
let routes = router.registered_routes();
assert_eq!(routes.len(), 1);
let info = routes.get("/users/:id").unwrap();
assert_eq!(info.path, "/users/{id}");
assert_eq!(info.methods.len(), 1);
assert_eq!(info.methods[0], Method::GET);
}
#[test]
fn test_basic_router_nesting() {
async fn list_users() -> &'static str {
"list users"
}
async fn get_user() -> &'static str {
"get user"
}
let users_router = Router::new()
.route("/", get(list_users))
.route("/{id}", get(get_user));
let app = Router::new().nest("/api/users", users_router);
let routes = app.registered_routes();
assert_eq!(routes.len(), 2);
// Check that routes are registered with prefix
assert!(routes.contains_key("/api/users"));
assert!(routes.contains_key("/api/users/:id"));
// Check display paths
let list_info = routes.get("/api/users").unwrap();
assert_eq!(list_info.path, "/api/users");
let get_info = routes.get("/api/users/:id").unwrap();
assert_eq!(get_info.path, "/api/users/{id}");
}
#[test]
fn test_nested_route_matching() {
async fn handler() -> &'static str {
"handler"
}
let users_router = Router::new().route("/{id}", get(handler));
let app = Router::new().nest("/api/users", users_router);
// Test that the route can be matched
match app.match_route("/api/users/123", &Method::GET) {
RouteMatch::Found { params, .. } => {
assert_eq!(params.get("id"), Some(&"123".to_string()));
}
_ => panic!("Route should be found"),
}
}
#[test]
fn test_nested_route_matching_multiple_params() {
async fn handler() -> &'static str {
"handler"
}
let posts_router = Router::new().route("/{user_id}/posts/{post_id}", get(handler));
let app = Router::new().nest("/api", posts_router);
// Test that multiple parameters are correctly extracted
match app.match_route("/api/42/posts/100", &Method::GET) {
RouteMatch::Found { params, .. } => {
assert_eq!(params.get("user_id"), Some(&"42".to_string()));
assert_eq!(params.get("post_id"), Some(&"100".to_string()));
}
_ => panic!("Route should be found"),
}
}
#[test]
fn test_nested_route_matching_static_path() {
async fn handler() -> &'static str {
"handler"
}