reinhardt-urls 0.3.0

URL routing and proxy utilities for Reinhardt framework
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
//! Unit tests for ServerRouter, ServerRouter splitting, and helpers.

use super::*;
use hyper::Method;
use reinhardt_core::endpoint::EndpointInfo;
use reinhardt_http::{Handler, Request, Response, Result};
use rstest::rstest;
use std::sync::Arc;

struct TestEndpoint<const ID: u8>;

impl<const ID: u8> EndpointInfo for TestEndpoint<ID> {
	fn path() -> &'static str {
		match ID {
			1 => "/health",
			2 => "/list",
			3 => "/users/{id}",
			4 => "/users/{id}/posts",
			5 => "/posts/{post_id}/comments/{comment_id}",
			6 => "/orgs/{org}/clusters/{cluster_id}/",
			7 => "/users",
			8 => "/posts",
			9 => "/items",
			10 => "/api/users/",
			11 => "/api/server_fn/test",
			12 => "/api/users",
			13 => "/auth/register/",
			14 => "/auth/login/",
			15 => "/users/",
			16 => "/dashboard/",
			17 => "/api/health",
			18 => "/sub/action/",
			19 => "/profile/",
			20 => "/detail/",
			21 => "/edit/",
			22 => "/catch/",
			23 => "/users",
			24 => "/items",
			25 => "/users",
			26 => "/items",
			27 => "/users",
			28 => "/profile",
			_ => unreachable!("unsupported test endpoint"),
		}
	}

	fn method() -> Method {
		match ID {
			8 | 11 | 12 | 13 | 14 | 18 | 27 => Method::POST,
			21 => Method::PUT,
			_ => Method::GET,
		}
	}

	fn name() -> &'static str {
		match ID {
			1 => "health",
			2 => "list",
			3 => "users-detail",
			4 => "users-posts",
			5 => "post-comment",
			6 => "cluster-detail",
			7 => "users-list",
			8 => "posts-create",
			9 => "items-list",
			10 => "api-users",
			11 => "server-fn-test",
			12 => "api-users-create",
			13 => "auth-register",
			14 => "auth-login",
			15 => "users-index",
			16 => "dashboard",
			17 => "api-health",
			18 => "sub-action",
			19 => "profile",
			20 => "detail",
			21 => "edit",
			22 => "catch",
			23 => "list",
			24 => "list",
			25 => "users-list",
			26 => "items-list",
			27 => "users-create",
			28 => "!profile_detail",
			_ => unreachable!("unsupported test endpoint"),
		}
	}
}

#[async_trait::async_trait]
impl<const ID: u8> Handler for TestEndpoint<ID> {
	async fn handle(&self, _req: Request) -> Result<Response> {
		Ok(Response::ok())
	}
}

#[rstest]
fn test_new_router() {
	// Arrange & Act
	let router = ServerRouter::new();

	// Assert
	assert_eq!(router.prefix(), "");
	assert_eq!(router.namespace(), None);
	assert_eq!(router.children_count(), 0);
}

#[rstest]
fn test_with_prefix() {
	// Arrange & Act
	let router = ServerRouter::new().with_prefix("/api/v1");

	// Assert
	assert_eq!(router.prefix(), "/api/v1");
}

#[rstest]
fn test_with_namespace() {
	// Arrange & Act
	let router = ServerRouter::new().with_namespace("v1");

	// Assert
	assert_eq!(router.namespace(), Some("v1"));
}

#[rstest]
fn test_mount() {
	// Arrange
	let child = ServerRouter::new();

	// Act
	let router = ServerRouter::new().mount("/users/", child);

	// Assert
	assert_eq!(router.children_count(), 1);
}

#[rstest]
#[should_panic(expected = "path parameter placeholder")]
fn test_mount_panics_on_param_prefix() {
	// Arrange
	let child = ServerRouter::new();

	// Act
	// Mounting with a `{param}` placeholder in the prefix is not supported
	// and must panic at construction time.
	let _ = ServerRouter::new().mount("/orgs/{org}/clusters/", child);

	// Assert: handled by `#[should_panic]`.
}

#[rstest]
fn test_mount_inherits_di_context() {
	// Arrange
	let di_ctx =
		Arc::new(InjectionContext::builder(Arc::new(reinhardt_di::SingletonScope::new())).build());
	let child = ServerRouter::new();

	// Act
	let router = ServerRouter::new()
		.with_di_context(di_ctx.clone())
		.mount("/users/", child);

	// Assert
	assert!(router.di_context.is_some());
	assert_eq!(router.children_count(), 1);
}

#[rstest]
fn test_group() {
	// Arrange
	let users = ServerRouter::new().with_prefix("/users");
	let posts = ServerRouter::new().with_prefix("/posts");

	// Act
	let router = ServerRouter::new().group(vec![users, posts]);

	// Assert
	assert_eq!(router.children_count(), 2);
}

