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
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
//! Barbacane API gateway.
//!
//! Compiles OpenAPI specs into artifacts and runs the data plane server.
use barbacane_lib::{admin, control_plane, hot_reload};
use std::convert::Infallible;
use std::fs::File;
use std::io::BufReader;
use std::net::SocketAddr;
use std::path::Path;
use std::process::ExitCode;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use arc_swap::ArcSwap;
use bytes::Bytes;
use clap::{Parser, Subcommand};
use http_body_util::combinators::BoxBody;
use http_body_util::{BodyExt, Full, StreamBody};
use hyper::body::{Body, Frame, Incoming};
use hyper::header::{HeaderName, HeaderValue};
use hyper::service::service_fn;
use hyper::{Method, Request, Response, StatusCode};
/// Boxed response body type that works for both buffered and streaming responses.
type AnyBody = BoxBody<Bytes, Infallible>;
/// Convert a buffered `Response<Full<Bytes>>` to the unified `Response<AnyBody>`.
fn box_full(r: Response<Full<Bytes>>) -> Response<AnyBody> {
r.map(BoxBody::new)
}
use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
use hyper_util::server::conn::auto;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::ServerConfig;
use tokio::net::TcpListener;
use tokio::sync::watch;
use tokio_rustls::TlsAcceptor;
use uuid::Uuid;
/// Server version for the Server header.
const SERVER_VERSION: &str = concat!("barbacane/", env!("CARGO_PKG_VERSION"));
/// Metric `path` label used for requests that never matched a declared route
/// (unmatched, method-not-allowed, or rejected before routing). Using a fixed
/// sentinel instead of the raw request path keeps Prometheus series cardinality
/// bounded — a scanner hitting random URLs cannot create unbounded time-series.
const UNMATCHED_ROUTE_LABEL: &str = "<unmatched>";
use barbacane_telemetry::MetricsRegistry;
use std::collections::{HashMap, HashSet};
use barbacane_compiler::{
compile_with_manifest, load_manifest, load_plugins, load_routes, load_specs, CompileOptions,
CompiledOperation, Manifest, ProjectManifest,
};
use barbacane_lib::router::{RouteEntry, RouteMatch, Router};
use barbacane_lib::validator::{
OperationValidator, ProblemDetails, RequestLimits, ValidationError2,
};
/// Extract a reason string from a validation error for metrics.
fn validation_error_reason(err: &ValidationError2) -> String {
match err {
ValidationError2::MissingRequiredParameter { .. } => {
"missing_required_parameter".to_string()
}
ValidationError2::InvalidParameter { .. } => "invalid_parameter".to_string(),
ValidationError2::MissingRequiredBody => "missing_required_body".to_string(),
ValidationError2::UnsupportedContentType(_) => "unsupported_content_type".to_string(),
ValidationError2::InvalidBody { .. } => "invalid_body".to_string(),
ValidationError2::BodyTooLarge { .. } => "body_too_large".to_string(),
ValidationError2::TooManyHeaders { .. } => "too_many_headers".to_string(),
ValidationError2::HeaderTooLarge { .. } => "header_too_large".to_string(),
ValidationError2::UriTooLong { .. } => "uri_too_long".to_string(),
}
}
/// Recursively remove all keys starting with "x-barbacane-" from a JSON value.
/// Preserves standard OpenAPI/AsyncAPI fields and the x-sunset extension (RFC 8594).
fn strip_barbacane_keys_recursive(value: &mut serde_json::Value) {
match value {
serde_json::Value::Object(map) => {
// Remove x-barbacane-* keys
map.retain(|k, _| !k.starts_with("x-barbacane-"));
// Recurse into remaining values
for v in map.values_mut() {
strip_barbacane_keys_recursive(v);
}
}
serde_json::Value::Array(arr) => {
for item in arr.iter_mut() {
strip_barbacane_keys_recursive(item);
}
}
_ => {}
}
}
/// Detected spec type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SpecType {
OpenApi,
AsyncApi,
Unknown,
}
/// Detect whether a spec is OpenAPI or AsyncAPI by checking root keys.
fn detect_spec_type(content: &str) -> SpecType {
// Try to parse as YAML (also handles JSON)
let parsed: Result<serde_json::Value, _> = serde_yaml::from_str(content);
match parsed {
Ok(value) => {
if value.get("openapi").is_some() {
SpecType::OpenApi
} else if value.get("asyncapi").is_some() {
SpecType::AsyncApi
} else {
SpecType::Unknown
}
}
Err(_) => SpecType::Unknown,
}
}
/// Merge multiple OpenAPI specs into one.
/// Combines paths, components, and uses the first spec's info as base.
fn merge_openapi_specs(specs: &[(&String, &String)]) -> serde_json::Value {
let mut merged = serde_json::json!({
"openapi": "3.1.0",
"info": {
"title": "Merged API",
"version": "1.0.0"
},
"paths": {},
"components": {
"schemas": {},
"securitySchemes": {},
"parameters": {},
"responses": {},
"headers": {},
"requestBodies": {}
}
});
let mut titles = Vec::new();
for (filename, content) in specs {
let parsed: Option<serde_json::Value> = serde_yaml::from_str(content).ok();
if let Some(mut spec) = parsed {
// Strip barbacane extensions
strip_barbacane_keys_recursive(&mut spec);
// Collect title for merged info
if let Some(title) = spec.pointer("/info/title").and_then(|t| t.as_str()) {
titles.push(title.to_string());
}
// Use first spec's info as base
if titles.len() == 1 {
if let Some(info) = spec.get("info") {
merged["info"] = info.clone();
}
if let Some(version) = spec.get("openapi") {
merged["openapi"] = version.clone();
}
}
// Merge paths
if let Some(paths) = spec.get("paths").and_then(|p| p.as_object()) {
let merged_paths = merged["paths"]
.as_object_mut()
.expect("json macro produces object");
for (path, methods) in paths {
merged_paths.insert(path.clone(), methods.clone());
}
}
// Merge components
if let Some(components) = spec.get("components").and_then(|c| c.as_object()) {
let merged_components = merged["components"]
.as_object_mut()
.expect("json macro produces object");
for (component_type, items) in components {
if let Some(items_obj) = items.as_object() {
let target = merged_components
.entry(component_type.clone())
.or_insert_with(|| serde_json::json!({}));
if let Some(target_obj) = target.as_object_mut() {
for (name, value) in items_obj {
// Prefix with source filename to avoid conflicts
let key = if specs.len() > 1 && target_obj.contains_key(name) {
let base = filename
.trim_end_matches(".yaml")
.trim_end_matches(".json");
format!("{}_{}", base, name)
} else {
name.clone()
};
target_obj.insert(key, value.clone());
}
}
}
}
}
// Merge servers
if let Some(servers) = spec.get("servers").and_then(|s| s.as_array()) {
let merged_servers = merged
.as_object_mut()
.expect("json macro produces object")
.entry("servers")
.or_insert_with(|| serde_json::json!([]));
if let Some(arr) = merged_servers.as_array_mut() {
for server in servers {
if !arr.contains(server) {
arr.push(server.clone());
}
}
}
}
// Merge tags
if let Some(tags) = spec.get("tags").and_then(|t| t.as_array()) {
let merged_tags = merged
.as_object_mut()
.expect("json macro produces object")
.entry("tags")
.or_insert_with(|| serde_json::json!([]));
if let Some(arr) = merged_tags.as_array_mut() {
for tag in tags {
if !arr.contains(tag) {
arr.push(tag.clone());
}
}
}
}
}
}
// Update title if multiple specs were merged
if titles.len() > 1 {
merged["info"]["title"] = serde_json::json!(titles.join(" + "));
}
// Clean up empty component sections
if let Some(components) = merged.get_mut("components").and_then(|c| c.as_object_mut()) {
components.retain(|_, v| v.as_object().is_some_and(|o| !o.is_empty()));
}
if merged
.get("components")
.and_then(|c| c.as_object())
.is_some_and(|o| o.is_empty())
{
merged
.as_object_mut()
.expect("json macro produces object")
.remove("components");
}
merged
}
/// Merge multiple AsyncAPI specs into one.
/// Combines channels, operations, components, and uses the first spec's info as base.
fn merge_asyncapi_specs(specs: &[(&String, &String)]) -> serde_json::Value {
let mut merged = serde_json::json!({
"asyncapi": "3.0.0",
"info": {
"title": "Merged Async API",
"version": "1.0.0"
},
"channels": {},
"operations": {},
"components": {
"schemas": {},
"messages": {},
"securitySchemes": {},
"parameters": {}
}
});
let mut titles = Vec::new();
for (filename, content) in specs {
let parsed: Option<serde_json::Value> = serde_yaml::from_str(content).ok();
if let Some(mut spec) = parsed {
// Strip barbacane extensions
strip_barbacane_keys_recursive(&mut spec);
// Collect title for merged info
if let Some(title) = spec.pointer("/info/title").and_then(|t| t.as_str()) {
titles.push(title.to_string());
}
// Use first spec's info as base
if titles.len() == 1 {
if let Some(info) = spec.get("info") {
merged["info"] = info.clone();
}
if let Some(version) = spec.get("asyncapi") {
merged["asyncapi"] = version.clone();
}
}
// Merge channels
if let Some(channels) = spec.get("channels").and_then(|c| c.as_object()) {
let merged_channels = merged["channels"]
.as_object_mut()
.expect("json macro produces object");
for (name, channel) in channels {
// Prefix with source filename to avoid conflicts
let key = if specs.len() > 1 && merged_channels.contains_key(name) {
let base = filename.trim_end_matches(".yaml").trim_end_matches(".json");
format!("{}_{}", base, name)
} else {
name.clone()
};
merged_channels.insert(key, channel.clone());
}
}
// Merge operations
if let Some(operations) = spec.get("operations").and_then(|o| o.as_object()) {
let merged_ops = merged["operations"]
.as_object_mut()
.expect("json macro produces object");
for (name, op) in operations {
let key = if specs.len() > 1 && merged_ops.contains_key(name) {
let base = filename.trim_end_matches(".yaml").trim_end_matches(".json");
format!("{}_{}", base, name)
} else {
name.clone()
};
merged_ops.insert(key, op.clone());
}
}
// Merge components
if let Some(components) = spec.get("components").and_then(|c| c.as_object()) {
let merged_components = merged["components"]
.as_object_mut()
.expect("json macro produces object");
for (component_type, items) in components {
if let Some(items_obj) = items.as_object() {
let target = merged_components
.entry(component_type.clone())
.or_insert_with(|| serde_json::json!({}));
if let Some(target_obj) = target.as_object_mut() {
for (name, value) in items_obj {
let key = if specs.len() > 1 && target_obj.contains_key(name) {
let base = filename
.trim_end_matches(".yaml")
.trim_end_matches(".json");
format!("{}_{}", base, name)
} else {
name.clone()
};
target_obj.insert(key, value.clone());
}
}
}
}
}
// Merge servers
if let Some(servers) = spec.get("servers").and_then(|s| s.as_object()) {
let merged_servers = merged
.as_object_mut()
.expect("json macro produces object")
.entry("servers")
.or_insert_with(|| serde_json::json!({}));
if let Some(map) = merged_servers.as_object_mut() {
for (name, server) in servers {
if !map.contains_key(name) {
map.insert(name.clone(), server.clone());
}
}
}
}
}
}
// Update title if multiple specs were merged
if titles.len() > 1 {
merged["info"]["title"] = serde_json::json!(titles.join(" + "));
}
// Clean up empty sections
let obj = merged.as_object_mut().expect("json macro produces object");
if obj
.get("channels")
.and_then(|c| c.as_object())
.is_some_and(|c| c.is_empty())
{
obj.remove("channels");
}
if obj
.get("operations")
.and_then(|o| o.as_object())
.is_some_and(|o| o.is_empty())
{
obj.remove("operations");
}
if let Some(components) = obj.get_mut("components").and_then(|c| c.as_object_mut()) {
components.retain(|_, v| v.as_object().is_some_and(|o| !o.is_empty()));
}
if obj
.get("components")
.and_then(|c| c.as_object())
.is_some_and(|o| o.is_empty())
{
obj.remove("components");
}
merged
}
use barbacane_wasm::{
HttpClient, HttpClientConfig, InstancePool, PluginLimits, RateLimiter, ResponseCache,
WasmEngine,
};
#[derive(Parser, Debug)]
#[command(name = "barbacane", about = "Barbacane API gateway", version)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
#[allow(clippy::large_enum_variant)]
enum Commands {
/// Compile OpenAPI spec(s) into a .bca artifact.
Compile {
/// Input spec file(s) (YAML or JSON).
/// If omitted, discovers specs from the manifest's `specs` folder.
#[arg(short, long, num_args = 1..)]
spec: Vec<String>,
/// Output artifact path.
#[arg(short, long)]
output: String,
/// Path to barbacane.yaml manifest.
#[arg(short, long, required = true)]
manifest: String,
/// Allow plaintext HTTP upstream URLs (development only).
#[arg(long)]
allow_plaintext: bool,
/// Git commit SHA for build provenance tracking.
#[arg(long)]
provenance_commit: Option<String>,
/// Build source identifier for provenance (e.g., "ci/github-actions").
#[arg(long)]
provenance_source: Option<String>,
/// Bypass the plugin download cache entirely (no read, no write).
#[arg(long)]
no_cache: bool,
},
/// Validate OpenAPI spec(s) without compiling.
///
/// Checks for spec validity (E1001-E1004) and extension validity (E1010-E1014).
/// E1015 (unknown x-barbacane-* extension) is checked during compile.
/// Does not resolve plugins or produce an artifact.
Validate {
/// Input spec file(s) (YAML or JSON).
#[arg(short, long, required = true, num_args = 1..)]
spec: Vec<String>,
/// Output format (text or json).
#[arg(long, default_value = "text")]
format: String,
},
/// Initialize a new Barbacane project.
///
/// Creates a project directory with barbacane.yaml, spec files, and plugins directory.
Init {
/// Project name (creates a directory with this name).
#[arg(default_value = ".")]
name: String,
/// Template to use: basic (full example) or minimal (bare bones).
#[arg(short, long, default_value = "basic")]
template: String,
/// Download official plugins (mock, http-upstream) from GitHub releases.
#[arg(long)]
fetch_plugins: bool,
},
/// Start a local development server with auto-reload.
///
/// Compiles specs from barbacane.yaml, starts the gateway, watches for
/// file changes, and hot-reloads automatically. Equivalent to running
/// compile + serve in a loop.
Dev {
/// Listen address.
#[arg(long, default_value = "0.0.0.0:8080")]
listen: String,
/// Path to barbacane.yaml manifest.
#[arg(short, long, default_value = "barbacane.yaml")]
manifest: String,
/// Override spec files (uses these instead of the manifest's specs folder).
#[arg(short, long)]
spec: Vec<String>,
/// Log level (error, warn, info, debug, trace).
#[arg(long, default_value = "info")]
log_level: String,
/// Admin API listen address. Set to "off" to disable.
#[arg(long, default_value = "127.0.0.1:8081")]
admin_bind: String,
/// Debounce delay in milliseconds before recompiling after a file change.
#[arg(long, default_value = "300")]
debounce_ms: u64,
},
/// Run the gateway server.
Serve {
/// Path to the .bca artifact file.
#[arg(long)]
artifact: String,
/// Listen address.
#[arg(long, default_value = "0.0.0.0:8080")]
listen: String,
/// Enable development mode (verbose errors, detailed logs).
#[arg(long)]
dev: bool,
/// Log level (error, warn, info, debug, trace).
#[arg(long, default_value = "info")]
log_level: String,
/// Log format (json or pretty).
#[arg(long, default_value = "json")]
log_format: String,
/// OTLP endpoint for telemetry export (e.g., http://localhost:4317).
/// If not set, telemetry is collected locally but not exported.
#[arg(long)]
otlp_endpoint: Option<String>,
/// Trace sampling rate (0.0 to 1.0). Default: 1.0 (100% sampling).
/// Set to 0.0 to disable tracing, 0.1 for 10% sampling, etc.
#[arg(long, default_value = "1.0")]
trace_sampling: f64,
/// Maximum request body size in bytes (default: 1048576 = 1MB).
#[arg(long, default_value = "1048576")]
max_body_size: usize,
/// Maximum number of request headers (default: 100).
#[arg(long, default_value = "100")]
max_headers: usize,
/// Maximum size of a single header in bytes (default: 8192 = 8KB).
#[arg(long, default_value = "8192")]
max_header_size: usize,
/// Maximum URI length in characters (default: 8192 = 8KB).
#[arg(long, default_value = "8192")]
max_uri_length: usize,
/// Allow plaintext HTTP upstream connections (development only).
/// In production, only HTTPS upstreams are allowed.
#[arg(long)]
allow_plaintext_upstream: bool,
/// Path to TLS certificate file (PEM format).
/// If provided, --tls-key must also be specified.
#[arg(long)]
tls_cert: Option<String>,
/// Path to TLS private key file (PEM format).
/// If provided, --tls-cert must also be specified.
#[arg(long)]
tls_key: Option<String>,
/// Minimum TLS version (1.2 or 1.3). Default: 1.2.
/// Use 1.3 for maximum security (modern clients only).
#[arg(long, default_value = "1.2")]
tls_min_version: String,
/// HTTP keep-alive idle timeout in seconds (default: 60).
#[arg(long, default_value = "60")]
keepalive_timeout: u64,
/// Graceful shutdown timeout in seconds (default: 30).
/// After SIGTERM, wait this long for in-flight requests to complete.
#[arg(long, default_value = "30")]
shutdown_timeout: u64,
// Connected mode options (optional)
/// Control plane WebSocket URL (e.g., ws://control:8080/ws/data-plane).
/// When provided, the data plane connects to the control plane for centralized management.
#[arg(long)]
control_plane: Option<String>,
/// Project ID (UUID) for control plane registration.
/// Required if --control-plane is specified.
#[arg(long)]
project_id: Option<String>,
/// API key for control plane authentication.
/// Required if --control-plane is specified.
#[arg(long, env = "BARBACANE_API_KEY")]
api_key: Option<String>,
/// Data plane name for identification in control plane.
#[arg(long)]
data_plane_name: Option<String>,
/// Admin API listen address (health, metrics, provenance).
/// Set to "off" to disable.
#[arg(long, default_value = "127.0.0.1:8081")]
admin_bind: String,
},
}
// =============================================================================
// Hot-Reload Types
// =============================================================================
/// Shared gateway state that can be atomically swapped for hot-reload.
type SharedGateway = Arc<ArcSwap<Gateway>>;
// Re-export from library for local use
use hot_reload::HotReloadResult;
// =============================================================================
// Gateway
// =============================================================================
/// Shared gateway state.
struct Gateway {
manifest: Manifest,
router: Router,
operations: Vec<CompiledOperation>,
/// Pre-compiled validators for each operation.
validators: Vec<OperationValidator>,
/// Source specs embedded in the artifact (filename -> content).
specs: HashMap<String, String>,
/// Request limits (body size, headers, URI length).
limits: RequestLimits,
dev_mode: bool,
/// Whether plugin egress to internal/loopback/metadata targets is allowed
/// (BARBACANE_ALLOW_INTERNAL_EGRESS). The HTTP/broker clients carry their own
/// copy; this one guards WebSocket upstream connections.
allow_internal_egress: bool,
/// WASM engine for plugin execution (kept alive for engine lifetime).
_wasm_engine: Arc<WasmEngine>,
/// Plugin instance pool.
plugin_pool: Arc<InstancePool>,
/// Plugin resource limits (kept for future dynamic limit adjustment).
_plugin_limits: PluginLimits,
/// HTTP client for plugins making outbound calls (kept alive for pool lifetime).
_http_client: Arc<HttpClient>,
/// Metrics registry for observability.
metrics: Arc<MetricsRegistry>,
/// API name from the first spec's title (for metrics labels).
api_name: String,
/// Request counter for generating request IDs (fallback if UUID too slow).
_request_counter: AtomicU64,
/// MCP server (None if MCP is not enabled in the artifact).
mcp_server: Option<barbacane_lib::mcp::McpServer>,
}
impl Gateway {
/// Load a gateway from a .bca artifact.
fn load(
artifact_path: &Path,
dev_mode: bool,
limits: RequestLimits,
allow_plaintext_upstream: bool,
metrics: Arc<MetricsRegistry>,
) -> Result<Self, String> {
let manifest =
load_manifest(artifact_path).map_err(|e| format!("failed to load manifest: {}", e))?;
let routes =
load_routes(artifact_path).map_err(|e| format!("failed to load routes: {}", e))?;
let specs =
load_specs(artifact_path).map_err(|e| format!("failed to load specs: {}", e))?;
// Initialize HTTP client for upstream requests and plugin outbound calls.
// SSRF guard is on by default; operators opt out for trusted internal
// upstreams via BARBACANE_ALLOW_INTERNAL_EGRESS.
let allow_internal_egress = matches!(
std::env::var("BARBACANE_ALLOW_INTERNAL_EGRESS")
.ok()
.as_deref(),
Some("1" | "true" | "TRUE" | "yes")
);
// Cap the body the buffered plugin-egress path will read into host
// memory. Operators can raise/lower it; default is 16 MiB.
let max_response_bytes = std::env::var("BARBACANE_MAX_UPSTREAM_RESPONSE_BYTES")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.unwrap_or_else(|| HttpClientConfig::default().max_response_bytes);
let http_client_config = HttpClientConfig {
allow_plaintext: allow_plaintext_upstream,
allow_internal_egress,
max_response_bytes,
..Default::default()
};
let http_client = HttpClient::new(http_client_config)
.map_err(|e| format!("failed to create HTTP client: {}", e))?;
let http_client = Arc::new(http_client);
// Initialize WASM engine.
// Scale WASM memory to accommodate max_body_size: a base64-encoded body
// is ~1.37× the raw size, and the plugin holds the JSON input buffer,
// decoded body, and re-encoded output simultaneously. Use 4× the body
// limit (minimum 16 MB) so dispatchers have headroom for file uploads.
// Bodies travel via side-channel (raw bytes), not base64-in-JSON, so
// WASM only needs room for one copy of the body plus working memory.
let wasm_memory = std::cmp::max(16 * 1024 * 1024, limits.max_body_size + 4 * 1024 * 1024);
let plugin_limits = PluginLimits::default().with_memory(wasm_memory);
let wasm_engine = WasmEngine::with_limits(plugin_limits.clone())
.map_err(|e| format!("failed to create WASM engine: {}", e))?;
let wasm_engine = Arc::new(wasm_engine);
// Load plugins from the artifact
let bundled_plugins = load_plugins(artifact_path)
.map_err(|e| format!("failed to load plugins from artifact: {}", e))?;
if bundled_plugins.is_empty() {
tracing::warn!("no plugins bundled in artifact - ensure barbacane.yaml manifest was used during compilation");
}
// AR-1: verify artifact integrity before instantiating any plugin.
// The hash/checksum checks always run (detect tampering or corruption);
// an Ed25519 signature is additionally required when a trusted public
// key is pinned via BARBACANE_TRUSTED_PUBKEY.
barbacane_compiler::verify_artifact_hash(&manifest)
.map_err(|e| format!("artifact integrity check failed: {}", e))?;
for (name, loaded) in &bundled_plugins {
barbacane_compiler::verify_plugin_checksum(&manifest, name, &loaded.wasm_bytes)
.map_err(|e| format!("artifact integrity check failed: {}", e))?;
}
match std::env::var("BARBACANE_TRUSTED_PUBKEY") {
Ok(pubkey) if !pubkey.trim().is_empty() => {
barbacane_compiler::verify_artifact_signature(&manifest, &pubkey)
.map_err(|e| format!("artifact signature verification failed: {}", e))?;
tracing::info!("artifact Ed25519 signature verified");
}
_ => {
tracing::warn!(
"artifact signature verification disabled; set BARBACANE_TRUSTED_PUBKEY to require a valid Ed25519 signature"
);
}
}
// WA-1: capability enforcement only applies to artifacts whose per-plugin
// capabilities are authoritative (compiled from plugin.toml). Artifacts
// built without them (e.g. via the control-plane registry, which does
// not yet persist capabilities) are loaded without enforcement.
let enforce_capabilities = manifest.capabilities_enforced;
if !enforce_capabilities {
tracing::warn!(
"plugin capability enforcement disabled: artifact has no authoritative capabilities"
);
}
// Compile all plugin modules first (we'll register them after creating the final pool)
let mut compiled_modules = Vec::new();
for (name, loaded) in bundled_plugins {
let module = wasm_engine
.compile(
&loaded.wasm_bytes,
name.clone(),
loaded.version.clone(),
loaded.body_access,
)
.map_err(|e| format!("failed to compile plugin '{}': {}", name, e))?;
// WA-1: enforce the capability contract. The plugin may only import
// host functions covered by the capabilities it declared in
// plugin.toml (carried in the artifact manifest); anything else is a
// hard load failure (default-deny).
if enforce_capabilities {
let declared = manifest
.plugins
.iter()
.find(|p| p.name == name)
.map(|p| p.capabilities.host_functions.clone())
.unwrap_or_default();
barbacane_wasm::validate_imports(module.module(), &declared).map_err(|e| {
format!(
"plugin '{}' violates its declared capabilities: {}",
name, e
)
})?;
}
compiled_modules.push((name, loaded.version, module));
}
// Collect all configs to find secret references
let all_configs: Vec<&serde_json::Value> = routes
.operations
.iter()
.flat_map(|op| {
let mut configs: Vec<&serde_json::Value> =
op.middlewares.iter().map(|m| &m.config).collect();
configs.push(&op.dispatch.config);
configs
})
.collect();
// Debug: log all configs being checked for secrets
if dev_mode {
for config in &all_configs {
tracing::debug!(config = %config, "checking config for secret references");
}
let refs = all_configs
.iter()
.flat_map(|c| barbacane_wasm::collect_secret_references(c))
.collect::<Vec<_>>();
tracing::debug!(references = ?refs, "found secret references");
}
// Resolve all secrets
let secrets_store =
barbacane_wasm::resolve_all_secrets(&all_configs).map_err(|errors| {
let messages: Vec<String> = errors.iter().map(|e| e.to_string()).collect();
format!("failed to resolve secrets: {}", messages.join(", "))
})?;
// WA-3: map each plugin name to the secret references in its own config
// (collected from the raw, pre-substitution configs), so the pool can
// scope host_get_secret per plugin — a plugin can resolve the secrets it
// declares, not another plugin's secrets held in the shared store.
let mut secret_refs_by_plugin: HashMap<String, HashSet<String>> = HashMap::new();
for op in &routes.operations {
for mw in &op.middlewares {
secret_refs_by_plugin
.entry(mw.name.clone())
.or_default()
.extend(barbacane_wasm::collect_secret_references(&mw.config));
}
secret_refs_by_plugin
.entry(op.dispatch.name.clone())
.or_default()
.extend(barbacane_wasm::collect_secret_references(
&op.dispatch.config,
));
}
// Replace secret references in route configs with resolved values
let mut resolved_operations = routes.operations;
for op in &mut resolved_operations {
for mw in &mut op.middlewares {
mw.config = barbacane_wasm::resolve_config_secrets(&mw.config, &secrets_store);
}
op.dispatch.config =
barbacane_wasm::resolve_config_secrets(&op.dispatch.config, &secrets_store);
}
// Create rate limiter for host_rate_limit_check calls
let rate_limiter = RateLimiter::new();
// Create response cache for host_cache_get/set calls
let response_cache = ResponseCache::new();
// Create NATS publisher for host_nats_publish calls. Broker egress
// honors the same internal-egress policy as plugin HTTP calls.
let nats_publisher = barbacane_wasm::NatsPublisher::new(allow_internal_egress)
.map_err(|e| format!("failed to create NATS publisher: {}", e))?;
// Create Kafka publisher for host_kafka_publish calls
let kafka_publisher = barbacane_wasm::KafkaPublisher::new(allow_internal_egress)
.map_err(|e| format!("failed to create Kafka publisher: {}", e))?;
// Create pool with all options: HTTP client, secrets, rate limiter, cache, NATS, and Kafka
let plugin_pool = InstancePool::with_all_options(
wasm_engine.clone(),
plugin_limits.clone(),
Some(http_client.clone()),
Some(secrets_store),
Some(rate_limiter),
Some(response_cache),
Some(Arc::new(nats_publisher)),
Some(Arc::new(kafka_publisher)),
)
.with_secret_scopes(secret_refs_by_plugin);
// Register all compiled modules in the pool
for (name, version, module) in compiled_modules {
plugin_pool.register_module(module);
if dev_mode {
tracing::debug!(plugin = %name, version = %version, "loaded plugin from artifact");
}
}
let mut router = Router::new();
let mut validators = Vec::new();
for op in &resolved_operations {
// Map AsyncAPI methods to HTTP methods for sync-to-async bridge pattern:
// - SEND → POST (publish message via HTTP POST, get 202 Accepted)
// - RECEIVE → GET (for SSE/WebSocket subscriptions, less common)
let http_method = match op.method.as_str() {
"SEND" => "POST",
"RECEIVE" => "GET",
other => other,
};
router.insert(
&op.path,
http_method,
RouteEntry {
operation_index: op.index,
},
);
// Pre-compile validator for this operation
let validator = OperationValidator::new(&op.parameters, op.request_body.as_ref());
validators.push(validator);
// Log middleware chain for this operation (informational)
if !op.middlewares.is_empty() && dev_mode {
let names: Vec<_> = op.middlewares.iter().map(|m| m.name.as_str()).collect();
tracing::debug!(
path = %op.path,
method = %op.method,
middlewares = ?names,
"configured middleware chain"
);
}
}
// Extract API name from manifest (first source spec file or "default")
let api_name = manifest
.source_specs
.first()
.map(|s| {
// Remove extension and path, just keep the file name
Path::new(&s.file)
.file_stem()
.and_then(|n| n.to_str())
.unwrap_or("default")
.to_string()
})
.unwrap_or_else(|| "default".to_string());
// Construct MCP server if enabled
let mcp_server = if manifest.mcp.enabled {
Some(barbacane_lib::mcp::McpServer::new(
&resolved_operations,
&manifest.mcp,
))
} else {
None
};
Ok(Gateway {
manifest,
router,
operations: resolved_operations,
validators,
specs,
limits,
dev_mode,
allow_internal_egress,
_wasm_engine: wasm_engine,
plugin_pool: Arc::new(plugin_pool),
_plugin_limits: plugin_limits,
_http_client: http_client,
metrics,
api_name,
_request_counter: AtomicU64::new(0),
mcp_server,
})
}
/// Add standard headers to a response.
///
/// Includes:
/// - Server version
/// - Request/trace IDs for observability
/// - Security headers (X-Content-Type-Options, X-Frame-Options)
fn add_standard_headers<B>(
mut response: Response<B>,
request_id: &str,
trace_id: &str,
) -> Response<B> {
let headers = response.headers_mut();
// Observability headers. `request_id`/`trace_id` may originate from
// client-supplied headers, so never panic on a value that isn't a legal
// header value — fall back to a placeholder instead.
headers.insert("server", HeaderValue::from_static(SERVER_VERSION));
headers.insert(
"x-request-id",
HeaderValue::from_str(request_id)
.unwrap_or_else(|_| HeaderValue::from_static("invalid")),
);
headers.insert(
"x-trace-id",
HeaderValue::from_str(trace_id).unwrap_or_else(|_| HeaderValue::from_static("invalid")),
);
// Security headers (enabled by default)
headers.insert(
"x-content-type-options",
HeaderValue::from_static("nosniff"),
);
headers.insert("x-frame-options", HeaderValue::from_static("DENY"));
response
}
/// Add deprecation headers to a response if the operation is deprecated.
/// Implements RFC 8594 (Sunset header) and draft-ietf-httpapi-deprecation-header.
fn add_deprecation_headers<B>(
mut response: Response<B>,
operation: &CompiledOperation,
) -> Response<B> {
if operation.deprecated {
let headers = response.headers_mut();
// Deprecation header per draft-ietf-httpapi-deprecation-header
// Value "true" indicates the endpoint is deprecated
headers.insert("deprecation", HeaderValue::from_static("true"));
// Sunset header per RFC 8594 if a sunset date is specified
if let Some(sunset_date) = &operation.sunset {
if let Ok(val) = sunset_date.parse() {
headers.insert("sunset", val);
}
}
}
response
}
/// Handle an incoming HTTP request.
async fn handle_request(
&self,
req: Request<Incoming>,
client_addr: Option<SocketAddr>,
) -> Result<Response<AnyBody>, Infallible> {
let start_time = Instant::now();
let uri_string = req.uri().to_string();
let path = req.uri().path().to_string();
let query_string = req.uri().query().map(|s| s.to_string());
let method = req.method().clone();
let method_str = method.as_str().to_string();
// Generate or extract request ID (from incoming header or new UUID).
// Only accept a client-supplied id if it is a legal, non-empty header
// value; otherwise generate one (prevents header-injection / panics).
let request_id = req
.headers()
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.filter(|s| !s.is_empty() && HeaderValue::from_str(s).is_ok())
.map(|s| s.to_string())
.unwrap_or_else(|| Uuid::new_v4().to_string());
// Generate or extract trace ID (from traceparent header or new UUID)
let trace_id = req
.headers()
.get("traceparent")
.and_then(|v| v.to_str().ok())
.and_then(|tp| {
// traceparent format: 00-<trace-id>-<span-id>-<flags>
let parts: Vec<&str> = tp.split('-').collect();
if parts.len() >= 2 {
Some(parts[1].to_string())
} else {
None
}
})
.unwrap_or_else(|| Uuid::new_v4().simple().to_string());
// Check URI length limit early
if let Err(e) = self.limits.validate_uri(&uri_string) {
let response = self.validation_error_response(&[e]);
self.record_request_metrics(
&method_str,
// Bounded label: raw paths would let a scanner explode metric cardinality.
UNMATCHED_ROUTE_LABEL,
response.status().as_u16(),
0,
0,
start_time,
);
return Ok(box_full(Self::add_standard_headers(
response,
&request_id,
&trace_id,
)));
}
// MCP endpoint — needs body access, so handle before generic reserved endpoints
if path == "/__barbacane/mcp" {
let response = self
.handle_mcp_endpoint(req, &method, &request_id, &trace_id, start_time)
.await;
return Ok(response);
}
// Reserved /__barbacane/* endpoints (skip other limits for internal endpoints)
if path.starts_with("/__barbacane/") {
let response = self.handle_barbacane_endpoint(&path, &method, query_string.as_deref());
return Ok(box_full(Self::add_standard_headers(
response,
&request_id,
&trace_id,
)));
}
// Enforce header limits on the RAW header map first: `HeaderMap::len()`
// counts every header line (including repeated names), so a flood of
// duplicate-named headers can't slip under the count limit, and each
// value is size-checked (not just the last one for a given name).
let raw_headers = req.headers();
let header_limit_error = self
.limits
.validate_header_count(raw_headers.len())
.err()
.or_else(|| {
raw_headers.iter().find_map(|(name, value)| {
self.limits
.validate_header_size(name.as_str(), name.as_str().len() + value.len())
.err()
})
});
// Extract headers for downstream validation and plugin forwarding. This
// collapses duplicate names (last value wins), which is fine now that the
// limit checks above ran against the raw map.
let headers: HashMap<String, String> = req
.headers()
.iter()
.filter_map(|(k, v)| Some((k.as_str().to_string(), v.to_str().ok()?.to_string())))
.collect();
// Check header limits
if let Some(e) = header_limit_error {
let response = self.validation_error_response(&[e]);
self.record_request_metrics(
&method_str,
UNMATCHED_ROUTE_LABEL,
response.status().as_u16(),
0,
0,
start_time,
);
return Ok(box_full(Self::add_standard_headers(
response,
&request_id,
&trace_id,
)));
}
// Check content-length before reading body (if present)
if let Some(content_length) = headers.get("content-length") {
if let Ok(len) = content_length.parse::<usize>() {
if self.limits.validate_body_size(len).is_err() {
let response = self.payload_too_large_response(self.limits.max_body_size);
self.record_request_metrics(
&method_str,
UNMATCHED_ROUTE_LABEL,
response.status().as_u16(),
0,
0,
start_time,
);
return Ok(box_full(Self::add_standard_headers(
response,
&request_id,
&trace_id,
)));
}
}
}
// Route lookup
match self.router.lookup(&path, &method_str) {
RouteMatch::Found { entry, mut params } => {
// Canonically percent-decode captured path-parameter values once,
// so routing, validation, and the dispatcher all see the same
// decoded value (segments were matched raw; `%2F` stays a literal
// slash within its segment rather than acting as a separator).
for (_, value) in params.iter_mut() {
*value = barbacane_lib::validator::percent_decode(value);
}
let operation = &self.operations[entry.operation_index];
let validator = &self.validators[entry.operation_index];
let route_path = operation.path.clone();
let content_type = headers.get("content-type").map(|s| s.as_str());
// For WebSocket upgrade requests (ADR-0026), extract the upgrade
// handle before consuming the body. The body is empty for GET
// upgrade requests, so we skip collection.
let is_ws_upgrade = headers
.get("upgrade")
.is_some_and(|v| v.eq_ignore_ascii_case("websocket"));
let (body_bytes, upgrade_handle) = if is_ws_upgrade {
(Bytes::new(), Some(hyper::upgrade::on(req)))
} else {
// Cap the bytes read while collecting so a chunked body with
// no content-length can't be buffered past the limit (DoS).
// `Limited` errors as soon as the cap is exceeded.
let limited =
http_body_util::Limited::new(req.into_body(), self.limits.max_body_size);
match limited.collect().await {
Ok(collected) => (collected.to_bytes(), None),
Err(e) => {
let response = if e
.downcast_ref::<http_body_util::LengthLimitError>()
.is_some()
{
self.metrics.record_validation_failure(
&method_str,
&route_path,
"body_too_large",
);
self.payload_too_large_response(self.limits.max_body_size)
} else {
self.bad_request_response("failed to read request body")
};
self.record_request_metrics(
&method_str,
&route_path,
response.status().as_u16(),
0,
0,
start_time,
);
return Ok(box_full(Self::add_standard_headers(
response,
&request_id,
&trace_id,
)));
}
}
};
let request_size = body_bytes.len() as u64;
// Validate actual body size (in case content-length was missing or wrong)
if self.limits.validate_body_size(body_bytes.len()).is_err() {
self.metrics.record_validation_failure(
&method_str,
&route_path,
"body_too_large",
);
let response = self.payload_too_large_response(self.limits.max_body_size);
self.record_request_metrics(
&method_str,
&route_path,
response.status().as_u16(),
request_size,
0,
start_time,
);
return Ok(box_full(Self::add_standard_headers(
response,
&request_id,
&trace_id,
)));
}
// Validate request against OpenAPI spec
if let Err(errors) = validator.validate_request(
¶ms,
query_string.as_deref(),
&headers,
content_type,
&body_bytes,
) {
// Record validation failures - use error variant name as reason
for err in &errors {
let reason = validation_error_reason(err);
self.metrics
.record_validation_failure(&method_str, &route_path, &reason);
}
let response = self.validation_error_response(&errors);
self.record_request_metrics(
&method_str,
&route_path,
response.status().as_u16(),
request_size,
0,
start_time,
);
return Ok(box_full(Self::add_standard_headers(
response,
&request_id,
&trace_id,
)));
}
let response: Response<AnyBody> = self
.dispatch(
operation,
&path,
params,
query_string,
&body_bytes,
&headers,
client_addr,
upgrade_handle,
)
.await?;
// Add deprecation headers if the operation is deprecated
let response = Self::add_deprecation_headers(response, operation);
let response_size = response.body().size_hint().upper().unwrap_or(0);
self.record_request_metrics(
&method_str,
&route_path,
response.status().as_u16(),
request_size,
response_size,
start_time,
);
Ok(Self::add_standard_headers(response, &request_id, &trace_id))
}
RouteMatch::MethodNotAllowed { allowed } => {
// Check if this is a CORS preflight request
// Preflight = OPTIONS + Origin + Access-Control-Request-Method headers
if method == Method::OPTIONS
&& headers.contains_key("origin")
&& headers.contains_key("access-control-request-method")
{
// Try to handle as CORS preflight by finding an operation with CORS middleware
if let Some(first_method) = allowed.first() {
if let RouteMatch::Found { entry, params: _ } =
self.router.lookup(&path, first_method)
{
let operation = &self.operations[entry.operation_index];
// Check if this operation has a CORS middleware
let cors_middleware =
operation.middlewares.iter().find(|mw| mw.name == "cors");
if let Some(cors_mw) = cors_middleware {
// Execute only the CORS middleware for preflight
let response = self
.handle_cors_preflight(
cors_mw,
&headers,
&request_id,
&trace_id,
)
.await;
self.record_request_metrics(
&method_str,
UNMATCHED_ROUTE_LABEL,
response.status().as_u16(),
0,
0,
start_time,
);
return Ok(box_full(response));
}
}
}
}
// Not a CORS preflight or no CORS middleware found - return 405
let response = self.method_not_allowed_response(allowed, &method_str, &path);
self.record_request_metrics(
&method_str,
UNMATCHED_ROUTE_LABEL,
response.status().as_u16(),
0,
0,
start_time,
);
Ok(box_full(Self::add_standard_headers(
response,
&request_id,
&trace_id,
)))
}
RouteMatch::NotFound => {
let response = self.not_found_response();
self.record_request_metrics(
&method_str,
UNMATCHED_ROUTE_LABEL,
response.status().as_u16(),
0,
0,
start_time,
);
Ok(box_full(Self::add_standard_headers(
response,
&request_id,
&trace_id,
)))
}
}
}
/// Record request metrics.
fn record_request_metrics(
&self,
method: &str,
path: &str,
status: u16,
request_size: u64,
response_size: u64,
start_time: Instant,
) {
let duration = start_time.elapsed().as_secs_f64();
self.metrics.record_request(
method,
path,
status,
&self.api_name,
duration,
request_size,
response_size,
);
}
/// Dispatch a request to the appropriate handler.
#[allow(clippy::too_many_arguments)]
async fn dispatch(
&self,
operation: &CompiledOperation,
request_path: &str,
params: Vec<(String, String)>,
query_string: Option<String>,
request_body: &[u8],
headers: &HashMap<String, String>,
client_addr: Option<SocketAddr>,
upgrade_handle: Option<hyper::upgrade::OnUpgrade>,
) -> Result<Response<AnyBody>, Infallible> {
let dispatch = &operation.dispatch;
// Build the Request object for plugins (using BTreeMap for WASM compatibility)
let path_params: std::collections::BTreeMap<String, String> = params.into_iter().collect();
let headers_btree: std::collections::BTreeMap<String, String> = headers
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
// Extract body separately — it travels via side-channel, not in JSON.
let raw_body = if request_body.is_empty() {
None
} else {
Some(request_body.to_vec())
};
let plugin_request = barbacane_wasm::Request {
method: operation.method.clone(),
path: request_path.to_string(),
query: query_string,
headers: headers_btree,
body: None, // Body travels via side-channel
client_ip: client_addr
.map(|addr| addr.ip().to_string())
.unwrap_or_else(|| "0.0.0.0".to_string()),
path_params,
};
let request_json = match serde_json::to_vec(&plugin_request) {
Ok(j) => j,
Err(e) => {
return Ok(box_full(self.dev_error_response(format_args!(
"failed to serialize request: {}",
e
))));
}
};
// Execute middleware on_request chain
let (final_request_json, final_body, middleware_instances, middleware_context) =
if !operation.middlewares.is_empty() {
match self.execute_middleware_on_request(
&operation.middlewares,
&request_json,
raw_body,
) {
Ok((req, body, instances, ctx)) => (req, body, instances, ctx),
Err(resp) => return Ok(box_full(resp)), // Short-circuit response
}
} else {
(
request_json,
raw_body,
Vec::new(),
barbacane_wasm::RequestContext::default(),
)
};
// All dispatchers must be WASM plugins loaded from the artifact
if !self.plugin_pool.has_plugin(&dispatch.name) {
return Ok(box_full(self.dev_error_response(format_args!(
"unknown dispatcher '{}' - not found in artifact plugins",
dispatch.name
))));
}
// Dispatch to the plugin.
// Returns either a buffered response, streaming response (ADR-0023),
// or WebSocket upgrade response (ADR-0026).
let dispatch_outcome = match self
.dispatch_wasm_plugin_inner(
&dispatch.name,
&dispatch.config,
final_request_json,
final_body,
middleware_instances,
middleware_context,
upgrade_handle,
)
.await
{
Ok(r) => r,
Err(e) => return Ok(box_full(e)),
};
Ok(dispatch_outcome)
}
/// Execute middleware on_request chain.
/// Returns the final request JSON, body, middleware instances, and context
/// (for on_response), or a short-circuit response.
#[allow(clippy::result_large_err, clippy::type_complexity)]
fn execute_middleware_on_request(
&self,
middlewares: &[barbacane_compiler::MiddlewareConfig],
request_json: &[u8],
raw_body: Option<Vec<u8>>,
) -> Result<
(
Vec<u8>,
Option<Vec<u8>>,
Vec<barbacane_wasm::PluginInstance>,
barbacane_wasm::RequestContext,
),
Response<Full<Bytes>>,
> {
use barbacane_wasm::RequestContext;
let mut instances = Vec::new();
// Create instances for each middleware
for mw in middlewares {
if !self.plugin_pool.has_plugin(&mw.name) {
tracing::error!(middleware = %mw.name, "middleware plugin not found in artifact");
return Err(self.dev_error_response(format_args!(
"middleware '{}' not found - ensure it's declared in barbacane.yaml",
mw.name
)));
}
let instance_key = barbacane_wasm::InstanceKey::new(&mw.name, &mw.config);
let config_json = serde_json::to_vec(&mw.config).unwrap_or_default();
self.plugin_pool
.register_config(instance_key.clone(), config_json);
match self.plugin_pool.get_instance(&instance_key) {
Ok(instance) => instances.push(instance),
Err(e) => {
tracing::error!(middleware = %mw.name, error = %e, "failed to get middleware instance");
return Err(self.dev_error_response(format_args!(
"failed to get middleware '{}': {}",
mw.name, e
)));
}
}
}
if instances.is_empty() {
return Ok((
request_json.to_vec(),
raw_body,
instances,
RequestContext::default(),
));
}
// Build per-middleware body_access flags
let body_access_flags: Vec<bool> = middlewares
.iter()
.map(|mw| self.plugin_pool.body_access(&mw.name))
.collect();
// Side-channel body control (SPEC-008): body travels via host functions,
// not embedded in JSON. Only body-access middleware receives the body.
let mut body_ctrl = barbacane_wasm::BodyAccessControl::new(request_json.to_vec(), raw_body);
let mut current_context = RequestContext::default();
for (index, instance) in instances.iter_mut().enumerate() {
let has_body_access = body_access_flags[index];
let request_for_wasm = body_ctrl.prepare_instance(instance, has_body_access);
instance.set_context(current_context.clone());
let start = std::time::Instant::now();
let middleware_name = instance.name().to_string();
match instance.on_request(&request_for_wasm) {
Ok(result_code) => {
let output = instance.take_output();
match barbacane_wasm::parse_middleware_output(&output, result_code) {
Ok(barbacane_wasm::OnRequestResult::Continue(new_request)) => {
self.metrics.record_middleware(
&middleware_name,
"request",
start.elapsed().as_secs_f64(),
false,
);
current_context = instance.get_context();
body_ctrl.collect_after(instance, new_request, has_body_access);
}
Ok(barbacane_wasm::OnRequestResult::ShortCircuit(response)) => {
self.metrics.record_middleware(
&middleware_name,
"request",
start.elapsed().as_secs_f64(),
true,
);
// Always collect short-circuit response body from side-channel.
// body_access only controls whether the plugin *receives* the
// request body — any middleware can set a response body on
// short-circuit (e.g. error responses with JSON problem details).
let sc_body = instance.take_output_body().unwrap_or(None);
let final_context = instance.get_context();
let final_response = barbacane_wasm::execute_on_response_partial(
&mut instances,
&response,
index,
final_context,
);
return match serde_json::from_slice::<barbacane_wasm::Response>(
&final_response,
) {
Ok(mut plugin_response) => {
plugin_response.body = sc_body;
Err(Self::build_response_from_plugin(&plugin_response))
}
Err(e) => {
tracing::error!(error = %e, "failed to parse middleware response");
Err(self.dev_error_response(format_args!(
"failed to parse middleware response: {}",
e
)))
}
};
}
Err(e) => {
self.metrics.record_middleware(
&middleware_name,
"request",
start.elapsed().as_secs_f64(),
false,
);
tracing::error!(error = %e, "middleware chain execution failed");
return Err(self.dev_error_response(format_args!(
"middleware chain error: {}",
e
)));
}
}
}
Err(e) => {
self.metrics.record_middleware(
&middleware_name,
"request",
start.elapsed().as_secs_f64(),
false,
);
tracing::error!(error = %e, "middleware chain execution failed");
return Err(
self.dev_error_response(format_args!("middleware chain error: {}", e))
);
}
}
}
let (metadata, body) = body_ctrl.finalize();
Ok((metadata, body, instances, current_context))
}
/// Execute middleware on_response chain.
///
/// Like the on_request path (SPEC-008), response body is stripped for
/// middleware that don't declare `body_access = true`. Bodies travel via
/// side-channel host functions, not embedded in JSON.
fn execute_middleware_on_response(
&self,
mut instances: Vec<barbacane_wasm::PluginInstance>,
response: barbacane_wasm::Response,
context: barbacane_wasm::RequestContext,
) -> barbacane_wasm::Response {
// Extract body — it travels via side-channel, not in JSON.
let resp_body = response.body.clone();
let mut resp_for_json = response.clone();
resp_for_json.body = None;
let response_json = match serde_json::to_vec(&resp_for_json) {
Ok(j) => j,
Err(_) => return response,
};
// Side-channel body control: body only goes to body-access middleware.
let mut body_ctrl = barbacane_wasm::BodyAccessControl::new(response_json, resp_body);
let metrics = &self.metrics;
// Process in reverse order (on_response runs last-to-first).
for instance in instances.iter_mut().rev() {
let has_body_access = self.plugin_pool.body_access(instance.name());
let response_for_wasm = body_ctrl.prepare_instance(instance, has_body_access);
instance.set_context(context.clone());
let start = std::time::Instant::now();
let middleware_name = instance.name().to_string();
match instance.on_response(&response_for_wasm) {
Ok(_result_code) => {
metrics.record_middleware(
&middleware_name,
"response",
start.elapsed().as_secs_f64(),
false,
);
let output = instance.take_output();
body_ctrl.collect_after(instance, output, has_body_access);
}
Err(e) => {
metrics.record_middleware(
&middleware_name,
"response",
start.elapsed().as_secs_f64(),
false,
);
let trap_result = barbacane_wasm::TrapResult::from_error(
&e,
barbacane_wasm::TrapContext::OnResponse,
);
tracing::warn!(
error = %trap_result.message(),
"Middleware on_response failed, continuing with original response"
);
}
}
}
// Reconstruct Response from metadata JSON + side-channel body.
let (final_json, final_body) = body_ctrl.finalize();
match serde_json::from_slice::<barbacane_wasm::Response>(&final_json) {
Ok(mut resp) => {
resp.body = final_body;
resp
}
Err(_) => response,
}
}
/// Build an HTTP response from a plugin Response.
///
/// Does not use `self` (associated fn) so it can be unit-tested directly for
/// the untrusted-header handling below.
fn build_response_from_plugin(
plugin_response: &barbacane_wasm::Response,
) -> Response<Full<Bytes>> {
let status = StatusCode::from_u16(plugin_response.status).unwrap_or(StatusCode::OK);
let mut builder = Response::builder().status(status);
for (key, value) in &plugin_response.headers {
// Skip framing headers that the plugin (or its upstream) may have
// set for a different body. hyper recomputes `content-length` from
// the actual `Full<Bytes>` payload; keeping a stale value would
// cause the client to see a truncated response (`IncompleteMessage`)
// when a middleware — e.g. `ai-response-guard` redaction —
// modifies the body length.
let key_lc = key.to_ascii_lowercase();
if matches!(
key_lc.as_str(),
"content-length" | "transfer-encoding" | "connection" | "keep-alive"
) {
continue;
}
// Validate the plugin-supplied header before insertion. The `http`
// crate defers validation to `.body()`, so an illegal name/value
// (empty, whitespace, control byte, or a value with CR/LF) would
// otherwise surface as a panic there. Plugins are untrusted, so skip
// invalid headers instead of aborting the connection task (a plugin
// reflecting an attacker field into a header could otherwise DoS the
// route). Mirrors add_standard_headers' defensive handling.
let name = match HeaderName::from_bytes(key.as_bytes()) {
Ok(name) => name,
Err(_) => {
tracing::debug!(header = %key, "skipping invalid plugin response header name");
continue;
}
};
let header_value = match HeaderValue::from_str(value) {
Ok(v) => v,
Err(_) => {
tracing::debug!(header = %key, "skipping invalid plugin response header value");
continue;
}
};
builder = builder.header(name, header_value);
}
let body = plugin_response.body.clone().unwrap_or_default();
match builder.body(Full::new(Bytes::from(body))) {
Ok(resp) => resp,
Err(e) => {
// Header validation above should make this unreachable, but never
// panic on plugin-derived data: return a clean 502 instead.
tracing::error!(error = %e, "failed to build response from plugin; returning 502");
Response::builder()
.status(StatusCode::BAD_GATEWAY)
.body(Full::new(Bytes::from_static(b"invalid upstream response")))
.expect("static 502 response is always valid")
}
}
}
/// Dispatch via a WASM plugin (inner function taking pre-serialized request).
///
/// Handles both buffered and streaming (ADR-0023) dispatch paths:
/// - **Buffered**: WASM returns a `Response` directly; on_response middleware runs synchronously.
/// - **Streaming**: WASM calls `host_http_stream`; headers arrive via channel before WASM
/// returns, body streams via `StreamBody`. on_response runs in a background task for
/// observability only (modifications are discarded since the response is already sent).
#[allow(clippy::too_many_arguments)]
async fn dispatch_wasm_plugin_inner(
&self,
plugin_name: &str,
config: &serde_json::Value,
request_json: Vec<u8>,
request_body: Option<Vec<u8>>,
middleware_instances: Vec<barbacane_wasm::PluginInstance>,
middleware_context: barbacane_wasm::RequestContext,
upgrade_handle: Option<hyper::upgrade::OnUpgrade>,
) -> Result<Response<AnyBody>, Response<Full<Bytes>>> {
use barbacane_wasm::StreamEvent;
use futures_util::stream;
// Create instance key for this (plugin, config) pair
let instance_key = barbacane_wasm::InstanceKey::new(plugin_name, config);
let config_json = serde_json::to_vec(config).unwrap_or_default();
self.plugin_pool
.register_config(instance_key.clone(), config_json);
// Get a plugin instance
let mut instance = match self.plugin_pool.get_instance(&instance_key) {
Ok(i) => i,
Err(e) => {
return Err(
self.dev_error_response(format_args!("failed to get plugin instance: {}", e))
);
}
};
// Pre-compute Sec-WebSocket-Accept for WebSocket upgrades (RFC 6455 §4.2.2).
// Extract the key from request_json before it's moved into the dispatch closure.
let ws_accept = serde_json::from_slice::<serde_json::Value>(&request_json)
.ok()
.and_then(|v| v["headers"]["sec-websocket-key"].as_str().map(String::from))
.map(|key| {
tokio_tungstenite::tungstenite::handshake::derive_accept_key(key.as_bytes())
});
// Set up streaming channel (ADR-0023). The sender is injected into the instance so that
// `host_http_stream` can push `StreamEvent::Headers` then `StreamEvent::Chunk` events
// before `dispatch()` returns.
let (stream_tx, mut stream_rx) = tokio::sync::mpsc::unbounded_channel::<StreamEvent>();
instance.set_stream_sender(Arc::new(stream_tx));
// Inject request body via side-channel before dispatch.
instance.set_request_body(request_body);
// Carry the middleware chain's accumulated context into the
// dispatcher so it can read keys written upstream (e.g. `ai.target`
// set by a `cel` routing instance). The dispatcher may also write
// new keys (e.g. `ai.prompt_tokens`); we capture those below and
// thread them through to `on_response`.
instance.set_context(middleware_context.clone());
// Run WASM dispatch on a blocking thread (WASM execution is synchronous).
let mut wasm_handle = tokio::task::spawn_blocking(move || {
let result = instance.dispatch(&request_json);
let output = instance.take_output();
let output_body = instance.take_output_body();
let last_http = instance.take_last_http_result();
let ws_upgrade_request = instance.take_ws_upgrade_request();
let post_dispatch_context = instance.get_context();
(
result,
output,
output_body,
last_http,
ws_upgrade_request,
post_dispatch_context,
)
});
// Race: first stream event vs. WASM completion.
// In the streaming path `host_http_stream` sends `StreamEvent::Headers` before
// `dispatch()` returns, so `stream_rx.recv()` always wins the race in that case.
let mut maybe_wasm_result = None;
let first_event: Option<StreamEvent>;
tokio::select! {
biased;
e = stream_rx.recv() => first_event = e,
r = &mut wasm_handle => {
maybe_wasm_result = Some(r);
first_event = None;
}
}
match first_event {
// ── Streaming path ──────────────────────────────────────────────────────────
Some(StreamEvent::Headers { status, headers }) => {
let status_code = StatusCode::from_u16(status).unwrap_or(StatusCode::OK);
let mut builder = Response::builder().status(status_code);
for (k, v) in &headers {
// Same defensive validation as build_response_from_plugin:
// skip framing headers and any name/value the `http` crate
// would reject (which would otherwise panic at `.body()`).
let k_lc = k.to_ascii_lowercase();
if matches!(
k_lc.as_str(),
"content-length" | "transfer-encoding" | "connection" | "keep-alive"
) {
continue;
}
let name = match HeaderName::from_bytes(k.as_bytes()) {
Ok(name) => name,
Err(_) => {
tracing::debug!(header = %k, "skipping invalid streamed response header name");
continue;
}
};
let value = match HeaderValue::from_str(v) {
Ok(value) => value,
Err(_) => {
tracing::debug!(header = %k, "skipping invalid streamed response header value");
continue;
}
};
builder = builder.header(name, value);
}
// Convert remaining Chunk events into HTTP body frames.
let chunk_stream = stream::unfold(stream_rx, |mut rx| async move {
loop {
match rx.recv().await {
Some(StreamEvent::Chunk(bytes)) => {
return Some((
Ok::<Frame<Bytes>, Infallible>(Frame::data(bytes)),
rx,
));
}
// Skip unexpected extra Headers events.
Some(StreamEvent::Headers { .. }) => continue,
// Sender dropped — stream complete.
None => return None,
}
}
});
let response = match builder.body(BoxBody::new(StreamBody::new(chunk_stream))) {
Ok(r) => r,
Err(e) => {
// Validated headers make this unreachable, but never panic
// on plugin-derived data: return a clean 502 instead.
tracing::error!(error = %e, "failed to build streaming response; returning 502");
Response::builder()
.status(StatusCode::BAD_GATEWAY)
.body(BoxBody::new(Full::new(Bytes::from_static(
b"invalid upstream response",
))))
.expect("static 502 response is always valid")
}
};
// Background task: wait for WASM to finish, then run on_response for
// observability. Modifications are discarded (response already sent).
// Strip the response body to avoid WASM OOM with large streamed payloads.
let wh = wasm_handle;
let metrics = Arc::clone(&self.metrics);
tokio::spawn(async move {
match wh.await {
Ok((Ok(_), _, _, Some(last_http), _, post_ctx))
if !middleware_instances.is_empty() =>
{
if let Ok(plugin_resp) =
serde_json::from_slice::<barbacane_wasm::Response>(&last_http)
{
// Strip body: observability-only, modifications discarded.
// Body is already None (side-channel), just pass metadata.
let mut instances = middleware_instances;
let resp_json =
serde_json::to_vec(&plugin_resp).unwrap_or_default();
let cb = |name: &str, phase: &str, dur: f64, sc: bool| {
metrics.record_middleware(name, phase, dur, sc);
};
barbacane_wasm::execute_on_response_with_metrics(
&mut instances,
&resp_json,
post_ctx,
Some(&cb),
);
}
}
Ok((Err(e), _, _, _, _, _)) => {
tracing::warn!(
error = %e,
"streaming dispatch error (response already sent)"
);
}
Err(e) => {
tracing::warn!(
error = %e,
"streaming WASM task panicked (response already sent)"
);
}
_ => {}
}
});
Ok(response)
}
// ── Buffered path ────────────────────────────────────────────────────────────
_ => {
// Retrieve the WASM result. In the normal buffered case `maybe_wasm_result` is
// already set. The fallback await handles the rare case where recv() returned
// `None` (channel closed) and won the race just as WASM completed.
let wasm_result = match maybe_wasm_result {
Some(r) => r,
None => wasm_handle.await,
};
let (
dispatch_result,
output,
output_body,
_,
ws_upgrade_request,
post_dispatch_context,
) = match wasm_result {
Ok(r) => r,
Err(e) => {
return Err(
self.dev_error_response(format_args!("plugin task panicked: {}", e))
);
}
};
if let Err(e) = dispatch_result {
return Err(
self.dev_error_response(format_args!("plugin dispatch failed: {}", e))
);
}
if output.is_empty() {
return Err(self.dev_error_response("plugin returned empty output"));
}
let mut plugin_response: barbacane_wasm::Response =
match serde_json::from_slice(&output) {
Ok(r) => r,
Err(e) => {
return Err(self.dev_error_response(format_args!(
"failed to parse plugin response: {}",
e
)));
}
};
// Inject body from side-channel (output_body from host_body_set/clear).
if let Some(body) = output_body {
plugin_response.body = body;
}
// status=0 is the streamed_response() sentinel. If WASM returned it without
// sending stream events, that is a plugin bug.
if plugin_response.status == 0 {
return Err(self.dev_error_response(
"plugin returned streaming sentinel without stream events",
));
}
// ── WebSocket upgrade path (ADR-0026) ──────────────────────────────────
// status=101 with a ws_upgrade_request means the dispatcher called
// host_ws_upgrade successfully. Connect to the upstream on the main
// runtime (so the TcpStream's I/O driver stays alive), complete the
// client-side upgrade, and spawn bidirectional frame relay.
if plugin_response.status == 101 {
let ws_request = match ws_upgrade_request {
Some(req) => req,
None => {
return Err(self.dev_error_response(
"plugin returned 101 without calling host_ws_upgrade",
));
}
};
let upgrade_handle = match upgrade_handle {
Some(h) => h,
None => {
return Err(self.dev_error_response(
"plugin returned 101 but request is not an HTTP upgrade",
));
}
};
// Connect to the upstream WebSocket on the main runtime.
// This MUST happen here (not in a temporary runtime) so the
// TcpStream is registered with the I/O driver that will drive
// the relay task.
let ws_upstream = match barbacane_wasm::ws_client::connect_upstream(
ws_request,
self.allow_internal_egress,
)
.await
{
Ok(stream) => stream,
Err(err) => {
tracing::warn!(
error = %err,
"WebSocket upstream connection failed"
);
return Err(self.dev_error_response(format_args!(
"WebSocket upstream connection failed: {}",
err
)));
}
};
// Run on_response for observability (modifications discarded).
if !middleware_instances.is_empty() {
let sentinel_response = barbacane_wasm::Response {
status: 101,
headers: std::collections::BTreeMap::new(),
body: None,
};
let _ = self.execute_middleware_on_response(
middleware_instances,
sentinel_response,
post_dispatch_context.clone(),
);
}
// Spawn the WebSocket relay as a background task.
// The client-side upgrade completes when we return the 101 response.
tokio::spawn(async move {
// Wait for hyper to complete the HTTP upgrade.
let upgraded = match upgrade_handle.await {
Ok(u) => u,
Err(e) => {
tracing::warn!(
error = %e,
"WebSocket client upgrade failed"
);
return;
}
};
// Wrap the upgraded client connection as a WebSocket.
let client_ws = tokio_tungstenite::WebSocketStream::from_raw_socket(
TokioIo::new(upgraded),
tokio_tungstenite::tungstenite::protocol::Role::Server,
None,
)
.await;
// Relay frames bidirectionally.
Self::relay_websocket(client_ws, ws_upstream).await;
});
// Return 101 Switching Protocols to the client.
// hyper will handle the actual protocol switch.
let mut builder = Response::builder()
.status(StatusCode::SWITCHING_PROTOCOLS)
.header("upgrade", "websocket")
.header("connection", "Upgrade");
if let Some(accept) = &ws_accept {
builder = builder.header("sec-websocket-accept", accept.as_str());
}
let response = builder
.body(BoxBody::new(Full::new(Bytes::new())))
.expect("valid 101 response");
return Ok(response);
}
// Run on_response middleware chain with the post-dispatch
// context so middlewares can observe keys written by the
// dispatcher (e.g. `ai.prompt_tokens` from `ai-proxy`).
let final_response = if !middleware_instances.is_empty() {
self.execute_middleware_on_response(
middleware_instances,
plugin_response,
post_dispatch_context,
)
} else {
plugin_response
};
Ok(box_full(Self::build_response_from_plugin(&final_response)))
}
}
}
/// Handle reserved /__barbacane/* endpoints.
///
/// These endpoints always allow cross-origin requests (`Access-Control-Allow-Origin: *`)
/// so that Swagger UI, Redoc, or similar tools hosted on different domains can fetch specs.
fn handle_barbacane_endpoint(
&self,
path: &str,
method: &Method,
query: Option<&str>,
) -> Response<Full<Bytes>> {
// Handle CORS preflight for internal endpoints
if method == Method::OPTIONS {
return Response::builder()
.status(StatusCode::NO_CONTENT)
.header("access-control-allow-origin", "*")
.header("access-control-allow-methods", "GET, OPTIONS")
.header("access-control-allow-headers", "content-type, accept")
.header("access-control-max-age", "86400")
.body(Full::new(Bytes::new()))
.expect("valid response");
}
if method != Method::GET {
return self.method_not_allowed_response(
vec!["GET".to_string()],
method.as_str(),
path,
);
}
// Parse format from query string (default: yaml for specs, json for index)
let format = query
.and_then(|q| q.split('&').find_map(|pair| pair.strip_prefix("format=")))
.unwrap_or("yaml");
let mut response = match path {
"/__barbacane/health" => self.health_response(),
"/__barbacane/specs" => self.specs_index_response(),
"/__barbacane/specs/openapi" => self.merged_openapi_response(format),
"/__barbacane/specs/asyncapi" => self.merged_asyncapi_response(format),
_ => {
// Check for specific spec file: /__barbacane/specs/{filename}
if let Some(filename) = path.strip_prefix("/__barbacane/specs/") {
self.spec_file_response(filename, format)
} else {
self.not_found_response()
}
}
};
response
.headers_mut()
.insert("access-control-allow-origin", HeaderValue::from_static("*"));
response
}
/// Handle MCP endpoint requests (POST /__barbacane/mcp, DELETE /__barbacane/mcp).
async fn handle_mcp_endpoint(
&self,
req: Request<Incoming>,
method: &Method,
request_id: &str,
trace_id: &str,
start_time: std::time::Instant,
) -> Response<AnyBody> {
let mcp_server = match &self.mcp_server {
Some(s) => s,
None => {
let response = Response::builder()
.status(StatusCode::NOT_FOUND)
.header("content-type", "application/problem+json")
.body(Full::new(Bytes::from(
r#"{"type":"urn:barbacane:error:not-found","title":"Not Found","status":404,"detail":"MCP is not enabled in this artifact"}"#,
)))
.expect("valid response");
return box_full(Self::add_standard_headers(response, request_id, trace_id));
}
};
// CORS preflight
if *method == Method::OPTIONS {
let response = Response::builder()
.status(StatusCode::NO_CONTENT)
.header("access-control-allow-origin", "*")
.header("access-control-allow-methods", "POST, DELETE, OPTIONS")
.header(
"access-control-allow-headers",
"content-type, authorization, mcp-session-id",
)
.header("access-control-max-age", "86400")
.body(Full::new(Bytes::new()))
.expect("valid response");
return box_full(Self::add_standard_headers(response, request_id, trace_id));
}
// Handle session termination
if *method == Method::DELETE {
if let Some(session_id) = req
.headers()
.get("mcp-session-id")
.and_then(|v| v.to_str().ok())
{
mcp_server.remove_session(session_id);
}
let response = Response::builder()
.status(StatusCode::NO_CONTENT)
.body(Full::new(Bytes::new()))
.expect("valid response");
return box_full(Self::add_standard_headers(response, request_id, trace_id));
}
// Only POST is allowed
if *method != Method::POST {
let response = Response::builder()
.status(StatusCode::METHOD_NOT_ALLOWED)
.header("allow", "POST, DELETE, OPTIONS")
.header("content-type", "application/problem+json")
.body(Full::new(Bytes::from(
r#"{"type":"urn:barbacane:error:method-not-allowed","title":"Method Not Allowed","status":405,"detail":"MCP endpoint only accepts POST and DELETE"}"#,
)))
.expect("valid response");
return box_full(Self::add_standard_headers(response, request_id, trace_id));
}
// Extract session ID and all request headers before consuming the body
let session_id = req
.headers()
.get("mcp-session-id")
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string());
// Forward all request headers for tool call dispatch (auth middleware
// may inspect any header — Authorization, Cookie, X-Api-Key, etc.)
let forwarded_headers: HashMap<String, String> = req
.headers()
.iter()
.filter_map(|(k, v)| Some((k.as_str().to_string(), v.to_str().ok()?.to_string())))
.collect();
// Check content-length against body size limit before collecting
if let Some(content_length) = req
.headers()
.get("content-length")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<usize>().ok())
{
if self.limits.validate_body_size(content_length).is_err() {
let response = self.payload_too_large_response(self.limits.max_body_size);
return box_full(Self::add_standard_headers(response, request_id, trace_id));
}
}
// Cap the bytes read while collecting so a chunked body with no
// content-length can't be buffered past the limit (DoS).
let limited = http_body_util::Limited::new(req.into_body(), self.limits.max_body_size);
let body = match limited.collect().await {
Ok(collected) => collected.to_bytes(),
Err(e) => {
let response = if e
.downcast_ref::<http_body_util::LengthLimitError>()
.is_some()
{
self.payload_too_large_response(self.limits.max_body_size)
} else {
Response::builder()
.status(StatusCode::BAD_REQUEST)
.header("content-type", "application/problem+json")
.body(Full::new(Bytes::from(
r#"{"type":"urn:barbacane:error:bad-request","title":"Bad Request","status":400,"detail":"failed to read request body"}"#,
)))
.expect("valid response")
};
return box_full(Self::add_standard_headers(response, request_id, trace_id));
}
};
// Single parse: handle_request returns the appropriate result type
let result = mcp_server.handle_request(&body, session_id.as_deref());
match result {
barbacane_lib::mcp::McpResult::NeedsDispatch {
operation_index,
path,
query,
body: tool_body,
json_rpc_id,
} => {
// Dispatch through the middleware + dispatcher pipeline
let operation = &self.operations[operation_index];
let request_body = tool_body.as_deref().unwrap_or(&[]);
// Build headers: content-type + forwarded request headers
let mut headers = forwarded_headers;
if !request_body.is_empty() {
headers.insert("content-type".to_string(), "application/json".to_string());
}
// Extract path params from the resolved path
let params: Vec<(String, String)> = operation
.parameters
.iter()
.filter(|p| p.location == "path")
.filter_map(|p| {
extract_path_param(&operation.path, &path, &p.name)
.map(|v| (p.name.clone(), v))
})
.collect();
let dispatch_result = self
.dispatch(
operation,
&path,
params,
query,
request_body,
&headers,
None, // no client_addr for internal dispatch
None, // no upgrade handle
)
.await;
// Convert the HTTP response to MCP tool result
match dispatch_result {
Ok(response) => {
let status = response.status().as_u16();
let resp_body =
match http_body_util::BodyExt::collect(response.into_body()).await {
Ok(collected) => Some(collected.to_bytes().to_vec()),
Err(_) => None,
};
let mcp_response = barbacane_lib::mcp::format_tool_result(
json_rpc_id,
status,
resp_body.as_deref(),
);
self.record_request_metrics(
"POST",
"/__barbacane/mcp",
200,
body.len() as u64,
mcp_response.len() as u64,
start_time,
);
let response = Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json")
.body(Full::new(Bytes::from(mcp_response)))
.expect("valid response");
box_full(Self::add_standard_headers(response, request_id, trace_id))
}
Err(_) => {
// This shouldn't happen since dispatch returns Result<_, Infallible>
let response = Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Full::new(Bytes::new()))
.expect("valid response");
box_full(Self::add_standard_headers(response, request_id, trace_id))
}
}
}
barbacane_lib::mcp::McpResult::Response {
body: resp_body,
session_id: new_session_id,
} => {
self.record_request_metrics(
"POST",
"/__barbacane/mcp",
200,
body.len() as u64,
resp_body.len() as u64,
start_time,
);
let mut builder = Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json");
if let Some(sid) = new_session_id {
builder = builder.header("mcp-session-id", sid);
}
let response = builder
.body(Full::new(Bytes::from(resp_body)))
.expect("valid response");
box_full(Self::add_standard_headers(response, request_id, trace_id))
}
barbacane_lib::mcp::McpResult::NoResponse => {
// JSON-RPC notification — return 204
let response = Response::builder()
.status(StatusCode::NO_CONTENT)
.body(Full::new(Bytes::new()))
.expect("valid response");
box_full(Self::add_standard_headers(response, request_id, trace_id))
}
}
}
/// Build the specs index response (always JSON).
fn specs_index_response(&self) -> Response<Full<Bytes>> {
let mut openapi_specs = Vec::new();
let mut asyncapi_specs = Vec::new();
for (name, content) in &self.specs {
let spec_type = detect_spec_type(content);
let entry = serde_json::json!({
"name": name,
"url": format!("/__barbacane/specs/{}", name),
});
match spec_type {
SpecType::OpenApi => openapi_specs.push(entry),
SpecType::AsyncApi => asyncapi_specs.push(entry),
SpecType::Unknown => {} // Skip unknown specs
}
}
let body = serde_json::json!({
"openapi": {
"specs": openapi_specs,
"count": openapi_specs.len(),
"merged_url": "/__barbacane/specs/openapi"
},
"asyncapi": {
"specs": asyncapi_specs,
"count": asyncapi_specs.len(),
"merged_url": "/__barbacane/specs/asyncapi"
}
});
Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json")
.body(Full::new(Bytes::from(body.to_string())))
.expect("valid response")
}
/// Serve merged OpenAPI spec (all OpenAPI specs combined).
fn merged_openapi_response(&self, format: &str) -> Response<Full<Bytes>> {
// Collect all OpenAPI specs
let openapi_specs: Vec<_> = self
.specs
.iter()
.filter(|(_, content)| matches!(detect_spec_type(content), SpecType::OpenApi))
.collect();
if openapi_specs.is_empty() {
return self.not_found_response();
}
// Merge specs
let merged = merge_openapi_specs(&openapi_specs);
self.serve_spec_content(&merged, format)
}
/// Serve merged AsyncAPI spec (all AsyncAPI specs combined).
fn merged_asyncapi_response(&self, format: &str) -> Response<Full<Bytes>> {
// Collect all AsyncAPI specs
let asyncapi_specs: Vec<_> = self
.specs
.iter()
.filter(|(_, content)| matches!(detect_spec_type(content), SpecType::AsyncApi))
.collect();
if asyncapi_specs.is_empty() {
return self.not_found_response();
}
// Merge specs
let merged = merge_asyncapi_specs(&asyncapi_specs);
self.serve_spec_content(&merged, format)
}
/// Serve spec content in requested format.
fn serve_spec_content(&self, value: &serde_json::Value, format: &str) -> Response<Full<Bytes>> {
let (content, content_type) = if format == "json" {
(
serde_json::to_string_pretty(value).unwrap_or_default(),
"application/json",
)
} else {
(
serde_yaml::to_string(value).unwrap_or_default(),
"text/yaml",
)
};
Response::builder()
.status(StatusCode::OK)
.header("content-type", content_type)
.body(Full::new(Bytes::from(content)))
.expect("valid response")
}
/// Serve a specific spec file.
fn spec_file_response(&self, filename: &str, format: &str) -> Response<Full<Bytes>> {
if let Some(content) = self.specs.get(filename) {
let is_source_json = filename.ends_with(".json");
// Parse the spec
let parsed: Option<serde_json::Value> = if is_source_json {
serde_json::from_str(content).ok()
} else {
serde_yaml::from_str(content).ok()
};
match parsed {
Some(mut value) => {
// Strip x-barbacane-* extensions
strip_barbacane_keys_recursive(&mut value);
self.serve_spec_content(&value, format)
}
None => {
// If parsing fails, return original content
let content_type = if is_source_json {
"application/json"
} else {
"text/yaml"
};
Response::builder()
.status(StatusCode::OK)
.header("content-type", content_type)
.body(Full::new(Bytes::from(content.clone())))
.expect("valid response")
}
}
} else {
self.not_found_response()
}
}
/// Build the health response.
fn health_response(&self) -> Response<Full<Bytes>> {
let body = serde_json::json!({
"status": "healthy",
"artifact_version": self.manifest.barbacane_artifact_version,
"compiler_version": self.manifest.compiler_version,
"routes_count": self.manifest.routes_count,
});
Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json")
.body(Full::new(Bytes::from(body.to_string())))
.expect("valid response")
}
/// Build a 404 Not Found response (RFC 9457).
fn not_found_response(&self) -> Response<Full<Bytes>> {
let body = serde_json::json!({
"type": "urn:barbacane:error:not-found",
"title": "Not Found",
"status": 404,
});
Response::builder()
.status(StatusCode::NOT_FOUND)
.header("content-type", "application/problem+json")
.body(Full::new(Bytes::from(body.to_string())))
.expect("valid response")
}
/// Build a 405 Method Not Allowed response (RFC 9457).
fn method_not_allowed_response(
&self,
allowed: Vec<String>,
method: &str,
path: &str,
) -> Response<Full<Bytes>> {
let allow_header = allowed.join(", ");
let body = serde_json::json!({
"type": "urn:barbacane:error:method-not-allowed",
"title": "Method Not Allowed",
"status": 405,
"detail": format!("{method} is not allowed on {path}. Allowed methods: {allow_header}"),
});
Response::builder()
.status(StatusCode::METHOD_NOT_ALLOWED)
.header("content-type", "application/problem+json")
.header("allow", allow_header)
.body(Full::new(Bytes::from(body.to_string())))
.expect("valid response")
}
/// Handle CORS preflight request by executing only the CORS middleware.
///
/// This is called when an OPTIONS request with CORS headers is received
/// for a path that has a CORS middleware configured on one of its operations.
async fn handle_cors_preflight(
&self,
cors_middleware: &barbacane_compiler::MiddlewareConfig,
headers: &HashMap<String, String>,
request_id: &str,
trace_id: &str,
) -> Response<Full<Bytes>> {
// Build a minimal request for the CORS middleware
let headers_btree: std::collections::BTreeMap<String, String> = headers
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let plugin_request = barbacane_wasm::Request {
method: "OPTIONS".to_string(),
path: String::new(),
query: None,
headers: headers_btree,
body: None,
client_ip: "0.0.0.0".to_string(),
path_params: std::collections::BTreeMap::new(),
};
let request_json = match serde_json::to_vec(&plugin_request) {
Ok(j) => j,
Err(_) => {
return Self::add_standard_headers(
self.internal_error_response(None),
request_id,
trace_id,
);
}
};
// Execute only the CORS middleware
let middlewares = vec![cors_middleware.clone()];
match self.execute_middleware_on_request(&middlewares, &request_json, None) {
Ok((_, _, _, _)) => {
// CORS middleware didn't short-circuit, return empty 204
// (This shouldn't happen for valid preflights, but handle it gracefully)
Self::add_standard_headers(
Response::builder()
.status(StatusCode::NO_CONTENT)
.body(Full::new(Bytes::new()))
.expect("valid response"),
request_id,
trace_id,
)
}
Err(response) => {
// CORS middleware short-circuited with a response (expected for preflights)
Self::add_standard_headers(response, request_id, trace_id)
}
}
}
/// Build a 400 Bad Request response for generic errors.
fn bad_request_response(&self, message: &str) -> Response<Full<Bytes>> {
let body = serde_json::json!({
"type": "urn:barbacane:error:bad-request",
"title": "Bad Request",
"status": 400,
"detail": message,
});
Response::builder()
.status(StatusCode::BAD_REQUEST)
.header("content-type", "application/problem+json")
.body(Full::new(Bytes::from(body.to_string())))
.expect("valid response")
}
/// Build a 400 validation error response (RFC 9457).
fn validation_error_response(&self, errors: &[ValidationError2]) -> Response<Full<Bytes>> {
let problem = ProblemDetails::validation_error(errors, self.dev_mode);
Response::builder()
.status(StatusCode::BAD_REQUEST)
.header("content-type", "application/problem+json")
.body(Full::new(Bytes::from(problem.to_json())))
.expect("valid response")
}
/// Build a 413 Payload Too Large response (RFC 9457). Used when the request
/// body exceeds the configured size limit, whether detected via
/// `Content-Length` or while streaming a chunked body.
fn payload_too_large_response(&self, limit: usize) -> Response<Full<Bytes>> {
let body = serde_json::json!({
"type": "urn:barbacane:error:payload-too-large",
"title": "Payload Too Large",
"status": 413,
"detail": format!("Request body exceeds the maximum allowed size of {limit} bytes."),
});
Response::builder()
.status(StatusCode::PAYLOAD_TOO_LARGE)
.header("content-type", "application/problem+json")
.body(Full::new(Bytes::from(body.to_string())))
.expect("valid response")
}
/// Build a 500 Internal Server Error response (RFC 9457).
fn internal_error_response(&self, detail: Option<&str>) -> Response<Full<Bytes>> {
let body = if self.dev_mode {
serde_json::json!({
"type": "urn:barbacane:error:internal-error",
"title": "Internal Server Error",
"status": 500,
"detail": detail.unwrap_or("An internal error occurred"),
})
} else {
serde_json::json!({
"type": "urn:barbacane:error:internal-error",
"title": "Internal Server Error",
"status": 500,
})
};
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header("content-type", "application/problem+json")
.body(Full::new(Bytes::from(body.to_string())))
.expect("valid response")
}
/// Build a 500 response with detail visible only in dev mode.
fn dev_error_response(&self, msg: impl std::fmt::Display) -> Response<Full<Bytes>> {
let detail = if self.dev_mode {
Some(msg.to_string())
} else {
None
};
self.internal_error_response(detail.as_deref())
}
/// Relay WebSocket frames bidirectionally between client and upstream (ADR-0026).
///
/// Runs until either side closes or an error occurs. Frames are forwarded
/// as-is with no inspection or transformation.
async fn relay_websocket<C, U>(client_ws: C, upstream_ws: U)
where
C: futures_util::Sink<
tokio_tungstenite::tungstenite::Message,
Error = tokio_tungstenite::tungstenite::Error,
> + futures_util::Stream<
Item = Result<
tokio_tungstenite::tungstenite::Message,
tokio_tungstenite::tungstenite::Error,
>,
> + Send
+ 'static,
U: futures_util::Sink<
tokio_tungstenite::tungstenite::Message,
Error = tokio_tungstenite::tungstenite::Error,
> + futures_util::Stream<
Item = Result<
tokio_tungstenite::tungstenite::Message,
tokio_tungstenite::tungstenite::Error,
>,
> + Send
+ 'static,
{
use futures_util::{SinkExt, StreamExt};
let (mut client_tx, mut client_rx) = client_ws.split();
let (mut upstream_tx, mut upstream_rx) = upstream_ws.split();
// Client → Upstream
let client_to_upstream = async move {
while let Some(msg) = client_rx.next().await {
match msg {
Ok(m) if m.is_close() => {
let _ = upstream_tx.close().await;
break;
}
Ok(m) => {
if upstream_tx.send(m).await.is_err() {
break;
}
}
Err(_) => break,
}
}
};
// Upstream → Client
let upstream_to_client = async move {
while let Some(msg) = upstream_rx.next().await {
match msg {
Ok(m) if m.is_close() => {
let _ = client_tx.close().await;
break;
}
Ok(m) => {
if client_tx.send(m).await.is_err() {
break;
}
}
Err(_) => break,
}
}
};
// Run both directions concurrently; when one ends, drop the other.
tokio::select! {
() = client_to_upstream => {},
() = upstream_to_client => {},
}
tracing::debug!("WebSocket relay closed");
}
}
/// Validation result for a single spec file.
#[derive(serde::Serialize)]
struct ValidationResult {
file: String,
valid: bool,
errors: Vec<ValidationIssue>,
warnings: Vec<ValidationIssue>,
}
#[derive(serde::Serialize)]
struct ValidationIssue {
code: String,
message: String,
#[serde(skip_serializing_if = "Option::is_none")]
location: Option<String>,
}
/// Run the validate command.
fn run_validate(specs: &[String], output_format: &str) -> ExitCode {
let mut results = Vec::new();
let mut has_errors = false;
// Track all routes across specs for conflict detection (E1010)
// Key: (path, method), Value: spec file where first defined
let mut seen_routes: HashMap<(String, String), String> = HashMap::new();
// Collect parsed specs for cross-spec validation
let mut parsed_specs: Vec<(String, barbacane_compiler::ApiSpec)> = Vec::new();
// Phase 1: Parse and validate each spec individually
for spec_path in specs {
let path = Path::new(spec_path);
let mut errors = Vec::new();
let mut warnings = Vec::new();
// Check file exists
if !path.exists() {
errors.push(ValidationIssue {
code: "E1000".to_string(),
message: format!("file not found: {}", spec_path),
location: None,
});
has_errors = true;
results.push(ValidationResult {
file: spec_path.clone(),
valid: false,
errors,
warnings,
});
continue;
}
// Try to parse the spec
match barbacane_compiler::parse_spec_file(path) {
Ok(spec) => {
// Check for missing x-barbacane-dispatch on operations
for op in &spec.operations {
if op.dispatch.is_none() {
warnings.push(ValidationIssue {
code: "E1020".to_string(),
message: format!(
"operation {} {} is missing x-barbacane-dispatch",
op.method, op.path
),
location: Some(format!("{}:{} {}", spec_path, op.path, op.method)),
});
}
// Check middlewares have required 'name' field (E1011)
if let Some(middlewares) = &op.middlewares {
for (idx, mw) in middlewares.iter().enumerate() {
if mw.name.is_empty() {
errors.push(ValidationIssue {
code: "E1011".to_string(),
message: format!(
"middleware #{} in {} {} is missing 'name'",
idx + 1,
op.method,
op.path
),
location: Some(format!(
"{}:{} {}",
spec_path, op.path, op.method
)),
});
has_errors = true;
}
}
}
}
// Check global middlewares have required 'name' field (E1011)
for (idx, mw) in spec.global_middlewares.iter().enumerate() {
if mw.name.is_empty() {
errors.push(ValidationIssue {
code: "E1011".to_string(),
message: format!("global middleware #{} is missing 'name'", idx + 1),
location: Some(format!("{}:x-barbacane-middlewares", spec_path)),
});
has_errors = true;
}
}
// Note: E1015 (unknown x-barbacane-* extension) checking is done during compile,
// not validate, to avoid false positives on non-barbacane extensions.
// Store for cross-spec validation
parsed_specs.push((spec_path.clone(), spec));
results.push(ValidationResult {
file: spec_path.clone(),
valid: errors.is_empty(),
errors,
warnings,
});
}
Err(e) => {
let (code, message) = match &e {
barbacane_compiler::ParseError::UnknownFormat => {
("E1001".to_string(), e.to_string())
}
barbacane_compiler::ParseError::ParseError(_) => {
("E1002".to_string(), e.to_string())
}
barbacane_compiler::ParseError::UnresolvedRef(_) => {
("E1003".to_string(), e.to_string())
}
barbacane_compiler::ParseError::SchemaError(_) => {
("E1004".to_string(), e.to_string())
}
barbacane_compiler::ParseError::Io(io_err) => {
("E1000".to_string(), format!("I/O error: {}", io_err))
}
};
errors.push(ValidationIssue {
code,
message,
location: Some(spec_path.clone()),
});
has_errors = true;
results.push(ValidationResult {
file: spec_path.clone(),
valid: false,
errors,
warnings,
});
}
}
}
// Phase 2: Check for routing conflicts across specs (E1010)
if parsed_specs.len() > 1 {
for (spec_path, spec) in &parsed_specs {
for op in &spec.operations {
let key = (op.path.clone(), op.method.clone());
if let Some(other_spec) = seen_routes.get(&key) {
// Find the result for this spec and add the conflict error
if let Some(result) = results.iter_mut().find(|r| &r.file == spec_path) {
result.errors.push(ValidationIssue {
code: "E1010".to_string(),
message: format!(
"routing conflict: {} {} is also declared in '{}'",
op.method, op.path, other_spec
),
location: Some(format!("{}:{} {}", spec_path, op.path, op.method)),
});
result.valid = false;
has_errors = true;
}
} else {
seen_routes.insert(key, spec_path.clone());
}
}
}
}
// Output results
if output_format == "json" {
let output = serde_json::json!({
"results": results,
"summary": {
"total": results.len(),
"valid": results.iter().filter(|r| r.valid).count(),
"invalid": results.iter().filter(|r| !r.valid).count(),
}
});
println!(
"{}",
serde_json::to_string_pretty(&output).expect("serializable json")
);
} else {
// Text format
for result in &results {
if result.valid && result.warnings.is_empty() {
eprintln!("✓ {} is valid", result.file);
} else if result.valid {
eprintln!(
"✓ {} is valid (with {} warning(s))",
result.file,
result.warnings.len()
);
} else {
eprintln!("✗ {} has {} error(s)", result.file, result.errors.len());
}
for err in &result.errors {
if let Some(loc) = &err.location {
eprintln!(" {} [{}]: {}", err.code, loc, err.message);
} else {
eprintln!(" {}: {}", err.code, err.message);
}
}
for warn in &result.warnings {
if let Some(loc) = &warn.location {
eprintln!(" {} [{}]: {} (warning)", warn.code, loc, warn.message);
} else {
eprintln!(" {}: {} (warning)", warn.code, warn.message);
}
}
}
let valid_count = results.iter().filter(|r| r.valid).count();
let total = results.len();
eprintln!();
eprintln!(
"validated {} spec(s): {} valid, {} invalid",
total,
valid_count,
total - valid_count
);
}
if has_errors {
ExitCode::from(1)
} else {
ExitCode::SUCCESS
}
}
/// Official plugins available for download.
const OFFICIAL_PLUGINS: &[(&str, &str)] = &[
("mock", "mock.wasm"),
("http-upstream", "http-upstream.wasm"),
];
/// GitHub release URL base for official plugins.
const PLUGIN_RELEASE_BASE: &str =
"https://github.com/barbacane-dev/barbacane/releases/latest/download";
/// Download a plugin from GitHub releases.
async fn download_plugin(name: &str, filename: &str, dest_dir: &Path) -> Result<(), String> {
let url = format!("{}/{}", PLUGIN_RELEASE_BASE, filename);
let dest_path = dest_dir.join(filename);
eprint!(" Downloading {}...", name);
let client = reqwest::Client::new();
let response = client
.get(&url)
.send()
.await
.map_err(|e| format!("failed to fetch {}: {}", url, e))?;
if !response.status().is_success() {
return Err(format!(
"failed to download {}: HTTP {}",
filename,
response.status()
));
}
let bytes = response
.bytes()
.await
.map_err(|e| format!("failed to read response: {}", e))?;
std::fs::write(&dest_path, &bytes)
.map_err(|e| format!("failed to write {}: {}", dest_path.display(), e))?;
eprintln!(" done ({} bytes)", bytes.len());
Ok(())
}
/// Run the init command.
async fn run_init(name: &str, template: &str, fetch_plugins: bool) -> ExitCode {
use std::fs;
// Validate template
if template != "basic" && template != "minimal" {
eprintln!(
"error: unknown template '{}'. Use 'basic' or 'minimal'.",
template
);
return ExitCode::from(1);
}
// Determine project directory
let project_dir = if name == "." {
std::env::current_dir().unwrap_or_else(|_| Path::new(".").to_path_buf())
} else {
Path::new(name).to_path_buf()
};
// Check if directory is empty (if not ".")
if name != "." {
if project_dir.exists() {
if fs::read_dir(&project_dir)
.map(|mut d| d.next().is_some())
.unwrap_or(false)
{
eprintln!("error: directory '{}' is not empty", name);
return ExitCode::from(1);
}
} else if let Err(e) = fs::create_dir_all(&project_dir) {
eprintln!("error: failed to create directory '{}': {}", name, e);
return ExitCode::from(1);
}
}
// Create plugins and specs directories
let plugins_dir = project_dir.join("plugins");
if let Err(e) = fs::create_dir_all(&plugins_dir) {
eprintln!("error: failed to create plugins directory: {}", e);
return ExitCode::from(1);
}
let specs_dir = project_dir.join("specs");
if let Err(e) = fs::create_dir_all(&specs_dir) {
eprintln!("error: failed to create specs directory: {}", e);
return ExitCode::from(1);
}
// Download plugins if requested
let mut downloaded_plugins = Vec::new();
if fetch_plugins {
eprintln!("Fetching official plugins...");
for (plugin_name, filename) in OFFICIAL_PLUGINS {
match download_plugin(plugin_name, filename, &plugins_dir).await {
Ok(()) => downloaded_plugins.push((*plugin_name, *filename)),
Err(e) => {
eprintln!(" failed");
eprintln!("warning: {}", e);
}
}
}
if downloaded_plugins.is_empty() {
eprintln!("warning: no plugins were downloaded");
}
eprintln!();
}
// Create barbacane.yaml with downloaded plugins or empty template
let manifest_content = if downloaded_plugins.is_empty() {
r#"# Barbacane project manifest
# See https://barbacane.dev/docs/guide/spec-configuration for details
specs: ./specs/
plugins: {}
# Example plugin configuration:
# my-plugin:
# path: ./plugins/my-plugin.wasm
"#
.to_string()
} else {
let mut content = String::from(
"# Barbacane project manifest\n\
# See https://barbacane.dev/docs/guide/spec-configuration for details\n\n\
specs: ./specs/\n\n\
plugins:\n",
);
for (plugin_name, filename) in &downloaded_plugins {
content.push_str(&format!(
" {}:\n path: ./plugins/{}\n",
plugin_name, filename
));
}
content
};
if let Err(e) = fs::write(project_dir.join("barbacane.yaml"), &manifest_content) {
eprintln!("error: failed to create barbacane.yaml: {}", e);
return ExitCode::from(1);
}
// Create spec file based on template
let spec_content = if template == "basic" {
r#"openapi: "3.1.0"
info:
title: My API
version: "1.0.0"
description: A Barbacane-powered API
servers:
- url: http://localhost:8080
description: Local development
paths:
/health:
get:
summary: Health check
operationId: healthCheck
x-barbacane-dispatch:
name: mock
config:
status: 200
body: '{"status": "ok"}'
headers:
Content-Type: application/json
responses:
"200":
description: Service is healthy
content:
application/json:
schema:
type: object
properties:
status:
type: string
example: ok
/users:
get:
summary: List users
operationId: listUsers
x-barbacane-dispatch:
name: mock
config:
status: 200
body: '{"users": []}'
headers:
Content-Type: application/json
parameters:
- name: limit
in: query
schema:
type: integer
minimum: 1
maximum: 100
default: 10
responses:
"200":
description: List of users
content:
application/json:
schema:
type: object
properties:
users:
type: array
items:
type: object
post:
summary: Create user
operationId: createUser
x-barbacane-dispatch:
name: mock
config:
status: 201
body: '{"id": "user-123", "message": "Created"}'
headers:
Content-Type: application/json
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- name
- email
properties:
name:
type: string
minLength: 1
email:
type: string
format: email
responses:
"201":
description: User created
"400":
description: Invalid request
/users/{id}:
get:
summary: Get user by ID
operationId: getUser
x-barbacane-dispatch:
name: mock
config:
status: 200
body: '{"id": "{id}", "name": "John Doe"}'
headers:
Content-Type: application/json
parameters:
- name: id
in: path
required: true
schema:
type: string
format: uuid
responses:
"200":
description: User details
"404":
description: User not found
"#
} else {
// minimal template
r#"openapi: "3.1.0"
info:
title: My API
version: "1.0.0"
paths:
/health:
get:
summary: Health check
x-barbacane-dispatch:
name: mock
config:
status: 200
body: '{"status": "ok"}'
responses:
"200":
description: OK
"#
};
if let Err(e) = fs::write(specs_dir.join("api.yaml"), spec_content) {
eprintln!("error: failed to create specs/api.yaml: {}", e);
return ExitCode::from(1);
}
// Create .gitignore
let gitignore_content = r#"# Build artifacts
*.bca
target/
# IDE
.idea/
.vscode/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
"#;
if let Err(e) = fs::write(project_dir.join(".gitignore"), gitignore_content) {
eprintln!("error: failed to create .gitignore: {}", e);
return ExitCode::from(1);
}
// Success message
let dir_name = if name == "." {
"current directory"
} else {
name
};
eprintln!("✓ Initialized Barbacane project in {}", dir_name);
eprintln!();
eprintln!("Created:");
eprintln!(" barbacane.yaml - project manifest");
eprintln!(
" specs/api.yaml - OpenAPI specification ({} template)",
template
);
if !downloaded_plugins.is_empty() {
for (plugin_name, filename) in &downloaded_plugins {
eprintln!(" plugins/{} - {} plugin", filename, plugin_name);
}
} else {
eprintln!(" plugins/ - directory for WASM plugins");
}
eprintln!(" .gitignore - Git ignore file");
eprintln!();
eprintln!("Next steps:");
if downloaded_plugins.is_empty() && !fetch_plugins {
eprintln!(" 1. Download plugins: barbacane init . --fetch-plugins");
eprintln!(" Or add them manually to plugins/");
eprintln!(" 2. Edit specs/api.yaml to define your API");
eprintln!(" 3. Run: barbacane dev");
} else {
eprintln!(" 1. Edit specs/api.yaml to define your API");
eprintln!(" 2. Run: barbacane dev");
}
ExitCode::SUCCESS
}
// =============================================================================
// Hot-Reload Functions
// =============================================================================
/// Perform hot-reload: download, verify, load, and swap the gateway state.
async fn perform_hot_reload(
notification: control_plane::ArtifactNotification,
shared_gateway: &SharedGateway,
artifact_dir: &Path,
dev_mode: bool,
limits: RequestLimits,
allow_plaintext_upstream: bool,
metrics: Arc<MetricsRegistry>,
) -> HotReloadResult {
let artifact_id = notification.artifact_id;
// Acquire lock to prevent concurrent hot-reloads
let _guard = match hot_reload::HOT_RELOAD_LOCK.try_lock() {
Ok(guard) => guard,
Err(_) => {
tracing::warn!(
artifact_id = %artifact_id,
"Hot-reload already in progress, skipping"
);
return HotReloadResult::Failed {
artifact_id,
error: "hot-reload already in progress".to_string(),
};
}
};
tracing::info!(
artifact_id = %artifact_id,
download_url = %notification.download_url,
"Starting hot-reload"
);
// Create HTTP client for download
let http_client = reqwest::Client::new();
// Step 1: Download and verify artifact
let artifact_path = match hot_reload::download_artifact(
&http_client,
¬ification.download_url,
¬ification.sha256,
artifact_dir,
)
.await
{
Ok(path) => path,
Err(e) => {
tracing::error!(
artifact_id = %artifact_id,
error = %e,
"Hot-reload download failed"
);
return HotReloadResult::Failed {
artifact_id,
error: format!("download failed: {}", e),
};
}
};
// Step 2: Load and compile new Gateway
let new_gateway = match Gateway::load(
&artifact_path,
dev_mode,
limits,
allow_plaintext_upstream,
metrics,
) {
Ok(g) => g,
Err(e) => {
// Clean up downloaded artifact on failure
let _ = tokio::fs::remove_file(&artifact_path).await;
tracing::error!(
artifact_id = %artifact_id,
error = %e,
"Hot-reload load failed"
);
return HotReloadResult::Failed {
artifact_id,
error: format!("load failed: {}", e),
};
}
};
// Step 3: Atomic swap
let old_gateway = shared_gateway.swap(Arc::new(new_gateway));
tracing::info!(
artifact_id = %artifact_id,
old_routes = old_gateway.manifest.routes_count,
new_routes = shared_gateway.load().manifest.routes_count,
"Hot-reload completed successfully"
);
// Drop old gateway on a blocking thread to avoid panic when wasmtime's
// runtime is dropped inside an async context.
tokio::task::spawn_blocking(move || drop(old_gateway));
HotReloadResult::Success { artifact_id }
}
/// Run the compile command.
fn run_compile(
specs: &[String],
output: &str,
manifest_file: &str,
allow_plaintext: bool,
provenance_commit: Option<String>,
provenance_source: Option<String>,
no_cache: bool,
) -> ExitCode {
let output_path = Path::new(output);
let options = CompileOptions {
allow_plaintext,
provenance_commit,
provenance_source,
no_cache,
..Default::default()
};
let manifest_path = Path::new(manifest_file);
if !manifest_path.exists() {
eprintln!("error: manifest file not found: {}", manifest_file);
return ExitCode::from(1);
}
// Load the project manifest
let project_manifest = match ProjectManifest::load(manifest_path) {
Ok(m) => m,
Err(e) => {
eprintln!("error: failed to load manifest: {}", e);
return ExitCode::from(1);
}
};
// Get the base path for resolving plugin paths (directory containing the manifest)
let base_path = manifest_path.parent().unwrap_or(Path::new("."));
// Determine spec paths: from --spec args, or discover from manifest's specs folder.
let discovered_specs: Vec<std::path::PathBuf>;
let spec_paths: Vec<&Path> = if !specs.is_empty() {
specs.iter().map(Path::new).collect()
} else {
match project_manifest.discover_spec_files(base_path) {
Ok(paths) if paths.is_empty() => {
eprintln!(
"error: no spec files provided. Use --spec or add 'specs: ./specs/' to {}",
manifest_file
);
return ExitCode::from(1);
}
Ok(paths) => {
discovered_specs = paths;
discovered_specs.iter().map(|p| p.as_path()).collect()
}
Err(e) => {
eprintln!("error: {}", e);
return ExitCode::from(1);
}
}
};
// Check that all spec files exist
for path in &spec_paths {
if !path.exists() {
eprintln!("error: spec file not found: {}", path.display());
return ExitCode::from(1);
}
}
let result = compile_with_manifest(
&spec_paths,
&project_manifest,
base_path,
output_path,
&options,
);
match result {
Ok(compile_result) => {
// Print warnings if any
for warning in &compile_result.warnings {
eprintln!(
"warning[{}]: {}{}",
warning.code,
warning.message,
warning
.location
.as_ref()
.map(|l| format!(" ({})", l))
.unwrap_or_default()
);
}
let manifest = &compile_result.manifest;
let plugin_info = if manifest.plugins.is_empty() {
String::new()
} else {
format!(", {} plugin(s) bundled", manifest.plugins.len())
};
eprintln!(
"compiled {} spec(s) to {} ({} routes{})",
spec_paths.len(),
output,
manifest.routes_count,
plugin_info
);
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("error: compilation failed: {}", e);
ExitCode::from(1)
}
}
}
/// Run the dev server: compile, serve, watch, and hot-reload on changes.
async fn run_dev(
manifest_file: &str,
spec_overrides: &[String],
listen: &str,
metrics: Arc<MetricsRegistry>,
admin_bind: &str,
debounce_ms: u64,
) -> ExitCode {
use barbacane_lib::dev::DevWatcher;
let manifest_path = Path::new(manifest_file);
if !manifest_path.exists() {
eprintln!("barbacane dev: manifest not found: {}", manifest_file);
return ExitCode::from(1);
}
let manifest_dir = manifest_path
.parent()
.unwrap_or(Path::new("."))
.to_path_buf();
// Load manifest.
let mut project_manifest = match ProjectManifest::load(manifest_path) {
Ok(m) => m,
Err(e) => {
eprintln!("barbacane dev: {}", e);
return ExitCode::from(1);
}
};
// Determine spec files.
let mut spec_paths = if !spec_overrides.is_empty() {
spec_overrides
.iter()
.map(std::path::PathBuf::from)
.collect()
} else {
match project_manifest.discover_spec_files(&manifest_dir) {
Ok(paths) if paths.is_empty() => {
eprintln!(
"barbacane dev: no specs found. Add 'specs: ./specs/' to {} or pass --spec",
manifest_file
);
return ExitCode::from(1);
}
Ok(paths) => paths,
Err(e) => {
eprintln!("barbacane dev: {}", e);
return ExitCode::from(1);
}
}
};
let spec_count = spec_paths.len();
let plugin_count = project_manifest.plugins.len();
eprintln!(
"barbacane dev: loaded {} ({} spec(s), {} plugin(s))",
manifest_file, spec_count, plugin_count,
);
// Initial compile.
// no_cache is false: local path: plugins are always read fresh from disk,
// and url: plugins should use the download cache to avoid re-fetching on every reload.
let compile_options = CompileOptions {
allow_plaintext: true,
..Default::default()
};
let mut temp_artifact = match tempfile::NamedTempFile::new() {
Ok(f) => f,
Err(e) => {
eprintln!("barbacane dev: failed to create temp file: {}", e);
return ExitCode::from(1);
}
};
let temp_path = temp_artifact.path().to_path_buf();
let spec_refs: Vec<&Path> = spec_paths.iter().map(|p| p.as_path()).collect();
let compile_start = Instant::now();
if let Err(e) = compile_with_manifest(
&spec_refs,
&project_manifest,
&manifest_dir,
&temp_path,
&compile_options,
) {
eprintln!("barbacane dev: compile error: {}", e);
return ExitCode::from(1);
}
let compile_ms = compile_start.elapsed().as_millis();
// Load gateway.
let limits = RequestLimits::default();
let gateway: SharedGateway =
match Gateway::load(&temp_path, true, limits.clone(), true, metrics.clone()) {
Ok(g) => {
eprintln!(
"barbacane dev: compiled {} route(s) in {}ms",
g.manifest.routes_count, compile_ms
);
Arc::new(ArcSwap::new(Arc::new(g)))
}
Err(e) => {
eprintln!("barbacane dev: {}", e);
return ExitCode::from(1);
}
};
// Parse listen address.
let addr: SocketAddr = match listen.parse() {
Ok(a) => a,
Err(_) => {
eprintln!("barbacane dev: invalid listen address: {}", listen);
return ExitCode::from(1);
}
};
let listener = match TcpListener::bind(addr).await {
Ok(l) => l,
Err(e) => {
eprintln!("barbacane dev: failed to bind to {}: {}", addr, e);
return ExitCode::from(1);
}
};
eprintln!("barbacane dev: listening on http://{}", addr);
// Shutdown signal.
let (shutdown_tx, mut shutdown_rx) = watch::channel(false);
let shutdown_tx_clone = shutdown_tx.clone();
tokio::spawn(async move {
let _ = wait_for_shutdown_signal().await;
eprintln!("\nbarbacane dev: shutting down...");
let _ = shutdown_tx_clone.send(true);
});
// Admin API.
let admin_manifest: Arc<ArcSwap<barbacane_compiler::Manifest>> = {
let gw = gateway.load();
Arc::new(ArcSwap::new(Arc::new(gw.manifest.clone())))
};
let drift_detected = Arc::new(std::sync::atomic::AtomicBool::new(false));
if admin_bind != "off" {
let admin_addr: SocketAddr = match admin_bind.parse() {
Ok(a) => a,
Err(e) => {
eprintln!(
"barbacane dev: invalid --admin-bind address '{}': {}",
admin_bind, e
);
return ExitCode::from(1);
}
};
let admin_state = Arc::new(admin::AdminState {
manifest: admin_manifest.clone(),
metrics: metrics.clone(),
drift_detected: drift_detected.clone(),
started_at: Instant::now(),
});
let admin_shutdown_rx = shutdown_rx.clone();
tokio::spawn(async move {
if let Err(e) =
admin::start_admin_server(admin_addr, admin_state, admin_shutdown_rx).await
{
tracing::error!(error = %e, "Admin server failed");
}
});
eprintln!("barbacane dev: admin API on http://{}", admin_addr);
}
// File watcher.
let mut watch_paths: Vec<std::path::PathBuf> = vec![manifest_path
.canonicalize()
.unwrap_or(manifest_path.to_path_buf())];
// Watch spec sources: specs folder (if using manifest discovery) or individual files (if --spec overrides).
if spec_overrides.is_empty() {
if let Some(ref specs_dir) = project_manifest.specs {
let resolved = if Path::new(specs_dir).is_absolute() {
std::path::PathBuf::from(specs_dir)
} else {
manifest_dir.join(specs_dir)
};
if resolved.is_dir() {
watch_paths.push(resolved);
}
} else {
for p in &spec_paths {
watch_paths.push(p.clone());
}
}
} else {
for p in &spec_paths {
watch_paths.push(p.clone());
}
}
// Watch local plugin .wasm files.
for p in project_manifest.local_plugin_paths(&manifest_dir) {
if p.exists() {
watch_paths.push(p);
}
}
let watch_display: Vec<String> = watch_paths
.iter()
.filter_map(|p| p.strip_prefix(&manifest_dir).ok().or(Some(p.as_path())))
.map(|p| p.display().to_string())
.collect();
eprintln!("barbacane dev: watching {}", watch_display.join(", "));
let mut watcher = match DevWatcher::new(&watch_paths) {
Ok(w) => w,
Err(e) => {
eprintln!("barbacane dev: {}", e);
return ExitCode::from(1);
}
};
let debounce = Duration::from_millis(debounce_ms);
// MCP session eviction task.
{
let gw = gateway.clone();
let mut evict_shutdown = shutdown_rx.clone();
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(300));
interval.tick().await;
loop {
tokio::select! {
_ = interval.tick() => {
let g = gw.load();
if let Some(ref mcp) = g.mcp_server {
mcp.evict_expired_sessions();
}
}
_ = evict_shutdown.changed() => break,
}
}
});
}
// Main loop: accept connections + watch for file changes.
loop {
tokio::select! {
// Shutdown.
_ = shutdown_rx.changed() => {
if *shutdown_rx.borrow() {
break;
}
}
// File change detected.
changed = watcher.next_change(debounce) => {
if changed.is_empty() {
continue;
}
let changed_display: Vec<String> = changed
.iter()
.filter_map(|p| p.strip_prefix(&manifest_dir).ok().or(Some(p.as_path())))
.map(|p| p.display().to_string())
.collect();
eprint!("barbacane dev: [{}] recompiling...", changed_display.join(", "));
// Re-read manifest if it changed.
let manifest_canonical = manifest_path
.canonicalize()
.unwrap_or(manifest_path.to_path_buf());
let manifest_changed = changed.iter().any(|p| {
p.canonicalize().unwrap_or(p.clone()) == manifest_canonical
});
if manifest_changed {
match ProjectManifest::load(manifest_path) {
Ok(m) => project_manifest = m,
Err(e) => {
eprintln!(" manifest error: {}", e);
eprintln!("barbacane dev: serving previous version");
continue;
}
}
}
// Re-discover specs if using manifest folder (picks up additions/removals).
if spec_overrides.is_empty() {
match project_manifest.discover_spec_files(&manifest_dir) {
Ok(paths) if !paths.is_empty() => spec_paths = paths,
Ok(_) => {
eprintln!(" no spec files found");
eprintln!("barbacane dev: serving previous version");
continue;
}
Err(e) => {
eprintln!(" {}", e);
eprintln!("barbacane dev: serving previous version");
continue;
}
}
}
// Compile to new temp file.
let new_temp = match tempfile::NamedTempFile::new() {
Ok(f) => f,
Err(e) => {
eprintln!(" temp file error: {}", e);
continue;
}
};
let new_path = new_temp.path().to_path_buf();
let spec_refs: Vec<&Path> = spec_paths.iter().map(|p| p.as_path()).collect();
let compile_start = Instant::now();
if let Err(e) = compile_with_manifest(
&spec_refs,
&project_manifest,
&manifest_dir,
&new_path,
&compile_options,
) {
eprintln!(" compile error: {}", e);
eprintln!("barbacane dev: serving previous version");
continue;
}
// Load new gateway.
match Gateway::load(&new_path, true, limits.clone(), true, metrics.clone()) {
Ok(new_gw) => {
let routes = new_gw.manifest.routes_count;
let ms = compile_start.elapsed().as_millis();
// Atomic swap.
let old = gateway.swap(Arc::new(new_gw));
tokio::task::spawn_blocking(move || drop(old));
// Update admin manifest.
let gw = gateway.load();
admin_manifest.store(Arc::new(gw.manifest.clone()));
// Replace temp artifact.
temp_artifact = new_temp;
eprintln!(" reloaded {} route(s) in {}ms", routes, ms);
}
Err(e) => {
eprintln!(" load error: {}", e);
eprintln!("barbacane dev: serving previous version");
}
}
// Update watches if manifest changed (new plugins or specs folder).
if manifest_changed {
let mut new_watch_paths: Vec<std::path::PathBuf> = vec![
manifest_path.canonicalize().unwrap_or(manifest_path.to_path_buf()),
];
if let Some(ref specs_dir) = project_manifest.specs {
let resolved = if Path::new(specs_dir).is_absolute() {
std::path::PathBuf::from(specs_dir)
} else {
manifest_dir.join(specs_dir)
};
if resolved.is_dir() {
new_watch_paths.push(resolved);
}
}
for p in project_manifest.local_plugin_paths(&manifest_dir) {
if p.exists() {
new_watch_paths.push(p);
}
}
if let Err(e) = watcher.update_watches(&new_watch_paths) {
tracing::warn!(error = %e, "failed to update file watches");
}
}
}
// Accept new connection.
accept_result = listener.accept() => {
let (stream, peer_addr) = match accept_result {
Ok(conn) => conn,
Err(e) => {
tracing::debug!(error = %e, "accept failed");
continue;
}
};
metrics.connection_opened();
let gateway_snapshot = gateway.load_full();
let conn_metrics = metrics.clone();
let mut conn_shutdown_rx = shutdown_rx.clone();
let client_addr = Some(peer_addr);
tokio::spawn(async move {
let service = service_fn(move |req| {
let gateway = Arc::clone(&gateway_snapshot);
let client_addr = client_addr;
async move { gateway.handle_request(req, client_addr).await }
});
let io = TokioIo::new(stream);
let mut builder = auto::Builder::new(TokioExecutor::new());
configure_conn_builder(&mut builder, DEFAULT_KEEPALIVE);
let conn = builder.serve_connection_with_upgrades(io, service);
tokio::pin!(conn);
loop {
tokio::select! {
result = conn.as_mut() => {
if let Err(e) = result {
if !e.to_string().contains("connection closed") {
tracing::debug!(error = %e, "connection error");
}
}
break;
}
_ = conn_shutdown_rx.changed() => {
if *conn_shutdown_rx.borrow() {
conn.as_mut().graceful_shutdown();
}
}
}
}
conn_metrics.connection_closed();
});
}
}
}
// Clean up temp artifact.
drop(temp_artifact);
ExitCode::SUCCESS
}
/// Default ceiling on concurrently served connections, bounding file-descriptor
/// and task growth under a connection flood. Override with
/// `BARBACANE_MAX_CONNECTIONS`.
const DEFAULT_MAX_CONNECTIONS: usize = 10_000;
/// Maximum time allowed to complete a TLS handshake before the connection is
/// dropped. Bounds slowloris-style handshake stalls.
const TLS_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
/// Default idle keep-alive timeout used where no operator value is supplied
/// (e.g. the dev server). Also the per-request header-read deadline.
const DEFAULT_KEEPALIVE: Duration = Duration::from_secs(60);
/// Maximum number of concurrent HTTP/2 streams per connection, bounding a
/// single client's ability to multiplex a flood of streams.
const HTTP2_MAX_CONCURRENT_STREAMS: u32 = 256;
/// Apply ingress DoS hardening to a connection builder: a header-read deadline
/// (slowloris defense, doubling as the HTTP/1 idle keep-alive timeout), an
/// HTTP/2 keep-alive probe + timeout, and a per-connection stream cap.
fn configure_conn_builder(builder: &mut auto::Builder<TokioExecutor>, keepalive: Duration) {
builder
.http1()
// A timer is required for `header_read_timeout` to function.
.timer(TokioTimer::new())
.keep_alive(true)
.header_read_timeout(keepalive);
builder
.http2()
.timer(TokioTimer::new())
.keep_alive_interval(Some(Duration::from_secs(20)))
.keep_alive_timeout(keepalive)
.max_concurrent_streams(HTTP2_MAX_CONCURRENT_STREAMS);
}
/// TLS configuration for the server.
struct TlsConfig {
cert_path: String,
key_path: String,
/// Minimum TLS version: "1.2" or "1.3"
min_version: String,
}
/// Configuration for connected mode (optional control plane connection).
#[derive(Clone)]
struct ConnectedModeConfig {
/// WebSocket URL for the control plane (e.g., ws://control:8080/ws/data-plane).
control_plane_url: String,
/// Project ID to register with.
project_id: uuid::Uuid,
/// API key for authentication.
api_key: String,
/// Optional name for this data plane.
data_plane_name: Option<String>,
/// Artifact ID currently loaded (set after loading).
initial_artifact_id: Option<uuid::Uuid>,
}
/// Convert a WebSocket URL to an HTTP base URL.
///
/// E.g., `ws://host:9090/ws/data-plane` → `http://host:9090`
/// `wss://host:9090/ws/data-plane` → `https://host:9090`
fn ws_url_to_http_base(ws_url: &str) -> String {
let http_url = ws_url
.replacen("wss://", "https://", 1)
.replacen("ws://", "http://", 1);
// Strip the path portion, keeping only scheme + authority
// Find the third '/' (after "http://") to locate where the path starts
if let Some(authority_end) = http_url
.find("://")
.and_then(|i| http_url[i + 3..].find('/').map(|j| i + 3 + j))
{
http_url[..authority_end].to_string()
} else {
http_url
}
}
/// Load TLS certificates and create a rustls ServerConfig.
///
/// Configuration:
/// - Minimum TLS version configurable (1.2 or 1.3)
/// - ALPN: h2, http/1.1
fn load_tls_config(config: &TlsConfig) -> Result<Arc<ServerConfig>, String> {
// Load certificate chain
let cert_file = File::open(&config.cert_path).map_err(|e| {
format!(
"failed to open certificate file '{}': {}",
config.cert_path, e
)
})?;
let mut cert_reader = BufReader::new(cert_file);
let certs: Vec<CertificateDer<'static>> = rustls_pemfile::certs(&mut cert_reader)
.collect::<Result<Vec<_>, _>>()
.map_err(|e| {
format!(
"failed to parse certificate file '{}': {}",
config.cert_path, e
)
})?;
if certs.is_empty() {
return Err(format!("no certificates found in '{}'", config.cert_path));
}
// Load private key
let key_file = File::open(&config.key_path)
.map_err(|e| format!("failed to open key file '{}': {}", config.key_path, e))?;
let mut key_reader = BufReader::new(key_file);
let key: PrivateKeyDer<'static> = rustls_pemfile::private_key(&mut key_reader)
.map_err(|e| format!("failed to parse key file '{}': {}", config.key_path, e))?
.ok_or_else(|| format!("no private key found in '{}'", config.key_path))?;
// Select TLS versions based on min_version setting
// Note: min_version is validated at startup, so only "1.2" or "1.3" are possible
let versions: Vec<&'static rustls::SupportedProtocolVersion> = match config.min_version.as_str()
{
"1.3" => vec![&rustls::version::TLS13],
_ => vec![&rustls::version::TLS13, &rustls::version::TLS12], // "1.2" (default)
};
// Build TLS config with configured version
let mut server_config = ServerConfig::builder_with_protocol_versions(&versions)
.with_no_client_auth()
.with_single_cert(certs, key)
.map_err(|e| format!("failed to build TLS config: {}", e))?;
// Set ALPN protocols: prefer HTTP/2, fallback to HTTP/1.1
server_config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
Ok(Arc::new(server_config))
}
/// Run the serve command.
#[allow(clippy::too_many_arguments)]
async fn run_serve(
artifact: &str,
listen: &str,
dev: bool,
limits: RequestLimits,
allow_plaintext_upstream: bool,
tls_config: Option<TlsConfig>,
metrics: Arc<MetricsRegistry>,
keepalive_timeout: u64,
shutdown_timeout: u64,
connected_mode: Option<ConnectedModeConfig>,
admin_bind: &str,
) -> ExitCode {
let artifact_path = Path::new(artifact);
if !artifact_path.exists() {
eprintln!("error: artifact not found: {}", artifact);
return ExitCode::from(1);
}
// Determine artifact directory for hot-reload downloads
let artifact_dir = artifact_path
.parent()
.unwrap_or(Path::new("."))
.to_path_buf();
let gateway: SharedGateway = match Gateway::load(
artifact_path,
dev,
limits.clone(),
allow_plaintext_upstream,
metrics.clone(),
) {
Ok(g) => Arc::new(ArcSwap::new(Arc::new(g))),
Err(e) => {
eprintln!("error: {}", e);
// Exit code 13 for secret resolution failures
if e.contains("failed to resolve secrets") {
return ExitCode::from(13);
}
return ExitCode::from(1);
}
};
eprintln!(
"barbacane: loaded {} route(s) from artifact",
gateway.load().manifest.routes_count
);
// Parse listen address
let addr: SocketAddr = match listen.parse() {
Ok(a) => a,
Err(_) => {
eprintln!("error: invalid listen address: {}", listen);
return ExitCode::from(1);
}
};
// Bind the listener
let listener = match TcpListener::bind(addr).await {
Ok(l) => l,
Err(e) => {
eprintln!("error: failed to bind to {}: {}", addr, e);
return ExitCode::from(1);
}
};
// Load TLS config if provided
let tls_acceptor = match &tls_config {
Some(config) => {
let server_config = match load_tls_config(config) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {}", e);
return ExitCode::from(1);
}
};
Some(TlsAcceptor::from(server_config))
}
None => None,
};
let protocol = if tls_acceptor.is_some() {
"https"
} else {
"http"
};
eprintln!("barbacane: listening on {}://{}", protocol, addr);
// Create shutdown signal channel
let (shutdown_tx, mut shutdown_rx) = watch::channel(false);
// Spawn signal handler task
let shutdown_tx_clone = shutdown_tx.clone();
tokio::spawn(async move {
let _ = wait_for_shutdown_signal().await;
eprintln!("barbacane: received shutdown signal, draining connections...");
let _ = shutdown_tx_clone.send(true);
});
// Artifact hash watch channel for drift detection
let initial_hash = gateway.load().manifest.artifact_hash.clone();
let (artifact_hash_tx, artifact_hash_rx) = watch::channel(Some(initial_hash));
// Shared manifest for admin API (updated on hot-reload)
let admin_manifest: Arc<ArcSwap<barbacane_compiler::Manifest>> = {
let gw = gateway.load();
Arc::new(ArcSwap::new(Arc::new(gw.manifest.clone())))
};
let drift_detected = Arc::new(std::sync::atomic::AtomicBool::new(false));
// Start control plane client if in connected mode
let (mut artifact_rx, response_tx, control_plane_http_base) = if let Some(config) =
connected_mode
{
eprintln!(
"barbacane: connecting to control plane at {}",
config.control_plane_url
);
let http_base = ws_url_to_http_base(&config.control_plane_url);
let client = control_plane::ControlPlaneClient::new(control_plane::ControlPlaneConfig {
control_plane_url: config.control_plane_url,
project_id: config.project_id,
api_key: config.api_key,
data_plane_name: config.data_plane_name,
initial_artifact_id: config.initial_artifact_id,
});
let (rx, tx) = client.start(
shutdown_rx.clone(),
artifact_hash_rx,
drift_detected.clone(),
);
(Some(rx), Some(tx), Some(http_base))
} else {
(None, None, None)
};
// Start admin API server if enabled
if admin_bind != "off" {
let admin_addr: SocketAddr = match admin_bind.parse() {
Ok(addr) => addr,
Err(e) => {
eprintln!(
"error: invalid --admin-bind address '{}': {}",
admin_bind, e
);
return ExitCode::from(1);
}
};
let admin_state = Arc::new(admin::AdminState {
manifest: admin_manifest.clone(),
metrics: metrics.clone(),
drift_detected: drift_detected.clone(),
started_at: Instant::now(),
});
let admin_shutdown_rx = shutdown_rx.clone();
tokio::spawn(async move {
if let Err(e) =
admin::start_admin_server(admin_addr, admin_state, admin_shutdown_rx).await
{
tracing::error!(error = %e, "Admin server failed");
}
});
eprintln!("barbacane: admin API on http://{}", admin_addr);
}
// MCP session eviction background task (runs every 5 minutes)
{
let gw = gateway.clone();
let mut evict_shutdown = shutdown_rx.clone();
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(300));
interval.tick().await; // skip immediate first tick
loop {
tokio::select! {
_ = interval.tick() => {
let g = gw.load();
if let Some(ref mcp) = g.mcp_server {
mcp.evict_expired_sessions();
}
}
_ = evict_shutdown.changed() => break,
}
}
});
}
// Keep-alive / idle timeout: bounds how long an idle connection may wait for
// the next request's headers (slowloris defense + HTTP keep-alive idle).
let keepalive_duration = Duration::from_secs(keepalive_timeout.max(1));
let shutdown_duration = Duration::from_secs(shutdown_timeout);
// Cap concurrently served connections to bound FD/task growth under a flood.
let max_connections = std::env::var("BARBACANE_MAX_CONNECTIONS")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.filter(|&n| n > 0)
.unwrap_or(DEFAULT_MAX_CONNECTIONS);
let conn_semaphore = Arc::new(tokio::sync::Semaphore::new(max_connections));
// Track active connections for graceful shutdown
let active_connections = Arc::new(AtomicU64::new(0));
// Accept connections
loop {
tokio::select! {
// Check for shutdown signal
_ = shutdown_rx.changed() => {
if *shutdown_rx.borrow() {
break;
}
}
// Handle artifact notifications from control plane
Some(mut notification) = async {
match artifact_rx.as_mut() {
Some(rx) => rx.recv().await,
None => std::future::pending().await,
}
} => {
// Resolve relative download URLs against control plane base
if notification.download_url.starts_with('/') {
if let Some(base) = &control_plane_http_base {
notification.download_url = format!("{}{}", base, notification.download_url);
}
}
eprintln!(
"barbacane: new artifact available: {}, initiating hot-reload",
notification.artifact_id
);
// Clone values for the spawned task
let gateway_clone = gateway.clone();
let artifact_dir_clone = artifact_dir.clone();
let limits_clone = limits.clone();
let metrics_clone = metrics.clone();
let response_tx_clone = response_tx.clone();
let artifact_hash_tx_clone = artifact_hash_tx.clone();
let admin_manifest_clone = admin_manifest.clone();
tokio::spawn(async move {
let result = perform_hot_reload(
notification,
&gateway_clone,
&artifact_dir_clone,
dev,
limits_clone,
allow_plaintext_upstream,
metrics_clone,
)
.await;
// Send response to control plane
let response = match &result {
HotReloadResult::Success { artifact_id } => {
eprintln!(
"barbacane: hot-reload successful for artifact {}",
artifact_id
);
// Update artifact hash for drift detection
let gw = gateway_clone.load();
let _ =
artifact_hash_tx_clone.send(Some(gw.manifest.artifact_hash.clone()));
// Update admin API manifest
admin_manifest_clone.store(Arc::new(gw.manifest.clone()));
control_plane::ArtifactDownloadedResponse {
artifact_id: *artifact_id,
success: true,
error: None,
}
}
HotReloadResult::Failed { artifact_id, error } => {
eprintln!(
"barbacane: hot-reload failed for artifact {}: {}",
artifact_id, error
);
control_plane::ArtifactDownloadedResponse {
artifact_id: *artifact_id,
success: false,
error: Some(error.clone()),
}
}
};
// Send response if we have a channel
if let Some(tx) = response_tx_clone {
if let Err(e) = tx.send(response).await {
tracing::warn!(error = %e, "Failed to send hot-reload response");
}
}
});
}
// Accept new connections
accept_result = listener.accept() => {
let (stream, peer_addr) = match accept_result {
Ok(conn) => conn,
Err(e) => {
eprintln!("error: accept failed: {}", e);
continue;
}
};
// Connection cap: shed load when at capacity rather than letting
// FDs/tasks grow without bound.
let permit = match conn_semaphore.clone().try_acquire_owned() {
Ok(p) => p,
Err(_) => {
tracing::warn!(%peer_addr, "connection limit reached; dropping connection");
drop(stream);
continue;
}
};
// Track connection
metrics.connection_opened();
active_connections.fetch_add(1, Ordering::SeqCst);
// Get a snapshot of the gateway for this connection.
// All requests on this connection will use this version,
// allowing in-flight requests to complete during hot-reload.
let gateway_snapshot = gateway.load_full();
let tls_acceptor = tls_acceptor.clone();
let conn_metrics = metrics.clone();
let conn_counter = active_connections.clone();
let mut conn_shutdown_rx = shutdown_rx.clone();
let client_addr = Some(peer_addr);
let conn_keepalive = keepalive_duration;
tokio::spawn(async move {
// Held for the connection's lifetime; released on drop.
let _permit = permit;
let service = service_fn(move |req| {
let gateway = Arc::clone(&gateway_snapshot);
let client_addr = client_addr;
async move { gateway.handle_request(req, client_addr).await }
});
if let Some(acceptor) = tls_acceptor {
// TLS connection - uses auto protocol detection (HTTP/1.1 or HTTP/2 via ALPN).
// Bound the handshake so a stalled client can't pin the task.
let accepted =
match tokio::time::timeout(TLS_HANDSHAKE_TIMEOUT, acceptor.accept(stream))
.await
{
Ok(Ok(tls_stream)) => Some(tls_stream),
Ok(Err(e)) => {
tracing::debug!(error = %e, "TLS handshake failed");
None
}
Err(_) => {
tracing::debug!("TLS handshake timed out");
None
}
};
if let Some(tls_stream) = accepted {
let io = TokioIo::new(tls_stream);
let mut builder = auto::Builder::new(TokioExecutor::new());
configure_conn_builder(&mut builder, conn_keepalive);
let conn = builder.serve_connection_with_upgrades(io, service);
// Pin the connection for graceful shutdown
tokio::pin!(conn);
loop {
tokio::select! {
result = conn.as_mut() => {
if let Err(e) = result {
if !e.to_string().contains("connection closed") {
tracing::debug!(error = %e, "connection error");
}
}
break;
}
_ = conn_shutdown_rx.changed() => {
if *conn_shutdown_rx.borrow() {
// Graceful shutdown - let current request complete
conn.as_mut().graceful_shutdown();
}
}
}
}
}
} else {
// Plain TCP connection - uses auto protocol detection
// Supports both HTTP/1.1 and HTTP/2 prior knowledge (h2c)
let io = TokioIo::new(stream);
let mut builder = auto::Builder::new(TokioExecutor::new());
configure_conn_builder(&mut builder, conn_keepalive);
let conn = builder.serve_connection_with_upgrades(io, service);
// Pin the connection for graceful shutdown
tokio::pin!(conn);
loop {
tokio::select! {
result = conn.as_mut() => {
if let Err(e) = result {
if !e.to_string().contains("connection closed") {
tracing::debug!(error = %e, "connection error");
}
}
break;
}
_ = conn_shutdown_rx.changed() => {
if *conn_shutdown_rx.borrow() {
// Graceful shutdown - let current request complete
conn.as_mut().graceful_shutdown();
}
}
}
}
}
// Connection closed
conn_metrics.connection_closed();
conn_counter.fetch_sub(1, Ordering::SeqCst);
});
}
}
}
// Wait for active connections to drain (with timeout)
let drain_start = Instant::now();
loop {
let active = active_connections.load(Ordering::SeqCst);
if active == 0 {
eprintln!("barbacane: all connections drained, shutting down");
break;
}
if drain_start.elapsed() > shutdown_duration {
eprintln!(
"barbacane: shutdown timeout reached, {} connection(s) still active",
active
);
break;
}
eprintln!(
"barbacane: waiting for {} active connection(s) to complete...",
active
);
tokio::time::sleep(Duration::from_millis(500)).await;
}
ExitCode::SUCCESS
}
/// Wait for shutdown signal (SIGTERM or SIGINT).
async fn wait_for_shutdown_signal() {
#[cfg(unix)]
{
use tokio::signal::unix::{signal, SignalKind};
let mut sigterm = signal(SignalKind::terminate()).expect("failed to register SIGTERM");
let mut sigint = signal(SignalKind::interrupt()).expect("failed to register SIGINT");
tokio::select! {
_ = sigterm.recv() => {}
_ = sigint.recv() => {}
}
}
#[cfg(not(unix))]
{
tokio::signal::ctrl_c()
.await
.expect("failed to register ctrl+c handler");
}
}
#[tokio::main]
async fn main() -> ExitCode {
// Install the default crypto provider for rustls (required for TLS operations).
// This must be done before any TLS operations. Ignore errors if already installed.
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
let cli = Cli::parse();
match cli.command {
Commands::Compile {
spec,
output,
manifest,
allow_plaintext,
provenance_commit,
provenance_source,
no_cache,
} => run_compile(
&spec,
&output,
&manifest,
allow_plaintext,
provenance_commit,
provenance_source,
no_cache,
),
Commands::Validate { spec, format } => run_validate(&spec, &format),
Commands::Dev {
listen,
manifest,
spec,
log_level,
admin_bind,
debounce_ms,
} => {
let log_fmt = barbacane_telemetry::LogFormat::Pretty;
let telemetry_config = barbacane_telemetry::TelemetryConfig::new()
.with_log_level(&log_level)
.with_log_format(log_fmt);
let telemetry = match barbacane_telemetry::Telemetry::init(telemetry_config) {
Ok(t) => t,
Err(e) => {
eprintln!("error: failed to initialize telemetry: {}", e);
return ExitCode::from(1);
}
};
run_dev(
&manifest,
&spec,
&listen,
telemetry.metrics_clone(),
&admin_bind,
debounce_ms,
)
.await
}
Commands::Init {
name,
template,
fetch_plugins,
} => run_init(&name, &template, fetch_plugins).await,
Commands::Serve {
artifact,
listen,
dev,
log_level,
log_format,
otlp_endpoint,
trace_sampling,
max_body_size,
max_headers,
max_header_size,
max_uri_length,
allow_plaintext_upstream,
tls_cert,
tls_key,
tls_min_version,
keepalive_timeout,
shutdown_timeout,
control_plane,
project_id,
api_key,
data_plane_name,
admin_bind,
} => {
// Initialize telemetry
let log_fmt = barbacane_telemetry::LogFormat::parse(&log_format)
.unwrap_or(barbacane_telemetry::LogFormat::Json);
let mut telemetry_config = barbacane_telemetry::TelemetryConfig::new()
.with_log_level(&log_level)
.with_log_format(log_fmt)
.with_trace_sampling(trace_sampling);
if let Some(endpoint) = otlp_endpoint {
telemetry_config = telemetry_config.with_otlp_endpoint(endpoint);
}
let telemetry = match barbacane_telemetry::Telemetry::init(telemetry_config) {
Ok(t) => t,
Err(e) => {
eprintln!("error: failed to initialize telemetry: {}", e);
return ExitCode::from(1);
}
};
let metrics = telemetry.metrics_clone();
// Validate TLS min version
if tls_min_version != "1.2" && tls_min_version != "1.3" {
eprintln!(
"error: --tls-min-version must be '1.2' or '1.3', got '{}'",
tls_min_version
);
return ExitCode::from(1);
}
// Validate TLS arguments
let tls_config = match (tls_cert, tls_key) {
(Some(cert), Some(key)) => Some(TlsConfig {
cert_path: cert,
key_path: key,
min_version: tls_min_version,
}),
(None, None) => None,
(Some(_), None) => {
eprintln!("error: --tls-cert requires --tls-key");
return ExitCode::from(1);
}
(None, Some(_)) => {
eprintln!("error: --tls-key requires --tls-cert");
return ExitCode::from(1);
}
};
let limits = RequestLimits {
max_body_size,
max_headers,
max_header_size,
max_uri_length,
};
// Validate connected mode options
let connected_mode = match (&control_plane, &project_id, &api_key) {
(Some(cp), Some(pid), Some(key)) => {
// Parse project_id as UUID
let project_uuid = match uuid::Uuid::parse_str(pid) {
Ok(u) => u,
Err(_) => {
eprintln!("error: --project-id must be a valid UUID");
return ExitCode::from(1);
}
};
Some(ConnectedModeConfig {
control_plane_url: cp.clone(),
project_id: project_uuid,
api_key: key.clone(),
data_plane_name: data_plane_name.clone(),
initial_artifact_id: None,
})
}
(None, None, None) => None,
_ => {
eprintln!(
"error: --control-plane, --project-id, and --api-key must all be specified together"
);
return ExitCode::from(1);
}
};
run_serve(
&artifact,
&listen,
dev,
limits,
allow_plaintext_upstream,
tls_config,
metrics,
keepalive_timeout,
shutdown_timeout,
connected_mode,
&admin_bind,
)
.await
}
}
}
/// Extract a path parameter value from a resolved path by comparing with the template.
///
/// For example, given template "/users/{id}" and resolved path "/users/123",
/// extracts "123" for parameter "id".
///
/// For wildcard params like "/files/{path+}" and resolved "/files/a/b/c",
/// extracts "a/b/c" (all remaining segments joined).
fn extract_path_param(template: &str, resolved: &str, param_name: &str) -> Option<String> {
let template_segments: Vec<&str> = template.split('/').collect();
let resolved_segments: Vec<&str> = resolved.split('/').collect();
for (i, t_seg) in template_segments.iter().enumerate() {
let placeholder = format!("{{{}}}", param_name);
let wildcard_placeholder = format!("{{{}+}}", param_name);
if *t_seg == wildcard_placeholder {
// Wildcard: join all remaining resolved segments
if i < resolved_segments.len() {
return Some(resolved_segments[i..].join("/"));
}
return None;
}
if *t_seg == placeholder {
return resolved_segments.get(i).map(|s| s.to_string());
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn build_response_from_plugin_skips_invalid_headers_without_panicking() {
use std::collections::BTreeMap;
// An untrusted plugin returns headers with an illegal name, an illegal
// value (embedded newline), and framing headers — none may panic the
// task, and the invalid/framing ones must be dropped.
let mut headers = BTreeMap::new();
headers.insert("x-ok".to_string(), "fine".to_string());
headers.insert("bad name".to_string(), "1".to_string()); // space in name
headers.insert("".to_string(), "empty-name".to_string()); // empty name
headers.insert("x-inject".to_string(), "a\r\nb".to_string()); // CRLF in value
headers.insert("content-length".to_string(), "999".to_string()); // framing
let plugin_response = barbacane_wasm::Response {
status: 200,
headers,
body: Some(b"hello".to_vec()),
};
let resp = Gateway::build_response_from_plugin(&plugin_response);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get("x-ok").unwrap(), "fine");
assert!(resp.headers().get("bad name").is_none());
assert!(resp.headers().get("x-inject").is_none());
// Framing header is dropped (hyper recomputes content-length).
assert!(resp.headers().get("content-length").is_none());
}
#[test]
fn test_ws_url_to_http_base() {
assert_eq!(
ws_url_to_http_base("ws://localhost:9090/ws/data-plane"),
"http://localhost:9090"
);
assert_eq!(
ws_url_to_http_base("wss://control.example.com/ws/data-plane"),
"https://control.example.com"
);
assert_eq!(
ws_url_to_http_base("ws://10.0.0.1:8080/ws/data-plane"),
"http://10.0.0.1:8080"
);
// No path
assert_eq!(
ws_url_to_http_base("ws://localhost:9090"),
"http://localhost:9090"
);
}
#[test]
fn test_extract_path_param_simple() {
assert_eq!(
extract_path_param("/users/{id}", "/users/123", "id"),
Some("123".to_string())
);
}
#[test]
fn test_extract_path_param_multiple() {
assert_eq!(
extract_path_param(
"/users/{userId}/orders/{orderId}",
"/users/abc/orders/456",
"userId"
),
Some("abc".to_string())
);
assert_eq!(
extract_path_param(
"/users/{userId}/orders/{orderId}",
"/users/abc/orders/456",
"orderId"
),
Some("456".to_string())
);
}
#[test]
fn test_extract_path_param_not_found() {
assert_eq!(
extract_path_param("/users/{id}", "/users/123", "name"),
None
);
}
#[test]
fn test_extract_path_param_wildcard() {
assert_eq!(
extract_path_param("/files/{path+}", "/files/a/b/c", "path"),
Some("a/b/c".to_string())
);
}
#[test]
fn test_extract_path_param_wildcard_single_segment() {
assert_eq!(
extract_path_param("/files/{path+}", "/files/readme.txt", "path"),
Some("readme.txt".to_string())
);
}
#[test]
fn test_extract_path_param_wildcard_with_prefix() {
assert_eq!(
extract_path_param(
"/storage/{bucket}/{key+}",
"/storage/uploads/2024/01/report.pdf",
"bucket"
),
Some("uploads".to_string())
);
assert_eq!(
extract_path_param(
"/storage/{bucket}/{key+}",
"/storage/uploads/2024/01/report.pdf",
"key"
),
Some("2024/01/report.pdf".to_string())
);
}
}