ordinary-config 0.7.1

Config for Ordinary
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
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
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc = include_str!("../README.md")]
#![doc = include_str!("../docs/config-reference.md")]
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::missing_errors_doc)]

// Copyright (C) 2026 Ordinary Labs, LLC.
//
// SPDX-License-Identifier: AGPL-3.0-only

mod validate;

pub use crate::validate::DOMAIN_REGEX;
use crate::validate::validate;

use anyhow::bail;
use arrayvec::ArrayVec;
use hashbrown::HashSet;
use ordinary_types::{Field, Kind};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::env;
use std::fmt::{Display, Formatter, Write};
use std::path::Path;
use std::process::Command;
use tracing::instrument;

fn default_env_name() -> String {
    "development".to_string()
}

#[derive(Deserialize, Serialize, Clone)]
pub struct OrdinaryApiConfig {
    pub domain: String,
    pub contacts: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub public_dns_ip: Option<[u8; 4]>,
    #[serde(default = "default_env_name")]
    pub env_name: String,
    #[serde(default)]
    pub limits: OrdinaryApiLimits,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct AssetsLimits {
    /// Allowed extensions corresponding to
    /// [MIME](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types) types.
    ///
    /// (More to be supported in the future)
    ///
    /// Supported:
    /// - "txt"
    /// - "xml"
    /// - "html"
    /// - "css"
    /// - "css.map"
    /// - "csv"
    /// - "js"
    /// - "png"
    /// - "apng"
    /// - "gif"
    /// - "svg"
    /// - "jpg"
    /// - "jpeg"
    /// - "bmp"
    /// - "tif"
    /// - "tiff"
    /// - "webp"
    /// - "avif"
    /// - "ico"
    /// - "pdf"
    /// - "json"
    /// - "wasm"
    ///
    /// Special:
    /// - "none" (for no extension; uses "application/octet-stream")
    /// - "any" (for unsupported extensions; also uses "application/octet-stream")
    pub allowed_extensions: Vec<String>,
    /// Limit on total storage for all assets within an app
    /// (bytes).
    pub max_store_size: u64,
    /// Limit on individual asset size (bytes).
    pub max_asset_size: u64,
}

impl Default for AssetsLimits {
    fn default() -> Self {
        Self {
            allowed_extensions: vec![
                "otf".into(),
                "ttf".into(),
                "woff".into(),
                "woff2".into(),
                "txt".into(),
                "xml".into(),
                "html".into(),
                "css".into(),
                "css.map".into(),
                "csv".into(),
                "js".into(),
                "png".into(),
                "apng".into(),
                "gif".into(),
                "svg".into(),
                "jpg".into(),
                "jpeg".into(),
                "bmp".into(),
                "tif".into(),
                "tiff".into(),
                "webp".into(),
                "avif".into(),
                "ico".into(),
                "pdf".into(),
                "json".into(),
                "wasm".into(),
            ],
            max_store_size: 100_000_000,
            max_asset_size: 1_500_000,
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ArtifactLimits {
    pub max_store_size: u64,
    pub max_artifact_size: u64,
}

impl Default for ArtifactLimits {
    fn default() -> Self {
        Self {
            max_store_size: 10_000_000,
            max_artifact_size: 500_000,
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct CacheLimits {
    pub max_size_range: (u64, u64),
    pub max_count_range: (usize, usize),

    pub clean_interval_ranges: ((u64, u64), (u64, u64)),
}

impl Default for CacheLimits {
    fn default() -> Self {
        Self {
            max_size_range: (1_000_000, 10_000_000),
            max_count_range: (100, 500),

            clean_interval_ranges: ((5, 10), (15, 20)),
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ContentLimits {
    pub search_enabled: bool,

    pub max_content_definitions: u8,
    pub max_content_fields: u8,

    pub max_store_size: u64,
    pub max_object_size: u64,
    pub max_field_size: u64,
}

impl Default for ContentLimits {
    fn default() -> Self {
        Self {
            search_enabled: true,

            max_content_definitions: 255,
            max_content_fields: 255,

            max_store_size: 10_000_000,
            max_object_size: 400_000,
            max_field_size: 200_000,
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ModelLimits {
    pub search_enabled: bool,

    pub max_model_definitions: u8,
    pub max_model_fields: u8,

    pub max_item_size: u64,
    pub max_field_size: u64,
}

impl Default for ModelLimits {
    fn default() -> Self {
        Self {
            search_enabled: true,

            max_model_definitions: 255,
            max_model_fields: 255,

            max_item_size: 400_000,
            max_field_size: 100_000,
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct SecretsLimits {
    pub max_count: u8,
    pub max_size: u64,
}

impl Default for SecretsLimits {
    fn default() -> Self {
        Self {
            max_count: 225,
            max_size: 2_000,
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct StorageLimits {
    /// Maximum total storage for all apps and api.
    ///
    /// Unit: bytes.
    ///
    /// Default: 10 GB
    pub max_storage: u64,
    /// Maximum per-app storage.
    ///
    /// Unit: bytes.
    ///
    /// Default: 50 MB
    pub max_app_storage: u64,

    pub assets: AssetsLimits,
    pub artifact: ArtifactLimits,
    pub cache: CacheLimits,
    pub content: ContentLimits,
    pub model: ModelLimits,
    pub secrets: SecretsLimits,
}

impl Default for StorageLimits {
    fn default() -> Self {
        Self {
            max_storage: 20_000_000_000,
            max_app_storage: 50_000_000,

            assets: AssetsLimits::default(),
            artifact: ArtifactLimits::default(),
            cache: CacheLimits::default(),
            content: ContentLimits::default(),
            model: ModelLimits::default(),
            secrets: SecretsLimits::default(),
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct MonitorLimits {}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct IntegrationLimits {
    /// Max number of integrations per app.
    pub count: u8,

    /// Integration request timeout.
    ///
    /// Unit: seconds.
    pub max_timeout: u16,
}

impl Default for IntegrationLimits {
    fn default() -> Self {
        Self {
            count: 255,
            max_timeout: 10,
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ActionLimits {
    /// Max number of actions per app.
    pub count: u8,

    /// Action request timeout.
    ///
    /// Unit: seconds.
    pub max_timeout: u16,
}

impl Default for ActionLimits {
    fn default() -> Self {
        Self {
            count: 255,
            max_timeout: 10,
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct AuthLimits {}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ProxyLimits {
    /// max number of proxies per application.
    pub count: u8,
    /// a list of any internal or external target
    /// regexes that should be disallowed.
    pub disallowed_targets: Vec<String>,
}

impl Default for ProxyLimits {
    fn default() -> Self {
        Self {
            count: 255,
            disallowed_targets: vec![],
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct TemplateLimits {
    /// Max number of templates per app.
    pub count: u8,

    /// Template request timeout.
    ///
    /// Unit: seconds.
    pub max_timeout: u16,
}

impl Default for TemplateLimits {
    fn default() -> Self {
        Self {
            count: 255,
            max_timeout: 10,
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct OrdinaryApiLimits {
    pub app_domains: Vec<String>,
    pub privileged_domains: Vec<String>,

    /// Max default timeout for all HTTP requests.
    ///
    /// Default: 10
    pub max_default_timeout: u16,

    pub proxy: ProxyLimits,

    pub action: ActionLimits,
    pub auth: AuthLimits,
    pub integration: IntegrationLimits,
    pub monitor: MonitorLimits,
    pub storage: StorageLimits,
    pub template: TemplateLimits,
}

impl Default for OrdinaryApiLimits {
    fn default() -> Self {
        Self {
            app_domains: vec![],
            privileged_domains: vec![],

            max_default_timeout: 10,

            proxy: ProxyLimits::default(),

            action: ActionLimits::default(),
            auth: AuthLimits::default(),
            integration: IntegrationLimits::default(),
            monitor: MonitorLimits::default(),
            storage: StorageLimits::default(),
            template: TemplateLimits::default(),
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ClientLoggingConfig {
    /// bottom end of the delayed delivery range (seconds)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    min_delay: Option<u32>,
    /// top end of delayed delivery range (seconds)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    max_delay: Option<u32>,
    /// max number of events to be buffered on the client
    /// prior to flush.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    max_buffer: Option<u16>,
    /// sets the max number of events in a given request.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    max_batch: Option<u16>,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum RedactedHashAlg {
    Blake2,
    Blake3,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ServerLoggingConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub ips: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub headers: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub credentials: Option<RedactedHashAlg>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub timing: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub sizes: Option<bool>,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct LoggingConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub client: Option<ClientLoggingConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub server: Option<ServerLoggingConfig>,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Check {
    // todo: what to validate the token against
    // ?? i.e "token.fields.account is included in list of post.author.followers.accounts"
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum TokenAlgorithm {
    HmacBlake2b256,
}

/// Configuration for refresh tokens.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct RefreshTokenConfig {
    /// Algorithm used for verifying the token.
    pub algorithm: TokenAlgorithm,
    /// How long a token should be valid for (seconds).
    pub lifetime: u32,
    /// how frequently the key should be rotated
    pub rotation: u32,
}

impl Default for RefreshTokenConfig {
    fn default() -> RefreshTokenConfig {
        RefreshTokenConfig {
            algorithm: TokenAlgorithm::HmacBlake2b256,
            lifetime: 60 * 60 * 24 * 7,
            rotation: 60 * 60 * 24 * 7 * 2,
        }
    }
}

/// Configuration for access tokens.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct AccessTokenConfig {
    /// Algorithm used for verifying the token.
    pub algorithm: TokenAlgorithm,
    /// How long a token should be valid for (seconds).
    pub lifetime: u32,
    /// how frequently the key should be rotated
    pub rotation: u32,
    /// Token claims structuring.
    ///
    /// Note: `idx` starts at 1 to create space for system claims (id, domain, and account).
    pub claims: Vec<Field>,
}

impl Default for AccessTokenConfig {
    fn default() -> AccessTokenConfig {
        AccessTokenConfig {
            algorithm: TokenAlgorithm::HmacBlake2b256,
            lifetime: 60 * 60 * 24,
            rotation: 60 * 60 * 24 * 3,
            claims: vec![],
        }
    }
}

/// Configuration for client password hashing.
///
/// When JavaScript or WASM modes are enabled, passwords are
/// hashed with the application name, and account, before transit
/// (or in the case of WASM prior to the Opaque client operations
/// if Opaque is selected for the `PasswordProtocol`).
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum ClientPasswordHash {
    /// Limited by what browsers can support, SHA-256 is
    /// a good option for a client-side hash to enable
    /// slightly better password protection when in
    /// javascript-only mode, without the WASM for Opaque.
    Sha256,
}

/// Configuration for password protocol.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum PasswordProtocol {
    /// When WASM is enabled, this will run the client portions
    /// browser-side. When JavaScript-only, passwords will be hashed
    /// and then sent to the server where the client portion will
    /// be done on behalf of the user. In noscript mode, the password
    /// is sent only protected by TLS, hashed and then the client operations
    /// are done server side.
    ///
    /// If a user later decides to enable JavaScript or WASM, they'll be
    /// able to opt in to the no-plain-password-sent modes without interruption.
    Opaque,
    // todo: SRP and Bcrypt/Argon2 hashing?
}

/// Configuration for passwords.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct PasswordConfig {
    pub protocol: PasswordProtocol,
}

impl Default for PasswordConfig {
    fn default() -> PasswordConfig {
        PasswordConfig {
            protocol: PasswordProtocol::Opaque,
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum TotpAlgorithm {
    /// only allowing SHA1 for now
    /// because many of the major MFA authenticator
    /// apps don't support SHA256 or SHA512, and fail silently.
    Sha1,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct TotpConfig {
    /// Used for response after registration form is submitted.
    /// Will just return a QR code SVG if not set.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub template: Option<String>,
    pub algorithm: TotpAlgorithm,
}

impl Default for TotpConfig {
    fn default() -> TotpConfig {
        TotpConfig {
            template: None,
            algorithm: TotpAlgorithm::Sha1,
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct MfaConfig {
    pub totp: TotpConfig,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum InviteMode {
    /// only the root user can invite
    Root,
    /// only a site admin can invite
    Admin,
    /// anyone who has been invited can invite anyone else
    Viral,
    // ?? anyone who has been invited has a limited set of invites they
    // ?? can share on an optional interval.
    // todo: Limited,
    // ?? only those invited with permission to invite can invite others
    // todo: Selective,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct InviteConfig {
    pub mode: InviteMode,
    /// How long a token is valid for.
    ///
    /// Defaults to 7 days.
    pub lifetime: u32,
    /// On what interval to clean up expired token ids.
    ///
    /// Defaults to 30 - 90 seconds.
    pub clean_interval: (u32, u32),
    /// Values that can be used internally in the API server to
    /// set default permissions for new accounts.
    ///
    /// TODO: in the future, these can also be set in order to pre-validate
    /// TODO: or constrain `app` account registrations. This will require the
    /// TODO: use of an `InviteCreate` action trigger (for validating and setting
    /// TODO: the invite token claims), and a pre-registration `InviteValidate`,
    /// TODO: as well as passing the invite token claims to the `Registration` trigger
    /// TODO: (allowing for the validated invite claims to be used in the account
    /// TODO: claims setting operation).
    ///
    /// Note: `idx` starts at 1 to create space for system claims (id, domain, and account).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub claims: Option<Vec<Field>>,
}

impl Default for InviteConfig {
    fn default() -> InviteConfig {
        InviteConfig {
            mode: InviteMode::Viral,
            lifetime: 60 * 60 * 24 * 7,
            clean_interval: (30, 90),
            claims: None,
        }
    }
}

/// Auth configuration.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct AuthConfig {
    /// Configuration for passwords.
    pub password: PasswordConfig,
    /// MFA configuration for auth.
    pub mfa: MfaConfig,
    /// Configuration for refresh tokens.
    pub refresh_token: RefreshTokenConfig,
    /// Configuration for access tokens.
    pub access_token: AccessTokenConfig,
    /// Determines whether cookies should be used
    /// for browser based template navigation, and form submissions
    ///
    /// Note: when set to `false`, `protected` templates, and actions triggered
    /// by form submission will fail. Form based registration and login will
    /// necessarily be disabled, also.
    ///
    /// !! Important: when set to `true`, tokens retrieved for `js` and `noscript` flavors
    /// !! do not support client signatures, because http-only cookies cannot be signed by
    /// !! the client.
    pub cookies_enabled: bool,
    /// what algorithm is used to hash passwords and MFA codes
    pub client_hash: ClientPasswordHash,

    /// invite config
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub invite: Option<InviteConfig>,
}

impl Default for AuthConfig {
    fn default() -> AuthConfig {
        AuthConfig {
            password: PasswordConfig::default(),
            mfa: MfaConfig::default(),
            refresh_token: RefreshTokenConfig::default(),
            access_token: AccessTokenConfig::default(),
            cookies_enabled: false,
            client_hash: ClientPasswordHash::Sha256,
            invite: None,
        }
    }
}

/// Compression algorithms
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub enum CompressionAlgorithm {
    All,
    Gzip,
    Zstd { level: u8 },
    Brotli,
    Deflate,
}

impl CompressionAlgorithm {
    #[must_use]
    pub fn as_u8(&self) -> u8 {
        match self {
            Self::All => 0,
            Self::Gzip => 1,
            Self::Zstd { level: _ } => 2,
            Self::Brotli => 3,
            Self::Deflate => 4,
        }
    }

    #[must_use]
    pub fn as_char(&self) -> char {
        match self {
            Self::All => '0',
            Self::Gzip => '1',
            Self::Zstd { level: _ } => '2',
            Self::Brotli => '3',
            Self::Deflate => '4',
        }
    }

    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::All => "",
            Self::Gzip => "gzip",
            Self::Zstd { level: _ } => "zstd",
            Self::Brotli => "br",
            Self::Deflate => "deflate",
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum StoredCachePolicy {
    /// No eviction on clean or write. Constrained only by overall storage limit or `max_size`
    /// (if set). Will only be evicted if dependencies change and `evict_on_dependency_change`
    /// is set.
    Permanent,
    /// Prioritize the most Frequently accessed, Recently accessed and smallest Sized items
    ///
    /// (`frequency_equality_threshold` (hit count), `recency_equality_threshold` (seconds))
    FRs(u64, u64),
}

/// Render caching policy.
///
/// IMPORTANT: Very experimental, may not work as described. `policy: Permanent` is currently
/// the most likely to behave correctly.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct StoredCache {
    pub policy: StoredCachePolicy,

    /// Which compression formats should be stored
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub compression: Option<CompressionAlgorithms>,

    #[serde(skip_serializing)]
    #[serde(default)]
    pub internal_compression: Option<ArrayVec<CompressionAlgorithm, 4>>,

    /// Upper limit on total time a cached item can be stored
    ///
    /// Unit: seconds
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub max_ttl: Option<u64>,

    /// Compared with time since last hit.
    ///
    /// Unit: seconds
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub hit_ttl: Option<u64>,

    /// Upper limit on the cumulative size of all cached responses
    /// for a given template.
    ///
    /// Unit: bytes
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub max_size: Option<u64>,

    /// Upper limit on the number of cached responses stored at
    /// a given time, for a given template.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub max_count: Option<usize>,

    /// How long an LFU "hit" tick is valid for
    ///
    /// Unit: seconds
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub frequency_window: Option<u64>,

    /// Rate at which the cache is cleaned based on other rules.
    ///
    /// Option<(min, max)>
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub clean_interval: Option<(u64, u64)>,

    /// Whether a cached item should also track the of models and content
    /// which it depends on, and evict when they are modified.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub evict_on_dependency_change: Option<bool>,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum XXH3Variation {
    Bit64,
    Bit128,
}

/// Hashing algorithm options for generating etags.
///
/// `AHash` is the default if none is selected.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum HttpEtagAlgorithm {
    AHash,
    XXH3(XXH3Variation),
    Rustc,
    Blake3,
}

/// HTTP Cache-Control.
/// See: <https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control>
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct HttpEtag {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub alg: Option<HttpEtagAlgorithm>,
}

/// HTTP Cache-Control.
/// See: <https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control>
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct HttpCacheControl {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub max_age: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub s_maxage: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub no_cache: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub no_store: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub no_transform: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub must_revalidate: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub proxy_revalidate: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub private: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub public: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub immutable: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub stale_while_revalidate: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub stale_if_error: Option<bool>,
}

impl HttpCacheControl {
    pub fn header_value(&self, cache_control: &mut String, default: &str) -> anyhow::Result<()> {
        if let Some(max_age) = self.max_age {
            write!(cache_control, "max-age={max_age}, ")?;
        }
        if let Some(s_maxage) = self.s_maxage {
            write!(cache_control, "s-maxage={s_maxage}, ")?;
        }
        if let Some(no_cache) = self.no_cache
            && no_cache
        {
            write!(cache_control, "no-cache, ")?;
        }
        if let Some(no_store) = self.no_store
            && no_store
        {
            write!(cache_control, "no-store, ")?;
        }
        if let Some(no_transform) = self.no_transform
            && no_transform
        {
            write!(cache_control, "no-transform, ")?;
        }
        if let Some(must_revalidate) = self.must_revalidate
            && must_revalidate
        {
            write!(cache_control, "must-revalidate, ")?;
        }
        if let Some(proxy_revalidate) = self.proxy_revalidate
            && proxy_revalidate
        {
            write!(cache_control, "proxy-revalidate, ")?;
        }
        if let Some(stale_while_revalidate) = self.stale_while_revalidate
            && stale_while_revalidate
        {
            write!(cache_control, "stale-while-revalidate, ")?;
        }
        if let Some(private) = self.private
            && private
        {
            write!(cache_control, "private, ")?;
        }
        if let Some(public) = self.public
            && public
        {
            write!(cache_control, "public, ")?;
        }
        if let Some(immutable) = self.immutable
            && immutable
        {
            write!(cache_control, "immutable, ")?;
        }
        if let Some(stale_if_error) = self.stale_if_error
            && stale_if_error
        {
            write!(cache_control, "stale-if-error, ")?;
        }

        if cache_control.is_empty() {
            cache_control.push_str(default);
        } else {
            cache_control.pop();
            cache_control.pop();
        }

        Ok(())
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct HttpCache {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub cache_control: Option<HttpCacheControl>,

    /// Corresponds to the HTTP Expires header.
    /// <https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Expires>
    ///
    /// Unit: seconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub expires: Option<u64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub etag: Option<HttpEtag>,
}

/// Field used within the scope of a single template.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct TemplateField {
    /// Field name
    pub name: String,
    /// Specifies the type of the value.
    pub kind: Kind,
    /// JSON value for template field.
    pub value: serde_json::Value,
}

/// Query expression to be used in template bindings.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum QueryExpression {
    Gte,
    Gt,
    Lte,
    Lt,
    Eq,
    BeginsWith,
}

/// Binding options for template field refs.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum TemplateRefFieldBind {
    /// Bind this property to a token field.
    Token {
        /// Name of the field that this property should bind to.
        /// (i.e "account" if you'd like to have an "/account" route
        /// that interprets the request based on the logged-in user's
        /// token claims/fields).
        field: String,
        /// Include if the parent field is queryable.
        #[serde(skip_serializing_if = "Option::is_none")]
        #[serde(default)]
        expression: Option<QueryExpression>,
    },
    /// Bind this property to a route segment (i.e /{something})
    Segment {
        /// Specifies the name of the route segment that this property is binding to.
        name: String,
        /// Include if the parent field is queryable.
        #[serde(skip_serializing_if = "Option::is_none")]
        #[serde(default)]
        expression: Option<QueryExpression>,
    },
}

/// Declaration for which fields from a content definition
/// or data model to include.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct TemplateRefField {
    /// Specifies index for reference field. Index
    /// must be unique across fields for a given reference.
    pub idx: u8,
    /// Name of field to be included.
    pub name: String,
    /// Option to bind this field's value to a route
    /// segment, querystring parameter or token field.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub bind: Option<TemplateRefFieldBind>,
    /// List of any nested subfields to include for this field.
    #[cfg_attr(feature = "utoipa", schema(no_recursion))]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub fields: Option<Vec<TemplateRefField>>,
}

/// How templates reference Content Definitions
/// and Data Models, and the specific fields it
/// wants to include.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct TemplateRef {
    /// Specifies the index position for the referenced
    /// data. Index must be unique across flags, params, data models and
    /// content definitions.
    pub idx: u8,
    /// Name of the model or content definition.
    pub name: String,
    /// Which fields to include.
    pub fields: Vec<TemplateRefField>,
    /// for requesting multiple top-level items
    ///
    /// note: only supported for content. models use relationships.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub all: Option<String>,
}

/// Server flags can only be used in templates whose cache is
/// set to "Never".
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct TemplateFlagRef {
    /// Specifies the index position for the referenced
    /// data. Index must be unique across flags, data models and
    /// content definitions.
    pub idx: u8,
    /// Name of the flag.
    pub name: String,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct TemplateParamRef {
    /// Specifies the index position for the referenced
    /// data. Index must be unique across flags, data models, params, and
    /// content definitions.
    pub idx: u8,
    /// Name of the param.
    pub name: String,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct TemplateCache {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub stored: Option<StoredCache>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub http: Option<HttpCache>,
}

/// Corresponds to <https://docs.rs/wasm-opt/latest/wasm_opt/struct.OptimizationOptions.html#impl-OptimizationOptions>.
///
/// Certain levels may not work with `wasmtime`/`cranelift`.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum WasmOpt {
    Size,
    SizeAggressive,
    Level0,
    Level1,
    Level2,
    Level3,
    Level4,
}

impl WasmOpt {
    #[must_use]
    pub fn as_flag(&self) -> &'static str {
        match self {
            Self::Size => "-Os",
            Self::SizeAggressive => "-Oz",
            Self::Level0 => "-O0",
            Self::Level1 => "-O1",
            Self::Level2 => "-O2",
            Self::Level3 => "-O3",
            Self::Level4 => "-O4",
        }
    }
}

#[allow(clippy::derivable_impls)]
impl Default for TemplateFfiVersion {
    fn default() -> Self {
        Self::V1
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum TemplateFfiVersion {
    V1,
}

#[allow(clippy::derivable_impls)]
impl Default for TemplateFfiSerialization {
    fn default() -> Self {
        Self::FlexBufferVector
    }
}

/// Input serialization format. Output is always an array of bytes.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum TemplateFfiSerialization {
    FlexBufferVector,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct TemplateFfi {
    pub version: TemplateFfiVersion,
    pub serialization: TemplateFfiSerialization,
}

/// Template configuration for Ordinary Applications.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct TemplateConfig {
    /// Foreign function interface config
    pub ffi: TemplateFfi,

    /// Unique index for template.
    pub idx: u8,
    /// Template's name.
    pub name: String,
    /// Used as the `content-type` header for HTTP responses.
    /// Validated against file extension (if `path` is present).
    // todo: switch this to an enum of mime types
    pub mime: String,
    /// Specifies whether the content in the file should
    /// be "minified"/have whitespace removed.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub minify: Option<bool>,
    /// Relative path to the template file
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub path: Option<String>,
    /// The route used in the HTTP server to serve this template.
    /// Can use segments to bind to properties on models or content
    pub route: String,
    /// What to check the token fields against. If left blank, route is considered public.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub protected: Option<Check>,
    /// Used to specify the cache policy for this template.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub cache: Option<TemplateCache>,

    /// HTTP Content Security Policy configuration.
    ///
    /// <https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP>
    ///
    /// "Base" defaults to `default-src 'self';` and tacks on SHA-256 integrity
    /// hashes for all inlined scripts and styles (generated at build time) to
    /// `script-src 'self' sha256-b64` and `style-src 'self' sha256-b64`, respectively.
    ///
    /// `https:` is used when not running in `--insecure` mode.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub csp: Option<HttpCsp>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub cors: Option<HttpCors>,

    /// Max duration for the template.
    ///
    /// Unit: seconds
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub timeout: Option<u16>,

    /// Used for template-specific variables that don't need to be shared
    /// beyond the scope of the given template, and don't warrant a content
    /// object.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub fields: Option<Vec<TemplateField>>,
    /// List of global variables to be included with the compiled template
    /// binary. Globals are excluded by default and have to be explicitly
    /// listed in the globals to be accessed from the template.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub globals: Option<Vec<String>>,
    /// List of flags to be referenced by the template.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub flags: Option<Vec<TemplateFlagRef>>,
    /// List of params to be referenced by the template.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub params: Option<Vec<TemplateParamRef>>,
    /// List of models and what fields the template needs from the models.
    /// This is effectively a query definition.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub models: Option<Vec<TemplateRef>>,
    /// List of content definitions and the content definition fields
    /// that this template will use.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub content: Option<Vec<TemplateRef>>,

    /// Specifies which actions this template triggers, and adds
    /// this template's route pattern to the action's list of valid
    /// origins.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub actions: Option<Vec<String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub wasm_opt: Option<WasmOpt>,

    /// List of build time environment variables.
    ///
    /// format in template: `{{ YOUR_VAR }}`
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub variables: Option<Vec<String>>,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct CompressionAlgorithms(pub Vec<CompressionAlgorithm>);

impl CompressionAlgorithms {
    #[must_use]
    fn get_list(&self) -> ArrayVec<CompressionAlgorithm, 4> {
        let mut list = ArrayVec::<CompressionAlgorithm, 4>::new();
        let mut has_all = false;

        for alg in &self.0 {
            if *alg == CompressionAlgorithm::All {
                has_all = true;
            } else if !list.contains(alg) {
                list.push(alg.clone());
            }
        }

        if has_all {
            for alg in [
                CompressionAlgorithm::Brotli,
                CompressionAlgorithm::Zstd { level: 17 },
                CompressionAlgorithm::Deflate,
                CompressionAlgorithm::Gzip,
            ] {
                if !list.contains(&alg) {
                    list.push(alg);
                }
            }
        }

        list
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct AssetsConfig {
    /// Relative path to assets directory.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub dir_path: Option<String>,

    /// Note: must start with a `/` and cannot end with a `/` unless
    /// `/` is the entire route.
    #[serde(default = "AssetsConfig::default_base_route")]
    pub base_route: String,

    /// whether to add `index.html` to the base route
    /// and the end of routes having a trailing slash
    /// or missing an extension.
    ///
    /// i.e. `https://example.com/static`, `https://example.com/static/`,
    /// `https://example.com/static/{*path}/` and `https://example.com/static/{*path}`
    /// (with no extension) would return the contents of
    /// `/static/index.html` or `/static/{*path}/index.html`.
    ///
    /// primarily useful when serving a generated static site.
    ///
    /// Note: cannot be used with `append_index_ext`
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub append_index_html: Option<bool>,

    /// whether the `{base_route}` and `{base_route}/` routes should
    /// skip returning the `index.html` at the root of the static dir.
    ///
    /// useful when the static dir `base_route` is set to `/` but you'd
    /// like to have a template use the `/` route.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub skip_base_route_index_html: Option<bool>,

    /// whether to append `.html` to routes that do not
    /// include an extension.
    ///
    /// i.e. `https://example.com/static/about` would return the contents of
    /// `/static/about.html`.
    ///
    /// primarily useful when serving a generated static site.
    ///
    /// Note: cannot be used with `append_index_html`
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub append_html_ext: Option<bool>,

    /// will not strip the exif data from images.
    ///
    /// Important: only use if you want all metadata (including
    /// location data) on your photos.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub preserve_exif: Option<bool>,

    /// content security policy for HTML assets
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub html_csp: Option<HttpCsp>,

    /// HTTP cache configuration.
    ///
    /// TODO: provide a way to pattern match files for which to apply
    /// TODO: specific cache controls.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub http: Option<HttpCache>,

    /// Which encodings to use when precompressing assets.
    ///
    /// Serving priority is dictated by specified order.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub precompression: Option<CompressionAlgorithms>,

    #[serde(skip_serializing)]
    #[serde(default)]
    pub internal_precompression: Option<ArrayVec<CompressionAlgorithm, 4>>,

    /// Determines whether CSS files should be minified,
    /// prior to write.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub minify_css: Option<bool>,

    /// Determines whether JS files should be minified,
    /// prior to write.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub minify_js: Option<bool>,

    /// Determines whether HTML files should be minified,
    /// prior to write.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub minify_html: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub internal_cache_control_header_value: Option<String>,
}

impl AssetsConfig {
    fn default_base_route() -> String {
        "/assets".to_string()
    }
}

impl AssetsConfig {
    pub fn init(&mut self, default_cache_control_header_value: &str) -> anyhow::Result<()> {
        if let Some(http_cache) = &self.http
            && let Some(http_cache_control) = &http_cache.cache_control
        {
            let mut header = String::new();
            http_cache_control.header_value(&mut header, default_cache_control_header_value)?;

            self.internal_cache_control_header_value = Some(header);
        }

        Ok(())
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct FragmentsConfig {
    /// Relative path to fragments directory.
    pub dir_path: String,
}

/// Global constant definitions, for use in [`ordinary_template::Template`]s.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Global {
    /// Name of the global constant.
    pub name: String,
    /// Type definition for the global variable.
    pub kind: Kind,
    /// JSON value of the global constant.
    pub value: serde_json::Value,
}

/// Where Ordinary will look for the secret.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum SecretSource {
    /// Name of the host provided environment variable/secret.
    ///
    /// `Env` secrets are available to every tenant for a given
    /// API server (when running in "multi" mode).
    ///
    /// This is useful in scenarios where a provider running the API
    /// server would like to expose convenient integrations with 3rd parties, for
    /// which it only wants to maintain a single set of credentials.
    ///
    /// `Env` secrets are also useful when you're running a standalone
    /// application and do not need a more complicated secrets management
    /// paradigm.
    Env,
    /// Name of a stored secret.
    ///
    /// `Stored` secrets are application scoped, and can be set
    /// through an API server on which the application runs.
    ///
    /// `Stored` secrets live in their own database and are only
    /// accessible to components with permissions.
    Stored,
    // `Manager` mode allows you to select an external secrets
    // manager, by setting a `Stored` secret with the external `Manager`'s
    // token/password.
    // todo: Manager
}

/// Where the secret is accessible from.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum SecretVisibility {
    // `Actions` visibility level should only be set in cases
    // where you're confident in the code that's being executed,
    // or the secret is not shared between trusted/untrusted modules.
    //
    // Because `Action` visible secrets are passed into the module,
    // they can be (intentionally OR unintentionally) leaked if
    // included in what's returned by the module.
    // todo: Actions,
    /// `Integrations` level visibility runs the risk of unintentionally
    /// sending a secret to the incorrect endpoint, but does not expose
    /// secrets to any user defined modules.
    Integrations,
}

/// Mechanism for exposing secrets to `Integration`s.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Secret {
    /// Name of the secret.
    pub name: String,
    /// Where to retrieve the secret from.
    pub source: SecretSource,
    /// Where the secret is to be used.
    pub visibility: SecretVisibility,
}

/// Option for the feature flag.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct FlagOption {
    /// Unique index for this flag option.
    pub idx: u8,
    /// Name of this feature flag option.
    pub name: String,
    /// Percentage of users that will have this
    /// flag turned on.
    pub percentage: u8,
}

/// Feature flag definition.
///
/// Note: Flags use cookies for non-logged in users,
/// and use fields set on their token after they're logged in
/// so that users have the ability to configure their preference
/// if they have one.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Flag {
    /// Unique index for the feature flag.
    pub idx: u8,
    /// Name of the feature flag.
    pub name: String,
    /// Options for this flag. Percentage must
    /// total 100.
    pub options: Vec<FlagOption>,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ContentDefinition {
    /// Unique index for the content definition.
    pub idx: u8,

    /// Name of the content definition.
    pub name: String,

    /// Fields for the content definition.
    ///
    /// Note: only fields with the `String` and `Uuid` kinds can
    /// be indexed (for now).
    pub fields: Vec<Field>,

    /// configure scripts for responding to object lifecycle events.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub lifecycle: Option<ContentObjectLifecycle>,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ContentObjectLifecycle {
    /// run script before all commands in the set
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub before_all: Option<Vec<Vec<String>>>,
    /// hook for running scripts before/after an object
    /// is added via CLI or studio.
    ///
    /// `after` receives the stringified JSON object as the
    /// first stdarg.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub on_add: Option<LifecycleBeforeAfterScripts>,
    /// hook for running scripts before/after an object
    /// is edited via CLI or studio.
    ///
    /// `after` receives the stringified JSON object as the
    /// first stdarg.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub on_edit: Option<LifecycleBeforeAfterScripts>,
    /// hook for running scripts before/after an object
    /// is deleted via CLI or studio.
    ///
    /// `after` receives the stringified JSON object as the
    /// first stdarg.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub on_delete: Option<LifecycleBeforeAfterScripts>,
}

/// Content is used for static values that should be updated
/// independent of document structure, stylings or behavior.
///
/// Content is stored in a denormalized format for indexed fields
/// to optimize for maximum read efficiency.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct Content {
    /// Specifies the path to the JSON file which contains
    /// the content objects.
    pub file_path: String,
    /// Definitions/structure of the content objects in the
    /// `content.json`.
    pub definitions: Vec<ContentDefinition>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub update: Option<ContentUpdateConfig>,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ContentUpdateConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub lifecycle: Option<LifecycleBeforeAfterScripts>,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum UuidVersion {
    V4,
    V7,
}

/// Defines a model in the Ordinary Database.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ModelConfig {
    /// Index of the model. Used for its kind
    /// for storage keys. There can be no gaps in
    /// index values.
    ///
    /// Note: the first (0) index is always skipped as it
    /// is reserved for the item UUID.
    pub idx: u8,
    /// Name of the model.
    pub name: String,
    /// Fields on the model.
    pub fields: Vec<Field>,
    /// Every model is generated with a UUID key. If this value
    /// is blank, it will default to V4. If you'd like records to
    /// be ordered by time, V7 is recommended.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub uuid: Option<UuidVersion>,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum IntegrationProtocolHttpEncoding {
    Json,
    Text,
    None,
}

/// The protocol for the integration.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum IntegrationProtocol {
    /// For integrating an external HTTP API.
    Http {
        /// HTTP method.
        method: String,
        /// static http headers
        headers: Vec<(String, String)>,
        /// how to encode the value passed from the action
        send_encoding: IntegrationProtocolHttpEncoding,
        /// how to decode the value passed back to the action
        recv_encoding: IntegrationProtocolHttpEncoding,
    },
    // When integrating an external gRPC API.
    // todo: Grpc { metadata: Vec<(String, String)> },
    // When integrating an external Cap'n Proto API.
    // todo: CapnProto,
    // When integrating an external GraphQL API.
    // todo: GraphQL,
    // When integrating an external PostgreSQL database.
    // todo: Postgres { statement: String },
    // When integrating an external OpenSearch database.
    // todo: OpenSearch,
    // For integrating with SMTP mail server
    // todo: Smtp,
}

/// The mechanism for reverse proxying and calling
/// out to external APIs.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct IntegrationConfig {
    /// Unique index for integration
    pub idx: u8,
    /// Name of the integration.
    pub name: String,
    /// Protocol used for communicating with the external service.
    pub protocol: IntegrationProtocol,
    /// Endpoint that the external service lives at.
    pub endpoint: String,
    /// Definition for the parameters of the receiving service.
    ///
    /// (Automatically translated to the service's protocol/encoding format).
    pub send: Kind,
    /// Definition for the returned value of the external service.
    ///
    /// (Automatically translated from the service's protocol/encoding format).
    pub recv: Kind,
    /// Names of secrets to include
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub secrets: Option<Vec<String>>,

    /// Max duration for the template.
    ///
    /// Unit: seconds
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub timeout: Option<u16>,
}

/// The language in which the action is written.
///
/// Many more languages will be supported in the future.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum ActionLang {
    /// Action is written in the Rust programming language.
    ///
    /// Uses zero-copy `FlexBuffer` vectors for serialization format.
    Rust,
    /// Action is written in JavaScript.
    ///
    /// `QuickJS` runtime embedded in a Rust WASM which itself uses
    /// `FlexBuffer` vectors for FFI serialization, but then translates
    /// to JSON when communicating across the `QuickJS` runtime barrier.
    JavaScript,
    // todo: Golang,
    // todo: DotNet,
    // todo: Kotlin,
}

/// Model operations that an action is allowed to make.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum ActionAccessModelOps {
    /// Can create an item for this model.
    Insert,
    /// Can get an item for this model by UUID or Index.
    Get,
    /// Can query an item for this model by queryable field.
    Query,
    /// Can search an item for this model by searchable field.
    Search,
    /// Can update an item for this model.
    Update,
    /// Can delete an item for this model.
    Delete,
}

/// Auth operations that an action can make.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum ActionAccessAuthOps {
    /// Allows the action the ability to set
    /// a user's access token fields/claims.
    SetTokenFields,
}

/// Defines access permissions that an Ordinary
/// Action can configure.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum ActionAccessPermission {
    /// Provides the action access to a given model.
    Model {
        /// Name of the model.
        name: String,
        /// List of allowed operations that the action
        /// can take on the model.
        ops: Vec<ActionAccessModelOps>,
    },
    /// Provides the action access to a given content def.
    Content {
        /// Content definition name.
        name: String,
    },
    /// Provides the action access to a given integration.
    Integration {
        /// Name of the integration the action can access.
        name: String,
    },
    /// Provides the action access to another action.
    Action {
        /// Name of the other action.
        name: String,
    },
    /// Provides the action access to Ordinary Auth.
    Auth {
        /// Which operations the action is allowed to take.
        ops: Vec<ActionAccessAuthOps>,
    },
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum HttpMethod {
    PUT,
    POST,
    GET,
    DELETE,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum ActionTriggerModelOps {
    Insert,
    Update,
    Delete,
}

/// Action trigger options.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum ActionTrigger {
    /// HTTP request with the Ordinary data format
    Ordinary,
    /// JSON formatted API call
    Json {
        /// API rout
        route: String,
        /// HTTP method
        method: HttpMethod,
    },
    /// Web Form Submission
    Form {
        /// endpoint the form should point at
        route: String,
        /// method for the form to use
        method: HttpMethod,
        /// redirect for after submission.
        ///
        /// note: it is allowed to use return values in the route
        /// via {return} or {`return.some_field_name`}
        redirect: String,
    },
    /// Login event from Auth
    Login,
    /// Registration event from Auth
    Registration,
    /// For when content updates
    Content { name: String },
    // Run on model insert/update/delete
    // with affected item as argument.
    // todo: Model {
    //     name: String,
    //     op: ActionAccessModelOps,
    // },

    // Have the action triggered on a regular cadence.
    // todo: Job { expression: String },

    // gRPC formatted request
    // todo: Grpc,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum ActionFfiVersion {
    V1,
}

/// Input/output serialization for module and host functions.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum ActionFfiSerialization {
    FlexBufferVector,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ActionFfi {
    pub version: ActionFfiVersion,
    pub serialization: ActionFfiSerialization,
}

/// Configuration parameters for Ordinary Actions.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ActionConfig {
    /// Foreign function interface config
    pub ffi: ActionFfi,
    /// Unique index value for action.
    pub idx: u8,
    /// Action name. Must be unique.
    pub name: String,
    /// The source language the action is written in.
    pub lang: ActionLang,
    /// Relative path to the source directory for the action.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub dir_path: Option<String>,
    /// What to check the token fields against. If blank
    /// action is public.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub protected: Option<Check>,
    /// whether the storage interactions
    /// are executed under a single transaction.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub transactional: Option<bool>,
    /// Which Ordinary Application resources the action has access to.
    pub access: Vec<ActionAccessPermission>,
    /// Input definition for the action.
    pub accepts: Kind,
    /// Output definition for the action.
    pub returns: Kind,
    /// How this action is called (i.e. side effect from DB/Auth,
    /// http API call, browser form submission, etc.)
    pub triggered_by: Vec<ActionTrigger>,

    /// Max duration for the action.
    ///
    /// Unit: seconds
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub timeout: Option<u16>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub cors: Option<HttpCors>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub wasm_opt: Option<WasmOpt>,

    /// Whether the action should have bindings for API server interaction.
    ///
    /// Can only be set on applications which have been explicitly
    /// allow-listed by the API server administrator via their domain.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub privileged: Option<bool>,

    /// List of build time environment variables.
    ///
    /// format in template: `{{ YOUR_VAR }}`
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub variables: Option<Vec<String>>,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct ErrorConfig {
    /// Refers to the error template by name.
    ///
    /// Note: if set, will override the `asset` field
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub template: Option<String>,

    /// Refers to the asset by path.
    ///
    /// Note: if `template` is set it will override this field
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub asset: Option<String>,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum RuntimeMode {
    /// Application will run on the shared multithreaded
    /// tokio runtime.
    Shared,
    /// Application will run on a separate thread with its
    /// own single-threaded tokio runtime.
    SingleThreaded,
    /// Application will run on a separate thread with its
    /// own multithreaded tokio runtime.
    MultiThreaded,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum HttpCorsAllowHeaders {
    Any,
    /// <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers>
    Headers(Vec<String>),
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum HttpCorsExposeHeaders {
    Any,
    /// <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers>
    Headers(Vec<String>),
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum HttpCorsAllowMethods {
    Any,
    /// <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods>
    Methods(Vec<String>),
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum HttpCorsAllowOrigin {
    Any,
    /// <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin>
    Origins(Vec<String>),
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct HttpCors {
    pub allow_credentials: Option<bool>,

    pub allow_headers: Option<HttpCorsAllowHeaders>,

    /// unit: Seconds
    pub max_age: Option<u32>,

    pub allow_methods: Option<HttpCorsAllowMethods>,

    pub allow_origin: Option<HttpCorsAllowOrigin>,

    pub expose_headers: Option<HttpCorsExposeHeaders>,

    pub allow_private_network: Option<bool>,
}

impl HttpCors {
    #[must_use]
    pub fn overwrite(&self, base: &Self) -> Self {
        Self {
            allow_credentials: if self.allow_credentials.is_none() {
                base.allow_credentials
            } else {
                self.allow_credentials
            },
            allow_headers: if self.allow_headers.is_none() {
                base.allow_headers.clone()
            } else {
                self.allow_headers.clone()
            },
            max_age: if self.max_age.is_none() {
                base.max_age
            } else {
                self.max_age
            },
            allow_methods: if self.allow_methods.is_none() {
                base.allow_methods.clone()
            } else {
                self.allow_methods.clone()
            },
            allow_origin: if self.allow_origin.is_none() {
                base.allow_origin.clone()
            } else {
                self.allow_origin.clone()
            },
            expose_headers: if self.expose_headers.is_none() {
                base.expose_headers.clone()
            } else {
                self.expose_headers.clone()
            },
            allow_private_network: if self.allow_private_network.is_none() {
                base.allow_private_network
            } else {
                self.allow_private_network
            },
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct HttpCsp {
    /// defaults to `'self'` (`default-src ` does not need to be included)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub default_src: Option<String>,

    /// defaults to unset unless inline hashes are included,
    /// in which case the directive will start with `'self'` (`script-src ` does not need to be included).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub script_src: Option<String>,

    /// defaults to unset unless inline hashes are included,
    /// in which case the directive will start with `'self'` (`style-src ` does not need to be included).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub style_src: Option<String>,

    /// defaults to unset.
    ///
    /// (`font-src ` does not need to be included).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub font_src: Option<String>,

    /// defaults to unset.
    ///
    /// (`img-src ` does not need to be included).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub img_src: Option<String>,

    /// defaults to unset.
    ///
    /// (`frame-src ` does not need to be included).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub frame_src: Option<String>,

    /// defaults to `true`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub include_inline_hashes: Option<bool>,
}

impl HttpCsp {
    #[must_use]
    #[allow(clippy::too_many_lines)]
    pub fn build_string(
        &self,
        base: &Self,
        inline_style_hashes: Option<Vec<String>>,
        inline_script_hashes: Option<Vec<String>>,
        script_urls: Option<Vec<String>>,
        secure: bool,
        has_wasm: bool,
    ) -> String {
        let mut out = String::new();

        let include_inline_hashes = self
            .include_inline_hashes
            .unwrap_or(base.include_inline_hashes.unwrap_or(true));

        let default_src = self
            .default_src
            .clone()
            .unwrap_or(base.default_src.clone().unwrap_or("'self'".to_string()));

        if !default_src.is_empty() {
            out.push_str("default-src ");
            out.push_str(default_src.as_str());
            out.push_str("; ");
        }

        let mut script_src = self
            .script_src
            .clone()
            .unwrap_or(base.script_src.clone().unwrap_or_default());

        if include_inline_hashes
            && let Some(script_hashes) = inline_script_hashes
            && !script_hashes.is_empty()
        {
            if script_src.is_empty() {
                script_src.push_str("'self'");
                if has_wasm {
                    script_src.push_str(" 'wasm-unsafe-eval'");
                }
            }

            for hash in script_hashes {
                script_src.push_str(" '");
                script_src.push_str(hash.as_str());
                script_src.push('\'');
            }
        }

        if let Some(script_urls) = script_urls {
            if script_src.is_empty() {
                script_src.push_str("'self'");
            }

            for script_url in script_urls {
                script_src.push(' ');
                script_src.push_str(&script_url);
            }
        }

        if !script_src.is_empty() {
            out.push_str("script-src ");
            out.push_str(script_src.as_str());
            out.push_str("; ");
        }

        let mut style_src = self
            .style_src
            .clone()
            .unwrap_or(base.style_src.clone().unwrap_or_default());

        if include_inline_hashes
            && let Some(style_hashes) = inline_style_hashes
            && !style_hashes.is_empty()
        {
            if style_src.is_empty() {
                style_src.push_str("'self'");
            }

            for hash in style_hashes {
                style_src.push_str(" '");
                style_src.push_str(hash.as_str());
                style_src.push('\'');
            }
        }

        if !style_src.is_empty() {
            out.push_str("style-src ");
            out.push_str(style_src.as_str());
            out.push_str("; ");
        }

        let font_src = self
            .font_src
            .clone()
            .unwrap_or(base.font_src.clone().unwrap_or_default());
        if !font_src.is_empty() {
            out.push_str("font-src ");
            out.push_str(font_src.as_str());
            out.push_str("; ");
        }

        let img_src = self
            .img_src
            .clone()
            .unwrap_or(base.img_src.clone().unwrap_or_default());
        if !img_src.is_empty() {
            out.push_str("img-src ");
            out.push_str(img_src.as_str());
            out.push_str("; ");
        }

        let frame_src = self
            .frame_src
            .clone()
            .unwrap_or(base.frame_src.clone().unwrap_or_default());
        if !frame_src.is_empty() {
            out.push_str("frame-src ");
            out.push_str(frame_src.as_str());
            out.push_str("; ");
        }

        if secure {
            out.push_str("upgrade-insecure-requests; ");
        }

        out.push_str("report-to csp");

        out = out.trim().to_string();
        out
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct LifecycleBeforeAfterScripts {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub before: Option<Vec<Vec<String>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub after: Option<Vec<Vec<String>>>,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct TopLevelLifecycle {
    /// run before every lifecycle operation
    pub before_all: Option<Vec<Vec<String>>>,

    /// configure build lifecycle hooks
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub build: Option<LifecycleBeforeAfterScripts>,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum RedirectMethod {
    /// 307 <https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/307>
    Temporary,
    /// 308 <https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/308>
    Permanent,
}

impl Display for RedirectMethod {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Temporary => write!(f, "TEMPORARY"),
            Self::Permanent => write!(f, "PERMANENT"),
        }
    }
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct HostRedirect {
    /// from host name
    pub from: String,
    /// to host name
    pub to: String,
    /// redirect method
    pub method: RedirectMethod,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct RouteRedirect {
    /// [axum route](https://docs.rs/axum/latest/axum/struct.Router.html#method.route) pattern
    pub condition: String,
    /// translation regexes map to [`Regex::replace_all`](https://docs.rs/regex/latest/regex/#example-replacement-with-named-capture-groups)
    /// where `rule.0` is body of `Regex::new()` and `rule.1` is second param of `re.replace_all()`.
    pub rule: (String, String),
    /// redirect method
    pub method: RedirectMethod,
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Redirects {
    /// host redirects
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub host: Option<Vec<HostRedirect>>,
    /// route redirects
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub route: Option<Vec<RouteRedirect>>,
}

/// proxy configuration.
///
/// **Note:** `path` should not be set at the same time as either `domain`
/// or `port`. `path` takes precedence and the other sources will be ignored.
///
/// if the `path`, `domain` and `port` are all unset, validation will fail.
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ProxyConfig {
    /// an `axum` [route](https://docs.rs/axum/latest/axum/routing/struct.Router.html#method.route)
    /// with a `*path` wildcard that will be appended to the target.
    ///
    /// i.e. `"/some/path/{*path}"`
    ///
    /// **Note:** MUST end in a trailing `/{*path}`
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub path: Option<String>,
    /// custom domain with an ALIAS/CNAME pointing at the primary `OrdinaryConfig::domain`
    /// and a TXT record indicating ownership (i.e. `ordinary-proxy=your.config.domain`).
    ///
    /// i.e `example.com`
    ///
    /// **Note:** if a `path` is specified, the `domain` will be ignored
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub domain: Option<String>,

    /// preferred port that the proxy will listen on in a `--dedicated-ports`
    /// configured multi-tenant server OR a standalone app instance.
    ///
    /// i.e `8081`
    ///
    /// **Note:** if a `path` is specified, the `port` will be ignored,
    /// and `port` will not be tried without `domain` being present.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub port: Option<u16>,

    /// url for resource to proxy.
    ///
    /// i.e. `https://example.com`
    pub target: String,
}

/// Config definition for an Ordinary Application
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "docs", derive(schemars::JsonSchema))]
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct OrdinaryConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub lifecycle: Option<TopLevelLifecycle>,

    /// Domain name for the application to be run from the
    /// deployment environment.
    pub domain: String,

    /// additional domains with a CNAME or ALIAS records
    /// pointing at the primary `OrdinaryConfig::domain`.
    ///
    /// add a TXT record in the following format:
    ///`ordinary=your.config.domain`
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub cnames: Option<Vec<String>>,

    /// specify which of the `domain` or `cnames` is
    /// the "canonical" location.
    ///
    /// this is useful for [indexing](https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls)
    /// and situations where you want to display the primary
    /// URL as text on the page itself (i.e. pick one of `example.some.host`, `example.com`, and `www.example.com`).
    ///
    /// defaults to `domain` if `cnames` is empty. defaults to first `cname` in list if `cnames`
    /// are not empty.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub canonical: Option<String>,

    /// configuration of internal redirects
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub redirects: Option<Redirects>,

    /// configuration of proxied services
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub proxies: Option<Vec<ProxyConfig>>,

    /// list of email addresses that can be used to contact
    /// the application owner or administrators.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub contacts: Option<Vec<String>>,

    /// whether contacts should be hidden (defaults to `true`)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub hide_contacts: Option<bool>,

    /// Version of the site build.
    pub version: String,

    /// Storage size in bytes (rounded up to nearest OS page size).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default = "OrdinaryConfig::default_storage_size")]
    pub storage_size: Option<u64>,

    /// Default request timeout.
    ///
    /// Unit (seconds).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub default_timeout: Option<u16>,

    /// HTTP Content Security Policy configuration.
    ///
    /// <https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP>
    ///
    /// "Base" defaults to `default-src 'self';` and tacks on SHA-256 integrity
    /// hashes for all inlined scripts and styles (generated at build time) to
    /// `script-src 'self' sha256-b64` and `style-src 'self' sha256-b64`, respectively.
    ///
    /// `https:` is used when not running in `--insecure` mode.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub csp: Option<HttpCsp>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub cors: Option<HttpCors>,

    /// Specifies runtime mode for application on the host.
    ///
    /// If none is specified, defaults to Shared (or host default).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub runtime: Option<RuntimeMode>,

    /// When set to true, `{{ domain }}/.ordinary/schema`
    /// is not addressable.
    ///
    /// Note: this can break applications which depend on
    /// flags, and `action`/`template` query descriptors.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub hide_schema: Option<bool>,

    /// Include template rendering code in the client WASM.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub client_rendering: Option<bool>,

    /// Include E2EE handler code in the client WASM.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub obfuscation: Option<bool>,

    /// Include E2EE handler code in the client WASM.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub client_events: Option<bool>,

    /// Port to be used for standalone "run" instances.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub port: Option<u16>,
    /// port used for redirecting from http when
    /// standalone is running in secure mode.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub redirect_port: Option<u16>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub logging: Option<LoggingConfig>,
    /// Configures error handling.
    ///
    /// Note: If not included just the error message will be
    /// sent back as text.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub error: Option<ErrorConfig>,
    /// Auth config for the Ordinary application.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub auth: Option<AuthConfig>,
    /// Global constants that can be accessed from templates
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub globals: Option<Vec<Global>>,
    /// Secrets that can be used by actions or integrations.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub secrets: Option<Vec<Secret>>,
    /// Feature flags which can be referenced from templates
    /// to inform application behavior, and run experiments.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub flags: Option<Vec<Flag>>,
    /// Definitions for static content "types"/object structure
    /// that can be used to inform template/page development (i.e.
    /// one might define a "post" content definition, and then create
    /// a template for their blog).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub content: Option<Content>,
    /// Definitions for the models that will be stored in the Ordinary database.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub models: Option<Vec<ModelConfig>>,
    /// Definitions for the external APIs that will be integrated
    /// into the Ordinary application.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub integrations: Option<Vec<IntegrationConfig>>,
    /// IO, access and language configuration for actions that
    /// are compiled to and executed as WebAssembly modules.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub actions: Option<Vec<ActionConfig>>,
    /// Specifies the asset directory and per-path configuration
    /// details for assets that require preprocessing (TypeScript, SCSS,
    /// JavaScript minification, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub assets: Option<AssetsConfig>,
    /// Configuration for the template fragments
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub fragments: Option<FragmentsConfig>,
    /// Configuration for the templates/pages that the application
    /// will render. Each template is compiled to a WebAssembly module
    /// which accepts runtime arguments for models/content/integrations, and can be
    /// executed on either the server or the client.
    ///
    /// With the option to render on the client, only the result of the server
    /// query needs to be sent, in a compact, optimized, format.
    ///
    /// Currently, all rendering is happening server-side, and only HTML is being sent.
    ///
    /// In an ideal/future state multiple modes will be supported, even up to a full
    /// 'noscript' config.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub templates: Option<Vec<TemplateConfig>>,
}

impl OrdinaryConfig {
    /// gets ordinary.json from project path and deserializes to struct.
    pub fn get(proj_path: &str) -> anyhow::Result<OrdinaryConfig> {
        let path = Path::new(proj_path).join("ordinary.json");
        let config_json = fs_err::read_to_string(&path)?;

        let mut config = match serde_json::from_str::<OrdinaryConfig>(config_json.as_str()) {
            Ok(config) => config,
            Err(err) => bail!("{}: {err}", path.display()),
        };

        config.load_internal_compression();

        Ok(config)
    }

    pub fn load_internal_compression(&mut self) {
        if let Some(assets) = self.assets.as_mut()
            && let Some(precompression) = &assets.precompression
        {
            assets.internal_precompression = Some(precompression.get_list());
        }

        if let Some(templates) = self.templates.as_mut() {
            for template in templates {
                if let Some(cache) = template.cache.as_mut()
                    && let Some(stored) = cache.stored.as_mut()
                    && let Some(compression) = &stored.compression
                {
                    stored.internal_compression = Some(compression.get_list());
                }
            }
        }
    }

    /// gets ordinary.json from project path, deserializes to struct and
    /// strips out all client-only values.
    pub fn for_send(&self) -> anyhow::Result<OrdinaryConfig> {
        let mut config = self.clone();

        config.lifecycle = None;

        if let Some(assets) = config.assets.as_mut() {
            assets.dir_path = None;
        }

        if let Some(content) = config.content.as_mut() {
            content.update = None;

            for def in &mut content.definitions {
                def.lifecycle = None;
            }
        }

        if let Some(templates) = config.templates.as_mut() {
            for template in templates {
                template.path = None;
                template.wasm_opt = None;
                template.minify = None;
            }
        }

        if let Some(actions) = config.actions.as_mut() {
            for action in actions {
                action.wasm_opt = None;
                action.dir_path = None;
            }
        }

        Ok(config)
    }

    /// check that all configuration values are internally consistent
    /// and no non-existent properties or fields are used.
    #[instrument(skip_all, err, level = "debug")]
    pub fn validate(&self) -> anyhow::Result<()> {
        validate(self)
    }

    // defaults
    #[must_use]
    #[allow(clippy::unnecessary_wraps)]
    pub fn default_storage_size() -> Option<u64> {
        Some(5_000_000)
    }
    // end defaults

    #[must_use]
    pub fn has_ordinary_actions(&self) -> bool {
        if let Some(actions) = &self.actions {
            actions
                .iter()
                .find(|a| {
                    for trigger in &a.triggered_by {
                        if let ActionTrigger::Ordinary = trigger {
                            return true;
                        }
                    }

                    false
                })
                .is_some()
        } else {
            false
        }
    }

    /// Check that all the configuration properties are within API specified
    /// limits.
    ///
    /// Note: privileged domains are not subject to limitations checks.
    #[allow(clippy::too_many_lines)]
    pub fn check_config_against_limits(
        &self,
        limits: &OrdinaryApiLimits,
        privileged_domains: &HashSet<String>,
    ) -> anyhow::Result<()> {
        if privileged_domains.contains(&self.domain) {
            return Ok(());
        }

        if let Some(canonical) = &self.canonical {
            let mut is_valid = false;

            if canonical == &self.domain {
                is_valid = true;
            }

            if let Some(cnames) = &self.cnames {
                for cname in cnames {
                    if cname == canonical {
                        is_valid = true;
                        break;
                    }
                }
            }

            if !is_valid {
                bail!("canonical: {canonical}, is not in 'domain' or 'cnames'");
            }
        }

        if let Some(default_timeout) = self.default_timeout
            && default_timeout > limits.max_default_timeout
        {
            bail!(
                "default timeout {} greater than limit {}",
                default_timeout,
                limits.max_default_timeout
            );
        }

        if let Some(proxies) = &self.proxies {
            if proxies.len() > limits.proxy.count as usize {
                bail!(
                    "proxy count {} greater than limit {}",
                    proxies.len(),
                    limits.proxy.count
                );
            }

            let mut disallowed_target_regexes =
                Vec::with_capacity(limits.proxy.disallowed_targets.len());

            for disallowed in &limits.proxy.disallowed_targets {
                disallowed_target_regexes.push(Regex::new(disallowed)?);
            }

            for proxy in proxies {
                for re in &disallowed_target_regexes {
                    if re.is_match(&proxy.target) {
                        bail!(
                            "proxy target {} is disallowed by rule {}",
                            proxy.target,
                            re.as_str()
                        )
                    }
                }
            }
        }

        if let Some(templates) = &self.templates {
            if templates.len() > limits.template.count as usize {
                bail!(
                    "template count {} greater than limit {}",
                    templates.len(),
                    limits.template.count
                );
            }

            for template in templates {
                if let Some(timeout) = template.timeout
                    && timeout > limits.template.max_timeout
                {
                    bail!(
                        "template timeout {} greater than limit {} for {}",
                        timeout,
                        limits.template.max_timeout,
                        template.name
                    );
                }

                if let Some(cache) = &template.cache
                    && let Some(stored_cache) = &cache.stored
                {
                    if let Some(max_size) = stored_cache.max_size
                        && (max_size < limits.storage.cache.max_size_range.0
                            || max_size > limits.storage.cache.max_size_range.1)
                    {
                        bail!(
                            "template cache max_size {} is not within range [{}, {}] for {}",
                            max_size,
                            limits.storage.cache.max_size_range.0,
                            limits.storage.cache.max_size_range.1,
                            template.name
                        );
                    }

                    if let Some(max_count) = stored_cache.max_count
                        && (max_count < limits.storage.cache.max_count_range.0
                            || max_count > limits.storage.cache.max_count_range.1)
                    {
                        bail!(
                            "template cache max_count {} is not within range [{}, {}] for {}",
                            max_count,
                            limits.storage.cache.max_count_range.0,
                            limits.storage.cache.max_count_range.1,
                            template.name
                        );
                    }

                    if let Some((clean_interval_min, clean_interval_max)) =
                        stored_cache.clean_interval
                    {
                        if clean_interval_min < limits.storage.cache.clean_interval_ranges.0.0
                            || clean_interval_min > limits.storage.cache.clean_interval_ranges.0.1
                        {
                            bail!(
                                "template cache clean_interval min {} is not within range [{}, {}] for {}",
                                clean_interval_min,
                                limits.storage.cache.clean_interval_ranges.0.0,
                                limits.storage.cache.clean_interval_ranges.0.1,
                                template.name
                            );
                        }

                        if clean_interval_max < limits.storage.cache.clean_interval_ranges.1.0
                            || clean_interval_max > limits.storage.cache.clean_interval_ranges.1.1
                        {
                            bail!(
                                "template cache clean_interval min {} is not within range [{}, {}] for {}",
                                clean_interval_max,
                                limits.storage.cache.clean_interval_ranges.1.0,
                                limits.storage.cache.clean_interval_ranges.1.1,
                                template.name
                            );
                        }
                    }
                }
            }
        }

        if let Some(integrations) = &self.integrations {
            if integrations.len() > limits.integration.count as usize {
                bail!(
                    "integration count {} greater than limit {}",
                    integrations.len(),
                    limits.integration.count
                );
            }

            for integration in integrations {
                if let Some(timeout) = integration.timeout
                    && timeout > limits.integration.max_timeout
                {
                    bail!(
                        "integration timeout {} greater than limit {} for {}",
                        timeout,
                        limits.integration.max_timeout,
                        integration.name,
                    );
                }
            }
        }

        if let Some(actions) = &self.actions {
            if actions.len() > limits.action.count as usize {
                bail!(
                    "action count {} greater than limit {}",
                    actions.len(),
                    limits.action.count
                );
            }

            for action in actions {
                if action.privileged == Some(true) {
                    bail!("action {} is not under a privileged domain", action.name);
                }

                if let Some(timeout) = action.timeout
                    && timeout > limits.action.max_timeout
                {
                    bail!(
                        "action timeout {} greater than limit {} for {}",
                        timeout,
                        limits.action.max_timeout,
                        action.name
                    );
                }
            }
        }

        if let Some(storage_size) = self.storage_size
            && storage_size > limits.storage.max_app_storage
        {
            bail!("storage size is greater than limit");
        }

        if let Some(content) = &self.content {
            if content.definitions.len() > limits.storage.content.max_content_definitions as usize {
                bail!(
                    "content definition count {} greater than limit {}",
                    content.definitions.len(),
                    limits.storage.content.max_content_definitions
                );
            }

            for content_def in &content.definitions {
                if content_def.fields.len() > limits.storage.content.max_content_fields as usize {
                    bail!(
                        "content field count {} greater than limit {} for {}",
                        content_def.fields.len(),
                        limits.storage.content.max_content_fields,
                        content_def.name,
                    );
                }

                for field in &content_def.fields {
                    if field.searchable == Some(true) && !limits.storage.content.search_enabled {
                        bail!(
                            "content field cannot be 'searchable' for field {} on definition {}",
                            field.name,
                            content_def.name,
                        );
                    }
                }
            }
        }

        if let Some(models) = &self.models {
            if models.len() > limits.storage.model.max_model_definitions as usize {
                bail!(
                    "model definition count {} greater than limit {}",
                    models.len(),
                    limits.storage.model.max_model_definitions
                );
            }

            for model in models {
                if model.fields.len() > limits.storage.model.max_model_fields as usize {
                    bail!(
                        "model field count {} greater than limit {} for {}",
                        model.fields.len(),
                        limits.storage.content.max_content_fields,
                        model.name,
                    );
                }

                for field in &model.fields {
                    if field.searchable == Some(true) && !limits.storage.content.search_enabled {
                        bail!(
                            "content field cannot be 'searchable' for field {} on definition {}",
                            field.name,
                            model.name,
                        );
                    }
                }
            }
        }

        if let Some(secrets) = &self.secrets
            && secrets.len() > limits.storage.secrets.max_count as usize
        {
            bail!(
                "secrets len {} exceeds max count limit {}",
                secrets.len(),
                limits.storage.secrets.max_count
            );
        }

        Ok(())
    }

    pub fn exec_lifecycle_script(
        proj_path: &Path,
        argument: &Option<String>,
        name: &str,
        when: &str,
        scripts: &Vec<Vec<String>>,
    ) -> anyhow::Result<()> {
        let span = tracing::info_span!("lifecycle", %when, %name);

        span.in_scope(|| {
            let curr_dir = env::current_dir()?;
            env::set_current_dir(proj_path)?;

            for script in scripts {
                let mut script_iter = script.iter();

                if let Some(command) = script_iter.nth(0) {
                    let mut command_str = command.clone();
                    let mut command = Command::new(command);

                    for arg in script_iter {
                        write!(command_str, " {arg}")?;
                        command.arg(arg);
                    }

                    tracing::info!(cmd = %command_str, "exec");

                    let output = match &argument {
                        Some(arg) => command.arg(arg).output()?,
                        None => command.output()?,
                    };

                    if output.status.success() {
                        tracing::info!("success");
                    } else {
                        let stderr = str::from_utf8(&output.stderr)?;
                        let stdout = str::from_utf8(&output.stdout)?;

                        tracing::error!(%stderr, %stdout, "failed");
                        bail!(stderr.to_string());
                    }
                }
            }

            env::set_current_dir(curr_dir)?;

            anyhow::Ok(())
        })
    }
}