#[rstest]
fn test_get_all_routes() {
	// Arrange
	let router = ServerRouter::new()
		.with_prefix("/api")
		.with_namespace("api");

	// Act
	let routes = router.get_all_routes();

	// Assert
	assert_eq!(routes.len(), 0);
}

#[rstest]
fn test_get_all_routes_strips_optout_sigil_from_endpoint_name() {
	// Arrange
	let router = ServerRouter::new().endpoint(|| TestEndpoint::<28>);

	// Act
	let routes = router.get_all_routes();

	// Assert
	assert_eq!(routes.len(), 1);
	assert_eq!(routes[0].1.as_deref(), Some("profile_detail"));
}

#[rstest]
fn test_get_full_namespace_no_parent() {
	// Arrange
	let router = ServerRouter::new().with_namespace("users");

	// Act & Assert
	assert_eq!(router.get_full_namespace(None), Some("users".to_string()));
}

#[rstest]
fn test_get_full_namespace_with_parent() {
	// Arrange
	let router = ServerRouter::new().with_namespace("users");

	// Act & Assert
	assert_eq!(
		router.get_full_namespace(Some("v1")),
		Some("v1:users".to_string())
	);
}

#[rstest]
fn test_get_full_namespace_no_namespace() {
	// Arrange
	let router = ServerRouter::new();

	// Act & Assert
	assert_eq!(
		router.get_full_namespace(Some("v1")),
		Some("v1".to_string())
	);
	assert_eq!(router.get_full_namespace(None), None);
}

#[rstest]
fn test_hierarchical_namespace() {
	// Arrange
	let child = ServerRouter::new().with_namespace("users");

	// Act
	let parent = ServerRouter::new()
		.with_namespace("v1")
		.mount("/users/", child);

	// Assert
	assert_eq!(parent.namespace(), Some("v1"));
	assert_eq!(parent.children_count(), 1);
}

#[rstest]
fn test_register_all_routes_with_namespace() {
	// Arrange
	let mut router = ServerRouter::new()
		.with_namespace("api")
		.endpoint(|| TestEndpoint::<1>);

	// Act
	let errors = router.register_all_routes();
	assert!(errors.is_empty());

	// Assert
	let url = router.reverse("api:health", &[]);
	assert!(url.is_some());
	assert_eq!(url.unwrap(), "/health");
}

#[rstest]
fn test_nested_namespace_registration() {
	// Arrange
	let users = ServerRouter::new()
		.with_namespace("users")
		.endpoint(|| TestEndpoint::<2>);

	let mut api = ServerRouter::new()
		.with_namespace("v1")
		.with_prefix("/api/v1")
		.mount("/users/", users);

	// Act
	let errors = api.register_all_routes();
	assert!(errors.is_empty());

	// Assert
	let url = api.reverse("v1:users:list", &[]);
	assert!(url.is_some());
	assert_eq!(url.unwrap(), "/api/v1/users/list");
}

#[rstest]
fn test_mount_prefix_inheritance() {
	// Arrange
	let child = ServerRouter::new();

	// Act
	let parent = ServerRouter::new().with_prefix("/api").mount("/v1/", child);

	// Assert
	assert_eq!(parent.children_count(), 1);
}

#[rstest]
fn test_multiple_child_routers() {
	// Arrange
	let users = ServerRouter::new().with_namespace("users");
	let posts = ServerRouter::new().with_namespace("posts");
	let comments = ServerRouter::new().with_namespace("comments");

	// Act
	let router = ServerRouter::new()
		.mount("/users/", users)
		.mount("/posts/", posts)
		.mount("/comments/", comments);

	// Assert
	assert_eq!(router.children_count(), 3);
}

#[rstest]
fn test_deep_nesting() {
	// Arrange
	let resource = ServerRouter::new().with_namespace("resource");
	let v2 = ServerRouter::new()
		.with_namespace("v2")
		.mount("/resource/", resource);
	let v1 = ServerRouter::new().with_namespace("v1").mount("/v2/", v2);

	// Act
	let api = ServerRouter::new().with_namespace("api").mount("/v1/", v1);

	// Assert
	assert_eq!(api.children_count(), 1);
}

