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
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
//! RustApi application builder
use crate::error::Result;
use crate::events::LifecycleHooks;
use crate::interceptor::{InterceptorChain, RequestInterceptor, ResponseInterceptor};
use crate::middleware::{BodyLimitLayer, LayerStack, MiddlewareLayer, DEFAULT_BODY_LIMIT};
use crate::response::IntoResponse;
use crate::router::{MethodRouter, Router};
use crate::server::Server;
use std::collections::BTreeMap;
use std::future::Future;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
/// Main application builder for RustAPI
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
/// RustApi::new()
/// .state(AppState::new())
/// .route("/", get(hello))
/// .route("/users/{id}", get(get_user))
/// .run("127.0.0.1:8080")
/// .await
/// }
/// ```
pub struct RustApi {
router: Router,
openapi_spec: rustapi_openapi::OpenApiSpec,
layers: LayerStack,
body_limit: Option<usize>,
interceptors: InterceptorChain,
lifecycle_hooks: LifecycleHooks,
hot_reload: bool,
#[cfg(feature = "http3")]
http3_config: Option<crate::http3::Http3Config>,
health_check: Option<crate::health::HealthCheck>,
health_endpoint_config: Option<crate::health::HealthEndpointConfig>,
status_config: Option<crate::status::StatusConfig>,
}
/// Configuration for RustAPI's built-in production baseline preset.
///
/// This preset bundles together the most common foundation pieces for a
/// production HTTP service:
/// - request IDs on every response
/// - structured tracing spans with service metadata
/// - standard `/health`, `/ready`, and `/live` probes
#[derive(Debug, Clone)]
pub struct ProductionDefaultsConfig {
service_name: String,
version: Option<String>,
tracing_level: tracing::Level,
health_endpoint_config: Option<crate::health::HealthEndpointConfig>,
enable_request_id: bool,
enable_tracing: bool,
enable_health_endpoints: bool,
}
impl ProductionDefaultsConfig {
/// Create a new production baseline configuration.
pub fn new(service_name: impl Into<String>) -> Self {
Self {
service_name: service_name.into(),
version: None,
tracing_level: tracing::Level::INFO,
health_endpoint_config: None,
enable_request_id: true,
enable_tracing: true,
enable_health_endpoints: true,
}
}
/// Annotate tracing spans and default health payloads with an application version.
pub fn version(mut self, version: impl Into<String>) -> Self {
self.version = Some(version.into());
self
}
/// Set the tracing log level used by the preset tracing layer.
pub fn tracing_level(mut self, level: tracing::Level) -> Self {
self.tracing_level = level;
self
}
/// Override the default health endpoint paths.
pub fn health_endpoint_config(mut self, config: crate::health::HealthEndpointConfig) -> Self {
self.health_endpoint_config = Some(config);
self
}
/// Enable or disable request ID propagation.
pub fn request_id(mut self, enabled: bool) -> Self {
self.enable_request_id = enabled;
self
}
/// Enable or disable structured tracing middleware.
pub fn tracing(mut self, enabled: bool) -> Self {
self.enable_tracing = enabled;
self
}
/// Enable or disable built-in health endpoints.
pub fn health_endpoints(mut self, enabled: bool) -> Self {
self.enable_health_endpoints = enabled;
self
}
}
impl RustApi {
/// Create a new RustAPI application
pub fn new() -> Self {
// Initialize tracing if not already done
let _ = tracing_subscriber::registry()
.with(
EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("info,rustapi=debug")),
)
.with(tracing_subscriber::fmt::layer())
.try_init();
Self {
router: Router::new(),
openapi_spec: rustapi_openapi::OpenApiSpec::new("RustAPI Application", "1.0.0")
.register::<rustapi_openapi::ErrorSchema>()
.register::<rustapi_openapi::ErrorBodySchema>()
.register::<rustapi_openapi::ValidationErrorSchema>()
.register::<rustapi_openapi::ValidationErrorBodySchema>()
.register::<rustapi_openapi::FieldErrorSchema>(),
layers: LayerStack::new(),
body_limit: Some(DEFAULT_BODY_LIMIT), // Default 1MB limit
interceptors: InterceptorChain::new(),
lifecycle_hooks: LifecycleHooks::new(),
hot_reload: false,
#[cfg(feature = "http3")]
http3_config: None,
health_check: None,
health_endpoint_config: None,
status_config: None,
}
}
/// Create a zero-config RustAPI application.
///
/// All routes decorated with `#[rustapi::get]`, `#[rustapi::post]`, etc.
/// are automatically registered. Swagger UI is enabled at `/docs` by default.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// #[rustapi::get("/users")]
/// async fn list_users() -> Json<Vec<User>> {
/// Json(vec![])
/// }
///
/// #[rustapi::main]
/// async fn main() -> Result<()> {
/// // Zero config - routes are auto-registered!
/// RustApi::auto()
/// .run("0.0.0.0:8080")
/// .await
/// }
/// ```
#[cfg(feature = "swagger-ui")]
pub fn auto() -> Self {
// Build app with grouped auto-routes and auto-schemas, then enable docs.
Self::new().mount_auto_routes_grouped().docs("/docs")
}
/// Create a zero-config RustAPI application (without swagger-ui feature).
///
/// All routes decorated with `#[rustapi::get]`, `#[rustapi::post]`, etc.
/// are automatically registered.
#[cfg(not(feature = "swagger-ui"))]
pub fn auto() -> Self {
Self::new().mount_auto_routes_grouped()
}
/// Create a configurable RustAPI application with auto-routes.
///
/// Provides builder methods for customization while still
/// auto-registering all decorated routes.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// RustApi::config()
/// .docs_path("/api-docs")
/// .body_limit(5 * 1024 * 1024) // 5MB
/// .openapi_info("My API", "2.0.0", Some("API Description"))
/// .run("0.0.0.0:8080")
/// .await?;
/// ```
pub fn config() -> RustApiConfig {
RustApiConfig::new()
}
/// Set the global body size limit for request bodies
///
/// This protects against denial-of-service attacks via large payloads.
/// The default limit is 1MB (1024 * 1024 bytes).
///
/// # Arguments
///
/// * `limit` - Maximum body size in bytes
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// RustApi::new()
/// .body_limit(5 * 1024 * 1024) // 5MB limit
/// .route("/upload", post(upload_handler))
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn body_limit(mut self, limit: usize) -> Self {
self.body_limit = Some(limit);
self
}
/// Disable the body size limit
///
/// Warning: This removes protection against large payload attacks.
/// Only use this if you have other mechanisms to limit request sizes.
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .no_body_limit() // Disable body size limit
/// .route("/upload", post(upload_handler))
/// ```
pub fn no_body_limit(mut self) -> Self {
self.body_limit = None;
self
}
/// Add a middleware layer to the application
///
/// Layers are executed in the order they are added (outermost first).
/// The first layer added will be the first to process the request and
/// the last to process the response.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
/// use rustapi_core::middleware::{RequestIdLayer, TracingLayer};
///
/// RustApi::new()
/// .layer(RequestIdLayer::new()) // First to process request
/// .layer(TracingLayer::new()) // Second to process request
/// .route("/", get(handler))
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn layer<L>(mut self, layer: L) -> Self
where
L: MiddlewareLayer,
{
self.layers.push(Box::new(layer));
self
}
/// Add a request interceptor to the application
///
/// Request interceptors are executed in registration order before the route handler.
/// Each interceptor can modify the request before passing it to the next interceptor
/// or handler.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::{RustApi, interceptor::RequestInterceptor, Request};
///
/// #[derive(Clone)]
/// struct AddRequestId;
///
/// impl RequestInterceptor for AddRequestId {
/// fn intercept(&self, mut req: Request) -> Request {
/// req.extensions_mut().insert(uuid::Uuid::new_v4());
/// req
/// }
///
/// fn clone_box(&self) -> Box<dyn RequestInterceptor> {
/// Box::new(self.clone())
/// }
/// }
///
/// RustApi::new()
/// .request_interceptor(AddRequestId)
/// .route("/", get(handler))
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn request_interceptor<I>(mut self, interceptor: I) -> Self
where
I: RequestInterceptor,
{
self.interceptors.add_request_interceptor(interceptor);
self
}
/// Add a response interceptor to the application
///
/// Response interceptors are executed in reverse registration order after the route
/// handler completes. Each interceptor can modify the response before passing it
/// to the previous interceptor or client.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::{RustApi, interceptor::ResponseInterceptor, Response};
///
/// #[derive(Clone)]
/// struct AddServerHeader;
///
/// impl ResponseInterceptor for AddServerHeader {
/// fn intercept(&self, mut res: Response) -> Response {
/// res.headers_mut().insert("X-Server", "RustAPI".parse().unwrap());
/// res
/// }
///
/// fn clone_box(&self) -> Box<dyn ResponseInterceptor> {
/// Box::new(self.clone())
/// }
/// }
///
/// RustApi::new()
/// .response_interceptor(AddServerHeader)
/// .route("/", get(handler))
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn response_interceptor<I>(mut self, interceptor: I) -> Self
where
I: ResponseInterceptor,
{
self.interceptors.add_response_interceptor(interceptor);
self
}
/// Add application state
///
/// State is shared across all handlers and can be extracted using `State<T>`.
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Clone)]
/// struct AppState {
/// db: DbPool,
/// }
///
/// RustApi::new()
/// .state(AppState::new())
/// ```
pub fn state<S>(self, _state: S) -> Self
where
S: Clone + Send + Sync + 'static,
{
// Store state in the router's shared Extensions so `State<T>` extractor can retrieve it.
let state = _state;
let mut app = self;
app.router = app.router.state(state);
app
}
/// Register an `on_start` lifecycle hook
///
/// The callback runs **after** route registration and **before** the server
/// begins accepting connections. Multiple hooks execute in registration order.
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .on_start(|| async {
/// println!("🚀 Server starting...");
/// // e.g. run DB migrations, warm caches
/// })
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn on_start<F, Fut>(mut self, hook: F) -> Self
where
F: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
self.lifecycle_hooks
.on_start
.push(Box::new(move || Box::pin(hook())));
self
}
/// Register an `on_shutdown` lifecycle hook
///
/// The callback runs **after** the shutdown signal is received and the server
/// stops accepting new connections. Multiple hooks execute in registration order.
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .on_shutdown(|| async {
/// println!("👋 Server shutting down...");
/// // e.g. flush logs, close DB connections
/// })
/// .run_with_shutdown("127.0.0.1:8080", ctrl_c())
/// .await
/// ```
pub fn on_shutdown<F, Fut>(mut self, hook: F) -> Self
where
F: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
self.lifecycle_hooks
.on_shutdown
.push(Box::new(move || Box::pin(hook())));
self
}
/// Enable hot-reload mode for development
///
/// When enabled:
/// - A dev-mode banner is printed at startup
/// - The `RUSTAPI_HOT_RELOAD` env var is set so that `cargo rustapi watch`
/// can detect the server is reload-aware
/// - If the server is **not** already running under the CLI watcher,
/// a helpful hint is printed suggesting `cargo rustapi run --watch`
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .hot_reload(true)
/// .route("/", get(hello))
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn hot_reload(mut self, enabled: bool) -> Self {
self.hot_reload = enabled;
self
}
/// Register an OpenAPI schema
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Schema)]
/// struct User { ... }
///
/// RustApi::new()
/// .register_schema::<User>()
/// ```
pub fn register_schema<T: rustapi_openapi::schema::RustApiSchema>(mut self) -> Self {
self.openapi_spec = self.openapi_spec.register::<T>();
self
}
/// Configure OpenAPI info (title, version, description)
pub fn openapi_info(mut self, title: &str, version: &str, description: Option<&str>) -> Self {
// NOTE: Do not reset the spec here; doing so would drop collected paths/schemas.
// This is especially important for `RustApi::auto()` and `RustApi::config()`.
self.openapi_spec.info.title = title.to_string();
self.openapi_spec.info.version = version.to_string();
self.openapi_spec.info.description = description.map(|d| d.to_string());
self
}
/// Get the current OpenAPI spec (for advanced usage/testing).
pub fn openapi_spec(&self) -> &rustapi_openapi::OpenApiSpec {
&self.openapi_spec
}
fn mount_auto_routes_grouped(mut self) -> Self {
let routes = crate::auto_route::collect_auto_routes();
// Use BTreeMap for deterministic route registration order
let mut by_path: BTreeMap<String, MethodRouter> = BTreeMap::new();
for route in routes {
let crate::handler::Route {
path: route_path,
method,
handler,
operation,
component_registrar,
..
} = route;
let method_enum = match method {
"GET" => http::Method::GET,
"POST" => http::Method::POST,
"PUT" => http::Method::PUT,
"DELETE" => http::Method::DELETE,
"PATCH" => http::Method::PATCH,
_ => http::Method::GET,
};
let path = if route_path.starts_with('/') {
route_path.to_string()
} else {
format!("/{}", route_path)
};
let entry = by_path.entry(path).or_default();
entry.insert_boxed_with_operation(method_enum, handler, operation, component_registrar);
}
#[cfg(feature = "tracing")]
let route_count: usize = by_path.values().map(|mr| mr.allowed_methods().len()).sum();
#[cfg(feature = "tracing")]
let path_count = by_path.len();
for (path, method_router) in by_path {
self = self.route(&path, method_router);
}
crate::trace_info!(
paths = path_count,
routes = route_count,
"Auto-registered routes"
);
// Apply any auto-registered schemas.
crate::auto_schema::apply_auto_schemas(&mut self.openapi_spec);
self
}
/// Add a route
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .route("/", get(index))
/// .route("/users", get(list_users).post(create_user))
/// .route("/users/{id}", get(get_user).delete(delete_user))
/// ```
pub fn route(mut self, path: &str, method_router: MethodRouter) -> Self {
for register_components in &method_router.component_registrars {
register_components(&mut self.openapi_spec);
}
// Register operations in OpenAPI spec
for (method, op) in &method_router.operations {
let mut op = op.clone();
add_path_params_to_operation(path, &mut op, &BTreeMap::new());
self.openapi_spec = self.openapi_spec.path(path, method.as_str(), op);
}
self.router = self.router.route(path, method_router);
self
}
/// Add a typed route
pub fn typed<P: crate::typed_path::TypedPath>(self, method_router: MethodRouter) -> Self {
self.route(P::PATH, method_router)
}
/// Mount a handler (convenience method)
///
/// Alias for `.route(path, method_router)` for a single handler.
#[deprecated(note = "Use route() directly or mount_route() for macro-based routing")]
pub fn mount(self, path: &str, method_router: MethodRouter) -> Self {
self.route(path, method_router)
}
/// Mount a route created with `#[rustapi::get]`, `#[rustapi::post]`, etc.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// #[rustapi::get("/users")]
/// async fn list_users() -> Json<Vec<User>> {
/// Json(vec![])
/// }
///
/// RustApi::new()
/// .mount_route(route!(list_users))
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn mount_route(mut self, route: crate::handler::Route) -> Self {
let method_enum = match route.method {
"GET" => http::Method::GET,
"POST" => http::Method::POST,
"PUT" => http::Method::PUT,
"DELETE" => http::Method::DELETE,
"PATCH" => http::Method::PATCH,
_ => http::Method::GET,
};
(route.component_registrar)(&mut self.openapi_spec);
// Register operation in OpenAPI spec
let mut op = route.operation;
add_path_params_to_operation(route.path, &mut op, &route.param_schemas);
self.openapi_spec = self.openapi_spec.path(route.path, route.method, op);
self.route_with_method(route.path, method_enum, route.handler)
}
/// Helper to mount a single method handler
fn route_with_method(
self,
path: &str,
method: http::Method,
handler: crate::handler::BoxedHandler,
) -> Self {
use crate::router::MethodRouter;
// use http::Method; // Removed
// This is simplified. In a real implementation we'd merge with existing router at this path
// For now we assume one handler per path or we simply allow overwriting for this MVP step
// (matchit router doesn't allow easy merging/updating existing entries without rebuilding)
//
// TOOD: Enhance Router to support method merging
let path = if !path.starts_with('/') {
format!("/{}", path)
} else {
path.to_string()
};
// Check if we already have this path?
// For MVP, valid assumption: user calls .route() or .mount() once per path-method-combo
// But we need to handle multiple methods on same path.
// Our Router wrapper currently just inserts.
// Since we can't easily query matchit, we'll just insert.
// Limitations: strictly sequential mounting for now.
let mut handlers = std::collections::HashMap::new();
handlers.insert(method, handler);
let method_router = MethodRouter::from_boxed(handlers);
self.route(&path, method_router)
}
/// Nest a router under a prefix
///
/// All routes from the nested router will be registered with the prefix
/// prepended to their paths. OpenAPI operations from the nested router
/// are also propagated to the parent's OpenAPI spec with prefixed paths.
///
/// # Example
///
/// ```rust,ignore
/// let api_v1 = Router::new()
/// .route("/users", get(list_users));
///
/// RustApi::new()
/// .nest("/api/v1", api_v1)
/// ```
pub fn nest(mut self, prefix: &str, router: Router) -> Self {
// Normalize the prefix for OpenAPI paths
let normalized_prefix = normalize_prefix_for_openapi(prefix);
// Propagate OpenAPI operations from nested router with prefixed paths
// We need to do this before calling router.nest() because it consumes the router
for (matchit_path, method_router) in router.method_routers() {
for register_components in &method_router.component_registrars {
register_components(&mut self.openapi_spec);
}
// Get the display path from registered_routes (has {param} format)
let display_path = router
.registered_routes()
.get(matchit_path)
.map(|info| info.path.clone())
.unwrap_or_else(|| matchit_path.clone());
// Build the prefixed display path for OpenAPI
let prefixed_path = if display_path == "/" {
normalized_prefix.clone()
} else {
format!("{}{}", normalized_prefix, display_path)
};
// Register each operation in the OpenAPI spec
for (method, op) in &method_router.operations {
let mut op = op.clone();
add_path_params_to_operation(&prefixed_path, &mut op, &BTreeMap::new());
self.openapi_spec = self.openapi_spec.path(&prefixed_path, method.as_str(), op);
}
}
// Delegate to Router::nest for actual route registration
self.router = self.router.nest(prefix, router);
self
}
/// Serve static files from a directory
///
/// Maps a URL path prefix to a filesystem directory. Requests to paths under
/// the prefix will serve files from the corresponding location in the directory.
///
/// # Arguments
///
/// * `prefix` - URL path prefix (e.g., "/static", "/assets")
/// * `root` - Filesystem directory path
///
/// # Features
///
/// - Automatic MIME type detection
/// - ETag and Last-Modified headers for caching
/// - Index file serving for directories
/// - Path traversal prevention
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// RustApi::new()
/// .serve_static("/assets", "./public")
/// .serve_static("/uploads", "./uploads")
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn serve_static(self, prefix: &str, root: impl Into<std::path::PathBuf>) -> Self {
self.serve_static_with_config(crate::static_files::StaticFileConfig::new(root, prefix))
}
/// Serve static files with custom configuration
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::static_files::StaticFileConfig;
///
/// let config = StaticFileConfig::new("./public", "/assets")
/// .max_age(86400) // Cache for 1 day
/// .fallback("index.html"); // SPA fallback
///
/// RustApi::new()
/// .serve_static_with_config(config)
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub fn serve_static_with_config(self, config: crate::static_files::StaticFileConfig) -> Self {
use crate::router::MethodRouter;
use std::collections::HashMap;
let prefix = config.prefix.clone();
let catch_all_path = format!("{}/*path", prefix.trim_end_matches('/'));
// Create the static file handler
let handler: crate::handler::BoxedHandler =
std::sync::Arc::new(move |req: crate::Request| {
let config = config.clone();
let path = req.uri().path().to_string();
Box::pin(async move {
let relative_path = path.strip_prefix(&config.prefix).unwrap_or(&path);
match crate::static_files::StaticFile::serve(relative_path, &config).await {
Ok(response) => response,
Err(err) => err.into_response(),
}
})
as std::pin::Pin<Box<dyn std::future::Future<Output = crate::Response> + Send>>
});
let mut handlers = HashMap::new();
handlers.insert(http::Method::GET, handler);
let method_router = MethodRouter::from_boxed(handlers);
self.route(&catch_all_path, method_router)
}
/// Enable response compression
///
/// Adds gzip/deflate compression for response bodies. The compression
/// is based on the client's Accept-Encoding header.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
///
/// RustApi::new()
/// .compression()
/// .route("/", get(handler))
/// .run("127.0.0.1:8080")
/// .await
/// ```
#[cfg(feature = "compression")]
pub fn compression(self) -> Self {
self.layer(crate::middleware::CompressionLayer::new())
}
/// Enable response compression with custom configuration
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::middleware::CompressionConfig;
///
/// RustApi::new()
/// .compression_with_config(
/// CompressionConfig::new()
/// .min_size(512)
/// .level(9)
/// )
/// .route("/", get(handler))
/// ```
#[cfg(feature = "compression")]
pub fn compression_with_config(self, config: crate::middleware::CompressionConfig) -> Self {
self.layer(crate::middleware::CompressionLayer::with_config(config))
}
/// Enable Swagger UI documentation
///
/// This adds two endpoints:
/// - `{path}` - Swagger UI interface
/// - `{path}/openapi.json` - OpenAPI JSON specification
///
/// **Important:** Call `.docs()` AFTER registering all routes. The OpenAPI
/// specification is captured at the time `.docs()` is called, so routes
/// added afterwards will not appear in the documentation.
///
/// # Example
///
/// ```text
/// RustApi::new()
/// .route("/users", get(list_users)) // Add routes first
/// .route("/posts", get(list_posts)) // Add more routes
/// .docs("/docs") // Then enable docs - captures all routes above
/// .run("127.0.0.1:8080")
/// .await
/// ```
///
/// For `RustApi::auto()`, routes are collected before `.docs()` is called,
/// so this is handled automatically.
#[cfg(feature = "swagger-ui")]
pub fn docs(self, path: &str) -> Self {
let title = self.openapi_spec.info.title.clone();
let version = self.openapi_spec.info.version.clone();
let description = self.openapi_spec.info.description.clone();
self.docs_with_info(path, &title, &version, description.as_deref())
}
/// Enable Swagger UI documentation with custom API info
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .docs_with_info("/docs", "My API", "2.0.0", Some("API for managing users"))
/// ```
#[cfg(feature = "swagger-ui")]
pub fn docs_with_info(
mut self,
path: &str,
title: &str,
version: &str,
description: Option<&str>,
) -> Self {
use crate::router::get;
// Update spec info
self.openapi_spec.info.title = title.to_string();
self.openapi_spec.info.version = version.to_string();
if let Some(desc) = description {
self.openapi_spec.info.description = Some(desc.to_string());
}
let path = path.trim_end_matches('/');
let openapi_path = format!("{}/openapi.json", path);
// Clone values for closures
let spec_value = self.openapi_spec.to_json();
let spec_json = serde_json::to_string_pretty(&spec_value).unwrap_or_else(|e| {
// Safe fallback if JSON serialization fails (though unlikely for Value)
tracing::error!("Failed to serialize OpenAPI spec: {}", e);
"{}".to_string()
});
let openapi_url = openapi_path.clone();
// Add OpenAPI JSON endpoint
let spec_handler = move || {
let json = spec_json.clone();
async move {
http::Response::builder()
.status(http::StatusCode::OK)
.header(http::header::CONTENT_TYPE, "application/json")
.body(crate::response::Body::from(json))
.unwrap_or_else(|e| {
tracing::error!("Failed to build response: {}", e);
http::Response::builder()
.status(http::StatusCode::INTERNAL_SERVER_ERROR)
.body(crate::response::Body::from("Internal Server Error"))
.unwrap()
})
}
};
// Add Swagger UI endpoint
let docs_handler = move || {
let url = openapi_url.clone();
async move {
let response = rustapi_openapi::swagger_ui_html(&url);
response.map(crate::response::Body::Full)
}
};
self.route(&openapi_path, get(spec_handler))
.route(path, get(docs_handler))
}
/// Enable Swagger UI documentation with Basic Auth protection
///
/// When username and password are provided, the docs endpoint will require
/// Basic Authentication. This is useful for protecting API documentation
/// in production environments.
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .route("/users", get(list_users))
/// .docs_with_auth("/docs", "admin", "secret123")
/// .run("127.0.0.1:8080")
/// .await
/// ```
#[cfg(feature = "swagger-ui")]
pub fn docs_with_auth(self, path: &str, username: &str, password: &str) -> Self {
let title = self.openapi_spec.info.title.clone();
let version = self.openapi_spec.info.version.clone();
let description = self.openapi_spec.info.description.clone();
self.docs_with_auth_and_info(
path,
username,
password,
&title,
&version,
description.as_deref(),
)
}
/// Enable Swagger UI documentation with Basic Auth and custom API info
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .docs_with_auth_and_info(
/// "/docs",
/// "admin",
/// "secret",
/// "My API",
/// "2.0.0",
/// Some("Protected API documentation")
/// )
/// ```
#[cfg(feature = "swagger-ui")]
pub fn docs_with_auth_and_info(
mut self,
path: &str,
username: &str,
password: &str,
title: &str,
version: &str,
description: Option<&str>,
) -> Self {
use crate::router::MethodRouter;
use base64::{engine::general_purpose::STANDARD, Engine};
use std::collections::HashMap;
// Update spec info
self.openapi_spec.info.title = title.to_string();
self.openapi_spec.info.version = version.to_string();
if let Some(desc) = description {
self.openapi_spec.info.description = Some(desc.to_string());
}
let path = path.trim_end_matches('/');
let openapi_path = format!("{}/openapi.json", path);
// Create expected auth header value
let credentials = format!("{}:{}", username, password);
let encoded = STANDARD.encode(credentials.as_bytes());
let expected_auth = format!("Basic {}", encoded);
// Clone values for closures
let spec_value = self.openapi_spec.to_json();
let spec_json = serde_json::to_string_pretty(&spec_value).unwrap_or_else(|e| {
tracing::error!("Failed to serialize OpenAPI spec: {}", e);
"{}".to_string()
});
let openapi_url = openapi_path.clone();
let expected_auth_spec = expected_auth.clone();
let expected_auth_docs = expected_auth;
// Create spec handler with auth check
let spec_handler: crate::handler::BoxedHandler =
std::sync::Arc::new(move |req: crate::Request| {
let json = spec_json.clone();
let expected = expected_auth_spec.clone();
Box::pin(async move {
if !check_basic_auth(&req, &expected) {
return unauthorized_response();
}
http::Response::builder()
.status(http::StatusCode::OK)
.header(http::header::CONTENT_TYPE, "application/json")
.body(crate::response::Body::from(json))
.unwrap_or_else(|e| {
tracing::error!("Failed to build response: {}", e);
http::Response::builder()
.status(http::StatusCode::INTERNAL_SERVER_ERROR)
.body(crate::response::Body::from("Internal Server Error"))
.unwrap()
})
})
as std::pin::Pin<Box<dyn std::future::Future<Output = crate::Response> + Send>>
});
// Create docs handler with auth check
let docs_handler: crate::handler::BoxedHandler =
std::sync::Arc::new(move |req: crate::Request| {
let url = openapi_url.clone();
let expected = expected_auth_docs.clone();
Box::pin(async move {
if !check_basic_auth(&req, &expected) {
return unauthorized_response();
}
let response = rustapi_openapi::swagger_ui_html(&url);
response.map(crate::response::Body::Full)
})
as std::pin::Pin<Box<dyn std::future::Future<Output = crate::Response> + Send>>
});
// Create method routers with boxed handlers
let mut spec_handlers = HashMap::new();
spec_handlers.insert(http::Method::GET, spec_handler);
let spec_router = MethodRouter::from_boxed(spec_handlers);
let mut docs_handlers = HashMap::new();
docs_handlers.insert(http::Method::GET, docs_handler);
let docs_router = MethodRouter::from_boxed(docs_handlers);
self.route(&openapi_path, spec_router)
.route(path, docs_router)
}
/// Enable automatic status page with default configuration
pub fn status_page(self) -> Self {
self.status_page_with_config(crate::status::StatusConfig::default())
}
/// Enable automatic status page with custom configuration
pub fn status_page_with_config(mut self, config: crate::status::StatusConfig) -> Self {
self.status_config = Some(config);
self
}
/// Enable built-in `/health`, `/ready`, and `/live` endpoints with default paths.
///
/// The default health check includes a lightweight `self` probe so the
/// endpoints are immediately useful even before dependency checks are added.
pub fn health_endpoints(mut self) -> Self {
self.health_endpoint_config = Some(crate::health::HealthEndpointConfig::default());
if self.health_check.is_none() {
self.health_check = Some(crate::health::HealthCheckBuilder::default().build());
}
self
}
/// Enable built-in health endpoints with custom paths.
pub fn health_endpoints_with_config(
mut self,
config: crate::health::HealthEndpointConfig,
) -> Self {
self.health_endpoint_config = Some(config);
if self.health_check.is_none() {
self.health_check = Some(crate::health::HealthCheckBuilder::default().build());
}
self
}
/// Register a custom health check and enable built-in health endpoints.
///
/// The configured check is used by `/health` and `/ready`, while `/live`
/// remains a lightweight process-level probe.
pub fn with_health_check(mut self, health_check: crate::health::HealthCheck) -> Self {
self.health_check = Some(health_check);
if self.health_endpoint_config.is_none() {
self.health_endpoint_config = Some(crate::health::HealthEndpointConfig::default());
}
self
}
/// Apply a one-call production baseline preset.
///
/// This enables:
/// - `RequestIdLayer`
/// - `TracingLayer` with `service` and `environment` fields
/// - built-in `/health`, `/ready`, and `/live` probes
pub fn production_defaults(self, service_name: impl Into<String>) -> Self {
self.production_defaults_with_config(ProductionDefaultsConfig::new(service_name))
}
/// Apply the production baseline preset with custom configuration.
pub fn production_defaults_with_config(mut self, config: ProductionDefaultsConfig) -> Self {
if config.enable_request_id {
self = self.layer(crate::middleware::RequestIdLayer::new());
}
if config.enable_tracing {
let mut tracing_layer =
crate::middleware::TracingLayer::with_level(config.tracing_level)
.with_field("service", config.service_name.clone())
.with_field("environment", crate::error::get_environment().to_string());
if let Some(version) = &config.version {
tracing_layer = tracing_layer.with_field("version", version.clone());
}
self = self.layer(tracing_layer);
}
if config.enable_health_endpoints {
if self.health_check.is_none() {
let mut builder = crate::health::HealthCheckBuilder::default();
if let Some(version) = &config.version {
builder = builder.version(version.clone());
}
self.health_check = Some(builder.build());
}
if self.health_endpoint_config.is_none() {
self.health_endpoint_config =
Some(config.health_endpoint_config.unwrap_or_default());
}
}
self
}
/// Print a hot-reload dev banner if `.hot_reload(true)` is set
fn print_hot_reload_banner(&self, addr: &str) {
if !self.hot_reload {
return;
}
// Set the env var so the CLI watcher can detect it
std::env::set_var("RUSTAPI_HOT_RELOAD", "1");
let is_under_watcher = std::env::var("RUSTAPI_HOT_RELOAD")
.map(|v| v == "1")
.unwrap_or(false);
tracing::info!("🔄 Hot-reload mode enabled");
if is_under_watcher {
tracing::info!(" File watcher active — changes will trigger rebuild + restart");
} else {
tracing::info!(" Tip: Run with `cargo rustapi run --watch` for automatic hot-reload");
}
tracing::info!(" Listening on http://{addr}");
}
// Helper to apply status page logic (monitor, layer, route)
fn apply_health_endpoints(&mut self) {
if let Some(config) = &self.health_endpoint_config {
use crate::router::get;
let health_check = self
.health_check
.clone()
.unwrap_or_else(|| crate::health::HealthCheckBuilder::default().build());
let health_path = config.health_path.clone();
let readiness_path = config.readiness_path.clone();
let liveness_path = config.liveness_path.clone();
let health_handler = {
let health_check = health_check.clone();
move || {
let health_check = health_check.clone();
async move { crate::health::health_response(health_check).await }
}
};
let readiness_handler = {
let health_check = health_check.clone();
move || {
let health_check = health_check.clone();
async move { crate::health::readiness_response(health_check).await }
}
};
let liveness_handler = || async { crate::health::liveness_response().await };
let router = std::mem::take(&mut self.router);
self.router = router
.route(&health_path, get(health_handler))
.route(&readiness_path, get(readiness_handler))
.route(&liveness_path, get(liveness_handler));
}
}
fn apply_status_page(&mut self) {
if let Some(config) = &self.status_config {
let monitor = std::sync::Arc::new(crate::status::StatusMonitor::new());
// 1. Add middleware layer
self.layers
.push(Box::new(crate::status::StatusLayer::new(monitor.clone())));
// 2. Add status route
use crate::router::MethodRouter;
use std::collections::HashMap;
let monitor = monitor.clone();
let config = config.clone();
let path = config.path.clone(); // Clone path before moving config
let handler: crate::handler::BoxedHandler = std::sync::Arc::new(move |_| {
let monitor = monitor.clone();
let config = config.clone();
Box::pin(async move {
crate::status::status_handler(monitor, config)
.await
.into_response()
})
});
let mut handlers = HashMap::new();
handlers.insert(http::Method::GET, handler);
let method_router = MethodRouter::from_boxed(handlers);
// We need to take the router out to call route() which consumes it
let router = std::mem::take(&mut self.router);
self.router = router.route(&path, method_router);
}
}
/// Run the server
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .route("/", get(hello))
/// .run("127.0.0.1:8080")
/// .await
/// ```
pub async fn run(mut self, addr: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Hot-reload mode banner
self.print_hot_reload_banner(addr);
// Apply health endpoints if configured
self.apply_health_endpoints();
// Apply status page if configured
self.apply_status_page();
// Apply body limit layer if configured (should be first in the chain)
if let Some(limit) = self.body_limit {
// Prepend body limit layer so it's the first to process requests
self.layers.prepend(Box::new(BodyLimitLayer::new(limit)));
}
// Run on_start lifecycle hooks before accepting connections
for hook in self.lifecycle_hooks.on_start {
hook().await;
}
let server = Server::new(self.router, self.layers, self.interceptors);
server.run(addr).await
}
/// Run the server with graceful shutdown signal
pub async fn run_with_shutdown<F>(
mut self,
addr: impl AsRef<str>,
signal: F,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
where
F: std::future::Future<Output = ()> + Send + 'static,
{
// Hot-reload mode banner
self.print_hot_reload_banner(addr.as_ref());
// Apply health endpoints if configured
self.apply_health_endpoints();
// Apply status page if configured
self.apply_status_page();
if let Some(limit) = self.body_limit {
self.layers.prepend(Box::new(BodyLimitLayer::new(limit)));
}
// Run on_start lifecycle hooks before accepting connections
for hook in self.lifecycle_hooks.on_start {
hook().await;
}
// Wrap the shutdown signal to run on_shutdown hooks after signal fires
let shutdown_hooks = self.lifecycle_hooks.on_shutdown;
let wrapped_signal = async move {
signal.await;
// Run on_shutdown hooks after the shutdown signal fires
for hook in shutdown_hooks {
hook().await;
}
};
let server = Server::new(self.router, self.layers, self.interceptors);
server
.run_with_shutdown(addr.as_ref(), wrapped_signal)
.await
}
/// Get the inner router (for testing or advanced usage)
pub fn into_router(self) -> Router {
self.router
}
/// Get the layer stack (for testing)
pub fn layers(&self) -> &LayerStack {
&self.layers
}
/// Get the interceptor chain (for testing)
pub fn interceptors(&self) -> &InterceptorChain {
&self.interceptors
}
/// Enable HTTP/3 support with TLS certificates
///
/// HTTP/3 requires TLS certificates. For development, you can use
/// self-signed certificates with `run_http3_dev`.
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .route("/", get(hello))
/// .run_http3("0.0.0.0:443", "cert.pem", "key.pem")
/// .await
/// ```
#[cfg(feature = "http3")]
pub async fn run_http3(
mut self,
config: crate::http3::Http3Config,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
use std::sync::Arc;
// Apply health endpoints if configured
self.apply_health_endpoints();
// Apply status page if configured
self.apply_status_page();
// Apply body limit layer if configured
if let Some(limit) = self.body_limit {
self.layers.prepend(Box::new(BodyLimitLayer::new(limit)));
}
let server = crate::http3::Http3Server::new(
&config,
Arc::new(self.router),
Arc::new(self.layers),
Arc::new(self.interceptors),
)
.await?;
server.run().await
}
/// Run HTTP/3 server with self-signed certificate (development only)
///
/// This is useful for local development and testing.
/// **Do not use in production!**
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .route("/", get(hello))
/// .run_http3_dev("0.0.0.0:8443")
/// .await
/// ```
#[cfg(feature = "http3-dev")]
pub async fn run_http3_dev(
mut self,
addr: &str,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
use std::sync::Arc;
// Apply health endpoints if configured
self.apply_health_endpoints();
// Apply status page if configured
self.apply_status_page();
// Apply body limit layer if configured
if let Some(limit) = self.body_limit {
self.layers.prepend(Box::new(BodyLimitLayer::new(limit)));
}
let server = crate::http3::Http3Server::new_with_self_signed(
addr,
Arc::new(self.router),
Arc::new(self.layers),
Arc::new(self.interceptors),
)
.await?;
server.run().await
}
/// Configure HTTP/3 support for `run_http3` and `run_dual_stack`.
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .with_http3("cert.pem", "key.pem")
/// .run_dual_stack("127.0.0.1:8080")
/// .await
/// ```
#[cfg(feature = "http3")]
pub fn with_http3(mut self, cert_path: impl Into<String>, key_path: impl Into<String>) -> Self {
self.http3_config = Some(crate::http3::Http3Config::new(cert_path, key_path));
self
}
/// Run both HTTP/1.1 (TCP) and HTTP/3 (QUIC/UDP) simultaneously.
///
/// The HTTP/3 listener is bound to the same host and port as `http_addr`
/// so clients can upgrade to either protocol on one endpoint.
///
/// # Example
///
/// ```rust,ignore
/// RustApi::new()
/// .route("/", get(hello))
/// .with_http3("cert.pem", "key.pem")
/// .run_dual_stack("0.0.0.0:8080")
/// .await
/// ```
#[cfg(feature = "http3")]
pub async fn run_dual_stack(
mut self,
http_addr: &str,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
use std::sync::Arc;
let mut config = self
.http3_config
.take()
.ok_or("HTTP/3 config not set. Use .with_http3(...)")?;
let http_socket: std::net::SocketAddr = http_addr.parse()?;
config.bind_addr = if http_socket.ip().is_ipv6() {
format!("[{}]", http_socket.ip())
} else {
http_socket.ip().to_string()
};
config.port = http_socket.port();
let http_addr = http_socket.to_string();
// Apply health endpoints if configured
self.apply_health_endpoints();
// Apply status page if configured
self.apply_status_page();
// Apply body limit layer if configured
if let Some(limit) = self.body_limit {
self.layers.prepend(Box::new(BodyLimitLayer::new(limit)));
}
let router = Arc::new(self.router);
let layers = Arc::new(self.layers);
let interceptors = Arc::new(self.interceptors);
let http1_server =
Server::from_shared(router.clone(), layers.clone(), interceptors.clone());
let http3_server =
crate::http3::Http3Server::new(&config, router, layers, interceptors).await?;
tracing::info!(
http1_addr = %http_addr,
http3_addr = %config.socket_addr(),
"Starting dual-stack HTTP/1.1 + HTTP/3 servers"
);
tokio::try_join!(
http1_server.run_with_shutdown(&http_addr, std::future::pending::<()>()),
http3_server.run_with_shutdown(std::future::pending::<()>()),
)?;
Ok(())
}
}
fn add_path_params_to_operation(
path: &str,
op: &mut rustapi_openapi::Operation,
param_schemas: &BTreeMap<String, String>,
) {
let mut params: Vec<String> = Vec::new();
let mut in_brace = false;
let mut current = String::new();
for ch in path.chars() {
match ch {
'{' => {
in_brace = true;
current.clear();
}
'}' => {
if in_brace {
in_brace = false;
if !current.is_empty() {
params.push(current.clone());
}
}
}
_ => {
if in_brace {
current.push(ch);
}
}
}
}
if params.is_empty() {
return;
}
let op_params = &mut op.parameters;
for name in params {
let already = op_params
.iter()
.any(|p| p.location == "path" && p.name == name);
if already {
continue;
}
// Use custom schema if provided, otherwise infer from name
let schema = if let Some(schema_type) = param_schemas.get(&name) {
schema_type_to_openapi_schema(schema_type)
} else {
infer_path_param_schema(&name)
};
op_params.push(rustapi_openapi::Parameter {
name,
location: "path".to_string(),
required: true,
description: None,
deprecated: None,
schema: Some(schema),
});
}
}
/// Convert a schema type string to an OpenAPI schema reference
fn schema_type_to_openapi_schema(schema_type: &str) -> rustapi_openapi::SchemaRef {
match schema_type.to_lowercase().as_str() {
"uuid" => rustapi_openapi::SchemaRef::Inline(serde_json::json!({
"type": "string",
"format": "uuid"
})),
"integer" | "int" | "int64" | "i64" => {
rustapi_openapi::SchemaRef::Inline(serde_json::json!({
"type": "integer",
"format": "int64"
}))
}
"int32" | "i32" => rustapi_openapi::SchemaRef::Inline(serde_json::json!({
"type": "integer",
"format": "int32"
})),
"number" | "float" | "f64" | "f32" => {
rustapi_openapi::SchemaRef::Inline(serde_json::json!({
"type": "number"
}))
}
"boolean" | "bool" => rustapi_openapi::SchemaRef::Inline(serde_json::json!({
"type": "boolean"
})),
_ => rustapi_openapi::SchemaRef::Inline(serde_json::json!({
"type": "string"
})),
}
}
/// Infer the OpenAPI schema type for a path parameter based on naming conventions.
///
/// Common patterns:
/// - `*_id`, `*Id`, `id` → integer (but NOT *uuid)
/// - `*_count`, `*_num`, `page`, `limit`, `offset` → integer
/// - `*_uuid`, `uuid` → string with uuid format
/// - `year`, `month`, `day` → integer
/// - Everything else → string
fn infer_path_param_schema(name: &str) -> rustapi_openapi::SchemaRef {
let lower = name.to_lowercase();
// UUID patterns (check first to avoid false positive from "id" suffix)
let is_uuid = lower == "uuid" || lower.ends_with("_uuid") || lower.ends_with("uuid");
if is_uuid {
return rustapi_openapi::SchemaRef::Inline(serde_json::json!({
"type": "string",
"format": "uuid"
}));
}
// Integer patterns
// Integer patterns
let is_integer = lower == "page"
|| lower == "limit"
|| lower == "offset"
|| lower == "count"
|| lower.ends_with("_count")
|| lower.ends_with("_num")
|| lower == "year"
|| lower == "month"
|| lower == "day"
|| lower == "index"
|| lower == "position";
if is_integer {
rustapi_openapi::SchemaRef::Inline(serde_json::json!({
"type": "integer",
"format": "int64"
}))
} else {
rustapi_openapi::SchemaRef::Inline(serde_json::json!({ "type": "string" }))
}
}
/// Normalize a prefix for OpenAPI paths.
///
/// Ensures the prefix:
/// - Starts with exactly one leading slash
/// - Has no trailing slash (unless it's just "/")
/// - Has no double slashes
fn normalize_prefix_for_openapi(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
}
impl Default for RustApi {
fn default() -> Self {
Self::new()
}
}
/// Check Basic Auth header against expected credentials
#[cfg(feature = "swagger-ui")]
fn check_basic_auth(req: &crate::Request, expected: &str) -> bool {
req.headers()
.get(http::header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.map(|auth| auth == expected)
.unwrap_or(false)
}
/// Create 401 Unauthorized response with WWW-Authenticate header
#[cfg(feature = "swagger-ui")]
fn unauthorized_response() -> crate::Response {
http::Response::builder()
.status(http::StatusCode::UNAUTHORIZED)
.header(
http::header::WWW_AUTHENTICATE,
"Basic realm=\"API Documentation\"",
)
.header(http::header::CONTENT_TYPE, "text/plain")
.body(crate::response::Body::from("Unauthorized"))
.unwrap()
}
/// Configuration builder for RustAPI with auto-routes
pub struct RustApiConfig {
docs_path: Option<String>,
docs_enabled: bool,
api_title: String,
api_version: String,
api_description: Option<String>,
body_limit: Option<usize>,
layers: LayerStack,
}
impl Default for RustApiConfig {
fn default() -> Self {
Self::new()
}
}
impl RustApiConfig {
pub fn new() -> Self {
Self {
docs_path: Some("/docs".to_string()),
docs_enabled: true,
api_title: "RustAPI".to_string(),
api_version: "1.0.0".to_string(),
api_description: None,
body_limit: None,
layers: LayerStack::new(),
}
}
/// Set the docs path (default: "/docs")
pub fn docs_path(mut self, path: impl Into<String>) -> Self {
self.docs_path = Some(path.into());
self
}
/// Enable or disable docs (default: true)
pub fn docs_enabled(mut self, enabled: bool) -> Self {
self.docs_enabled = enabled;
self
}
/// Set OpenAPI info
pub fn openapi_info(
mut self,
title: impl Into<String>,
version: impl Into<String>,
description: Option<impl Into<String>>,
) -> Self {
self.api_title = title.into();
self.api_version = version.into();
self.api_description = description.map(|d| d.into());
self
}
/// Set body size limit
pub fn body_limit(mut self, limit: usize) -> Self {
self.body_limit = Some(limit);
self
}
/// Add a middleware layer
pub fn layer<L>(mut self, layer: L) -> Self
where
L: MiddlewareLayer,
{
self.layers.push(Box::new(layer));
self
}
/// Build the RustApi instance
pub fn build(self) -> RustApi {
let mut app = RustApi::new().mount_auto_routes_grouped();
// Apply configuration
if let Some(limit) = self.body_limit {
app = app.body_limit(limit);
}
app = app.openapi_info(
&self.api_title,
&self.api_version,
self.api_description.as_deref(),
);
#[cfg(feature = "swagger-ui")]
if self.docs_enabled {
if let Some(path) = self.docs_path {
app = app.docs(&path);
}
}
// Apply layers
// Note: layers are applied in reverse order in RustApi::layer logic (pushing to vec)
app.layers.extend(self.layers);
app
}
/// Build and run the server
pub async fn run(
self,
addr: impl AsRef<str>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.build().run(addr.as_ref()).await
}
}
#[cfg(test)]
mod tests {
use super::RustApi;
use crate::extract::{FromRequestParts, State};
use crate::path_params::PathParams;
use crate::request::Request;
use crate::router::{get, post, Router};
use bytes::Bytes;
use http::Method;
use proptest::prelude::*;
#[test]
fn state_is_available_via_extractor() {
let app = RustApi::new().state(123u32);
let router = app.into_router();
let req = http::Request::builder()
.method(Method::GET)
.uri("/test")
.body(())
.unwrap();
let (parts, _) = req.into_parts();
let request = Request::new(
parts,
crate::request::BodyVariant::Buffered(Bytes::new()),
router.state_ref(),
PathParams::new(),
);
let State(value) = State::<u32>::from_request_parts(&request).unwrap();
assert_eq!(value, 123u32);
}
#[test]
fn test_path_param_type_inference_integer() {
use super::infer_path_param_schema;
// Test common integer patterns
let int_params = [
"page",
"limit",
"offset",
"count",
"item_count",
"year",
"month",
"day",
"index",
"position",
];
for name in int_params {
let schema = infer_path_param_schema(name);
match schema {
rustapi_openapi::SchemaRef::Inline(v) => {
assert_eq!(
v.get("type").and_then(|v| v.as_str()),
Some("integer"),
"Expected '{}' to be inferred as integer",
name
);
}
_ => panic!("Expected inline schema for '{}'", name),
}
}
}
#[test]
fn test_path_param_type_inference_uuid() {
use super::infer_path_param_schema;
// Test UUID patterns
let uuid_params = ["uuid", "user_uuid", "sessionUuid"];
for name in uuid_params {
let schema = infer_path_param_schema(name);
match schema {
rustapi_openapi::SchemaRef::Inline(v) => {
assert_eq!(
v.get("type").and_then(|v| v.as_str()),
Some("string"),
"Expected '{}' to be inferred as string",
name
);
assert_eq!(
v.get("format").and_then(|v| v.as_str()),
Some("uuid"),
"Expected '{}' to have uuid format",
name
);
}
_ => panic!("Expected inline schema for '{}'", name),
}
}
}
#[test]
fn test_path_param_type_inference_string() {
use super::infer_path_param_schema;
// Test string (default) patterns
let string_params = [
"name", "slug", "code", "token", "username", "id", "user_id", "userId", "postId",
];
for name in string_params {
let schema = infer_path_param_schema(name);
match schema {
rustapi_openapi::SchemaRef::Inline(v) => {
assert_eq!(
v.get("type").and_then(|v| v.as_str()),
Some("string"),
"Expected '{}' to be inferred as string",
name
);
assert!(
v.get("format").is_none()
|| v.get("format").and_then(|v| v.as_str()) != Some("uuid"),
"Expected '{}' to NOT have uuid format",
name
);
}
_ => panic!("Expected inline schema for '{}'", name),
}
}
}
#[test]
fn test_schema_type_to_openapi_schema() {
use super::schema_type_to_openapi_schema;
// Test UUID schema
let uuid_schema = schema_type_to_openapi_schema("uuid");
match uuid_schema {
rustapi_openapi::SchemaRef::Inline(v) => {
assert_eq!(v.get("type").and_then(|v| v.as_str()), Some("string"));
assert_eq!(v.get("format").and_then(|v| v.as_str()), Some("uuid"));
}
_ => panic!("Expected inline schema for uuid"),
}
// Test integer schemas
for schema_type in ["integer", "int", "int64", "i64"] {
let schema = schema_type_to_openapi_schema(schema_type);
match schema {
rustapi_openapi::SchemaRef::Inline(v) => {
assert_eq!(v.get("type").and_then(|v| v.as_str()), Some("integer"));
assert_eq!(v.get("format").and_then(|v| v.as_str()), Some("int64"));
}
_ => panic!("Expected inline schema for {}", schema_type),
}
}
// Test int32 schema
let int32_schema = schema_type_to_openapi_schema("int32");
match int32_schema {
rustapi_openapi::SchemaRef::Inline(v) => {
assert_eq!(v.get("type").and_then(|v| v.as_str()), Some("integer"));
assert_eq!(v.get("format").and_then(|v| v.as_str()), Some("int32"));
}
_ => panic!("Expected inline schema for int32"),
}
// Test number/float schema
for schema_type in ["number", "float"] {
let schema = schema_type_to_openapi_schema(schema_type);
match schema {
rustapi_openapi::SchemaRef::Inline(v) => {
assert_eq!(v.get("type").and_then(|v| v.as_str()), Some("number"));
}
_ => panic!("Expected inline schema for {}", schema_type),
}
}
// Test boolean schema
for schema_type in ["boolean", "bool"] {
let schema = schema_type_to_openapi_schema(schema_type);
match schema {
rustapi_openapi::SchemaRef::Inline(v) => {
assert_eq!(v.get("type").and_then(|v| v.as_str()), Some("boolean"));
}
_ => panic!("Expected inline schema for {}", schema_type),
}
}
// Test string schema (default)
let string_schema = schema_type_to_openapi_schema("string");
match string_schema {
rustapi_openapi::SchemaRef::Inline(v) => {
assert_eq!(v.get("type").and_then(|v| v.as_str()), Some("string"));
}
_ => panic!("Expected inline schema for string"),
}
}
// **Feature: router-nesting, Property 11: OpenAPI Integration**
//
// For any nested routes with OpenAPI operations, the operations should appear
// in the parent's OpenAPI spec with prefixed paths and preserved metadata.
//
// **Validates: Requirements 4.1, 4.2**
proptest! {
#![proptest_config(ProptestConfig::with_cases(100))]
/// Property: Nested routes appear in OpenAPI spec with prefixed paths
///
/// For any router with routes nested under a prefix, all routes should
/// appear in the OpenAPI spec with the prefix prepended to their paths.
#[test]
fn prop_nested_routes_in_openapi_spec(
// Generate prefix segments
prefix_segments in prop::collection::vec("[a-z][a-z0-9]{0,5}", 1..3),
// Generate route path segments
route_segments in prop::collection::vec("[a-z][a-z0-9]{0,5}", 1..3),
has_param in any::<bool>(),
) {
async fn handler() -> &'static str { "handler" }
// Build the prefix
let prefix = format!("/{}", prefix_segments.join("/"));
// Build the route path
let mut route_path = format!("/{}", route_segments.join("/"));
if has_param {
route_path.push_str("/{id}");
}
// Create nested router and nest it through RustApi
let nested_router = Router::new().route(&route_path, get(handler));
let app = RustApi::new().nest(&prefix, nested_router);
// Build expected prefixed path for OpenAPI (uses {param} format)
let expected_openapi_path = format!("{}{}", prefix, route_path);
// Get the OpenAPI spec
let spec = app.openapi_spec();
// Property: The prefixed route should exist in OpenAPI paths
prop_assert!(
spec.paths.contains_key(&expected_openapi_path),
"Expected OpenAPI path '{}' not found. Available paths: {:?}",
expected_openapi_path,
spec.paths.keys().collect::<Vec<_>>()
);
// Property: The path item should have a GET operation
let path_item = spec.paths.get(&expected_openapi_path).unwrap();
prop_assert!(
path_item.get.is_some(),
"GET operation should exist for path '{}'",
expected_openapi_path
);
}
/// Property: Multiple HTTP methods are preserved in OpenAPI spec after nesting
///
/// For any router with routes having multiple HTTP methods, nesting should
/// preserve all method operations in the OpenAPI spec.
#[test]
fn prop_multiple_methods_preserved_in_openapi(
prefix_segments in prop::collection::vec("[a-z][a-z0-9]{0,5}", 1..3),
route_segments in prop::collection::vec("[a-z][a-z0-9]{0,5}", 1..3),
) {
async fn get_handler() -> &'static str { "get" }
async fn post_handler() -> &'static str { "post" }
// Build the prefix and route path
let prefix = format!("/{}", prefix_segments.join("/"));
let route_path = format!("/{}", route_segments.join("/"));
// Create nested router with both GET and POST using separate routes
// Since MethodRouter doesn't have chaining methods, we create two routes
let get_route_path = format!("{}/get", route_path);
let post_route_path = format!("{}/post", route_path);
let nested_router = Router::new()
.route(&get_route_path, get(get_handler))
.route(&post_route_path, post(post_handler));
let app = RustApi::new().nest(&prefix, nested_router);
// Build expected prefixed paths for OpenAPI
let expected_get_path = format!("{}{}", prefix, get_route_path);
let expected_post_path = format!("{}{}", prefix, post_route_path);
// Get the OpenAPI spec
let spec = app.openapi_spec();
// Property: Both paths should exist
prop_assert!(
spec.paths.contains_key(&expected_get_path),
"Expected OpenAPI path '{}' not found",
expected_get_path
);
prop_assert!(
spec.paths.contains_key(&expected_post_path),
"Expected OpenAPI path '{}' not found",
expected_post_path
);
// Property: GET operation should exist on get path
let get_path_item = spec.paths.get(&expected_get_path).unwrap();
prop_assert!(
get_path_item.get.is_some(),
"GET operation should exist for path '{}'",
expected_get_path
);
// Property: POST operation should exist on post path
let post_path_item = spec.paths.get(&expected_post_path).unwrap();
prop_assert!(
post_path_item.post.is_some(),
"POST operation should exist for path '{}'",
expected_post_path
);
}
/// Property: Path parameters are added to OpenAPI operations after nesting
///
/// For any nested route with path parameters, the OpenAPI operation should
/// include the path parameters.
#[test]
fn prop_path_params_in_openapi_after_nesting(
prefix_segments in prop::collection::vec("[a-z][a-z0-9]{0,5}", 1..3),
param_name in "[a-z][a-z0-9]{0,5}",
) {
async fn handler() -> &'static str { "handler" }
// Build the prefix and route path with parameter
let prefix = format!("/{}", prefix_segments.join("/"));
let route_path = format!("/{{{}}}", param_name);
// Create nested router
let nested_router = Router::new().route(&route_path, get(handler));
let app = RustApi::new().nest(&prefix, nested_router);
// Build expected prefixed path for OpenAPI
let expected_openapi_path = format!("{}{}", prefix, route_path);
// Get the OpenAPI spec
let spec = app.openapi_spec();
// Property: The path should exist
prop_assert!(
spec.paths.contains_key(&expected_openapi_path),
"Expected OpenAPI path '{}' not found",
expected_openapi_path
);
// Property: The GET operation should have the path parameter
let path_item = spec.paths.get(&expected_openapi_path).unwrap();
let get_op = path_item.get.as_ref().unwrap();
prop_assert!(
!get_op.parameters.is_empty(),
"Operation should have parameters for path '{}'",
expected_openapi_path
);
let params = &get_op.parameters;
let has_param = params.iter().any(|p| p.name == param_name && p.location == "path");
prop_assert!(
has_param,
"Path parameter '{}' should exist in operation parameters. Found: {:?}",
param_name,
params.iter().map(|p| &p.name).collect::<Vec<_>>()
);
}
}
// **Feature: router-nesting, Property 13: RustApi Integration**
//
// For any router nested through `RustApi::new().nest()`, the behavior should be
// identical to nesting through `Router::new().nest()`, and routes should appear
// in the OpenAPI spec.
//
// **Validates: Requirements 6.1, 6.2**
proptest! {
#![proptest_config(ProptestConfig::with_cases(100))]
/// Property: RustApi::nest delegates to Router::nest and produces identical route registration
///
/// For any router with routes nested under a prefix, nesting through RustApi
/// should produce the same route registration as nesting through Router directly.
#[test]
fn prop_rustapi_nest_delegates_to_router_nest(
prefix_segments in prop::collection::vec("[a-z][a-z0-9]{0,5}", 1..3),
route_segments in prop::collection::vec("[a-z][a-z0-9]{0,5}", 1..3),
has_param in any::<bool>(),
) {
async fn handler() -> &'static str { "handler" }
// Build the prefix
let prefix = format!("/{}", prefix_segments.join("/"));
// Build the route path
let mut route_path = format!("/{}", route_segments.join("/"));
if has_param {
route_path.push_str("/{id}");
}
// Create nested router
let nested_router_for_rustapi = Router::new().route(&route_path, get(handler));
let nested_router_for_router = Router::new().route(&route_path, get(handler));
// Nest through RustApi
let rustapi_app = RustApi::new().nest(&prefix, nested_router_for_rustapi);
let rustapi_router = rustapi_app.into_router();
// Nest through Router directly
let router_app = Router::new().nest(&prefix, nested_router_for_router);
// Property: Both should have the same registered routes
let rustapi_routes = rustapi_router.registered_routes();
let router_routes = router_app.registered_routes();
prop_assert_eq!(
rustapi_routes.len(),
router_routes.len(),
"RustApi and Router should have same number of routes"
);
// Property: All routes from Router should exist in RustApi
for (path, info) in router_routes {
prop_assert!(
rustapi_routes.contains_key(path),
"Route '{}' from Router should exist in RustApi routes",
path
);
let rustapi_info = rustapi_routes.get(path).unwrap();
prop_assert_eq!(
&info.path, &rustapi_info.path,
"Display paths should match for route '{}'",
path
);
prop_assert_eq!(
info.methods.len(), rustapi_info.methods.len(),
"Method count should match for route '{}'",
path
);
}
}
/// Property: RustApi::nest includes nested routes in OpenAPI spec
///
/// For any router with routes nested through RustApi, all routes should
/// appear in the OpenAPI specification with prefixed paths.
#[test]
fn prop_rustapi_nest_includes_routes_in_openapi(
prefix_segments in prop::collection::vec("[a-z][a-z0-9]{0,5}", 1..3),
route_segments in prop::collection::vec("[a-z][a-z0-9]{0,5}", 1..3),
has_param in any::<bool>(),
) {
async fn handler() -> &'static str { "handler" }
// Build the prefix
let prefix = format!("/{}", prefix_segments.join("/"));
// Build the route path
let mut route_path = format!("/{}", route_segments.join("/"));
if has_param {
route_path.push_str("/{id}");
}
// Create nested router and nest through RustApi
let nested_router = Router::new().route(&route_path, get(handler));
let app = RustApi::new().nest(&prefix, nested_router);
// Build expected prefixed path for OpenAPI
let expected_openapi_path = format!("{}{}", prefix, route_path);
// Get the OpenAPI spec
let spec = app.openapi_spec();
// Property: The prefixed route should exist in OpenAPI paths
prop_assert!(
spec.paths.contains_key(&expected_openapi_path),
"Expected OpenAPI path '{}' not found. Available paths: {:?}",
expected_openapi_path,
spec.paths.keys().collect::<Vec<_>>()
);
// Property: The path item should have a GET operation
let path_item = spec.paths.get(&expected_openapi_path).unwrap();
prop_assert!(
path_item.get.is_some(),
"GET operation should exist for path '{}'",
expected_openapi_path
);
}
/// Property: RustApi::nest route matching is identical to Router::nest
///
/// For any nested route, matching through RustApi should produce the same
/// result as matching through Router directly.
#[test]
fn prop_rustapi_nest_route_matching_identical(
prefix_segments in prop::collection::vec("[a-z][a-z0-9]{1,5}", 1..2),
route_segments in prop::collection::vec("[a-z][a-z0-9]{1,5}", 1..2),
param_value in "[a-z0-9]{1,10}",
) {
use crate::router::RouteMatch;
async fn handler() -> &'static str { "handler" }
// Build the prefix and route path with parameter
let prefix = format!("/{}", prefix_segments.join("/"));
let route_path = format!("/{}/{{id}}", route_segments.join("/"));
// Create nested routers
let nested_router_for_rustapi = Router::new().route(&route_path, get(handler));
let nested_router_for_router = Router::new().route(&route_path, get(handler));
// Nest through both RustApi and Router
let rustapi_app = RustApi::new().nest(&prefix, nested_router_for_rustapi);
let rustapi_router = rustapi_app.into_router();
let router_app = Router::new().nest(&prefix, nested_router_for_router);
// Build the full path to match
let full_path = format!("{}/{}/{}", prefix, route_segments.join("/"), param_value);
// Match through both
let rustapi_match = rustapi_router.match_route(&full_path, &Method::GET);
let router_match = router_app.match_route(&full_path, &Method::GET);
// Property: Both should return Found with same parameters
match (rustapi_match, router_match) {
(RouteMatch::Found { params: rustapi_params, .. }, RouteMatch::Found { params: router_params, .. }) => {
prop_assert_eq!(
rustapi_params.len(),
router_params.len(),
"Parameter count should match"
);
for (key, value) in &router_params {
prop_assert!(
rustapi_params.contains_key(key),
"RustApi should have parameter '{}'",
key
);
prop_assert_eq!(
rustapi_params.get(key).unwrap(),
value,
"Parameter '{}' value should match",
key
);
}
}
(rustapi_result, router_result) => {
prop_assert!(
false,
"Both should return Found, but RustApi returned {:?} and Router returned {:?}",
match rustapi_result {
RouteMatch::Found { .. } => "Found",
RouteMatch::NotFound => "NotFound",
RouteMatch::MethodNotAllowed { .. } => "MethodNotAllowed",
},
match router_result {
RouteMatch::Found { .. } => "Found",
RouteMatch::NotFound => "NotFound",
RouteMatch::MethodNotAllowed { .. } => "MethodNotAllowed",
}
);
}
}
}
}
/// Unit test: Verify OpenAPI operations are propagated during nesting
#[test]
fn test_openapi_operations_propagated_during_nesting() {
async fn list_users() -> &'static str {
"list users"
}
async fn get_user() -> &'static str {
"get user"
}
async fn create_user() -> &'static str {
"create user"
}
// Create nested router with multiple routes
// Note: We use separate routes since MethodRouter doesn't support chaining
let users_router = Router::new()
.route("/", get(list_users))
.route("/create", post(create_user))
.route("/{id}", get(get_user));
// Nest under /api/v1/users
let app = RustApi::new().nest("/api/v1/users", users_router);
let spec = app.openapi_spec();
// Verify /api/v1/users path exists with GET
assert!(
spec.paths.contains_key("/api/v1/users"),
"Should have /api/v1/users path"
);
let users_path = spec.paths.get("/api/v1/users").unwrap();
assert!(users_path.get.is_some(), "Should have GET operation");
// Verify /api/v1/users/create path exists with POST
assert!(
spec.paths.contains_key("/api/v1/users/create"),
"Should have /api/v1/users/create path"
);
let create_path = spec.paths.get("/api/v1/users/create").unwrap();
assert!(create_path.post.is_some(), "Should have POST operation");
// Verify /api/v1/users/{id} path exists with GET
assert!(
spec.paths.contains_key("/api/v1/users/{id}"),
"Should have /api/v1/users/{{id}} path"
);
let user_path = spec.paths.get("/api/v1/users/{id}").unwrap();
assert!(
user_path.get.is_some(),
"Should have GET operation for user by id"
);
// Verify path parameter is added
let get_user_op = user_path.get.as_ref().unwrap();
assert!(!get_user_op.parameters.is_empty(), "Should have parameters");
let params = &get_user_op.parameters;
assert!(
params
.iter()
.any(|p| p.name == "id" && p.location == "path"),
"Should have 'id' path parameter"
);
}
/// Unit test: Verify nested routes don't appear without nesting
#[test]
fn test_openapi_spec_empty_without_routes() {
let app = RustApi::new();
let spec = app.openapi_spec();
// Should have no paths (except potentially default ones)
assert!(
spec.paths.is_empty(),
"OpenAPI spec should have no paths without routes"
);
}
/// Unit test: Verify RustApi::nest delegates correctly to Router::nest
///
/// **Feature: router-nesting, Property 13: RustApi Integration**
/// **Validates: Requirements 6.1, 6.2**
#[test]
fn test_rustapi_nest_delegates_to_router_nest() {
use crate::router::RouteMatch;
async fn list_users() -> &'static str {
"list users"
}
async fn get_user() -> &'static str {
"get user"
}
async fn create_user() -> &'static str {
"create user"
}
// Create nested router with multiple routes
let users_router = Router::new()
.route("/", get(list_users))
.route("/create", post(create_user))
.route("/{id}", get(get_user));
// Nest through RustApi
let app = RustApi::new().nest("/api/v1/users", users_router);
let router = app.into_router();
// Verify routes are registered correctly
let routes = router.registered_routes();
assert_eq!(routes.len(), 3, "Should have 3 routes registered");
// Verify route paths
assert!(
routes.contains_key("/api/v1/users"),
"Should have /api/v1/users route"
);
assert!(
routes.contains_key("/api/v1/users/create"),
"Should have /api/v1/users/create route"
);
assert!(
routes.contains_key("/api/v1/users/:id"),
"Should have /api/v1/users/:id route"
);
// Verify route matching works
match router.match_route("/api/v1/users", &Method::GET) {
RouteMatch::Found { params, .. } => {
assert!(params.is_empty(), "Root route should have no params");
}
_ => panic!("GET /api/v1/users should be found"),
}
match router.match_route("/api/v1/users/create", &Method::POST) {
RouteMatch::Found { params, .. } => {
assert!(params.is_empty(), "Create route should have no params");
}
_ => panic!("POST /api/v1/users/create should be found"),
}
match router.match_route("/api/v1/users/123", &Method::GET) {
RouteMatch::Found { params, .. } => {
assert_eq!(
params.get("id"),
Some(&"123".to_string()),
"Should extract id param"
);
}
_ => panic!("GET /api/v1/users/123 should be found"),
}
// Verify method not allowed
match router.match_route("/api/v1/users", &Method::DELETE) {
RouteMatch::MethodNotAllowed { allowed } => {
assert!(allowed.contains(&Method::GET), "Should allow GET");
}
_ => panic!("DELETE /api/v1/users should return MethodNotAllowed"),
}
}
/// Unit test: Verify RustApi::nest includes routes in OpenAPI spec
///
/// **Feature: router-nesting, Property 13: RustApi Integration**
/// **Validates: Requirements 6.1, 6.2**
#[test]
fn test_rustapi_nest_includes_routes_in_openapi_spec() {
async fn list_items() -> &'static str {
"list items"
}
async fn get_item() -> &'static str {
"get item"
}
// Create nested router
let items_router = Router::new()
.route("/", get(list_items))
.route("/{item_id}", get(get_item));
// Nest through RustApi
let app = RustApi::new().nest("/api/items", items_router);
// Verify OpenAPI spec
let spec = app.openapi_spec();
// Verify paths exist
assert!(
spec.paths.contains_key("/api/items"),
"Should have /api/items in OpenAPI"
);
assert!(
spec.paths.contains_key("/api/items/{item_id}"),
"Should have /api/items/{{item_id}} in OpenAPI"
);
// Verify operations
let list_path = spec.paths.get("/api/items").unwrap();
assert!(
list_path.get.is_some(),
"Should have GET operation for /api/items"
);
let get_path = spec.paths.get("/api/items/{item_id}").unwrap();
assert!(
get_path.get.is_some(),
"Should have GET operation for /api/items/{{item_id}}"
);
// Verify path parameter is added
let get_op = get_path.get.as_ref().unwrap();
assert!(!get_op.parameters.is_empty(), "Should have parameters");
let params = &get_op.parameters;
assert!(
params
.iter()
.any(|p| p.name == "item_id" && p.location == "path"),
"Should have 'item_id' path parameter"
);
}
}