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
//! Type-safe API operation builder with compile-time guarantees
//!
//! This module implements a type-state builder pattern that ensures:
//! - `register()` cannot be called unless a handler is set
//! - `register()` cannot be called unless at least one response is declared
//! - Descriptive methods remain available at any stage
//! - No panics or unwraps in production hot paths
//! - Request body support (`json_request`, `json_request_schema`) so POST/PUT calls are invokable in UI
//! - Schema-aware responses (`json_response_with_schema`)
//! - Typed Router state `S` usage pattern: pass a state type once via `Router::with_state`,
//! then use plain function handlers (no per-route closures that capture/clones).
//! - Optional `method_router(...)` for advanced use (layers/middleware on route level).
use crate::api::{api_dto, problem};
use axum::{Router, handler::Handler, routing::MethodRouter};
use http::Method;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::marker::PhantomData;
/// Convert OpenAPI-style path placeholders to Axum 0.8+ style path parameters.
///
/// Axum 0.8+ uses `{id}` for path parameters and `{*path}` for wildcards, which is the same as `OpenAPI`.
/// However, `OpenAPI` wildcards are just `{path}` without the asterisk.
/// This function converts `OpenAPI` wildcards to Axum wildcards by detecting common wildcard names.
///
/// # Examples
///
/// ```
/// # use modkit::api::operation_builder::normalize_to_axum_path;
/// assert_eq!(normalize_to_axum_path("/users/{id}"), "/users/{id}");
/// assert_eq!(normalize_to_axum_path("/projects/{project_id}/items/{item_id}"), "/projects/{project_id}/items/{item_id}");
/// // Note: Most paths don't need normalization in Axum 0.8+
/// ```
#[must_use]
pub fn normalize_to_axum_path(path: &str) -> String {
// In Axum 0.8+, the path syntax is {param} for parameters and {*wildcard} for wildcards
// which is the same as OpenAPI except wildcards need the asterisk prefix.
// For now, we just pass through the path as-is since OpenAPI and Axum 0.8 use the same syntax
// for regular parameters. Wildcards need special handling if used.
path.to_owned()
}
/// Convert Axum 0.8+ style path parameters to OpenAPI-style placeholders.
///
/// Removes the asterisk prefix from Axum wildcards `{*path}` to make them OpenAPI-compatible `{path}`.
///
/// # Examples
///
/// ```
/// # use modkit::api::operation_builder::axum_to_openapi_path;
/// assert_eq!(axum_to_openapi_path("/users/{id}"), "/users/{id}");
/// assert_eq!(axum_to_openapi_path("/static/{*path}"), "/static/{path}");
/// ```
#[must_use]
pub fn axum_to_openapi_path(path: &str) -> String {
// In Axum 0.8+, wildcards are {*name} but OpenAPI expects {name}
// Regular parameters are the same in both
path.replace("{*", "{")
}
/// Type-state markers for compile-time enforcement
pub mod state {
/// Marker for missing required components
#[derive(Debug, Clone, Copy)]
pub struct Missing;
/// Marker for present required components
#[derive(Debug, Clone, Copy)]
pub struct Present;
/// Marker for auth requirement not yet set
#[derive(Debug, Clone, Copy)]
pub struct AuthNotSet;
/// Marker for auth requirement set (either `authenticated` or public)
#[derive(Debug, Clone, Copy)]
pub struct AuthSet;
/// Marker for license requirement not yet set
#[derive(Debug, Clone, Copy)]
pub struct LicenseNotSet;
/// Marker for license requirement set
#[derive(Debug, Clone, Copy)]
pub struct LicenseSet;
}
/// Internal trait mapping handler state to the concrete router slot type.
/// For `Missing` there is no router slot; for `Present` it is `MethodRouter<S>`.
/// Private sealed trait to enforce the implementation is only visible within this module.
mod sealed {
pub trait Sealed {}
pub trait SealedAuth {}
pub trait SealedLicenseReq {}
}
pub trait HandlerSlot<S>: sealed::Sealed {
type Slot;
}
/// Sealed trait for auth state markers
pub trait AuthState: sealed::SealedAuth {}
impl sealed::Sealed for Missing {}
impl sealed::Sealed for Present {}
impl sealed::SealedAuth for state::AuthNotSet {}
impl sealed::SealedAuth for state::AuthSet {}
impl AuthState for state::AuthNotSet {}
impl AuthState for state::AuthSet {}
pub trait LicenseState: sealed::SealedLicenseReq {}
impl sealed::SealedLicenseReq for state::LicenseNotSet {}
impl sealed::SealedLicenseReq for state::LicenseSet {}
impl LicenseState for state::LicenseNotSet {}
impl LicenseState for state::LicenseSet {}
impl<S> HandlerSlot<S> for Missing {
type Slot = ();
}
impl<S> HandlerSlot<S> for Present {
type Slot = MethodRouter<S>;
}
pub use state::{AuthNotSet, AuthSet, LicenseNotSet, LicenseSet, Missing, Present};
/// Parameter specification for API operations
#[derive(Clone, Debug)]
pub struct ParamSpec {
pub name: String,
pub location: ParamLocation,
pub required: bool,
pub description: Option<String>,
pub param_type: String, // JSON Schema type (string, integer, etc.)
}
pub trait LicenseFeature: AsRef<str> {}
impl<T: LicenseFeature + ?Sized> LicenseFeature for &T {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ParamLocation {
Path,
Query,
Header,
Cookie,
}
/// Request body schema variants for different kinds of request bodies
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RequestBodySchema {
/// Reference to a component schema in `#/components/schemas/{schema_name}`
Ref { schema_name: String },
/// Multipart form with a single file field
MultipartFile { field_name: String },
/// Raw binary body (e.g. application/octet-stream), represented as
/// type: string, format: binary in `OpenAPI`.
Binary,
/// A generic inline object schema with no predefined properties
InlineObject,
}
/// Request body specification for API operations
#[derive(Clone, Debug)]
pub struct RequestBodySpec {
pub content_type: &'static str,
pub description: Option<String>,
/// The schema for this request body
pub schema: RequestBodySchema,
/// Whether request body is required (`OpenAPI` default is `false`).
pub required: bool,
}
/// Response specification for API operations
#[derive(Clone, Debug)]
pub struct ResponseSpec {
pub status: u16,
pub content_type: &'static str,
pub description: String,
/// Name of a registered component schema (if any).
pub schema_name: Option<String>,
}
/// License requirement specification for an operation
#[derive(Clone, Debug)]
pub struct LicenseReqSpec {
pub license_names: Vec<String>,
}
/// Simplified operation specification for the type-safe builder
#[derive(Clone, Debug)]
pub struct OperationSpec {
pub method: Method,
pub path: String,
pub operation_id: Option<String>,
pub summary: Option<String>,
pub description: Option<String>,
pub tags: Vec<String>,
pub params: Vec<ParamSpec>,
pub request_body: Option<RequestBodySpec>,
pub responses: Vec<ResponseSpec>,
/// Internal handler id; can be used by registry/generator to map a handler identity
pub handler_id: String,
/// Whether this operation requires authentication.
/// `true` = authenticated endpoint, `false` = public endpoint.
pub authenticated: bool,
/// Explicitly mark route as public (no auth required)
pub is_public: bool,
/// Optional rate & concurrency limits for this operation
pub rate_limit: Option<RateLimitSpec>,
/// Optional whitelist of allowed request Content-Type values (without parameters).
/// Example: Some(vec!["application/json", "multipart/form-data", "application/pdf"])
/// When set, gateway middleware will enforce these types and return HTTP 415 for
/// requests with disallowed Content-Type headers. This is independent of the
/// request body schema and should not be used to create synthetic request bodies.
pub allowed_request_content_types: Option<Vec<&'static str>>,
/// `OpenAPI` vendor extensions (x-*)
pub vendor_extensions: VendorExtensions,
pub license_requirement: Option<LicenseReqSpec>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct VendorExtensions {
#[serde(rename = "x-odata-filter", skip_serializing_if = "Option::is_none")]
pub x_odata_filter: Option<ODataPagination<BTreeMap<String, Vec<String>>>>,
#[serde(rename = "x-odata-orderby", skip_serializing_if = "Option::is_none")]
pub x_odata_orderby: Option<ODataPagination<Vec<String>>>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct ODataPagination<T> {
#[serde(rename = "allowedFields")]
pub allowed_fields: T,
}
/// Per-operation rate & concurrency limit specification
#[derive(Clone, Debug, Default)]
pub struct RateLimitSpec {
/// Target steady-state requests per second
pub rps: u32,
/// Maximum burst size (token bucket capacity)
pub burst: u32,
/// Maximum number of in-flight requests for this route
pub in_flight: u32,
}
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct XPagination {
pub filter_fields: BTreeMap<String, Vec<String>>,
pub order_by: Vec<String>,
}
//
pub trait OperationBuilderODataExt<S, H, R> {
/// Adds optional `$filter` query parameter to `OpenAPI`.
#[must_use]
fn with_odata_filter<T>(self) -> Self
where
T: modkit_odata::filter::FilterField;
/// Adds optional `$select` query parameter to `OpenAPI`.
#[must_use]
fn with_odata_select(self) -> Self;
/// Adds optional `$orderby` query parameter to `OpenAPI`.
#[must_use]
fn with_odata_orderby<T>(self) -> Self
where
T: modkit_odata::filter::FilterField;
}
impl<S, H, R, A, L> OperationBuilderODataExt<S, H, R> for OperationBuilder<H, R, S, A, L>
where
H: HandlerSlot<S>,
A: AuthState,
L: LicenseState,
{
fn with_odata_filter<T>(mut self) -> Self
where
T: modkit_odata::filter::FilterField,
{
use modkit_odata::filter::FieldKind;
use std::fmt::Write as _;
let mut filter = self
.spec
.vendor_extensions
.x_odata_filter
.unwrap_or_default();
let mut description = "OData v4 filter expression".to_owned();
for field in T::FIELDS {
let name = field.name().to_owned();
let kind = field.kind();
let ops: Vec<String> = match kind {
FieldKind::String => vec!["eq", "ne", "contains", "startswith", "endswith", "in"],
FieldKind::Uuid => vec!["eq", "ne", "in"],
FieldKind::Bool => vec!["eq", "ne"],
FieldKind::I64
| FieldKind::F64
| FieldKind::Decimal
| FieldKind::DateTimeUtc
| FieldKind::Date
| FieldKind::Time => {
vec!["eq", "ne", "gt", "ge", "lt", "le", "in"]
}
}
.into_iter()
.map(String::from)
.collect();
_ = write!(description, "\n- {}: {}", name, ops.join("|"));
filter.allowed_fields.insert(name.clone(), ops);
}
self.spec.params.push(ParamSpec {
name: "$filter".to_owned(),
location: ParamLocation::Query,
required: false,
description: Some(description),
param_type: "string".to_owned(),
});
self.spec.vendor_extensions.x_odata_filter = Some(filter);
self
}
fn with_odata_select(mut self) -> Self {
self.spec.params.push(ParamSpec {
name: "$select".to_owned(),
location: ParamLocation::Query,
required: false,
description: Some("OData v4 select expression".to_owned()),
param_type: "string".to_owned(),
});
self
}
fn with_odata_orderby<T>(mut self) -> Self
where
T: modkit_odata::filter::FilterField,
{
use std::fmt::Write as _;
let mut order_by = self
.spec
.vendor_extensions
.x_odata_orderby
.unwrap_or_default();
let mut description = "OData v4 orderby expression".to_owned();
for field in T::FIELDS {
let name = field.name().to_owned();
// Add sort options (asc/desc)
let asc = format!("{name} asc");
let desc = format!("{name} desc");
_ = write!(description, "\n- {asc}\n- {desc}");
if !order_by.allowed_fields.contains(&asc) {
order_by.allowed_fields.push(asc);
}
if !order_by.allowed_fields.contains(&desc) {
order_by.allowed_fields.push(desc);
}
}
self.spec.params.push(ParamSpec {
name: "$orderby".to_owned(),
location: ParamLocation::Query,
required: false,
description: Some(description),
param_type: "string".to_owned(),
});
self.spec.vendor_extensions.x_odata_orderby = Some(order_by);
self
}
}
// Re-export from openapi_registry for backward compatibility
pub use crate::api::openapi_registry::{OpenApiRegistry, ensure_schema};
/// Type-safe operation builder with compile-time guarantees.
///
/// Generic parameters:
/// - `H`: Handler state (Missing | Present)
/// - `R`: Response state (Missing | Present)
/// - `S`: Router state type (what you put into `Router::with_state(S)`).
/// - `A`: Auth state (`AuthNotSet` | `AuthSet`)
/// - `L`: License requirement state (`LicenseNotSet` | `LicenseSet`)
#[must_use]
pub struct OperationBuilder<H = Missing, R = Missing, S = (), A = AuthNotSet, L = LicenseNotSet>
where
H: HandlerSlot<S>,
A: AuthState,
L: LicenseState,
{
spec: OperationSpec,
method_router: <H as HandlerSlot<S>>::Slot,
_has_handler: PhantomData<H>,
_has_response: PhantomData<R>,
#[allow(clippy::type_complexity)]
_state: PhantomData<fn() -> S>, // Zero-sized marker for type-state pattern
_auth_state: PhantomData<A>,
_license_state: PhantomData<L>,
}
// -------------------------------------------------------------------------------------------------
// Constructors — starts with both handler and response missing, auth not set
// -------------------------------------------------------------------------------------------------
impl<S> OperationBuilder<Missing, Missing, S, AuthNotSet> {
/// Create a new operation builder with an HTTP method and path
pub fn new(method: Method, path: impl Into<String>) -> Self {
let path_str = path.into();
let handler_id = format!(
"{}:{}",
method.as_str().to_lowercase(),
path_str.replace(['/', '{', '}'], "_")
);
Self {
spec: OperationSpec {
method,
path: path_str,
operation_id: None,
summary: None,
description: None,
tags: Vec::new(),
params: Vec::new(),
request_body: None,
responses: Vec::new(),
handler_id,
authenticated: false,
is_public: false,
rate_limit: None,
allowed_request_content_types: None,
vendor_extensions: VendorExtensions::default(),
license_requirement: None,
},
method_router: (), // no router in Missing state
_has_handler: PhantomData,
_has_response: PhantomData,
_state: PhantomData,
_auth_state: PhantomData,
_license_state: PhantomData,
}
}
/// Convenience constructor for GET requests
pub fn get(path: impl Into<String>) -> Self {
let path_str = path.into();
Self::new(Method::GET, normalize_to_axum_path(&path_str))
}
/// Convenience constructor for POST requests
pub fn post(path: impl Into<String>) -> Self {
let path_str = path.into();
Self::new(Method::POST, normalize_to_axum_path(&path_str))
}
/// Convenience constructor for PUT requests
pub fn put(path: impl Into<String>) -> Self {
let path_str = path.into();
Self::new(Method::PUT, normalize_to_axum_path(&path_str))
}
/// Convenience constructor for DELETE requests
pub fn delete(path: impl Into<String>) -> Self {
let path_str = path.into();
Self::new(Method::DELETE, normalize_to_axum_path(&path_str))
}
/// Convenience constructor for PATCH requests
pub fn patch(path: impl Into<String>) -> Self {
let path_str = path.into();
Self::new(Method::PATCH, normalize_to_axum_path(&path_str))
}
}
// -------------------------------------------------------------------------------------------------
// Descriptive methods — available at any stage
// -------------------------------------------------------------------------------------------------
impl<H, R, S, A, L> OperationBuilder<H, R, S, A, L>
where
H: HandlerSlot<S>,
A: AuthState,
L: LicenseState,
{
/// Inspect the spec (primarily for tests)
pub fn spec(&self) -> &OperationSpec {
&self.spec
}
/// Set the operation ID
pub fn operation_id(mut self, id: impl Into<String>) -> Self {
self.spec.operation_id = Some(id.into());
self
}
/// Require per-route rate and concurrency limits.
/// Stores metadata for the gateway to enforce.
pub fn require_rate_limit(&mut self, rps: u32, burst: u32, in_flight: u32) -> &mut Self {
self.spec.rate_limit = Some(RateLimitSpec {
rps,
burst,
in_flight,
});
self
}
/// Set the operation summary
pub fn summary(mut self, text: impl Into<String>) -> Self {
self.spec.summary = Some(text.into());
self
}
/// Set the operation description
pub fn description(mut self, text: impl Into<String>) -> Self {
self.spec.description = Some(text.into());
self
}
/// Add a tag to the operation
pub fn tag(mut self, tag: impl Into<String>) -> Self {
self.spec.tags.push(tag.into());
self
}
/// Add a parameter to the operation
pub fn param(mut self, param: ParamSpec) -> Self {
self.spec.params.push(param);
self
}
/// Add a path parameter with type inference (defaults to string)
pub fn path_param(mut self, name: impl Into<String>, description: impl Into<String>) -> Self {
self.spec.params.push(ParamSpec {
name: name.into(),
location: ParamLocation::Path,
required: true,
description: Some(description.into()),
param_type: "string".to_owned(),
});
self
}
/// Add a query parameter (defaults to string)
pub fn query_param(
mut self,
name: impl Into<String>,
required: bool,
description: impl Into<String>,
) -> Self {
self.spec.params.push(ParamSpec {
name: name.into(),
location: ParamLocation::Query,
required,
description: Some(description.into()),
param_type: "string".to_owned(),
});
self
}
/// Add a typed query parameter with explicit `OpenAPI` type
pub fn query_param_typed(
mut self,
name: impl Into<String>,
required: bool,
description: impl Into<String>,
param_type: impl Into<String>,
) -> Self {
self.spec.params.push(ParamSpec {
name: name.into(),
location: ParamLocation::Query,
required,
description: Some(description.into()),
param_type: param_type.into(),
});
self
}
/// Attach a JSON request body by *schema name* that you've already registered.
/// This variant sets a description (`Some(desc)`) and marks the body as **required**.
pub fn json_request_schema(
mut self,
schema_name: impl Into<String>,
desc: impl Into<String>,
) -> Self {
self.spec.request_body = Some(RequestBodySpec {
content_type: "application/json",
description: Some(desc.into()),
schema: RequestBodySchema::Ref {
schema_name: schema_name.into(),
},
required: true,
});
self
}
/// Attach a JSON request body by *schema name* with **no** description (`None`).
/// Marks the body as **required**.
pub fn json_request_schema_no_desc(mut self, schema_name: impl Into<String>) -> Self {
self.spec.request_body = Some(RequestBodySpec {
content_type: "application/json",
description: None,
schema: RequestBodySchema::Ref {
schema_name: schema_name.into(),
},
required: true,
});
self
}
/// Attach a JSON request body and auto-register its schema using `utoipa`.
/// This variant sets a description (`Some(desc)`) and marks the body as **required**.
pub fn json_request<T>(
mut self,
registry: &dyn OpenApiRegistry,
desc: impl Into<String>,
) -> Self
where
T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::RequestApiDto + 'static,
{
let name = ensure_schema::<T>(registry);
self.spec.request_body = Some(RequestBodySpec {
content_type: "application/json",
description: Some(desc.into()),
schema: RequestBodySchema::Ref { schema_name: name },
required: true,
});
self
}
/// Attach a JSON request body (auto-register schema) with **no** description (`None`).
/// Marks the body as **required**.
pub fn json_request_no_desc<T>(mut self, registry: &dyn OpenApiRegistry) -> Self
where
T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::RequestApiDto + 'static,
{
let name = ensure_schema::<T>(registry);
self.spec.request_body = Some(RequestBodySpec {
content_type: "application/json",
description: None,
schema: RequestBodySchema::Ref { schema_name: name },
required: true,
});
self
}
/// Make the previously attached request body **optional** (if any).
pub fn request_optional(mut self) -> Self {
if let Some(rb) = &mut self.spec.request_body {
rb.required = false;
}
self
}
/// Configure a multipart/form-data file upload request.
///
/// This is a convenience helper for file upload endpoints that:
/// - Sets the request body content type to "multipart/form-data"
/// - Sets a description for the request body
/// - Configures an inline object schema with a binary file field
/// - Restricts allowed Content-Type to only "multipart/form-data"
///
/// The file field will be documented in `OpenAPI` as a binary string with the
/// given field name. This generates the correct `OpenAPI` schema for UI tools
/// like Stoplight to display a file upload control.
///
/// # Arguments
/// * `field_name` - Name of the multipart form field (e.g., "file")
/// * `description` - Optional description for the request body
///
/// # Example
/// ```rust
/// # use axum::Router;
/// # use http::StatusCode;
/// # use modkit::api::{
/// # openapi_registry::OpenApiRegistryImpl,
/// # operation_builder::OperationBuilder,
/// # };
/// # async fn upload_handler() -> &'static str { "uploaded" }
/// # let registry = OpenApiRegistryImpl::new();
/// # let router: Router<()> = Router::new();
/// let router = OperationBuilder::post("/files/v1/upload")
/// .operation_id("upload_file")
/// .summary("Upload a file")
/// .multipart_file_request("file", Some("File to upload"))
/// .public()
/// .handler(upload_handler)
/// .json_response(StatusCode::OK, "Upload successful")
/// .register(router, ®istry);
/// # let _ = router;
/// ```
pub fn multipart_file_request(mut self, field_name: &str, description: Option<&str>) -> Self {
// Set request body with multipart/form-data content type
self.spec.request_body = Some(RequestBodySpec {
content_type: "multipart/form-data",
description: description
.map(|s| format!("{s} (expects field '{field_name}' with file data)")),
schema: RequestBodySchema::MultipartFile {
field_name: field_name.to_owned(),
},
required: true,
});
// Also configure MIME type validation
self.spec.allowed_request_content_types = Some(vec!["multipart/form-data"]);
self
}
/// Configure the request body as raw binary (application/octet-stream).
///
/// This is intended for endpoints that accept the entire request body
/// as a file or arbitrary bytes, without multipart form encoding.
///
/// The `OpenAPI` schema will be:
/// ```yaml
/// requestBody:
/// required: true
/// content:
/// application/octet-stream:
/// schema:
/// type: string
/// format: binary
/// ```
///
/// Tools like Stoplight will render this as a single file upload control
/// for the entire body.
///
/// # Arguments
/// * `description` - Optional description for the request body
///
/// # Example
/// ```rust
/// # use axum::Router;
/// # use http::StatusCode;
/// # use modkit::api::{
/// # openapi_registry::OpenApiRegistryImpl,
/// # operation_builder::OperationBuilder,
/// # };
/// # async fn upload_handler() -> &'static str { "uploaded" }
/// # let registry = OpenApiRegistryImpl::new();
/// # let router: Router<()> = Router::new();
/// let router = OperationBuilder::post("/files/v1/upload")
/// .operation_id("upload_file")
/// .summary("Upload a file")
/// .octet_stream_request(Some("Raw file bytes to parse"))
/// .public()
/// .handler(upload_handler)
/// .json_response(StatusCode::OK, "Upload successful")
/// .register(router, ®istry);
/// # let _ = router;
/// ```
pub fn octet_stream_request(mut self, description: Option<&str>) -> Self {
self.spec.request_body = Some(RequestBodySpec {
content_type: "application/octet-stream",
description: description.map(str::to_owned),
schema: RequestBodySchema::Binary,
required: true,
});
// Also configure MIME type validation
self.spec.allowed_request_content_types = Some(vec!["application/octet-stream"]);
self
}
/// Configure allowed request MIME types for this operation.
///
/// This attaches a whitelist of allowed Content-Type values (without parameters),
/// which will be enforced by gateway middleware. If a request arrives with a
/// Content-Type that is not in this list, gateway will return HTTP 415.
///
/// This is independent of the request body schema - it only configures gateway
/// validation and does not affect `OpenAPI` request body specifications.
///
/// # Example
/// ```rust
/// # use axum::Router;
/// # use http::StatusCode;
/// # use modkit::api::{
/// # openapi_registry::OpenApiRegistryImpl,
/// # operation_builder::OperationBuilder,
/// # };
/// # async fn upload_handler() -> &'static str { "uploaded" }
/// # let registry = OpenApiRegistryImpl::new();
/// # let router: Router<()> = Router::new();
/// let router = OperationBuilder::post("/files/v1/upload")
/// .operation_id("upload_file")
/// .allow_content_types(&["multipart/form-data", "application/pdf"])
/// .public()
/// .handler(upload_handler)
/// .json_response(StatusCode::OK, "Upload successful")
/// .register(router, ®istry);
/// # let _ = router;
/// ```
pub fn allow_content_types(mut self, types: &[&'static str]) -> Self {
self.spec.allowed_request_content_types = Some(types.to_vec());
self
}
}
/// License requirement setting — transitions `LicenseNotSet` -> `LicenseSet`
impl<H, R, S> OperationBuilder<H, R, S, AuthSet, LicenseNotSet>
where
H: HandlerSlot<S>,
{
/// Set (or explicitly clear) the license feature requirement for this operation.
///
/// This method is only available after the auth requirement has been decided
/// (i.e. after calling `authenticated()`).
///
/// **Mandatory for authenticated endpoints:** operations configured with `authenticated()`
/// must call `require_license_features(...)` before `register()`, because `register()` is only
/// available once the license requirement state has transitioned to `LicenseSet`.
///
/// **Not available for public endpoints:** public routes cannot (and do not need to) call this method.
///
/// Pass an empty iterator (e.g. `[]`) to explicitly declare that no license feature is required.
pub fn require_license_features<F>(
mut self,
licenses: impl IntoIterator<Item = F>,
) -> OperationBuilder<H, R, S, AuthSet, LicenseSet>
where
F: LicenseFeature,
{
let license_names: Vec<String> = licenses
.into_iter()
.map(|l| l.as_ref().to_owned())
.collect();
self.spec.license_requirement =
(!license_names.is_empty()).then_some(LicenseReqSpec { license_names });
OperationBuilder {
spec: self.spec,
method_router: self.method_router,
_has_handler: self._has_handler,
_has_response: self._has_response,
_state: self._state,
_auth_state: self._auth_state,
_license_state: PhantomData,
}
}
/// Explicitly declare that this operation does not require any license.
///
/// Use this for system/infrastructure endpoints that need authentication
/// but are not gated behind application-level license features.
///
/// This transitions from `LicenseNotSet` to `LicenseSet` without
/// attaching any license requirement.
pub fn no_license_required(self) -> OperationBuilder<H, R, S, AuthSet, LicenseSet> {
OperationBuilder {
spec: self.spec,
method_router: self.method_router,
_has_handler: self._has_handler,
_has_response: self._has_response,
_state: self._state,
_auth_state: self._auth_state,
_license_state: PhantomData,
}
}
}
// -------------------------------------------------------------------------------------------------
// Auth requirement setting — transitions AuthNotSet -> AuthSet
// -------------------------------------------------------------------------------------------------
impl<H, R, S, L> OperationBuilder<H, R, S, AuthNotSet, L>
where
H: HandlerSlot<S>,
L: LicenseState,
{
/// Mark this route as requiring authentication.
///
/// This is a binary marker — the route requires a valid bearer token.
/// Scope enforcement (which scopes are needed) is configured at the
/// gateway level, not per-route.
///
/// This method transitions from `AuthNotSet` to `AuthSet` state.
///
/// # Example
/// ```rust
/// # use modkit::api::operation_builder::{OperationBuilder, LicenseFeature};
/// # use axum::{extract::Json, Router };
/// # use serde::{Serialize};
/// #
/// # #[derive(Serialize)]
/// # pub struct User;
/// #
/// enum License {
/// Base,
/// }
///
/// impl AsRef<str> for License {
/// fn as_ref(&self) -> &str {
/// match self {
/// License::Base => "gts.x.core.lic.feat.v1~x.core.global.base.v1",
/// }
/// }
/// }
///
/// impl LicenseFeature for License {}
///
/// #
/// # fn register_rest(
/// # router: axum::Router,
/// # api: &dyn modkit::api::OpenApiRegistry,
/// # ) -> anyhow::Result<axum::Router> {
/// let router = OperationBuilder::get("/users-info/v1/users")
/// .authenticated()
/// .require_license_features::<License>([])
/// .handler(list_users_handler)
/// .json_response(axum::http::StatusCode::OK, "List of users")
/// .register(router, api);
/// # Ok(router)
/// # }
///
/// # async fn list_users_handler() -> Json<Vec<User>> {
/// # unimplemented!()
/// # }
/// ```
pub fn authenticated(mut self) -> OperationBuilder<H, R, S, AuthSet, L> {
self.spec.authenticated = true;
self.spec.is_public = false;
OperationBuilder {
spec: self.spec,
method_router: self.method_router,
_has_handler: self._has_handler,
_has_response: self._has_response,
_state: self._state,
_auth_state: PhantomData,
_license_state: self._license_state,
}
}
/// Mark this route as public (no authentication required).
///
/// This explicitly opts out of the `require_auth_by_default` setting.
/// This method transitions from `AuthNotSet` to `AuthSet` state.
///
/// # Example
/// ```rust
/// # use axum::Router;
/// # use http::StatusCode;
/// # use modkit::api::{
/// # openapi_registry::OpenApiRegistryImpl,
/// # operation_builder::OperationBuilder,
/// # };
/// # async fn health_check() -> &'static str { "OK" }
/// # let registry = OpenApiRegistryImpl::new();
/// # let router: Router<()> = Router::new();
/// let router = OperationBuilder::get("/users-info/v1/health")
/// .public()
/// .handler(health_check)
/// .json_response(StatusCode::OK, "OK")
/// .register(router, ®istry);
/// # let _ = router;
/// ```
pub fn public(mut self) -> OperationBuilder<H, R, S, AuthSet, LicenseSet> {
self.spec.is_public = true;
self.spec.authenticated = false;
OperationBuilder {
spec: self.spec,
method_router: self.method_router,
_has_handler: self._has_handler,
_has_response: self._has_response,
_state: self._state,
_auth_state: PhantomData,
_license_state: PhantomData,
}
}
}
// -------------------------------------------------------------------------------------------------
// Handler setting — transitions Missing -> Present for handler
// -------------------------------------------------------------------------------------------------
impl<R, S, A, L> OperationBuilder<Missing, R, S, A, L>
where
S: Clone + Send + Sync + 'static,
A: AuthState,
L: LicenseState,
{
/// Set the handler for this operation (function handlers are recommended).
///
/// This transitions the builder from `Missing` to `Present` handler state.
pub fn handler<F, T>(self, h: F) -> OperationBuilder<Present, R, S, A, L>
where
F: Handler<T, S> + Clone + Send + 'static,
T: 'static,
{
let method_router = match self.spec.method {
Method::GET => axum::routing::get(h),
Method::POST => axum::routing::post(h),
Method::PUT => axum::routing::put(h),
Method::DELETE => axum::routing::delete(h),
Method::PATCH => axum::routing::patch(h),
_ => axum::routing::any(|| async { axum::http::StatusCode::METHOD_NOT_ALLOWED }),
};
OperationBuilder {
spec: self.spec,
method_router, // concrete MethodRouter<S> in Present state
_has_handler: PhantomData::<Present>,
_has_response: self._has_response,
_state: self._state,
_auth_state: self._auth_state,
_license_state: self._license_state,
}
}
/// Alternative path: provide a pre-composed `MethodRouter<S>` yourself
/// (useful to attach per-route middleware/layers).
pub fn method_router(self, mr: MethodRouter<S>) -> OperationBuilder<Present, R, S, A, L> {
OperationBuilder {
spec: self.spec,
method_router: mr, // concrete MethodRouter<S> in Present state
_has_handler: PhantomData::<Present>,
_has_response: self._has_response,
_state: self._state,
_auth_state: self._auth_state,
_license_state: self._license_state,
}
}
}
// -------------------------------------------------------------------------------------------------
// Response setting — transitions Missing -> Present for response (first response)
// -------------------------------------------------------------------------------------------------
impl<H, S, A, L> OperationBuilder<H, Missing, S, A, L>
where
H: HandlerSlot<S>,
A: AuthState,
L: LicenseState,
{
/// Add a raw response spec (transitions from Missing to Present).
pub fn response(mut self, resp: ResponseSpec) -> OperationBuilder<H, Present, S, A, L> {
self.spec.responses.push(resp);
OperationBuilder {
spec: self.spec,
method_router: self.method_router,
_has_handler: self._has_handler,
_has_response: PhantomData::<Present>,
_state: self._state,
_auth_state: self._auth_state,
_license_state: self._license_state,
}
}
/// Add a JSON response (transitions from Missing to Present).
pub fn json_response(
mut self,
status: http::StatusCode,
description: impl Into<String>,
) -> OperationBuilder<H, Present, S, A, L> {
self.spec.responses.push(ResponseSpec {
status: status.as_u16(),
content_type: "application/json",
description: description.into(),
schema_name: None,
});
OperationBuilder {
spec: self.spec,
method_router: self.method_router,
_has_handler: self._has_handler,
_has_response: PhantomData::<Present>,
_state: self._state,
_auth_state: self._auth_state,
_license_state: self._license_state,
}
}
/// Add a JSON response with a registered schema (transitions from Missing to Present).
pub fn json_response_with_schema<T>(
mut self,
registry: &dyn OpenApiRegistry,
status: http::StatusCode,
description: impl Into<String>,
) -> OperationBuilder<H, Present, S, A, L>
where
T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
{
let name = ensure_schema::<T>(registry);
self.spec.responses.push(ResponseSpec {
status: status.as_u16(),
content_type: "application/json",
description: description.into(),
schema_name: Some(name),
});
OperationBuilder {
spec: self.spec,
method_router: self.method_router,
_has_handler: self._has_handler,
_has_response: PhantomData::<Present>,
_state: self._state,
_auth_state: self._auth_state,
_license_state: self._license_state,
}
}
/// Add a text response with a custom content type (transitions from Missing to Present).
///
/// # Arguments
/// * `status` - HTTP status code
/// * `description` - Description of the response
/// * `content_type` - **Pure media type without parameters** (e.g., `"text/plain"`, `"text/markdown"`)
///
/// # Important
/// The `content_type` must be a pure media type **without parameters** like `; charset=utf-8`.
/// `OpenAPI` media type keys cannot include parameters. Use `"text/markdown"` instead of
/// `"text/markdown; charset=utf-8"`. Actual HTTP response headers in handlers should still
/// include the charset parameter.
pub fn text_response(
mut self,
status: http::StatusCode,
description: impl Into<String>,
content_type: &'static str,
) -> OperationBuilder<H, Present, S, A, L> {
self.spec.responses.push(ResponseSpec {
status: status.as_u16(),
content_type,
description: description.into(),
schema_name: None,
});
OperationBuilder {
spec: self.spec,
method_router: self.method_router,
_has_handler: self._has_handler,
_has_response: PhantomData::<Present>,
_state: self._state,
_auth_state: self._auth_state,
_license_state: self._license_state,
}
}
/// Add an HTML response (transitions from Missing to Present).
pub fn html_response(
mut self,
status: http::StatusCode,
description: impl Into<String>,
) -> OperationBuilder<H, Present, S, A, L> {
self.spec.responses.push(ResponseSpec {
status: status.as_u16(),
content_type: "text/html",
description: description.into(),
schema_name: None,
});
OperationBuilder {
spec: self.spec,
method_router: self.method_router,
_has_handler: self._has_handler,
_has_response: PhantomData::<Present>,
_state: self._state,
_auth_state: self._auth_state,
_license_state: self._license_state,
}
}
/// Add an RFC 9457 `application/problem+json` response (transitions from Missing to Present).
pub fn problem_response(
mut self,
registry: &dyn OpenApiRegistry,
status: http::StatusCode,
description: impl Into<String>,
) -> OperationBuilder<H, Present, S, A, L> {
// Ensure `Problem` schema is registered in components
let problem_name = ensure_schema::<crate::api::problem::Problem>(registry);
self.spec.responses.push(ResponseSpec {
status: status.as_u16(),
content_type: problem::APPLICATION_PROBLEM_JSON,
description: description.into(),
schema_name: Some(problem_name),
});
OperationBuilder {
spec: self.spec,
method_router: self.method_router,
_has_handler: self._has_handler,
_has_response: PhantomData::<Present>,
_state: self._state,
_auth_state: self._auth_state,
_license_state: self._license_state,
}
}
/// First response: SSE stream of JSON events (`text/event-stream`).
pub fn sse_json<T>(
mut self,
openapi: &dyn OpenApiRegistry,
description: impl Into<String>,
) -> OperationBuilder<H, Present, S, A, L>
where
T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
{
let name = ensure_schema::<T>(openapi);
self.spec.responses.push(ResponseSpec {
status: http::StatusCode::OK.as_u16(),
content_type: "text/event-stream",
description: description.into(),
schema_name: Some(name),
});
OperationBuilder {
spec: self.spec,
method_router: self.method_router,
_has_handler: self._has_handler,
_has_response: PhantomData::<Present>,
_state: self._state,
_auth_state: self._auth_state,
_license_state: self._license_state,
}
}
}
// -------------------------------------------------------------------------------------------------
// Additional responses — for Present response state (additional responses)
// -------------------------------------------------------------------------------------------------
impl<H, S, A, L> OperationBuilder<H, Present, S, A, L>
where
H: HandlerSlot<S>,
A: AuthState,
L: LicenseState,
{
/// Add a JSON response (additional).
pub fn json_response(
mut self,
status: http::StatusCode,
description: impl Into<String>,
) -> Self {
self.spec.responses.push(ResponseSpec {
status: status.as_u16(),
content_type: "application/json",
description: description.into(),
schema_name: None,
});
self
}
/// Add a JSON response with a registered schema (additional).
pub fn json_response_with_schema<T>(
mut self,
registry: &dyn OpenApiRegistry,
status: http::StatusCode,
description: impl Into<String>,
) -> Self
where
T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
{
let name = ensure_schema::<T>(registry);
self.spec.responses.push(ResponseSpec {
status: status.as_u16(),
content_type: "application/json",
description: description.into(),
schema_name: Some(name),
});
self
}
/// Add a text response with a custom content type (additional).
///
/// # Arguments
/// * `status` - HTTP status code
/// * `description` - Description of the response
/// * `content_type` - **Pure media type without parameters** (e.g., `"text/plain"`, `"text/markdown"`)
///
/// # Important
/// The `content_type` must be a pure media type **without parameters** like `; charset=utf-8`.
/// `OpenAPI` media type keys cannot include parameters. Use `"text/markdown"` instead of
/// `"text/markdown; charset=utf-8"`. Actual HTTP response headers in handlers should still
/// include the charset parameter.
pub fn text_response(
mut self,
status: http::StatusCode,
description: impl Into<String>,
content_type: &'static str,
) -> Self {
self.spec.responses.push(ResponseSpec {
status: status.as_u16(),
content_type,
description: description.into(),
schema_name: None,
});
self
}
/// Add an HTML response (additional).
pub fn html_response(
mut self,
status: http::StatusCode,
description: impl Into<String>,
) -> Self {
self.spec.responses.push(ResponseSpec {
status: status.as_u16(),
content_type: "text/html",
description: description.into(),
schema_name: None,
});
self
}
/// Add an additional RFC 9457 `application/problem+json` response.
pub fn problem_response(
mut self,
registry: &dyn OpenApiRegistry,
status: http::StatusCode,
description: impl Into<String>,
) -> Self {
let problem_name = ensure_schema::<crate::api::problem::Problem>(registry);
self.spec.responses.push(ResponseSpec {
status: status.as_u16(),
content_type: problem::APPLICATION_PROBLEM_JSON,
description: description.into(),
schema_name: Some(problem_name),
});
self
}
/// Additional SSE response (if the operation already has a response).
pub fn sse_json<T>(
mut self,
openapi: &dyn OpenApiRegistry,
description: impl Into<String>,
) -> Self
where
T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
{
let name = ensure_schema::<T>(openapi);
self.spec.responses.push(ResponseSpec {
status: http::StatusCode::OK.as_u16(),
content_type: "text/event-stream",
description: description.into(),
schema_name: Some(name),
});
self
}
/// Add standard error responses (400, 401, 403, 404, 409, 422, 429, 500).
///
/// All responses reference the shared Problem schema (RFC 9457) for consistent
/// error handling across your API. This is the recommended way to declare
/// common error responses without repeating boilerplate.
///
/// # Example
///
/// ```rust
/// # use axum::Router;
/// # use http::StatusCode;
/// # use modkit::api::{
/// # openapi_registry::OpenApiRegistryImpl,
/// # operation_builder::OperationBuilder,
/// # };
/// # async fn list_users() -> &'static str { "[]" }
/// # let registry = OpenApiRegistryImpl::new();
/// # let router: Router<()> = Router::new();
/// let op = OperationBuilder::get("/user-info/v1/users")
/// .public()
/// .handler(list_users)
/// .json_response(StatusCode::OK, "List of users")
/// .standard_errors(®istry);
///
/// let router = op.register(router, ®istry);
/// # let _ = router;
/// ```
///
/// This adds the following error responses:
/// - 400 Bad Request
/// - 401 Unauthorized
/// - 403 Forbidden
/// - 404 Not Found
/// - 409 Conflict
/// - 422 Unprocessable Entity
/// - 429 Too Many Requests
/// - 500 Internal Server Error
pub fn standard_errors(mut self, registry: &dyn OpenApiRegistry) -> Self {
use http::StatusCode;
let problem_name = ensure_schema::<crate::api::problem::Problem>(registry);
let standard_errors = [
(StatusCode::BAD_REQUEST, "Bad Request"),
(StatusCode::UNAUTHORIZED, "Unauthorized"),
(StatusCode::FORBIDDEN, "Forbidden"),
(StatusCode::NOT_FOUND, "Not Found"),
(StatusCode::CONFLICT, "Conflict"),
(StatusCode::UNPROCESSABLE_ENTITY, "Unprocessable Entity"),
(StatusCode::TOO_MANY_REQUESTS, "Too Many Requests"),
(StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error"),
];
for (status, description) in standard_errors {
self.spec.responses.push(ResponseSpec {
status: status.as_u16(),
content_type: problem::APPLICATION_PROBLEM_JSON,
description: description.to_owned(),
schema_name: Some(problem_name.clone()),
});
}
self
}
/// Add 422 validation error response using `ValidationError` schema.
///
/// This method adds a specific 422 Unprocessable Entity response that uses
/// the `ValidationError` schema instead of the generic Problem schema. Use this
/// for endpoints that perform input validation and need structured error details.
///
/// # Example
///
/// ```rust
/// # use axum::Router;
/// # use http::StatusCode;
/// # use modkit::api::{
/// # openapi_registry::OpenApiRegistryImpl,
/// # operation_builder::OperationBuilder,
/// # };
/// # use serde::{Deserialize, Serialize};
/// # use utoipa::ToSchema;
/// #
/// #[modkit_macros::api_dto(request)]
/// struct CreateUserRequest {
/// email: String,
/// }
///
/// # async fn create_user() -> &'static str { "created" }
/// # let registry = OpenApiRegistryImpl::new();
/// # let router: Router<()> = Router::new();
/// let op = OperationBuilder::post("/users-info/v1/users")
/// .public()
/// .handler(create_user)
/// .json_request::<CreateUserRequest>(®istry, "User data")
/// .json_response(StatusCode::CREATED, "User created")
/// .with_422_validation_error(®istry);
///
/// let router = op.register(router, ®istry);
/// # let _ = router;
/// ```
pub fn with_422_validation_error(mut self, registry: &dyn OpenApiRegistry) -> Self {
let validation_error_name =
ensure_schema::<crate::api::problem::ValidationErrorResponse>(registry);
self.spec.responses.push(ResponseSpec {
status: http::StatusCode::UNPROCESSABLE_ENTITY.as_u16(),
content_type: problem::APPLICATION_PROBLEM_JSON,
description: "Validation Error".to_owned(),
schema_name: Some(validation_error_name),
});
self
}
/// Add a 400 Bad Request error response.
///
/// This is a convenience wrapper around `problem_response`.
pub fn error_400(self, registry: &dyn OpenApiRegistry) -> Self {
self.problem_response(registry, http::StatusCode::BAD_REQUEST, "Bad Request")
}
/// Add a 401 Unauthorized error response.
///
/// This is a convenience wrapper around `problem_response`.
pub fn error_401(self, registry: &dyn OpenApiRegistry) -> Self {
self.problem_response(registry, http::StatusCode::UNAUTHORIZED, "Unauthorized")
}
/// Add a 403 Forbidden error response.
///
/// This is a convenience wrapper around `problem_response`.
pub fn error_403(self, registry: &dyn OpenApiRegistry) -> Self {
self.problem_response(registry, http::StatusCode::FORBIDDEN, "Forbidden")
}
/// Add a 404 Not Found error response.
///
/// This is a convenience wrapper around `problem_response`.
pub fn error_404(self, registry: &dyn OpenApiRegistry) -> Self {
self.problem_response(registry, http::StatusCode::NOT_FOUND, "Not Found")
}
/// Add a 409 Conflict error response.
///
/// This is a convenience wrapper around `problem_response`.
pub fn error_409(self, registry: &dyn OpenApiRegistry) -> Self {
self.problem_response(registry, http::StatusCode::CONFLICT, "Conflict")
}
/// Add a 415 Unsupported Media Type error response.
///
/// This is a convenience wrapper around `problem_response`.
pub fn error_415(self, registry: &dyn OpenApiRegistry) -> Self {
self.problem_response(
registry,
http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
"Unsupported Media Type",
)
}
/// Add a 422 Unprocessable Entity error response.
///
/// This is a convenience wrapper around `problem_response`.
pub fn error_422(self, registry: &dyn OpenApiRegistry) -> Self {
self.problem_response(
registry,
http::StatusCode::UNPROCESSABLE_ENTITY,
"Unprocessable Entity",
)
}
/// Add a 429 Too Many Requests error response.
///
/// This is a convenience wrapper around `problem_response`.
pub fn error_429(self, registry: &dyn OpenApiRegistry) -> Self {
self.problem_response(
registry,
http::StatusCode::TOO_MANY_REQUESTS,
"Too Many Requests",
)
}
/// Add a 500 Internal Server Error response.
///
/// This is a convenience wrapper around `problem_response`.
pub fn error_500(self, registry: &dyn OpenApiRegistry) -> Self {
self.problem_response(
registry,
http::StatusCode::INTERNAL_SERVER_ERROR,
"Internal Server Error",
)
}
}
// -------------------------------------------------------------------------------------------------
// Registration — only available when handler, response, AND auth are all set
// -------------------------------------------------------------------------------------------------
impl<S> OperationBuilder<Present, Present, S, AuthSet, LicenseSet>
where
S: Clone + Send + Sync + 'static,
{
/// Register the operation with the router and `OpenAPI` registry.
///
/// This method is only available when:
/// - Handler is present
/// - Response is present
/// - Auth requirement is set (either `authenticated` or `public`)
///
/// All conditions are enforced at compile time by the type system.
pub fn register(self, router: Router<S>, openapi: &dyn OpenApiRegistry) -> Router<S> {
// Inform the OpenAPI registry (the implementation will translate OperationSpec
// into an OpenAPI Operation + RequestBody + Responses with component refs).
openapi.register_operation(&self.spec);
// In Present state the method_router is guaranteed to be a real MethodRouter<S>.
router.route(&self.spec.path, self.method_router)
}
}
// -------------------------------------------------------------------------------------------------
// Tests
// -------------------------------------------------------------------------------------------------
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
use super::*;
use axum::Json;
// Mock registry for testing: stores operations; records schema names
struct MockRegistry {
operations: std::sync::Mutex<Vec<OperationSpec>>,
schemas: std::sync::Mutex<Vec<String>>,
}
impl MockRegistry {
fn new() -> Self {
Self {
operations: std::sync::Mutex::new(Vec::new()),
schemas: std::sync::Mutex::new(Vec::new()),
}
}
}
enum TestLicenseFeatures {
FeatureA,
FeatureB,
}
impl AsRef<str> for TestLicenseFeatures {
fn as_ref(&self) -> &str {
match self {
TestLicenseFeatures::FeatureA => "feature_a",
TestLicenseFeatures::FeatureB => "feature_b",
}
}
}
impl LicenseFeature for TestLicenseFeatures {}
impl OpenApiRegistry for MockRegistry {
fn register_operation(&self, spec: &OperationSpec) {
if let Ok(mut ops) = self.operations.lock() {
ops.push(spec.clone());
}
}
fn ensure_schema_raw(
&self,
name: &str,
_schemas: Vec<(
String,
utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
)>,
) -> String {
let name = name.to_owned();
if let Ok(mut s) = self.schemas.lock() {
s.push(name.clone());
}
name
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
async fn test_handler() -> Json<serde_json::Value> {
Json(serde_json::json!({"status": "ok"}))
}
#[modkit_macros::api_dto(request)]
struct SampleDtoRequest;
#[modkit_macros::api_dto(response)]
struct SampleDtoResponse;
#[test]
fn builder_descriptive_methods() {
let builder = OperationBuilder::<Missing, Missing, (), AuthNotSet>::get("/tests/v1/test")
.operation_id("test.get")
.summary("Test endpoint")
.description("A test endpoint for validation")
.tag("test")
.path_param("id", "Test ID");
assert_eq!(builder.spec.method, Method::GET);
assert_eq!(builder.spec.path, "/tests/v1/test");
assert_eq!(builder.spec.operation_id, Some("test.get".to_owned()));
assert_eq!(builder.spec.summary, Some("Test endpoint".to_owned()));
assert_eq!(
builder.spec.description,
Some("A test endpoint for validation".to_owned())
);
assert_eq!(builder.spec.tags, vec!["test"]);
assert_eq!(builder.spec.params.len(), 1);
}
#[tokio::test]
async fn builder_with_request_response_and_handler() {
let registry = MockRegistry::new();
let router = Router::new();
let _router = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/test")
.summary("Test endpoint")
.json_request::<SampleDtoRequest>(®istry, "optional body") // registers schema
.public()
.handler(test_handler)
.json_response_with_schema::<SampleDtoResponse>(
®istry,
http::StatusCode::OK,
"Success response",
) // registers schema
.register(router, ®istry);
// Verify that the operation was registered
let ops = registry.operations.lock().unwrap();
assert_eq!(ops.len(), 1);
let op = &ops[0];
assert_eq!(op.method, Method::POST);
assert_eq!(op.path, "/tests/v1/test");
assert!(op.request_body.is_some());
assert!(op.request_body.as_ref().unwrap().required);
assert_eq!(op.responses.len(), 1);
assert_eq!(op.responses[0].status, 200);
// Verify schemas recorded
let schemas = registry.schemas.lock().unwrap();
assert!(!schemas.is_empty());
}
#[test]
fn convenience_constructors() {
let get_builder =
OperationBuilder::<Missing, Missing, (), AuthNotSet>::get("/tests/v1/get");
assert_eq!(get_builder.spec.method, Method::GET);
assert_eq!(get_builder.spec.path, "/tests/v1/get");
let post_builder =
OperationBuilder::<Missing, Missing, (), AuthNotSet>::post("/tests/v1/post");
assert_eq!(post_builder.spec.method, Method::POST);
assert_eq!(post_builder.spec.path, "/tests/v1/post");
let put_builder =
OperationBuilder::<Missing, Missing, (), AuthNotSet>::put("/tests/v1/put");
assert_eq!(put_builder.spec.method, Method::PUT);
assert_eq!(put_builder.spec.path, "/tests/v1/put");
let delete_builder =
OperationBuilder::<Missing, Missing, (), AuthNotSet>::delete("/tests/v1/delete");
assert_eq!(delete_builder.spec.method, Method::DELETE);
assert_eq!(delete_builder.spec.path, "/tests/v1/delete");
let patch_builder =
OperationBuilder::<Missing, Missing, (), AuthNotSet>::patch("/tests/v1/patch");
assert_eq!(patch_builder.spec.method, Method::PATCH);
assert_eq!(patch_builder.spec.path, "/tests/v1/patch");
}
#[test]
fn normalize_to_axum_path_should_normalize() {
// Axum 0.8+ uses {param} syntax, same as OpenAPI
assert_eq!(
normalize_to_axum_path("/tests/v1/users/{id}"),
"/tests/v1/users/{id}"
);
assert_eq!(
normalize_to_axum_path("/tests/v1/projects/{project_id}/items/{item_id}"),
"/tests/v1/projects/{project_id}/items/{item_id}"
);
assert_eq!(
normalize_to_axum_path("/tests/v1/simple"),
"/tests/v1/simple"
);
assert_eq!(
normalize_to_axum_path("/tests/v1/users/{id}/edit"),
"/tests/v1/users/{id}/edit"
);
}
#[test]
fn axum_to_openapi_path_should_convert() {
// Regular parameters stay the same
assert_eq!(
axum_to_openapi_path("/tests/v1/users/{id}"),
"/tests/v1/users/{id}"
);
assert_eq!(
axum_to_openapi_path("/tests/v1/projects/{project_id}/items/{item_id}"),
"/tests/v1/projects/{project_id}/items/{item_id}"
);
assert_eq!(axum_to_openapi_path("/tests/v1/simple"), "/tests/v1/simple");
// Wildcards: Axum uses {*path}, OpenAPI uses {path}
assert_eq!(
axum_to_openapi_path("/tests/v1/static/{*path}"),
"/tests/v1/static/{path}"
);
assert_eq!(
axum_to_openapi_path("/tests/v1/files/{*filepath}"),
"/tests/v1/files/{filepath}"
);
}
#[test]
fn path_normalization_in_constructors() {
// Test that paths are kept as-is (Axum 0.8+ uses same {param} syntax)
let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/users/{id}");
assert_eq!(builder.spec.path, "/tests/v1/users/{id}");
let builder = OperationBuilder::<Missing, Missing, ()>::post(
"/tests/v1/projects/{project_id}/items/{item_id}",
);
assert_eq!(
builder.spec.path,
"/tests/v1/projects/{project_id}/items/{item_id}"
);
// Simple paths remain unchanged
let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/simple");
assert_eq!(builder.spec.path, "/tests/v1/simple");
}
#[test]
fn standard_errors() {
let registry = MockRegistry::new();
let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
.public()
.handler(test_handler)
.json_response(http::StatusCode::OK, "Success")
.standard_errors(®istry);
// Should have 1 success response + 8 standard error responses
assert_eq!(builder.spec.responses.len(), 9);
// Check that all standard error status codes are present
let statuses: Vec<u16> = builder.spec.responses.iter().map(|r| r.status).collect();
assert!(statuses.contains(&200)); // success response
assert!(statuses.contains(&400));
assert!(statuses.contains(&401));
assert!(statuses.contains(&403));
assert!(statuses.contains(&404));
assert!(statuses.contains(&409));
assert!(statuses.contains(&422));
assert!(statuses.contains(&429));
assert!(statuses.contains(&500));
// All error responses should use Problem content type
let error_responses: Vec<_> = builder
.spec
.responses
.iter()
.filter(|r| r.status >= 400)
.collect();
for resp in error_responses {
assert_eq!(
resp.content_type,
crate::api::problem::APPLICATION_PROBLEM_JSON
);
assert!(resp.schema_name.is_some());
}
}
#[test]
fn authenticated() {
let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
.authenticated()
.handler(test_handler)
.json_response(http::StatusCode::OK, "Success");
assert!(builder.spec.authenticated);
assert!(!builder.spec.is_public);
}
#[test]
fn require_license_features_none() {
let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
.authenticated()
.require_license_features::<TestLicenseFeatures>([])
.handler(|| async {})
.json_response(http::StatusCode::OK, "OK");
assert!(builder.spec.license_requirement.is_none());
}
#[test]
fn no_license_required_transitions_and_allows_register() {
let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
.authenticated()
.no_license_required()
.handler(|| async {})
.json_response(http::StatusCode::OK, "OK");
assert!(builder.spec.license_requirement.is_none());
assert!(!builder.spec.is_public);
}
#[test]
fn require_license_features_one() {
let feature = TestLicenseFeatures::FeatureA;
let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
.authenticated()
.require_license_features([&feature])
.handler(|| async {})
.json_response(http::StatusCode::OK, "OK");
let license_req = builder
.spec
.license_requirement
.as_ref()
.expect("Should have license requirement");
assert_eq!(license_req.license_names, vec!["feature_a".to_owned()]);
}
#[test]
fn require_license_features_many() {
let feature_a = TestLicenseFeatures::FeatureA;
let feature_b = TestLicenseFeatures::FeatureB;
let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
.authenticated()
.require_license_features([&feature_a, &feature_b])
.handler(|| async {})
.json_response(http::StatusCode::OK, "OK");
let license_req = builder
.spec
.license_requirement
.as_ref()
.expect("Should have license requirement");
assert_eq!(
license_req.license_names,
vec!["feature_a".to_owned(), "feature_b".to_owned()]
);
}
#[tokio::test]
async fn public_does_not_require_license_features_and_can_register() {
let registry = MockRegistry::new();
let router = Router::new();
let _router = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
.public()
.handler(test_handler)
.json_response(http::StatusCode::OK, "Success")
.register(router, ®istry);
let ops = registry.operations.lock().unwrap();
assert_eq!(ops.len(), 1);
assert!(ops[0].license_requirement.is_none());
}
#[test]
fn with_422_validation_error() {
let registry = MockRegistry::new();
let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/test")
.public()
.handler(test_handler)
.json_response(http::StatusCode::CREATED, "Created")
.with_422_validation_error(®istry);
// Should have success response + validation error response
assert_eq!(builder.spec.responses.len(), 2);
let validation_response = builder
.spec
.responses
.iter()
.find(|r| r.status == 422)
.expect("Should have 422 response");
assert_eq!(validation_response.description, "Validation Error");
assert_eq!(
validation_response.content_type,
crate::api::problem::APPLICATION_PROBLEM_JSON
);
assert!(validation_response.schema_name.is_some());
}
#[test]
fn allow_content_types_with_existing_request_body() {
let registry = MockRegistry::new();
let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/test")
.json_request::<SampleDtoRequest>(®istry, "Test request")
.allow_content_types(&["application/json", "application/xml"])
.public()
.handler(test_handler)
.json_response(http::StatusCode::OK, "Success");
// allowed_content_types should be on OperationSpec, not RequestBodySpec
assert!(builder.spec.request_body.is_some());
assert!(builder.spec.allowed_request_content_types.is_some());
let allowed = builder.spec.allowed_request_content_types.as_ref().unwrap();
assert_eq!(allowed.len(), 2);
assert!(allowed.contains(&"application/json"));
assert!(allowed.contains(&"application/xml"));
}
#[test]
fn allow_content_types_without_existing_request_body() {
let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/test")
.allow_content_types(&["multipart/form-data"])
.public()
.handler(test_handler)
.json_response(http::StatusCode::OK, "Success");
// Should NOT create synthetic request body, only set allowed_request_content_types
assert!(builder.spec.request_body.is_none());
assert!(builder.spec.allowed_request_content_types.is_some());
let allowed = builder.spec.allowed_request_content_types.as_ref().unwrap();
assert_eq!(allowed.len(), 1);
assert!(allowed.contains(&"multipart/form-data"));
}
#[test]
fn allow_content_types_can_be_chained() {
let registry = MockRegistry::new();
let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/test")
.operation_id("test.post")
.summary("Test endpoint")
.json_request::<SampleDtoRequest>(®istry, "Test request")
.allow_content_types(&["application/json"])
.public()
.handler(test_handler)
.json_response(http::StatusCode::OK, "Success")
.problem_response(
®istry,
http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
"Unsupported Media Type",
);
assert_eq!(builder.spec.operation_id, Some("test.post".to_owned()));
assert!(builder.spec.request_body.is_some());
assert!(builder.spec.allowed_request_content_types.is_some());
assert_eq!(builder.spec.responses.len(), 2);
}
#[test]
fn multipart_file_request() {
let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/upload")
.operation_id("test.upload")
.summary("Upload file")
.multipart_file_request("file", Some("Upload a file"))
.public()
.handler(test_handler)
.json_response(http::StatusCode::OK, "Success");
// Should set request body with multipart/form-data
assert!(builder.spec.request_body.is_some());
let rb = builder.spec.request_body.as_ref().unwrap();
assert_eq!(rb.content_type, "multipart/form-data");
assert!(rb.description.is_some());
assert!(rb.description.as_ref().unwrap().contains("file"));
assert!(rb.required);
// Should use MultipartFile schema variant
assert_eq!(
rb.schema,
RequestBodySchema::MultipartFile {
field_name: "file".to_owned()
}
);
// Should also set allowed_request_content_types
assert!(builder.spec.allowed_request_content_types.is_some());
let allowed = builder.spec.allowed_request_content_types.as_ref().unwrap();
assert_eq!(allowed.len(), 1);
assert!(allowed.contains(&"multipart/form-data"));
}
#[test]
fn multipart_file_request_without_description() {
let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/upload")
.multipart_file_request("file", None)
.public()
.handler(test_handler)
.json_response(http::StatusCode::OK, "Success");
assert!(builder.spec.request_body.is_some());
let rb = builder.spec.request_body.as_ref().unwrap();
assert_eq!(rb.content_type, "multipart/form-data");
assert!(rb.description.is_none());
assert_eq!(
rb.schema,
RequestBodySchema::MultipartFile {
field_name: "file".to_owned()
}
);
}
#[test]
fn octet_stream_request() {
let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/upload")
.operation_id("test.upload")
.summary("Upload raw file")
.octet_stream_request(Some("Raw file bytes"))
.public()
.handler(test_handler)
.json_response(http::StatusCode::OK, "Success");
// Should set request body with application/octet-stream
assert!(builder.spec.request_body.is_some());
let rb = builder.spec.request_body.as_ref().unwrap();
assert_eq!(rb.content_type, "application/octet-stream");
assert_eq!(rb.description, Some("Raw file bytes".to_owned()));
assert!(rb.required);
// Should use Binary schema variant
assert_eq!(rb.schema, RequestBodySchema::Binary);
// Should also set allowed_request_content_types
assert!(builder.spec.allowed_request_content_types.is_some());
let allowed = builder.spec.allowed_request_content_types.as_ref().unwrap();
assert_eq!(allowed.len(), 1);
assert!(allowed.contains(&"application/octet-stream"));
}
#[test]
fn octet_stream_request_without_description() {
let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/upload")
.octet_stream_request(None)
.public()
.handler(test_handler)
.json_response(http::StatusCode::OK, "Success");
assert!(builder.spec.request_body.is_some());
let rb = builder.spec.request_body.as_ref().unwrap();
assert_eq!(rb.content_type, "application/octet-stream");
assert!(rb.description.is_none());
assert_eq!(rb.schema, RequestBodySchema::Binary);
}
#[test]
fn json_request_uses_ref_schema() {
let registry = MockRegistry::new();
let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/test")
.json_request::<SampleDtoRequest>(®istry, "Test request body")
.public()
.handler(test_handler)
.json_response(http::StatusCode::OK, "Success");
assert!(builder.spec.request_body.is_some());
let rb = builder.spec.request_body.as_ref().unwrap();
assert_eq!(rb.content_type, "application/json");
// Should use Ref schema variant with the registered schema name
match &rb.schema {
RequestBodySchema::Ref { schema_name } => {
assert!(!schema_name.is_empty());
}
_ => panic!("Expected RequestBodySchema::Ref for JSON request"),
}
}
#[test]
fn response_content_types_must_not_contain_parameters() {
// This test ensures OpenAPI correctness: media type keys cannot include
// parameters like "; charset=utf-8"
let registry = MockRegistry::new();
let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/test")
.operation_id("test.content_type_purity")
.summary("Test response content types")
.json_request::<SampleDtoRequest>(®istry, "Test")
.public()
.handler(test_handler)
.text_response(http::StatusCode::OK, "Text", "text/plain")
.text_response(http::StatusCode::OK, "Markdown", "text/markdown")
.html_response(http::StatusCode::OK, "HTML")
.json_response(http::StatusCode::OK, "JSON")
.problem_response(®istry, http::StatusCode::BAD_REQUEST, "Error");
// Verify no response content_type contains semicolon (parameter separator)
for response in &builder.spec.responses {
assert!(
!response.content_type.contains(';'),
"Response content_type '{}' must not contain parameters. \
Use pure media type without charset or other parameters. \
OpenAPI media type keys cannot include parameters.",
response.content_type
);
}
}
}