#[tokio::test]
async fn test_route_matching_correctness() {
	// Arrange
	let router = ServerRouter::new()
		.endpoint(|| TestEndpoint::<3>)
		.endpoint(|| TestEndpoint::<4>)
		.endpoint(|| TestEndpoint::<5>);
	router.compile_routes();

	// Act & Assert - exact path matching
	let result = router.match_own_routes("/users/123", &Method::GET);
	assert!(result.is_some());
	assert_eq!(result.unwrap().param("id"), Some("123"));

	// Act & Assert - nested path matching
	let result = router.match_own_routes("/users/456/posts", &Method::GET);
	assert!(result.is_some());
	assert_eq!(result.unwrap().param("id"), Some("456"));

	// Act & Assert - multiple parameters; verify both values AND
	// declaration order (post_id appears before comment_id in the URL).
	let route_match = router.match_own_routes("/posts/789/comments/101", &Method::GET);
	let route_match = route_match.unwrap();
	assert_eq!(route_match.param("post_id"), Some("789"));
	assert_eq!(route_match.param("comment_id"), Some("101"));
	assert_eq!(
		route_match.params.as_slice(),
		&[
			("post_id".to_string(), "789".to_string()),
			("comment_id".to_string(), "101".to_string()),
		],
		"path params must be stored in URL pattern declaration order (issue #4013)"
	);

	// Act & Assert - non-matching route
	let result = router.match_own_routes("/nonexistent", &Method::GET);
	assert!(result.is_none());
}

#[tokio::test]
async fn test_route_matching_preserves_url_pattern_order_issue_4013() {
	// Regression test for issue #4013: path parameters must be exposed in
	// URL pattern declaration order (not alphabetical), so that tuple
	// extractors `Path<(T1, T2)>` populate fields by position.

	// Arrange: alphabetical order would put `cluster_id` before `org`,
	// but URL declaration order is `org` first, `cluster_id` second.
	let router = ServerRouter::new().endpoint(|| TestEndpoint::<6>);
	router.compile_routes();

	// Act
	let route_match = router
		.match_own_routes("/orgs/myslug/clusters/5/", &Method::GET)
		.expect("route should match");

	// Assert
	assert_eq!(
		route_match.params.as_slice(),
		&[
			("org".to_string(), "myslug".to_string()),
			("cluster_id".to_string(), "5".to_string()),
		],
		"matched params must follow URL declaration order (issue #4013)"
	);
}

#[tokio::test]
async fn test_route_matching_different_methods() {
	// Arrange
	let router = ServerRouter::new()
		.endpoint(|| TestEndpoint::<7>)
		.endpoint(|| TestEndpoint::<27>);
	router.compile_routes();

	// Act & Assert - GET method
	let result = router.match_own_routes("/users", &Method::GET);
	assert!(result.is_some());

	// Act & Assert - POST method
	let result = router.match_own_routes("/users", &Method::POST);
	assert!(result.is_some());

	// Act & Assert - unsupported method
	let result = router.match_own_routes("/users", &Method::DELETE);
	assert!(result.is_none());
}

#[rstest]
fn test_validate_routes_success() {
	// Arrange
	let router = ServerRouter::new()
		.endpoint(|| TestEndpoint::<3>)
		.endpoint(|| TestEndpoint::<8>);

	// Act
	let result = router.validate_routes();

	// Assert
	assert!(result.is_ok());
}

#[rstest]
fn test_compile_routes_returns_errors_for_duplicate_routes() {
	// Arrange - register duplicate paths for the same method
	let router = ServerRouter::new()
		.endpoint(|| TestEndpoint::<7>)
		.endpoint(|| TestEndpoint::<25>);

	// Act
	let errors = router.compile_routes();

	// Assert - matchit should report a conflict for duplicate routes
	assert!(!errors.is_empty());
	assert!(errors[0].contains("Failed to compile route"));
}

#[rstest]
fn test_validate_routes_returns_errors_for_invalid_patterns() {
	// Arrange - duplicate routes cause matchit compilation errors
	let router = ServerRouter::new()
		.endpoint(|| TestEndpoint::<9>)
		.endpoint(|| TestEndpoint::<26>);

	// Act
	let result = router.validate_routes();

	// Assert
	assert!(result.is_err());
	let errors = result.unwrap_err();
	assert!(!errors.is_empty());
}

#[rstest]
fn test_router_recovers_from_poisoned_rwlock() {
	// Arrange
	let router = ServerRouter::new().endpoint(|| TestEndpoint::<1>);

	// Poison the routes_compiled RwLock by panicking while holding write guard
	let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
		let _guard = router.routes_compiled.write().unwrap();
		panic!("intentional panic to poison lock");
	}));

	// Act - compile_routes should recover from poisoned lock
	let errors = router.compile_routes();

	// Assert
	assert!(errors.is_empty());
	let result = router.match_own_routes("/health", &Method::GET);
	assert!(result.is_some());
}

#[rstest]
fn test_route_matching_recovers_from_poisoned_method_router() {
	// Arrange
	let router = ServerRouter::new().endpoint(|| TestEndpoint::<1>);
	router.compile_routes();

	// Poison the get_router RwLock
	let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
		let _guard = router.get_router.write().unwrap();
		panic!("intentional panic to poison lock");
	}));

	// Act - match_own_routes should recover from poisoned lock
	let result = router.match_own_routes("/health", &Method::GET);

	// Assert - route matching should still work
	assert!(result.is_some());
}

// --- ServerRouter::exclude() tests ---

// Simple no-op middleware for testing exclude()
struct NoopMiddleware;

#[async_trait::async_trait]
impl Middleware for NoopMiddleware {
	async fn process(
		&self,
		request: reinhardt_http::Request,
		next: std::sync::Arc<dyn reinhardt_http::Handler>,
	) -> reinhardt_http::Result<reinhardt_http::Response> {
		next.handle(request).await
	}
}

fn create_test_request(path: &str) -> reinhardt_http::Request {
	reinhardt_http::Request::builder()
		.method(Method::GET)
		.uri(path)
		.version(hyper::Version::HTTP_11)
		.headers(hyper::HeaderMap::new())
		.body(bytes::Bytes::new())
		.build()
		.unwrap()
}

#[rstest]
fn test_server_router_exclude_stores_exclusion() {
	// Arrange & Act
	let router = ServerRouter::new()
		.with_middleware(NoopMiddleware)
		.exclude("/api/auth/")
		.exclude("/health");

	// Assert
	assert_eq!(router.middleware_exclusions.len(), 1);
	assert_eq!(router.middleware_exclusions[0].len(), 2);
	assert_eq!(router.middleware_exclusions[0][0], "/api/auth/");
	assert_eq!(router.middleware_exclusions[0][1], "/health");
}

#[rstest]
fn test_server_router_exclude_only_affects_last_middleware() {
	// Arrange & Act
	let router = ServerRouter::new()
		.with_middleware(NoopMiddleware)
		.exclude("/admin/")
		.with_middleware(NoopMiddleware)
		.exclude("/api/auth/");

	// Assert
	assert_eq!(router.middleware_exclusions.len(), 2);
	assert_eq!(router.middleware_exclusions[0], vec!["/admin/"]);
	assert_eq!(router.middleware_exclusions[1], vec!["/api/auth/"]);
}

#[rstest]
#[should_panic(expected = "exclude() called with no middleware")]
fn test_server_router_exclude_panics_without_middleware() {
	// Arrange & Act & Assert
	let _router = ServerRouter::new().exclude("/api/auth/");
}

#[rstest]
fn test_server_router_build_middleware_with_exclusions() {
	// Arrange
	let router = ServerRouter::new()
		.with_middleware(NoopMiddleware)
		.exclude("/admin/")
		.with_middleware(NoopMiddleware);

	// Act
	let built = router.build_middleware_with_exclusions();

	// Assert
	assert_eq!(built.len(), 2);

	let request_admin = create_test_request("/admin/dashboard");
	let request_public = create_test_request("/public");

	// First middleware (with exclusion) skips /admin/
	assert!(!built[0].should_continue(&request_admin));
	assert!(built[0].should_continue(&request_public));
	// Second middleware (no exclusion) runs for all
	assert!(built[1].should_continue(&request_admin));
	assert!(built[1].should_continue(&request_public));
}

// --- Framework-level 404/405 middleware tests (#3234) ---

// Middleware that adds a security header to responses
struct SecurityHeaderTestMiddleware;

#[async_trait::async_trait]
impl Middleware for SecurityHeaderTestMiddleware {
	async fn process(
		&self,
		request: reinhardt_http::Request,
		next: std::sync::Arc<dyn reinhardt_http::Handler>,
	) -> reinhardt_http::Result<reinhardt_http::Response> {
		let mut response = next.handle(request).await?;
		response.headers.insert(
			hyper::header::HeaderName::from_static("x-security-test"),
			hyper::header::HeaderValue::from_static("applied"),
		);
		Ok(response)
	}
}

#[rstest]
#[tokio::test]
async fn test_404_response_gets_middleware_headers() {
	// Arrange: router with middleware and a registered route
	let router = ServerRouter::new()
		.with_middleware(SecurityHeaderTestMiddleware)
		.endpoint(|| TestEndpoint::<10>);

	// Act: request a non-existent path
	let request = create_test_request("/nonexistent");
	let response = Handler::handle(&router, request).await.unwrap();

	// Assert: 404 response has security header from middleware
	assert_eq!(response.status, hyper::StatusCode::NOT_FOUND);
	assert_eq!(
		response
			.headers
			.get("x-security-test")
			.map(|v| v.to_str().unwrap()),
		Some("applied"),
		"Framework-level 404 response should have middleware security header"
	);
}

#[rstest]
#[tokio::test]
async fn test_405_response_gets_middleware_headers() {
	// Arrange: router with middleware and a GET-only route
	let router = ServerRouter::new()
		.with_middleware(SecurityHeaderTestMiddleware)
		.endpoint(|| TestEndpoint::<10>);

	// Act: send POST to a GET-only route
	let request = reinhardt_http::Request::builder()
		.method(Method::POST)
		.uri("/api/users/")
		.version(hyper::Version::HTTP_11)
		.headers(hyper::HeaderMap::new())
		.body(bytes::Bytes::new())
		.build()
		.unwrap();
	let response = Handler::handle(&router, request).await.unwrap();

	// Assert: 405 response has security header from middleware
	assert_eq!(response.status, hyper::StatusCode::METHOD_NOT_ALLOWED);
	assert_eq!(
		response
			.headers
			.get("x-security-test")
			.map(|v| v.to_str().unwrap()),
		Some("applied"),
		"Framework-level 405 response should have middleware security header"
	);
}

#[rstest]
#[tokio::test]
async fn test_404_without_middleware_returns_error() {
	// Arrange: router with no middleware
	let router = ServerRouter::new().endpoint(|| TestEndpoint::<10>);

	// Act: request a non-existent path
	let request = create_test_request("/nonexistent");
	let result = Handler::handle(&router, request).await;

	// Assert: returns Err (not wrapped in middleware chain)
	assert!(result.is_err(), "404 without middleware should return Err");
}

#[rstest]
#[tokio::test]
async fn test_404_respects_middleware_exclusions() {
	// Arrange: router with middleware excluded for /admin/
	let router = ServerRouter::new()
		.with_middleware(SecurityHeaderTestMiddleware)
		.exclude("/admin/")
		.endpoint(|| TestEndpoint::<10>);

	// Act: request non-existent path under excluded prefix
	let request = create_test_request("/admin/nonexistent");
	let response = Handler::handle(&router, request).await.unwrap();

	// Assert: 404 response but security header absent (middleware excluded)
	assert_eq!(response.status, hyper::StatusCode::NOT_FOUND);
	assert!(
		response.headers.get("x-security-test").is_none(),
		"404 under excluded path should NOT have middleware security header"
	);
}

// --- Prefix double-application fix tests (#3407, #3408) ---

#[rstest]
#[tokio::test]
async fn test_endpoint_route_with_prefix_strips_prefix_during_compilation() {
	// Arrange: register a route whose path already contains the prefix,
	// simulating server function registration (e.g., ServerFnRegistration::PATH)
	let router = ServerRouter::new()
		.with_prefix("/api")
		.endpoint(|| TestEndpoint::<11>);

	// Act: resolve the full path (resolve() strips "/api" before matchit lookup)
	let result = router.resolve("/api/server_fn/test", &Method::POST);

	// Assert: route matches without double-prefix issue
	assert!(
		result.is_some(),
		"POST /api/server_fn/test should match when router has prefix /api"
	);
}

#[rstest]
#[tokio::test]
async fn test_endpoint_route_post_with_prefix_no_405() {
	// Arrange: register a POST route with a path that includes the prefix
	let router = ServerRouter::new()
		.with_prefix("/api")
		.endpoint(|| TestEndpoint::<12>);

	// Act: resolve POST request (verifies no 405 Method Not Allowed)
	let result = router.resolve("/api/users", &Method::POST);

	// Assert: POST route is reachable
	assert!(
		result.is_some(),
		"POST /api/users should match when router has prefix /api (no 405)"
	);

	// Also verify GET returns None (route is POST-only)
	let get_result = router.resolve("/api/users", &Method::GET);
	assert!(
		get_result.is_none(),
		"GET /api/users should not match a POST-only route"
	);
}

#[rstest]
#[tokio::test]
async fn test_endpoint_route_without_prefix_overlap_still_works() {
	// Arrange: route path does not start with the prefix
	let router = ServerRouter::new()
		.with_prefix("/api")
		.endpoint(|| TestEndpoint::<1>);

	// Act: resolve a path under the prefix
	let result = router.resolve("/api/health", &Method::GET);

	// Assert: route matches (path kept as-is since it does not start with prefix)
	assert!(
		result.is_some(),
		"/api/health should match /health route under /api prefix"
	);
}

// --- Leading slash normalization fix tests (#3419) ---
//
// strip_prefix_normalized: unit tests (normal / edge / error)

#[rstest]
// Normal: trailing-slash prefix strips correctly
#[case("/api/", "/api/auth/register/", "/auth/register/")]
// Normal: non-trailing-slash prefix strips correctly
#[case("/api", "/api/auth/register/", "/auth/register/")]
// Normal: prefix equals full path → root "/"
#[case("/api/", "/api/", "/")]
#[case("/api", "/api", "/")]
// Normal: single-segment after strip
#[case("/api/", "/api/health", "/health")]
#[case("/v1/", "/v1/users/", "/users/")]
// Edge: empty prefix returns path as-is
#[case("", "/anything", "/anything")]
#[case("", "/", "/")]
#[case("", "/a/b/c", "/a/b/c")]
// Edge: prefix is "/" — remainder loses leading slash, must be restored
#[case("/", "/health", "/health")]
#[case("/", "/a/b/c", "/a/b/c")]
// Edge: long multi-segment prefix
#[case("/api/v2/internal/", "/api/v2/internal/metrics", "/metrics")]
// Edge: path with URL-encoded segments
#[case("/api/", "/api/users%2F123/", "/users%2F123/")]
// Edge: path with hyphens and underscores
#[case("/api/", "/api/my-resource/sub_path/", "/my-resource/sub_path/")]
fn test_strip_prefix_normalized(#[case] prefix: &str, #[case] path: &str, #[case] expected: &str) {
	// Act
	let result = ServerRouter::strip_prefix_normalized(prefix, path);

	// Assert
	assert!(
		result.is_some(),
		"strip_prefix_normalized({prefix:?}, {path:?}) should return Some"
	);
	let normalized = result.unwrap();
	assert_eq!(
		normalized.as_ref(),
		expected,
		"strip_prefix_normalized({prefix:?}, {path:?})"
	);
}

#[rstest]
// Error: path doesn't start with prefix at all
#[case("/api/", "/web/page")]
#[case("/api", "/web/page")]
// Error: partial prefix match (not a real prefix)
#[case("/api/", "/ap")]
#[case("/api", "/ap")]
// Error: path is empty
#[case("/api/", "")]
#[case("/", "")]
// Error: prefix longer than path
#[case("/api/v2/", "/api/")]
fn test_strip_prefix_normalized_returns_none(#[case] prefix: &str, #[case] path: &str) {
	// Act
	let result = ServerRouter::strip_prefix_normalized(prefix, path);

	// Assert
	assert!(
		result.is_none(),
		"strip_prefix_normalized({prefix:?}, {path:?}) should return None"
	);
}

#[rstest]
fn test_strip_prefix_normalized_result_always_starts_with_slash() {
	// Arrange: various prefix/path combos that should succeed
	let cases = [
		("/api/", "/api/x"),
		("/a/b/c/", "/a/b/c/d"),
		("/", "/x"),
		("", "/x"),
		("/prefix/", "/prefix/rest/of/path"),
	];

	for (prefix, path) in cases {
		// Act
		let result = ServerRouter::strip_prefix_normalized(prefix, path);

		// Assert
		let normalized = result.unwrap();
		assert!(
			normalized.starts_with('/'),
			"result for ({prefix:?}, {path:?}) should start with '/' but got {normalized:?}"
		);
	}
}

// resolve(): normal cases with child routers

#[rstest]
#[tokio::test]
async fn test_resolve_trailing_slash_prefix_child_router_matches() {
	// Arrange: parent with trailing-slash prefix, child with its own prefix
	let child = ServerRouter::new()
		.with_prefix("/auth/")
		.endpoint(|| TestEndpoint::<13>);
	let parent = ServerRouter::new()
		.with_prefix("/api/")
		.mount("/auth/", child);

	// Act
	let result = parent.resolve("/api/auth/register/", &Method::POST);

	// Assert
	assert!(
		result.is_some(),
		"POST /api/auth/register/ should match child route through trailing-slash prefix"
	);
}

#[rstest]
#[tokio::test]
async fn test_resolve_no_trailing_slash_with_prefix_child_router_matches() {
	// Arrange: parent with_prefix (no trailing slash) + child mounted with trailing slash
	// Note: mount() requires trailing-slash prefix (Django convention),
	// but with_prefix() allows non-trailing-slash prefix
	let child = ServerRouter::new()
		.with_prefix("/auth/")
		.endpoint(|| TestEndpoint::<14>);
	let parent = ServerRouter::new()
		.with_prefix("/api")
		.mount("/auth/", child);

	// Act
	let result = parent.resolve("/api/auth/login/", &Method::POST);

	// Assert
	assert!(
		result.is_some(),
		"POST /api/auth/login/ should match child route with non-trailing-slash parent prefix"
	);
}

#[rstest]
#[tokio::test]
async fn test_resolve_multiple_children_with_trailing_slash_prefix() {
	// Arrange: parent with trailing-slash prefix, multiple children
	let auth = ServerRouter::new()
		.with_prefix("/auth/")
		.endpoint(|| TestEndpoint::<14>);
	let users = ServerRouter::new()
		.with_prefix("/users/")
		.endpoint(|| TestEndpoint::<15>);
	let parent = ServerRouter::new()
		.with_prefix("/api/")
		.mount("/auth/", auth)
		.mount("/users/", users);

	// Act & Assert: both children should be reachable
	assert!(
		parent.resolve("/api/auth/login/", &Method::POST).is_some(),
		"POST /api/auth/login/ should match auth child"
	);
	assert!(
		parent.resolve("/api/users/", &Method::GET).is_some(),
		"GET /api/users/ should match users child"
	);
}

#[rstest]
#[tokio::test]
async fn test_resolve_child_root_route_with_trailing_slash_prefix() {
	// Arrange: child's own root route (prefix stripped → "/")
	let child = ServerRouter::new()
		.with_prefix("/dashboard/")
		.endpoint(|| TestEndpoint::<16>);
	let parent = ServerRouter::new()
		.with_prefix("/app/")
		.mount("/dashboard/", child);

	// Act
	let result = parent.resolve("/app/dashboard/", &Method::GET);

	// Assert
	assert!(
		result.is_some(),
		"GET /app/dashboard/ should match child root route"
	);
}

#[rstest]
#[tokio::test]
async fn test_resolve_parent_own_route_still_works_with_trailing_slash_prefix() {
	// Arrange: parent has both own routes and children
	let child = ServerRouter::new()
		.with_prefix("/sub/")
		.endpoint(|| TestEndpoint::<18>);
	let parent = ServerRouter::new()
		.with_prefix("/api/")
		.endpoint(|| TestEndpoint::<17>)
		.mount("/sub/", child);

	// Act & Assert
	assert!(
		parent.resolve("/api/health", &Method::GET).is_some(),
		"Parent's own route should still work"
	);
	assert!(
		parent.resolve("/api/sub/action/", &Method::POST).is_some(),
		"Child route should also work"
	);
}

// resolve(): deep nesting

#[rstest]
#[tokio::test]
async fn test_resolve_deeply_nested_trailing_slash_prefixes() {
	// Arrange: 3 levels of trailing-slash prefixes
	let grandchild = ServerRouter::new()
		.with_prefix("/profile/")
		.endpoint(|| TestEndpoint::<19>);
	let child = ServerRouter::new()
		.with_prefix("/users/")
		.mount("/profile/", grandchild);
	let parent = ServerRouter::new()
		.with_prefix("/api/")
		.mount("/users/", child);

	// Act
	let result = parent.resolve("/api/users/profile/", &Method::GET);

	// Assert
	assert!(
		result.is_some(),
		"GET /api/users/profile/ should match through 3 levels of trailing-slash prefix stripping"
	);
}

#[rstest]
#[tokio::test]
async fn test_resolve_mixed_trailing_and_non_trailing_slash_nesting() {
	// Arrange: with_prefix uses non-trailing slash, mount uses trailing slash
	let grandchild = ServerRouter::new()
		.with_prefix("/detail")
		.endpoint(|| TestEndpoint::<20>);
	let child = ServerRouter::new()
		.with_prefix("/items/")
		.mount("/detail/", grandchild);
	let parent = ServerRouter::new()
		.with_prefix("/api/")
		.mount("/items/", child);

	// Act
	let result = parent.resolve("/api/items/detail/", &Method::GET);

	// Assert
	assert!(
		result.is_some(),
		"Mixed trailing/non-trailing prefix nesting should resolve correctly"
	);
}

// resolve(): error cases (should return None)

#[rstest]
#[tokio::test]
async fn test_resolve_path_not_matching_parent_prefix() {
	// Arrange
	let child = ServerRouter::new()
		.with_prefix("/auth/")
		.endpoint(|| TestEndpoint::<14>);
	let parent = ServerRouter::new()
		.with_prefix("/api/")
		.mount("/auth/", child);

	// Act
	let result = parent.resolve("/web/auth/login/", &Method::POST);

	// Assert
	assert!(
		result.is_none(),
		"Path not matching parent prefix should return None"
	);
}

#[rstest]
#[tokio::test]
async fn test_resolve_path_matches_parent_but_not_child() {
	// Arrange
	let child = ServerRouter::new()
		.with_prefix("/auth/")
		.endpoint(|| TestEndpoint::<14>);
	let parent = ServerRouter::new()
		.with_prefix("/api/")
		.mount("/auth/", child);

	// Act: path under parent prefix but doesn't match any child
	let result = parent.resolve("/api/unknown/path/", &Method::GET);

	// Assert
	assert!(
		result.is_none(),
		"Path matching parent but not child should return None"
	);
}

#[rstest]
#[tokio::test]
async fn test_resolve_wrong_method_through_child_with_trailing_slash_prefix() {
	// Arrange: child only has POST route
	let child = ServerRouter::new()
		.with_prefix("/auth/")
		.endpoint(|| TestEndpoint::<14>);
	let parent = ServerRouter::new()
		.with_prefix("/api/")
		.mount("/auth/", child);

	// Act: try GET instead of POST
	let result = parent.resolve("/api/auth/login/", &Method::GET);

	// Assert
	assert!(
		result.is_none(),
		"Wrong HTTP method through child router should return None"
	);
}

// path_exists_for_any_method(): normal / error / edge

#[rstest]
#[tokio::test]
async fn test_path_exists_with_trailing_slash_prefix_and_child() {
	// Arrange
	let child = ServerRouter::new()
		.with_prefix("/users/")
		.endpoint(|| TestEndpoint::<15>);
	let parent = ServerRouter::new()
		.with_prefix("/api/")
		.mount("/users/", child);

	// Act
	let exists = parent.path_exists_for_any_method("/api/users/");

	// Assert
	assert!(
		exists,
		"path_exists_for_any_method should find path in child router after prefix normalization"
	);
}

#[rstest]
#[tokio::test]
async fn test_path_exists_nonexistent_path_with_trailing_slash_prefix() {
	// Arrange
	let child = ServerRouter::new()
		.with_prefix("/users/")
		.endpoint(|| TestEndpoint::<15>);
	let parent = ServerRouter::new()
		.with_prefix("/api/")
		.mount("/users/", child);

	// Act
	let exists = parent.path_exists_for_any_method("/api/nonexistent/");

	// Assert
	assert!(
		!exists,
		"path_exists_for_any_method should return false for nonexistent path"
	);
}

#[rstest]
#[tokio::test]
async fn test_path_exists_wrong_prefix_returns_false() {
	// Arrange
	let child = ServerRouter::new()
		.with_prefix("/users/")
		.endpoint(|| TestEndpoint::<15>);
	let parent = ServerRouter::new()
		.with_prefix("/api/")
		.mount("/users/", child);

	// Act
	let exists = parent.path_exists_for_any_method("/web/users/");

	// Assert
	assert!(
		!exists,
		"path_exists_for_any_method with wrong parent prefix should return false"
	);
}

#[rstest]
#[tokio::test]
async fn test_path_exists_deeply_nested_with_trailing_slash_prefix() {
	// Arrange: 3-level nesting
	let grandchild = ServerRouter::new()
		.with_prefix("/edit/")
		.endpoint(|| TestEndpoint::<21>);
	let child = ServerRouter::new()
		.with_prefix("/items/")
		.mount("/edit/", grandchild);
	let parent = ServerRouter::new()
		.with_prefix("/api/")
		.mount("/items/", child);

	// Act
	let exists = parent.path_exists_for_any_method("/api/items/edit/");

	// Assert
	assert!(
		exists,
		"path_exists_for_any_method should find deeply nested path through trailing-slash prefixes"
	);
}

// Edge cases: compile_routes with trailing-slash prefix

#[rstest]
#[tokio::test]
async fn test_endpoint_route_with_trailing_slash_prefix_compiles_correctly() {
	// Arrange: route path includes prefix with trailing slash
	let router = ServerRouter::new()
		.with_prefix("/api/")
		.endpoint(|| TestEndpoint::<11>);

	// Act
	let result = router.resolve("/api/server_fn/test", &Method::POST);

	// Assert
	assert!(
		result.is_some(),
		"Route with trailing-slash prefix should compile and resolve correctly"
	);
}

#[rstest]
#[should_panic(expected = "URL route prefix cannot be an empty string")]
fn test_mount_with_empty_prefix_panics() {
	// Arrange & Act: mounting with empty prefix should panic
	let child = ServerRouter::new().endpoint(|| TestEndpoint::<22>);
	let _parent = ServerRouter::new().with_prefix("/api/").mount("", child);
}

#[rstest]
#[tokio::test]
async fn test_resolve_child_with_slash_prefix_under_trailing_slash_parent() {
	// Arrange: child router with "/" prefix under parent with trailing-slash prefix
	let child = ServerRouter::new()
		.with_prefix("/")
		.endpoint(|| TestEndpoint::<22>);
	let parent = ServerRouter::new().with_prefix("/api/").mount("/", child);

	// Act
	let result = parent.resolve("/api/catch/", &Method::GET);

	// Assert
	assert!(
		result.is_some(),
		"Child with '/' prefix under trailing-slash parent should match"
	);
}

// ===================================================================
// Duplicate route name detection tests (Issue #3462)
// ===================================================================

#[rstest]
fn test_register_all_routes_detects_duplicate_names() {
	// Arrange — two routes with the same name in the same router
	let mut router = ServerRouter::new()
		.with_namespace("api")
		.endpoint(|| TestEndpoint::<23>)
		.endpoint(|| TestEndpoint::<24>);

	// Act
	let errors = router.register_all_routes();

	// Assert
	assert_eq!(errors.len(), 1);
	assert!(errors[0].contains("Duplicate route name 'api:list'"));
}

#[rstest]
fn test_validate_route_names_succeeds_with_unique_names() {
	// Arrange
	let router = ServerRouter::new()
		.with_namespace("api")
		.endpoint(|| TestEndpoint::<25>)
		.endpoint(|| TestEndpoint::<26>);

	// Act
	let result = router.validate_route_names();

	// Assert
	assert!(result.is_ok());
}

#[rstest]
fn test_validate_routes_includes_name_errors() {
	// Arrange — duplicate name
	let router = ServerRouter::new()
		.with_namespace("api")
		.endpoint(|| TestEndpoint::<23>)
		.endpoint(|| TestEndpoint::<24>);

	// Act
	let result = router.validate_routes();

	// Assert
	assert!(result.is_err());
	let errors = result.unwrap_err();
	assert!(errors.iter().any(|e| e.contains("Duplicate route name")));
}