sozu-command-lib 2.3.4

configuration library to command a sozu instance
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
syntax = "proto2";
package command;

// JSON state-file forward compat: `SaveState`/`LoadState` write
// `WorkerRequest`s as `\n\0`-separated JSON records. Older clients (e.g.
// `sozu-command-lib = "1.1.1"`) emit only the field set their schema knew,
// so missing `repeated` / `map` fields must default to empty when the
// current schema deserializes them. New schema rules:
//   - new fields must be additive — proto2 `optional`, or `repeated`/`map`,
//   - never rename or change the type of an existing field,
//   - when adding a `repeated` or `map` field to a message that appears in
//     a state file (anything emitted by `ConfigState::generate_requests` or
//     carried in a `RequestType` an external client may build), add the
//     matching `field_attribute(... "#[serde(default)]")` line in
//     `command/build.rs`. Required scalars stay strict on purpose so
//     malformed records still fail before dispatch.
// Regression guard: `command/tests/state_compat_v1_1_1.rs`.

// A message received by Sōzu to change its state or query information
message Request {
  oneof request_type {
    // This message tells Sōzu to dump the current proxy state (backends,
    // front domains, certificates, etc) as a list of JSON-serialized Requests,
    // separated by a 0 byte, to a file. This file can be used later
    // to bootstrap the proxy. This message is not forwarded to workers.
    // If the specified path is relative, it will be calculated relative to the current
    // working directory of the proxy.
    string save_state = 1;
    // load a state file, given its path
    string load_state = 2;
    // list the workers and their status
    ListWorkers list_workers = 4;
    // list the frontends, filtered by protocol and/or domain
    FrontendFilters list_frontends = 5;
    // list all listeners
    ListListeners list_listeners = 6;
    // launch a new worker
    // never implemented, the tag is unused and probably not needed
    // we may still implement it later with no paramater
    // the main process will automatically assign a new id to a new worker
    string launch_worker = 7;
    // upgrade the main process
    UpgradeMain upgrade_main = 8;
    // upgrade an existing worker, giving its id
    uint32 upgrade_worker = 9;
    // subscribe to proxy events
    SubscribeEvents subscribe_events = 10;
    // reload the configuration from the config file, or a new file
    // CHECK: this used to be an option. None => use the config file, Some(string) => path_to_file
    // make sure it works using "" and "path_to_file"
    string reload_configuration = 11;
    // give status of main process and all workers
    Status status = 12;
    // add a cluster
    Cluster add_cluster = 13;
    // remove a cluster giving its id, with every HTTP, HTTPS, TCP and UDP
    // frontend and every backend that names it (a frontend without a
    // cluster_id stays)
    string remove_cluster = 14;
    // add an HTTP frontend
    RequestHttpFrontend add_http_frontend = 15;
    // remove an HTTP frontend
    RequestHttpFrontend remove_http_frontend = 16;
    // add an HTTPS frontend
    RequestHttpFrontend add_https_frontend = 17;
    // remove an HTTPS frontend
    RequestHttpFrontend remove_https_frontend = 18;
    // add a certificate
    AddCertificate add_certificate = 19;
    // replace a certificate
    ReplaceCertificate replace_certificate = 20;
    // remove a certificate
    RemoveCertificate remove_certificate = 21;
    // add a TCP frontend
    RequestTcpFrontend add_tcp_frontend = 22;
    // remove a TCP frontend
    RequestTcpFrontend remove_tcp_frontend = 23;
    // add a backend to an existing cluster: a backend naming a cluster that
    // was never added, or was removed, is refused
    AddBackend add_backend = 24;
    // remove a backend
    RemoveBackend remove_backend = 25;
    // add an HTTP listener
    HttpListenerConfig add_http_listener = 26;
    // add an HTTPS listener
    HttpsListenerConfig add_https_listener = 27;
    // add a TCP listener
    TcpListenerConfig add_tcp_listener = 28;
    // remove a listener
    RemoveListener remove_listener = 29;
    // activate a listener
    ActivateListener activate_listener = 30;
    // deactivate a listener
    DeactivateListener deactivate_listener = 31;
    // query a cluster by id
    string query_cluster_by_id = 35;
    // query clusters with a hostname and optional path
    QueryClusterByDomain query_clusters_by_domain = 36;
    // query clusters hashes
    QueryClustersHashes query_clusters_hashes = 37;
    // query metrics
    QueryMetricsOptions query_metrics = 38;
    // soft stop
    SoftStop soft_stop = 39;
    // hard stop
    HardStop hard_stop = 40;
    // enable, disable or clear the metrics 
    MetricsConfiguration configure_metrics = 41;
    // Change the logging level
    string Logging = 42;
    // Return the listen sockets
    ReturnListenSockets return_listen_sockets = 43;
    // Get certificates from the state (rather than from the workers)
    QueryCertificatesFilters query_certificates_from_the_state = 44;
    // Get certificates from the workers (rather than from the state)
    QueryCertificatesFilters query_certificates_from_workers = 45;
    // query the state about how many requests of each type has been received
    // since startup
    CountRequests count_requests = 46;
    // patch a running HTTP listener in place (no socket re-bind)
    UpdateHttpListenerConfig update_http_listener = 47;
    // patch a running HTTPS listener in place (no socket re-bind)
    UpdateHttpsListenerConfig update_https_listener = 48;
    // patch a running TCP listener in place (no socket re-bind)
    UpdateTcpListenerConfig update_tcp_listener = 49;
    // set the global per-(cluster, source-IP) connection limit at
    // runtime. `0` is "unlimited". Per-cluster overrides set on the
    // `Cluster` message take precedence at admit time.
    uint64 set_max_connections_per_ip = 50;
    // query the current global per-(cluster, source-IP) connection
    // limit. Workers reply with `MaxConnectionsPerIpLimit`.
    QueryMaxConnectionsPerIp query_max_connections_per_ip = 51;
    // set or update the health check configuration for a cluster.
    // Tags 47-49 carry in-place listener patches (HTTP/HTTPS/TCP) and
    // 50-51 carry the per-(cluster, source-IP) connection-limit
    // request/query, so health-check verbs start at 52.
    SetHealthCheck set_health_check = 52;
    // remove the health check configuration from a cluster.
    string remove_health_check = 53;
    // list health check configurations (optional cluster id filter).
    QueryHealthChecks query_health_checks = 54;
    // Apply, renew, or release a runtime cardinality lease on the metrics
    // drain. `sozu top` (and any future TUI client) leases DETAIL_BACKEND
    // for the duration of an interactive session; the worker's effective
    // detail is `max(configured, max(active leases))`. Leases self-expire
    // server-side after `ttl_seconds` so a crashed client never permanently
    // elevates cardinality. See doc/configure.md for the full semantics.
    SetMetricDetail set_metric_detail = 55;
    // add a UDP listener
    UdpListenerConfig add_udp_listener = 56;
    // patch a running UDP listener in place (no socket re-bind)
    UpdateUdpListenerConfig update_udp_listener = 57;
    // add a UDP frontend
    RequestUdpFrontend add_udp_frontend = 58;
    // remove a UDP frontend
    RequestUdpFrontend remove_udp_frontend = 59;
    // set the global per-(cluster, source-SUBNET) connection limit at
    // runtime. `0` is "unlimited" and is the default, which is why the
    // subnet limiter is inert until an operator turns it on. This is a
    // SECOND, independent counter: it does not replace, relax or
    // tighten `set_max_connections_per_ip`, and both gates must admit a
    // connection for it to proceed. Per-cluster overrides set on the
    // `Cluster` message take precedence at admit time. The prefix
    // lengths themselves are boot-time only (`ServerConfig`), because
    // changing a mask would re-key every live counter.
    uint64 set_max_connections_per_subnet = 60;
    // query the current global per-(cluster, source-SUBNET) connection
    // limit AND the two prefix lengths in force. Workers reply with
    // `MaxConnectionsPerSubnetLimit`.
    QueryMaxConnectionsPerSubnet query_max_connections_per_subnet = 61;
    // set the global backend connection attempt budget of every request
    // at runtime: how many backend connections a request may try, the
    // first included, before it is answered `503`. Between 1 and 255.
    // A cluster's own `Cluster.max_connection_attempts` takes precedence.
    // Not persisted: a worker started later reads `ServerConfig`.
    uint32 set_max_connection_attempts = 62;
    // add an HTTPS listener that authenticates clients with a certificate
    // (`client_auth` set to anything other than CLIENT_AUTH_NONE).
    //
    // Same payload as `add_https_listener`, distinct verb on purpose. A
    // worker or main process that predates mutual TLS decodes
    // `add_https_listener` but skips the unknown `client_auth` /
    // `client_ca_*` tags, so it would build the listener without client
    // authentication and acknowledge it. It cannot decode this verb at all,
    // so it never builds the listener: the request fails instead of
    // degrading to unauthenticated access. This matters while the fleet is
    // mixed, between `UpgradeMain` and the replacement of every worker.
    //
    // Emitters pick the verb from the config with
    // `RequestType::add_https_listener`, and the main process rewrites every
    // request it fans out to workers to that canonical verb, so an
    // `add_https_listener` that carries client authentication never reaches
    // a worker. A listener without client authentication keeps
    // `add_https_listener`, which every worker version understands.
    HttpsListenerConfig add_https_listener_with_client_auth = 63;
    // patch a running HTTPS listener whose patch replaces its client
    // authentication policy (`UpdateHttpsListenerConfig.client_auth_policy`
    // set). Same payload as `update_https_listener`, distinct verb for the
    // reason given on `add_https_listener_with_client_auth`: a worker that
    // predates this field would skip it and acknowledge the patch, keeping
    // the CA and CRLs it had, so a revocation the new CRL adds would never
    // apply there. It cannot decode this verb, so the patch fails instead.
    // `RequestType::into_canonical` picks the verb, and the main process
    // applies it to every request it fans out to workers.
    UpdateHttpsListenerConfig update_https_listener_with_client_auth = 64;
    // close the HTTP, HTTPS, TCP and WebSocket sessions of a cluster, or of
    // one backend of a cluster, on every worker. An action, never saved in
    // the state nor replayed by `load_state` or an upgrade. Workers reply
    // with `ClosedSessions`, which the main process gathers per worker in
    // `WorkerResponses`. See `doc/configure_cli.md` for the close semantics.
    CloseSessions close_sessions = 65;
    // add, or remove, an HTTP or HTTPS frontend that carries header
    // predicates (`RequestHttpFrontend.header_predicates` non-empty).
    //
    // Same payload as `add_http_frontend` & co, distinct verbs on purpose
    // (sozu-proxy/sozu#1253). A worker that predates header routing decodes
    // `add_http_frontend` but skips the unknown `header_predicates` tag, so
    // it would install the frontend WITHOUT its guard and send every request
    // for the host to the predicated cluster; a removal would take away the
    // unpredicated sibling that shares the rest of the key. It cannot decode
    // these verbs at all, so the request fails instead. Emitters pick the
    // verb with `RequestType::add_http_frontend` & co, and the main process
    // rewrites every request it fans out to workers with
    // `RequestType::into_canonical`. A frontend without predicates keeps the
    // historical verbs, which every worker version understands.
    //
    // Tags 65 (`close_sessions`), 70-71 (silent-close add HTTP/HTTPS) and 72
    // (`add_unix_backend`) are allocated to other verbs: do not reuse them.
    RequestHttpFrontend add_http_frontend_with_header_predicates = 66;
    RequestHttpFrontend remove_http_frontend_with_header_predicates = 67;
    RequestHttpFrontend add_https_frontend_with_header_predicates = 68;
    RequestHttpFrontend remove_https_frontend_with_header_predicates = 69;

    // add an HTTP frontend whose `redirect` is `SILENT_CLOSE`. Same payload as
    // `add_http_frontend`, distinct verb for the reason given on
    // `add_https_listener_with_client_auth`: a worker that predates
    // `SILENT_CLOSE` decodes the unknown enum value, resolves it to
    // `FORWARD` and installs a route that forwards the traffic the operator
    // asked to drop. It cannot decode this verb, so the request fails.
    // `RequestType::add_http_frontend` / `RequestType::into_canonical` pick
    // the verb, and the main process applies it to every request it fans out.
    RequestHttpFrontend add_http_frontend_with_silent_close = 70;
    // add an HTTPS frontend whose `redirect` is `SILENT_CLOSE`. See
    // `add_http_frontend_with_silent_close`.
    RequestHttpFrontend add_https_frontend_with_silent_close = 71;
    // add a backend that sozu dials over a UNIX domain stream socket
    // (`AddBackend.unix_path` set), with the same payload and the same
    // semantics as `add_backend`, distinct verb on purpose. A worker or main
    // process that predates UNIX backends decodes `add_backend` but skips the
    // unknown `unix_path` tag, so it would register the backend and dial its
    // identity `address` over TCP: traffic meant for a local socket reaching
    // whatever listens on that address, or nothing. It cannot decode this
    // verb at all (it sees no known request), so it never registers the
    // backend and never degrades it to an IP endpoint; it sends no response
    // for it. This matters while the fleet is mixed, between `UpgradeMain`
    // and the replacement of every worker.
    //
    // Emitters pick the verb with `RequestType::add_backend`, and the main
    // process rewrites every request it fans out to workers to that canonical
    // verb, so an `add_backend` that carries a `unix_path` never reaches a
    // worker. A backend without `unix_path` keeps `add_backend`, which every
    // worker version understands.
    //
    // Tags 65-71 are taken by other verbs (close sessions, header routing,
    // silent frontend close): 72 is this verb's, and must not be renumbered.
    AddBackend add_unix_backend = 72;
    // Protected variant of `set_health_check`: the same order plus the clear
    // bytes of the custom header values, which no other verb may carry. It is
    // a distinct verb, not a field of `SetHealthCheck`, so that a main process
    // which predates it decodes no verb at all and refuses the request instead
    // of configuring a probe without its credentials and answering success.
    //
    // Tags 65-72 are taken by other verbs: 73 is this verb's.
    SetProtectedHealthCheck set_protected_health_check = 73;
    // Internal main-to-worker verbs of the all-worker acknowledged protected
    // health check path. A client never sends them: the main process refuses
    // them on the command socket. A worker that predates them decodes no verb
    // and never answers with `protected_health_check_reply`, which is how the
    // main process learns it must not be sent a value.
    //
    // Tags 65-73 are taken by other verbs: 74 and 75 are these verbs'.
    QueryProtectedHealthCheckSupport query_protected_health_check_support = 74;
    ProtectedHealthCheckOrder protected_health_check_order = 75;
  }
}

// Selects the sessions `Request.close_sessions` closes: those with a backend
// connection to `cluster_id`, narrowed to one backend when `backend_id`, or
// `address`, or both are set (a backend matches only if every set field
// matches).
message CloseSessions {
    required string cluster_id = 1;
    optional string backend_id = 2;
    optional SocketAddress address = 3;
}

message QueryHealthChecks {
    optional string cluster_id = 1;
}

message SetHealthCheck {
    required string cluster_id = 1;
    required HealthCheckConfig config = 2;
}

// Sets the health check of a cluster together with the clear values of its
// custom headers. As received from an operator `config.headers` names the
// headers in order and carries no fingerprint; `values` holds one carrier per
// header, in the same order. The main process validates all of it, recomputes
// every fingerprint with its own key and forwards the same verb to the workers
// with the trusted fingerprints in place. Never persisted, never serialized to
// JSON: the carriers refuse serde.
message SetProtectedHealthCheck {
    required string cluster_id = 1;
    required HealthCheckConfig config = 2;
    repeated HealthCheckHeaderValue values = 3;
}

// Asks a worker whether it implements the protected health check protocol.
// Carries nothing: no cluster, no value.
message QueryProtectedHealthCheckSupport {}

// Where a protected health check change stands for one worker.
enum ProtectedHealthCheckPhase {
    // Positive answer to `QueryProtectedHealthCheckSupport`.
    PROTECTED_HEALTH_CHECK_CAPABILITY = 0;
    // Validate and stage `prepare` without applying it.
    PROTECTED_HEALTH_CHECK_PREPARE = 1;
    // Apply the staged `version`, configuration and values together.
    PROTECTED_HEALTH_CHECK_COMMIT = 2;
    // Drop the staged `version`, or restore the state that preceded it.
    PROTECTED_HEALTH_CHECK_ABORT = 3;
    // The change succeeded everywhere: forget the state that preceded it.
    PROTECTED_HEALTH_CHECK_RELEASE = 4;
}

// One internal order of the protected health check protocol. Only `PREPARE`
// carries `prepare`, which holds the clear header values: it is the single
// main-to-worker carrier of them, and lives in the channel buffers only.
message ProtectedHealthCheckOrder {
    required ProtectedHealthCheckPhase phase = 1;
    required string cluster_id = 2;
    required uint64 version = 3;
    optional SetProtectedHealthCheck prepare = 4;
}

// A worker's positive answer to a protected health check order: its phase,
// the cluster and the version it acted on, never a header name or value.
message ProtectedHealthCheckReply {
    required ProtectedHealthCheckPhase phase = 1;
    required string cluster_id = 2;
    required uint64 version = 3;
}

message ListWorkers {}
message ListListeners {}
message UpgradeMain {}
message SubscribeEvents {}
message Status {}
message QueryClustersHashes {}
message SoftStop {}
message HardStop {}
message ReturnListenSockets {}
message CountRequests {}
message QueryMaxConnectionsPerIp {}
message QueryMaxConnectionsPerSubnet {}

// Wrapper message to distinguish "absent" (preserve) from "present but empty"
// (reset to default) for ALPN protocols. A bare `repeated string` cannot make
// this distinction in proto2 since field absence is not detectable for repeated
// scalars without a sentinel.
message AlpnProtocols {
    repeated string values = 1;
}

// Partial-update patch for a running HTTP listener.
// Only fields that are `Some` in the patch will be applied;
// absent fields preserve their current value on the listener.
// Bind-only fields (address, interface, active) are intentionally absent — use
// RemoveListener + AddHttpListener to change them.
// `interface` is bind-only too, and not even a selector here: `address`
// names the listener, and the main process refuses the patch when several
// listeners share that address on different interfaces.
message UpdateHttpListenerConfig {
    // identifies the listener to patch (required — used as key)
    required SocketAddress address = 1;

    optional SocketAddress public_address = 2;
    optional bool expect_proxy = 3;
    optional string sticky_name = 4;
    // client inactive time, in seconds
    optional uint32 front_timeout = 5;
    // backend server inactive time, in seconds
    optional uint32 back_timeout = 6;
    // time to connect to the backend, in seconds
    optional uint32 connect_timeout = 7;
    // max time to send a complete request, in seconds
    optional uint32 request_timeout = 8;
    // DEPRECATED: per-status answer message. Prefer the `answers` map at
    // field 38. Kept on the wire so older managers can still patch a running
    // listener for one minor; on the worker side both fields are merged.
    optional CustomHttpAnswers http_answers = 9;

    // H2 flood thresholds — see HttpListenerConfig for semantics & CVE refs.
    // All values must be >= 1 (validated server-side before applying).
    // Maximum RST_STREAM frames per second window (CVE-2023-44487, CVE-2019-9514)
    optional uint32 h2_max_rst_stream_per_window     = 20;
    // Maximum PING frames per second window (CVE-2019-9512)
    optional uint32 h2_max_ping_per_window           = 21;
    // Maximum SETTINGS frames per second window (CVE-2019-9515)
    optional uint32 h2_max_settings_per_window       = 22;
    // Maximum empty DATA frames per second window (CVE-2019-9518)
    optional uint32 h2_max_empty_data_per_window     = 23;
    // Maximum CONTINUATION frames per header block (CVE-2024-27316)
    optional uint32 h2_max_continuation_frames       = 24;
    // Maximum accumulated protocol anomalies before ENHANCE_YOUR_CALM
    optional uint32 h2_max_glitch_count              = 25;
    // Connection-level receive window size in bytes (RFC 9113 §6.9.2)
    optional uint32 h2_initial_connection_window     = 26;
    // Maximum concurrent H2 streams (SETTINGS_MAX_CONCURRENT_STREAMS); >= 1
    optional uint32 h2_max_concurrent_streams        = 27;
    // Shrink threshold ratio for recycled stream slots; >= 2
    optional uint32 h2_stream_shrink_ratio           = 28;
    // Floor of the lifetime cap on RST_STREAM frames received (CVE-2023-44487)
    optional uint64 h2_max_rst_stream_lifetime       = 29;
    // Floor of the cap on pre-response RST_STREAM frames — Rapid Reset signature
    optional uint64 h2_max_rst_stream_abusive_lifetime   = 30;
    // Floor of the cap on peer-provoked RST_STREAM frames the server emits (CVE-2025-8671)
    optional uint64 h2_max_rst_stream_emitted_lifetime   = 31;
    // Maximum HPACK-decoded header list size per request (RFC 9113 §6.5.2)
    optional uint32 h2_max_header_list_size          = 32;
    // Maximum HPACK dynamic table size accepted from the peer
    optional uint32 h2_max_header_table_size         = 33;
    // Per-stream idle timeout in seconds
    optional uint32 h2_stream_idle_timeout_seconds   = 34;
    // Maximum wall-clock seconds to wait after GOAWAY(NO_ERROR). 0 = wait forever.
    optional uint32 h2_graceful_shutdown_deadline_seconds = 35;
    // Maximum unsolicited connection-level (stream 0) WINDOW_UPDATE frames per window; >= 1
    optional uint32 h2_max_window_update_stream0_per_window = 36;
    // Name of the correlation header injected per request (e.g. "Sozu-Id")
    optional string sozu_id_header                   = 37;
    // Per-status HTTP answer template bodies, keyed by HTTP status code
    // (e.g. "503"). Replaces the per-field shape of `CustomHttpAnswers` (field
    // 9). An entry with an empty value is treated as "preserve current"; an
    // entry with a non-empty value replaces the listener's stored template
    // for that status. To clear a status template, recreate the listener.
    map<string, string> answers                     = 38;
    // When true, any client-supplied `X-Real-IP` header is stripped from
    // requests before forwarding (anti-spoofing). See HttpListenerConfig.
    optional bool elide_x_real_ip                   = 39;
    // When true, a proxy-generated `X-Real-IP` header carrying the connection
    // peer IP is appended to every forwarded request. See HttpListenerConfig.
    optional bool send_x_real_ip                    = 40;
    // Maximum materialized header fields per request — see HttpListenerConfig.
    optional uint32 h2_max_header_fields            = 41;
    // Which forwarding header family the listener emits — see
    // HttpListenerConfig.
    optional ForwardedHeaders forwarded_headers     = 42;
    // Soft stream-refusal share of the pre-response RST_STREAM cap, in percent —
    // see HttpListenerConfig.
    optional uint32 h2_stream_refusal_percent       = 43;
    // Serve cleartext HTTP/2 to clients that open with the connection preface
    // (prior knowledge) — see HttpListenerConfig. Affects new connections only.
    optional bool h2c_prior_knowledge               = 44;
}

// Partial-update patch for a running HTTPS listener.
// Only fields that are `Some` in the patch will be applied;
// absent fields preserve their current value on the listener.
// Bind-only fields (tls_versions, cipher_list, cipher_suites,
// signature_algorithms, groups_list, certificate, certificate_chain, key,
// send_tls13_tickets, interface, active) are intentionally absent — use
// RemoveListener + AddHttpsListener to change them.
// `interface` is bind-only too, and not even a selector here: `address`
// names the listener, and the main process refuses the patch when several
// listeners share that address on different interfaces.
message UpdateHttpsListenerConfig {
    // identifies the listener to patch (required — used as key)
    required SocketAddress address = 1;

    optional SocketAddress public_address = 2;
    optional bool expect_proxy = 3;
    optional string sticky_name = 4;
    // client inactive time, in seconds
    optional uint32 front_timeout = 5;
    // backend server inactive time, in seconds
    optional uint32 back_timeout = 6;
    // time to connect to the backend, in seconds
    optional uint32 connect_timeout = 7;
    // max time to send a complete request, in seconds
    optional uint32 request_timeout = 8;
    // DEPRECATED: per-status answer message. Prefer the `answers` map at
    // field 38. Kept on the wire so older managers can still patch a running
    // listener for one minor; on the worker side both fields are merged.
    optional CustomHttpAnswers http_answers = 9;

    // ALPN protocols to advertise during TLS handshake.
    // Uses a wrapper message so "absent" (preserve) and "present but empty"
    // (reset to default ["h2","http/1.1"]) are unambiguous. Valid values per
    // element: "h2", "http/1.1". Validated server-side.
    optional AlpnProtocols alpn_protocols = 10;
    // When true, :authority/Host must match the TLS SNI (CWE-346/CWE-444)
    optional bool strict_sni_binding = 11;
    // When true, only H2 connections are accepted; HTTP/1.1 is dropped at handshake
    optional bool disable_http11 = 12;

    // H2 flood thresholds — same numbers/semantics as UpdateHttpListenerConfig.
    // All values must be >= 1 (validated server-side before applying).
    // Maximum RST_STREAM frames per second window (CVE-2023-44487, CVE-2019-9514)
    optional uint32 h2_max_rst_stream_per_window     = 20;
    // Maximum PING frames per second window (CVE-2019-9512)
    optional uint32 h2_max_ping_per_window           = 21;
    // Maximum SETTINGS frames per second window (CVE-2019-9515)
    optional uint32 h2_max_settings_per_window       = 22;
    // Maximum empty DATA frames per second window (CVE-2019-9518)
    optional uint32 h2_max_empty_data_per_window     = 23;
    // Maximum CONTINUATION frames per header block (CVE-2024-27316)
    optional uint32 h2_max_continuation_frames       = 24;
    // Maximum accumulated protocol anomalies before ENHANCE_YOUR_CALM
    optional uint32 h2_max_glitch_count              = 25;
    // Connection-level receive window size in bytes (RFC 9113 §6.9.2)
    optional uint32 h2_initial_connection_window     = 26;
    // Maximum concurrent H2 streams (SETTINGS_MAX_CONCURRENT_STREAMS); >= 1
    optional uint32 h2_max_concurrent_streams        = 27;
    // Shrink threshold ratio for recycled stream slots; >= 2
    optional uint32 h2_stream_shrink_ratio           = 28;
    // Floor of the lifetime cap on RST_STREAM frames received (CVE-2023-44487)
    optional uint64 h2_max_rst_stream_lifetime       = 29;
    // Floor of the cap on pre-response RST_STREAM frames — Rapid Reset signature
    optional uint64 h2_max_rst_stream_abusive_lifetime   = 30;
    // Floor of the cap on peer-provoked RST_STREAM frames the server emits (CVE-2025-8671)
    optional uint64 h2_max_rst_stream_emitted_lifetime   = 31;
    // Maximum HPACK-decoded header list size per request (RFC 9113 §6.5.2)
    optional uint32 h2_max_header_list_size          = 32;
    // Maximum HPACK dynamic table size accepted from the peer
    optional uint32 h2_max_header_table_size         = 33;
    // Per-stream idle timeout in seconds
    optional uint32 h2_stream_idle_timeout_seconds   = 34;
    // Maximum wall-clock seconds to wait after GOAWAY(NO_ERROR). 0 = wait forever.
    optional uint32 h2_graceful_shutdown_deadline_seconds = 35;
    // Maximum unsolicited connection-level (stream 0) WINDOW_UPDATE frames per window; >= 1
    optional uint32 h2_max_window_update_stream0_per_window = 36;
    // Name of the correlation header injected per request (e.g. "Sozu-Id")
    optional string sozu_id_header                   = 37;
    // Per-status HTTP answer template bodies, keyed by HTTP status code
    // (e.g. "503"). Replaces the per-field shape of `CustomHttpAnswers` (field
    // 9). An entry with an empty value is treated as "preserve current"; an
    // entry with a non-empty value replaces the listener's stored template
    // for that status. To clear a status template, recreate the listener.
    map<string, string> answers                     = 38;
    // When true, any client-supplied `X-Real-IP` header is stripped from
    // requests before forwarding (anti-spoofing). See HttpsListenerConfig.
    optional bool elide_x_real_ip                   = 39;
    // When true, a proxy-generated `X-Real-IP` header carrying the connection
    // peer IP is appended to every forwarded request. See HttpsListenerConfig.
    optional bool send_x_real_ip                    = 40;
    // Listener-default HSTS policy (RFC 6797). Full-object replacement on
    // partial update — when this field is `Some`, the supplied
    // `HstsConfig` overwrites whatever the listener currently holds; when
    // absent, the existing policy is preserved. Use
    // `Some(HstsConfig { enabled: Some(false), .. })` to explicitly
    // disable HSTS via partial update. Cites RFC 6797 §6.1 (single
    // header) and §7.2 (HTTPS-only).
    optional HstsConfig hsts                        = 41;
    // Maximum materialized header fields per request — see HttpsListenerConfig.
    optional uint32 h2_max_header_fields            = 42;
    // Which forwarding header family the listener emits — see
    // HttpsListenerConfig.
    optional ForwardedHeaders forwarded_headers     = 43;
    // Soft stream-refusal share of the pre-response RST_STREAM cap, in percent —
    // see HttpsListenerConfig.
    optional uint32 h2_stream_refusal_percent       = 44;
    // Client authentication policy. Full replacement: when set, the mode, the
    // trusted CAs and the CRLs all take the values given here, so a CA or CRL
    // left out is dropped, not kept; when absent, the policy is unchanged.
    // This is how a CRL or CA bundle is refreshed without recreating the
    // listener. Only new handshakes see the new policy.
    optional ClientAuthPolicy client_auth_policy    = 45;
}

// The client authentication policy of an HTTPS listener, as carried by an
// `UpdateHttpsListenerConfig` patch. Same meaning as the `client_auth`,
// `client_ca_certificates` and `client_ca_crls` fields of
// `HttpsListenerConfig`.
message ClientAuthPolicy {
    optional ClientAuthMode client_auth = 1;
    repeated string client_ca_certificates = 2;
    repeated string client_ca_crls = 3;
}

// Partial-update patch for a running TCP listener.
// Only fields that are `Some` in the patch will be applied;
// absent fields preserve their current value on the listener.
// Bind-only fields (address, interface, active) are intentionally absent.
// `interface` is bind-only too, and not even a selector here: `address`
// names the listener, and the main process refuses the patch when several
// listeners share that address on different interfaces.
message UpdateTcpListenerConfig {
    // identifies the listener to patch (required — used as key)
    required SocketAddress address = 1;

    optional SocketAddress public_address = 2;
    optional bool expect_proxy = 3;
    // client inactive time, in seconds
    optional uint32 front_timeout = 4;
    // backend server inactive time, in seconds
    optional uint32 back_timeout = 5;
    // time to connect to the backend, in seconds
    optional uint32 connect_timeout = 6;
}

// Partial-update patch for a running UDP listener.
// Only fields that are `Some` in the patch will be applied;
// absent fields preserve their current value on the listener.
// Bind-only fields (address, interface, active) are intentionally absent — use
// RemoveListener + AddUdpListener to change them.
// `interface` is bind-only too, and not even a selector here: `address`
// names the listener, and the main process refuses the patch when several
// listeners share that address on different interfaces.
message UpdateUdpListenerConfig {
    // identifies the listener to patch (required — used as key)
    required SocketAddress address = 1;

    optional SocketAddress public_address = 2;
    // client flow idle time, in seconds
    optional uint32 front_timeout = 3;
    // upstream flow idle time, in seconds
    optional uint32 back_timeout = 4;
    // maximum received datagram size, in bytes (capped at buffer_size at runtime)
    optional uint32 max_rx_datagram_size = 5;
    // maximum number of concurrent flows; 0 = auto (~70% soft RLIMIT_NOFILE)
    optional uint32 max_flows = 6;
}

// details of an HTTP listener
message HttpListenerConfig {
    required SocketAddress address = 1;
    optional SocketAddress public_address = 2;
    required bool expect_proxy = 5 [default = false];
    required string sticky_name = 6;
    // client inactive time, in seconds
    required uint32 front_timeout = 7 [default = 60];
    // backend server inactive time, in seconds
    required uint32 back_timeout = 8 [default = 30];
    // time to connect to the backend, in seconds
    required uint32 connect_timeout = 9 [default = 3];
    // max time to send a complete request, in seconds
    required uint32 request_timeout = 10 [default = 10];
    // wether the listener is actively listening on its socket
    required bool active = 11 [default = false];
    // DEPRECATED: per-status answer message. Prefer the `answers` map at
    // field 31. Kept on the wire so legacy state files round-trip cleanly;
    // workers populate both fields and treat them as equivalent on read.
    optional CustomHttpAnswers http_answers = 12;
    // H2 flood detection thresholds (CVE mitigations).
    // All are optional; when absent, built-in defaults are used.
    // Maximum RST_STREAM frames per second window (CVE-2023-44487, CVE-2019-9514)
    optional uint32 h2_max_rst_stream_per_window = 13;
    // Maximum PING frames per second window (CVE-2019-9512)
    optional uint32 h2_max_ping_per_window = 14;
    // Maximum SETTINGS frames per second window (CVE-2019-9515)
    optional uint32 h2_max_settings_per_window = 15;
    // Maximum empty DATA frames per second window (CVE-2019-9518)
    optional uint32 h2_max_empty_data_per_window = 16;
    // Maximum CONTINUATION frames per header block (CVE-2024-27316)
    optional uint32 h2_max_continuation_frames = 17;
    // Maximum accumulated protocol anomalies before ENHANCE_YOUR_CALM
    optional uint32 h2_max_glitch_count = 18;
    // H2 connection tuning parameters.
    // Connection-level receive window size in bytes (RFC 9113 §6.9.2).
    // Default: 16777216 (16 MiB). Credit is returned per half window received.
    optional uint32 h2_initial_connection_window = 19;
    // Maximum concurrent H2 streams the proxy accepts (SETTINGS_MAX_CONCURRENT_STREAMS).
    // Default: 100.
    optional uint32 h2_max_concurrent_streams = 20;
    // Shrink threshold ratio for recycled stream slots. Vec is shrunk when
    // total_slots > active_streams * ratio. Default: 2.
    optional uint32 h2_stream_shrink_ratio = 21;
    // Floor of the connection-lifetime cap on RST_STREAM frames received
    // (CVE-2023-44487): trips once the count exceeds this value and the
    // resets received after a response started or on a closed stream exceed
    // the streams a backend answered on the connection. Default: 200000.
    optional uint64 h2_max_rst_stream_lifetime = 22;
    // Floor of the cap on "abusive" (pre-response-start) RST_STREAM frames
    // received on a frontend H2 connection — the Rapid Reset signature: trips
    // once the count exceeds this value and more than half of the
    // backend-routed streams were reset before their response.
    // Default: 1000.
    optional uint64 h2_max_rst_stream_abusive_lifetime = 23;
    // Floor of the cap on RST_STREAM frames **emitted by the server** that
    // the peer provoked (CVE-2025-8671 "MadeYouReset"): trips once the count
    // exceeds this value and more than half of the
    // backend-routed streams were reset before their response. Covers the
    // emission-direction-flipped sibling of Rapid Reset, where an attacker
    // sends legitimate-looking frames (Content-Length mismatch, header parse
    // error, rejected priority, zero-increment WINDOW_UPDATE on an open
    // stream) that coerce the server into emitting RST_STREAM. Resets Sōzu
    // decides on its own (idle CANCEL, REFUSED_STREAM, STREAM_CLOSED,
    // backend-failure INTERNAL_ERROR) and `NoError` resets are not counted.
    // Default: 10000.
    optional uint64 h2_max_rst_stream_emitted_lifetime = 27;
    // Maximum accumulated HPACK-decoded header list size per request
    // (SETTINGS_MAX_HEADER_LIST_SIZE, RFC 9113 §6.5.2). Default: 65536.
    optional uint32 h2_max_header_list_size = 24;
    // Per-stream idle timeout, in seconds. An open H2 stream that receives
    // no meaningful application data (non-empty DATA or HEADERS frames) for
    // this duration is cancelled (RST_STREAM / CANCEL). Active uploads that
    // trickle DATA frames reset the timer on each non-empty frame. Defends
    // against slow-multiplex Slowloris where a client keeps connection-level
    // activity high (any frame resets the connection idle timer) while pinning
    // up to `h2_max_concurrent_streams` streams. Unset, it inherits
    // `back_timeout`, floored at 30 (so 30 with the default `back_timeout`);
    // an explicit value wins, `0` meaning 1.
    optional uint32 h2_stream_idle_timeout_seconds = 25;
    // Maximum HPACK dynamic table size (SETTINGS_HEADER_TABLE_SIZE) accepted
    // from the peer. Caps the peer-advertised value to prevent unbounded
    // HPACK encoder memory growth. Default: 65536.
    optional uint32 h2_max_header_table_size = 26;
    // Maximum wall-clock seconds to wait for in-flight H2 streams after
    // GOAWAY(NO_ERROR) before forcibly closing the connection. Default: 5.
    // Set to 0 to require streams to finish (no forced close).
    optional uint32 h2_graceful_shutdown_deadline_seconds = 28;
    // Maximum unsolicited connection-level (stream 0) WINDOW_UPDATE frames
    // per second window. Each DATA frame the proxy sends entitles the peer to
    // two that are not counted; only the excess counts. Caps non-zero stream-0
    // WINDOW_UPDATE floods that would otherwise stay under the generic glitch
    // counter (zero-increment stream-0 updates already trigger GOAWAY per
    // RFC 9113 §6.9). Default: 2000.
    optional uint32 h2_max_window_update_stream0_per_window = 29;
    // Name of the correlation header Sozu injects into every request and
    // response to carry the per-request ULID. Default: "Sozu-Id". Operators
    // who want to rebrand can set e.g. "X-Edge-Id" or "X-Request-Trace".
    optional string sozu_id_header = 30;
    // Per-status HTTP answer template bodies, keyed by HTTP status code
    // (e.g. "404", "503"). Replaces the per-field shape of `CustomHttpAnswers`
    // (field 12). The new field is populated alongside `http_answers` so
    // legacy state files round-trip; new code should read this map.
    map<string, string> answers = 31;
    // When true, any client-supplied `X-Real-IP` header is stripped from
    // requests before forwarding (anti-spoofing). Independently combinable
    // with `send_x_real_ip`. Default: false.
    optional bool elide_x_real_ip = 32 [default = false];
    // When true, a proxy-generated `X-Real-IP` header carrying the connection
    // peer IP (post-PROXY-v2 unwrap, i.e. the original client IP) is appended
    // to every forwarded request. Independently combinable with
    // `elide_x_real_ip`. Default: false.
    optional bool send_x_real_ip = 33 [default = false];
    // Maximum number of materialized header fields per request — HPACK fields
    // plus expanded cookie crumbs (RFC 9113 §8.2.3). Bounds the HPACK
    // indexed-reference header bomb, where 1-byte indexed references are
    // amplified into per-entry bookkeeping. Default: 128.
    optional uint32 h2_max_header_fields = 34;
    // Name of the network interface (e.g. "wg0") the listening socket is
    // bound to with SO_BINDTODEVICE, set before bind(). Linux only: the
    // configuration loader refuses the key on any other platform. Part of the
    // listener identity together with `address`, so two listeners may share an
    // address on different interfaces. Absent = not bound to an interface (the
    // historical behaviour). Not patchable: changing it needs a rebind, so it
    // is absent from the Update*ListenerConfig patches.
    optional string interface = 35;
    // Which forwarding header family is added to every forwarded request:
    // `X-Forwarded-*`, RFC 7239 `Forwarded`, both, or none. Independent of
    // `elide_x_real_ip` and `send_x_real_ip`. Default: both.
    optional ForwardedHeaders forwarded_headers = 36 [default = FORWARDED_HEADERS_BOTH];
    // Share, in percent, of the pre-response RST_STREAM cap's floor
    // (h2_max_rst_stream_abusive_lifetime) at which an H2 connection refuses
    // new client streams with RST_STREAM(REFUSED_STREAM), retryable per
    // RFC 9113 §8.7, and keeps serving its open streams. The cap itself still
    // ends the connection with GOAWAY(ENHANCE_YOUR_CALM). 0 disables the soft
    // state; 100 or more never engages it before the cap. Default: 50.
    optional uint32 h2_stream_refusal_percent = 37;
    // When true, a connection whose first 24 bytes are the HTTP/2 connection
    // preface (`PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n`, RFC 9113 §3.3 "prior
    // knowledge") is served as HTTP/2 over cleartext (h2c), exactly as an
    // HTTPS connection that negotiated `h2` through ALPN; every other
    // connection stays HTTP/1.x. The `Upgrade: h2c` mechanism is never
    // supported. When false, a preface is rejected as a malformed HTTP/1.x
    // request (400). Default: false.
    optional bool h2c_prior_knowledge = 38 [default = false];
}

// details of an HTTPS listener
message HttpsListenerConfig {
    required SocketAddress address = 1;
    optional SocketAddress public_address = 2;
    required bool expect_proxy = 5 [default = false];
    required string sticky_name = 6;
    // client inactive time, in seconds
    required uint32 front_timeout = 7 [default = 60];
    // backend server inactive time, in seconds
    required uint32 back_timeout = 8 [default = 30];
    // time to connect to the backend, in seconds
    required uint32 connect_timeout = 9 [default = 3];
    // max time to send a complete request, in seconds
    required uint32 request_timeout = 10 [default = 10];
    // wether the listener is actively listening on its socket
    required bool active = 11 [default = false];
    // TLS versions
    repeated TlsVersion versions = 12;
    repeated string cipher_list = 13;
    repeated string cipher_suites = 14;
    repeated string signature_algorithms = 15;
    repeated string groups_list = 16;
    optional string certificate = 17;
    repeated string certificate_chain = 18;
    optional string key = 19;
    // Number of TLS 1.3 tickets to send to a client when establishing a connection.
    // The tickets allow the client to resume a session. This protects the client
    // agains session tracking. Defaults to 4.
    required uint64 send_tls13_tickets = 20;
    // DEPRECATED: per-status answer message. Prefer the `answers` map at
    // field 43. Kept on the wire so legacy state files round-trip cleanly;
    // workers populate both fields and treat them as equivalent on read.
    optional CustomHttpAnswers http_answers = 21;
    // ALPN protocols to advertise during TLS handshake, in order of preference.
    // Valid values: "h2", "http/1.1". Defaults to ["h2", "http/1.1"].
    repeated string alpn_protocols = 22;
    // H2 flood detection thresholds (CVE mitigations).
    // All are optional; when absent, built-in defaults are used.
    // Maximum RST_STREAM frames per second window (CVE-2023-44487, CVE-2019-9514)
    optional uint32 h2_max_rst_stream_per_window = 23;
    // Maximum PING frames per second window (CVE-2019-9512)
    optional uint32 h2_max_ping_per_window = 24;
    // Maximum SETTINGS frames per second window (CVE-2019-9515)
    optional uint32 h2_max_settings_per_window = 25;
    // Maximum empty DATA frames per second window (CVE-2019-9518)
    optional uint32 h2_max_empty_data_per_window = 26;
    // Maximum CONTINUATION frames per header block (CVE-2024-27316)
    optional uint32 h2_max_continuation_frames = 27;
    // Maximum accumulated protocol anomalies before ENHANCE_YOUR_CALM
    optional uint32 h2_max_glitch_count = 28;
    // H2 connection tuning parameters.
    // Connection-level receive window size in bytes (RFC 9113 §6.9.2).
    // Default: 16777216 (16 MiB). Credit is returned per half window received.
    optional uint32 h2_initial_connection_window = 29;
    // Maximum concurrent H2 streams the proxy accepts (SETTINGS_MAX_CONCURRENT_STREAMS).
    // Default: 100.
    optional uint32 h2_max_concurrent_streams = 30;
    // Shrink threshold ratio for recycled stream slots. Vec is shrunk when
    // total_slots > active_streams * ratio. Default: 2.
    optional uint32 h2_stream_shrink_ratio = 31;
    // Floor of the connection-lifetime cap on RST_STREAM frames received
    // (CVE-2023-44487): trips once the count exceeds this value and the
    // resets received after a response started or on a closed stream exceed
    // the streams a backend answered on the connection. Default: 200000.
    optional uint64 h2_max_rst_stream_lifetime = 32;
    // Floor of the cap on "abusive" (pre-response-start) RST_STREAM frames
    // received on a frontend H2 connection — the Rapid Reset signature: trips
    // once the count exceeds this value and more than half of the
    // backend-routed streams were reset before their response.
    // Default: 1000.
    optional uint64 h2_max_rst_stream_abusive_lifetime = 33;
    // Floor of the cap on RST_STREAM frames **emitted by the server** that
    // the peer provoked (CVE-2025-8671 "MadeYouReset"): trips once the count
    // exceeds this value and more than half of the
    // backend-routed streams were reset before their response. Covers the
    // emission-direction-flipped sibling of Rapid Reset, where an attacker
    // sends legitimate-looking frames (Content-Length mismatch, header parse
    // error, rejected priority, zero-increment WINDOW_UPDATE on an open
    // stream) that coerce the server into emitting RST_STREAM. Resets Sōzu
    // decides on its own (idle CANCEL, REFUSED_STREAM, STREAM_CLOSED,
    // backend-failure INTERNAL_ERROR) and `NoError` resets are not counted.
    // Default: 10000.
    optional uint64 h2_max_rst_stream_emitted_lifetime = 39;
    // Maximum accumulated HPACK-decoded header list size per request
    // (SETTINGS_MAX_HEADER_LIST_SIZE, RFC 9113 §6.5.2). Default: 65536.
    optional uint32 h2_max_header_list_size = 34;
    // When true, every HTTP request served on this listener must have its
    // `:authority` / `Host` host exact-match the TLS SNI that was negotiated
    // at handshake (CWE-346 / CWE-444). Disabling this lifts the per-stream
    // TLS trust boundary, so leave enabled unless an operational need
    // requires cross-SNI routing. Default: true.
    optional bool strict_sni_binding = 35;
    // When true, this listener only accepts HTTP/2 connections: clients
    // that fail to negotiate `h2` via TLS ALPN (including those that
    // omit ALPN altogether) are dropped at handshake instead of silently
    // falling back to HTTP/1.1. Default: false — preserves the historical
    // "ALPN missing defaults to h1" behavior.
    optional bool disable_http11 = 36;
    // Per-stream idle timeout, in seconds. An open H2 stream that receives
    // no meaningful application data (non-empty DATA or HEADERS frames) for
    // this duration is cancelled (RST_STREAM / CANCEL). Active uploads that
    // trickle DATA frames reset the timer on each non-empty frame. Defends
    // against slow-multiplex Slowloris where a client keeps connection-level
    // activity high (any frame resets the connection idle timer) while pinning
    // up to `h2_max_concurrent_streams` streams. Unset, it inherits
    // `back_timeout`, floored at 30 (so 30 with the default `back_timeout`);
    // an explicit value wins, `0` meaning 1.
    optional uint32 h2_stream_idle_timeout_seconds = 37;
    // Maximum HPACK dynamic table size (SETTINGS_HEADER_TABLE_SIZE) accepted
    // from the peer. Caps the peer-advertised value to prevent unbounded
    // HPACK encoder memory growth. Default: 65536.
    optional uint32 h2_max_header_table_size = 38;
    // Maximum wall-clock seconds to wait for in-flight H2 streams after
    // GOAWAY(NO_ERROR) before forcibly closing the connection. Default: 5.
    // Set to 0 to require streams to finish (no forced close).
    optional uint32 h2_graceful_shutdown_deadline_seconds = 40;
    // Maximum unsolicited connection-level (stream 0) WINDOW_UPDATE frames
    // per second window. Each DATA frame the proxy sends entitles the peer to
    // two that are not counted; only the excess counts. Caps non-zero stream-0
    // WINDOW_UPDATE floods that would otherwise stay under the generic glitch
    // counter (zero-increment stream-0 updates already trigger GOAWAY per
    // RFC 9113 §6.9). Default: 2000.
    optional uint32 h2_max_window_update_stream0_per_window = 41;
    // Name of the correlation header Sozu injects into every request and
    // response to carry the per-request ULID. Default: "Sozu-Id". Operators
    // who want to rebrand can set e.g. "X-Edge-Id" or "X-Request-Trace".
    optional string sozu_id_header = 42;
    // Per-status HTTP answer template bodies, keyed by HTTP status code
    // (e.g. "404", "503"). Replaces the per-field shape of `CustomHttpAnswers`
    // (field 21). The new field is populated alongside `http_answers` so
    // legacy state files round-trip; new code should read this map.
    map<string, string> answers = 43;
    // When true, any client-supplied `X-Real-IP` header is stripped from
    // requests before forwarding (anti-spoofing). Independently combinable
    // with `send_x_real_ip`. Default: false.
    optional bool elide_x_real_ip = 44 [default = false];
    // When true, a proxy-generated `X-Real-IP` header carrying the connection
    // peer IP (post-PROXY-v2 unwrap, i.e. the original client IP) is appended
    // to every forwarded request. Independently combinable with
    // `elide_x_real_ip`. Default: false.
    optional bool send_x_real_ip = 45 [default = false];
    // Listener-default HSTS (HTTP Strict Transport Security, RFC 6797)
    // policy. When set, every successful response on this listener gains
    // a `Strict-Transport-Security` header derived from the materialised
    // policy (RFC 6797 §6.1 single-header requirement, §7.2 HTTPS-only
    // emission, §8.1 host scope, §11.4 max-age=0 kill-switch). A
    // per-frontend `RequestHttpFrontend.hsts` overrides this default.
    optional HstsConfig hsts = 46;
    // Maximum number of materialized header fields per request — HPACK fields
    // plus expanded cookie crumbs (RFC 9113 §8.2.3). Bounds the HPACK
    // indexed-reference header bomb, where 1-byte indexed references are
    // amplified into per-entry bookkeeping. Default: 128.
    optional uint32 h2_max_header_fields = 47;
    // Name of the network interface (e.g. "wg0") the listening socket is
    // bound to with SO_BINDTODEVICE, set before bind(). Linux only: the
    // configuration loader refuses the key on any other platform. Part of the
    // listener identity together with `address`, so two listeners may share an
    // address on different interfaces. Absent = not bound to an interface (the
    // historical behaviour). Not patchable: changing it needs a rebind, so it
    // is absent from the Update*ListenerConfig patches.
    optional string interface = 48;
    // Which forwarding header family is added to every forwarded request:
    // `X-Forwarded-*`, RFC 7239 `Forwarded`, both, or none. Independent of
    // `elide_x_real_ip` and `send_x_real_ip`. Default: both.
    optional ForwardedHeaders forwarded_headers = 49 [default = FORWARDED_HEADERS_BOTH];
    // Share, in percent, of the pre-response RST_STREAM cap's floor
    // (h2_max_rst_stream_abusive_lifetime) at which an H2 connection refuses
    // new client streams with RST_STREAM(REFUSED_STREAM), retryable per
    // RFC 9113 §8.7, and keeps serving its open streams. The cap itself still
    // ends the connection with GOAWAY(ENHANCE_YOUR_CALM). 0 disables the soft
    // state; 100 or more never engages it before the cap. Default: 50.
    optional uint32 h2_stream_refusal_percent = 50;
    // Mutual TLS (client certificate authentication) mode for this listener.
    // Absent or CLIENT_AUTH_NONE (the field-0 default) keeps the current
    // behavior: no CertificateRequest is sent and any client certificate is
    // ignored. OPTIONAL requests a client certificate but still accepts
    // connections that present none; REQUIRED aborts the handshake when the
    // client does not present a certificate chaining to a trusted CA.
    optional ClientAuthMode client_auth = 51;
    // PEM-encoded trusted CA certificates a client certificate must chain to
    // for OPTIONAL/REQUIRED modes. Ignored when client_auth is NONE. Multiple
    // entries build a single root store; each entry may itself hold a
    // concatenated PEM chain.
    repeated string client_ca_certificates = 52;
    // Optional PEM-encoded certificate revocation lists (CRLs). When present,
    // a presented client certificate is rejected if it (or an intermediate)
    // appears revoked. Ignored when client_auth is NONE.
    repeated string client_ca_crls = 53;
}

// details of an TCP listener
message TcpListenerConfig {
    required SocketAddress address = 1;
    optional SocketAddress public_address = 2;
    required bool expect_proxy = 3 [default = false];
    // client inactive time, in seconds
    required uint32 front_timeout = 4 [default = 60];
    // backend server inactive time, in seconds
    required uint32 back_timeout = 5 [default = 30];
    // time to connect to the backend, in seconds
    required uint32 connect_timeout = 6 [default = 3];
    // wether the listener is actively listening on its socket
    required bool active = 7 [default = false];
    // Time allowed to receive enough bytes of the TLS ClientHello to read the
    // SNI extension, in seconds. Only meaningful when at least one SNI-scoped
    // `RequestTcpFrontend` targets this listener; a listener with only
    // no-SNI frontends never prereads and ignores this value.
    optional uint32 sni_preread_timeout = 8 [default = 5];
    // Maximum number of bytes buffered while prereading the TLS ClientHello
    // looking for the SNI extension. Only meaningful when at least one
    // SNI-scoped `RequestTcpFrontend` targets this listener. Clamped by the
    // global `buffer_size`: a value greater than `buffer_size` is a
    // configuration error at load time (raise `buffer_size` instead).
    optional uint32 sni_preread_max_bytes = 9 [default = 16384];
    // Name of the network interface (e.g. "wg0") the listening socket is
    // bound to with SO_BINDTODEVICE, set before bind(). Linux only: the
    // configuration loader refuses the key on any other platform. Part of the
    // listener identity together with `address`, so two listeners may share an
    // address on different interfaces. Absent = not bound to an interface (the
    // historical behaviour). Not patchable: changing it needs a rebind, so it
    // is absent from the Update*ListenerConfig patches.
    optional string interface = 10;
}

// details of a UDP listener
message UdpListenerConfig {
    required SocketAddress address = 1;
    optional SocketAddress public_address = 2;
    // client flow idle time, in seconds
    required uint32 front_timeout = 3 [default = 30];
    // upstream flow idle time, in seconds
    required uint32 back_timeout = 4 [default = 30];
    // maximum received datagram size, in bytes (capped at buffer_size at runtime)
    required uint32 max_rx_datagram_size = 5 [default = 1500];
    // maximum number of concurrent flows; 0 = auto (~70% soft RLIMIT_NOFILE)
    required uint32 max_flows = 6 [default = 0];
    // wether the listener is actively listening on its socket
    required bool active = 7 [default = false];
    // Name of the network interface (e.g. "wg0") the listening socket is
    // bound to with SO_BINDTODEVICE, set before bind(). Linux only: the
    // configuration loader refuses the key on any other platform. Part of the
    // listener identity together with `address`, so two listeners may share an
    // address on different interfaces. Absent = not bound to an interface (the
    // historical behaviour). Not patchable: changing it needs a rebind, so it
    // is absent from the Update*ListenerConfig patches.
    optional string interface = 8;
}

// HSTS (HTTP Strict Transport Security, RFC 6797) policy attached to
// an HTTPS listener default or per-frontend. The materialised
// `Strict-Transport-Security: max-age=N[; includeSubDomains][; preload]`
// header is injected on every successful HTTPS response (including
// proxy-generated 3xx/401/5xx default answers). Per RFC 6797 §7.2 the
// header MUST NOT be emitted on plaintext-HTTP responses; sozu rejects
// HSTS configured on an HttpListenerConfig at config-load time and gates
// the runtime injection on `context.protocol == Protocol::HTTPS`.
//
// Validation:
// - `enabled = true` with `max_age = None` defaults `max_age` to
//  31536000 seconds (1 year) at config-load.
// - `max_age = 0` is the RFC 6797 §11.4 kill-switch and is allowed
//  silently; `0 < max_age < 86400` warns.
// - `preload = true` with `max_age < 31536000` or
//  `include_subdomains != true` warns (Chrome HSTS preload list
//  prerequisites at https://hstspreload.org/).
// - `preload` is opt-in only; never default-true (RFC 6797 §14.2 —
//  removal from the preload list is slow and partial).
message HstsConfig {
    // Whether HSTS is enabled for this scope. Required whenever the
    // parent message includes an HstsConfig — the partial-update path
    // treats `enabled = false` as the explicit-disable signal.
    optional bool enabled = 1;
    // Strict-Transport-Security `max-age` directive in seconds. When
    // `enabled = true` and this is unset, sozu substitutes 31536000
    // (1 year, HSTS preload list minimum) at config-load.
    optional uint32 max_age = 2;
    // Append `; includeSubDomains` to the rendered header.
    optional bool include_subdomains = 3;
    // Append `; preload` to the rendered header. Opt-in only — see
    // RFC 6797 §14.2 and https://hstspreload.org/.
    optional bool preload = 4;
    // Operator opt-in to override any backend-supplied
    // `Strict-Transport-Security` header with sozu's typed policy.
    //
    // RFC 6797 §6.1 default behaviour is to PRESERVE a backend-emitted
    // STS header when one is already present (sozu's HSTS edit uses
    // `HeaderEditMode::SetIfAbsent`). That keeps the backend's intent
    // intact for upstreams that ship their own HSTS policy.
    //
    // Set this to `true` for the harden-centrally case: backends behind
    // sozu emit a stale or weak HSTS policy (e.g. legacy `max-age=300`)
    // and the operator wants to enforce a stronger policy at the proxy
    // edge unconditionally. The materialiser then uses
    // `HeaderEditMode::Set` instead of `SetIfAbsent`, replacing every
    // backend-supplied STS header with sozu's rendered value.
    //
    // Cite: https://datatracker.ietf.org/doc/html/rfc6797#section-6.1
    optional bool force_replace_backend = 5;
}

// custom HTTP answers, useful for 404, 503 pages
message CustomHttpAnswers {
    // MovedPermanently
    optional string answer_301 = 1;
    // BadRequest
    optional string answer_400 = 2;
    // Unauthorized
    optional string answer_401 = 3;
    // NotFound
    optional string answer_404 = 4;
    // RequestTimeout
    optional string answer_408 = 5;
    // PayloadTooLarge
    optional string answer_413 = 6;
    // MisdirectedRequest (RFC 9110 §15.5.20, TLS SNI ↔ :authority mismatch)
    optional string answer_421 = 11;
    // BadGateway
    optional string answer_502 = 7;
    // ServiceUnavailable
    optional string answer_503 = 8;
    // GatewayTimeout
    optional string answer_504 = 9;
    // InsufficientStorage
    optional string answer_507 = 10;
    // TooManyRequests (per-(cluster, source-IP) connection limit hit)
    optional string answer_429 = 12;
}

message ActivateListener {
    required SocketAddress address = 1;
    required ListenerType proxy = 2;
    required bool from_scm = 3;
    // Interface of the targeted listener, when it was added with one: the
    // listener identity is (address, interface). Absent targets the listener
    // added without an interface.
    optional string interface = 4;
}

message DeactivateListener {
    required SocketAddress address = 1;
    required ListenerType proxy = 2;
    required bool to_scm = 3;
    // Interface of the targeted listener, when it was added with one: the
    // listener identity is (address, interface). Absent targets the listener
    // added without an interface.
    optional string interface = 4;
}

message RemoveListener {
    required SocketAddress address = 1;
    required ListenerType proxy = 2;
    // Interface of the targeted listener, when it was added with one: the
    // listener identity is (address, interface). Absent targets the listener
    // added without an interface.
    optional string interface = 3;
}

// The forwarding header family an HTTP or HTTPS listener adds to every
// forwarded request. `BOTH` is 0 so an absent field, or a listener written
// before the field existed, keeps the historical behaviour.
enum ForwardedHeaders {
    // `X-Forwarded-For`, `X-Forwarded-Proto`, `X-Forwarded-Port` and RFC 7239
    // `Forwarded`, each extended or synthesised.
    FORWARDED_HEADERS_BOTH = 0;
    // Only the `X-Forwarded-*` family; a client `Forwarded` passes through.
    FORWARDED_HEADERS_X_FORWARDED = 1;
    // Only RFC 7239 `Forwarded`; client `X-Forwarded-For`, `-Proto`, `-Port`
    // and `-Host` are removed.
    FORWARDED_HEADERS_RFC7239 = 2;
    // No forwarding header is added; client ones pass through untouched.
    FORWARDED_HEADERS_NONE = 3;
}

enum ListenerType {
    HTTP = 0;
    HTTPS = 1;
    TCP = 2;
    UDP = 3;
}

// All listeners, listed
message ListenersList {
    // listener key (address, plus `%<interface>` when bound) -> http listener config
    map<string, HttpListenerConfig> http_listeners = 1;
    // listener key -> https listener config
    map<string, HttpsListenerConfig> https_listeners = 2;
    // listener key -> tcp listener config
    map<string, TcpListenerConfig> tcp_listeners = 3;
    // listener key -> udp listener config
    map<string, UdpListenerConfig> udp_listeners = 4;
}

// Frontend-level redirect policy. Mirrors HAProxy's
// `http-request redirect|deny|auth` directives.
// FORWARD routes to the backend (default).
// PERMANENT returns 301 with a `Location` header derived from
// `redirect_scheme`, optional `rewrite_*` fields, and `cluster.https_redirect_port`.
// FOUND returns 302 — a temporary redirect (RFC 9110 §15.4.3); user agents may
// rewrite POST to GET on follow.
// PERMANENT_REDIRECT returns 308 — a permanent redirect (RFC 9110 §15.4.9); the
// HTTP method MUST be preserved on follow (no GET-rewrite on POST).
// UNAUTHORIZED returns 401 with `WWW-Authenticate: Basic realm=...`
// using `cluster.www_authenticate`; suitable for blanket deny-by-default
// routes that still want to surface a login prompt.
// SILENT_CLOSE sends no response at all, like nginx's `return 444`: an H1
// frontend connection is closed, an H2 frontend stream is reset with
// RST_STREAM(CANCEL) while the connection's other streams continue. The
// backend is never contacted; the access log records status 444.
enum RedirectPolicy {
    FORWARD = 0;
    PERMANENT = 1;
    UNAUTHORIZED = 2;
    FOUND = 3;
    PERMANENT_REDIRECT = 4;
    SILENT_CLOSE = 5;
}

// Scheme to use when building the `Location` header for a permanent redirect.
// USE_SAME preserves the request scheme (default), USE_HTTP forces `http://`,
// USE_HTTPS forces `https://`.
enum RedirectScheme {
    USE_SAME = 0;
    USE_HTTP = 1;
    USE_HTTPS = 2;
}

// Where a `Header` mutation applies. `BOTH` applies the same edit on the
// request side (before backend connect) and the response side (before kawa
// preparation). Mirrors HAProxy `http-request set-header` /
// `http-response set-header` parity.
enum HeaderPosition {
    // Reserve 0 for the proto-default-encoded shape so a `Header` written
    // by `..Default::default()` (or by an older client) deserialises into
    // an explicit "unset" rather than failing `HeaderPosition::try_from(0)`.
    // The runtime treats this as a hard config error and rejects the
    // header rather than guessing a position.
    HEADER_POSITION_UNSPECIFIED = 0;
    REQUEST = 1;
    RESPONSE = 2;
    BOTH = 3;
}

// A single header mutation applied to a request, response, or both.
//
// An empty `val` deletes the header by name (HAProxy `del-header` parity).
// A non-empty `val` performs a set/replace; a header with the same name is
// overwritten. Header names are matched case-insensitively per RFC 9110 §5.1.
message Header {
    required HeaderPosition position = 1;
    required string key = 2;
    // Empty `val` deletes the header by name (HAProxy `del-header` parity).
    required string val = 3;
}

// How a `HeaderPredicate` tests the request header it names
// (sozu-proxy/sozu#1253).
enum HeaderMatchKind {
    // The header's value equals `value`, byte for byte (case-sensitive).
    HEADER_MATCH_KIND_EXACT = 0;
    // The header's value matches the regular expression `value`, anchored
    // at both ends like a `REGEX` path rule: it must match the WHOLE value.
    HEADER_MATCH_KIND_REGEX = 1;
    // The header is present, whatever its value (including empty).
    // `value` must be absent.
    HEADER_MATCH_KIND_PRESENT = 2;
}

// A routing condition on one request header (sozu-proxy/sozu#1253).
//
// `name` is matched case-insensitively per RFC 9110 §5.1 against the FIRST
// occurrence of the header in the request. It must be an RFC 9110 token and
// can be neither `Host` (the request authority, not a header Sōzu keeps)
// nor `Cookie` (parsed into a jar). A request that does not carry the
// header fails every kind of predicate.
message HeaderPredicate {
    required string name = 1;
    required HeaderMatchKind kind = 2;
    // Required for EXACT and REGEX, forbidden for PRESENT.
    optional string value = 3;
}

// An HTTP or HTTPS frontend, as order to, or received from, Sōzu
message RequestHttpFrontend {
    optional string cluster_id = 1;
    required SocketAddress address = 2;
    required string hostname = 3;
    required PathRule path = 4;
    // Matched case-SENSITIVELY against the request's method token, per RFC
    // 9110 §9.1 (sozu-proxy/sozu#1451). Write it in the exact case the client
    // sends: `GET` does not match a request reading `get`, and `get` does not
    // match a canonical `GET`. Note this is the opposite precedent from its
    // siblings in the same configuration file — `redirect`, `redirect_scheme`
    // and a header `position` are all parsed case-insensitively
    // (`parse_redirect_policy`, `parse_redirect_scheme` in
    // `command/src/config.rs`), and header names match case-insensitively per
    // RFC 9110 §5.1, as documented on `Header` above.
    optional string method = 5;
    required RulePosition position = 6 [default = TREE];
    // custom tags to identify the frontend in the access logs
    map<string, string> tags = 7;
    // Redirect policy for this frontend. Default `FORWARD` (no redirect).
    optional RedirectPolicy redirect = 8 [default = FORWARD];
    // When true, requests routed through this frontend must carry a valid
    // `Authorization: Basic <user:pass>` header whose hash matches one of
    // `cluster.authorized_hashes`. Default: false.
    optional bool required_auth = 9;
    // Scheme to use when emitting a 301 `Location` header. Default `USE_SAME`
    // (preserve the request scheme).
    optional RedirectScheme redirect_scheme = 10 [default = USE_SAME];
    // Optional template applied when emitting a permanent redirect. Supports
    // `%REDIRECT_LOCATION` and the variables documented in `doc/configure.md`.
    optional string redirect_template = 11;
    // Rewrite host template. Supports `$HOST[n]` / `$PATH[n]` placeholders
    // populated from regex captures collected during routing. When set, both
    // the backend authority/path and the wire request line are rewritten.
    optional string rewrite_host = 12;
    // Rewrite path template. Same grammar as `rewrite_host`.
    optional string rewrite_path = 13;
    // Optional literal port override on the rewritten URL.
    optional uint32 rewrite_port = 14;
    // Header mutations applied to requests and/or responses passing through
    // this frontend. See `Header` for delete semantics.
    repeated Header headers = 15;
    // Per-frontend HSTS (RFC 6797) override. When `Some`, this entire
    // policy replaces the listener-default `HttpsListenerConfig.hsts`
    // for matched requests; when absent, the listener default applies.
    // Honours RFC 6797 §6.1 (single Strict-Transport-Security header on
    // the response) and §8.1 (HSTS host scope tied to the receiving
    // host). On HTTP-only frontends the value is rejected at config-load
    // (RFC 6797 §7.2). The §11.4 `max-age=0` kill-switch is honoured
    // verbatim so an operator can shadow a listener-wide HSTS for one
    // hostname.
    optional HstsConfig hsts = 16;
    // Header predicates the request must ALL satisfy for this frontend to
    // match (sozu-proxy/sozu#1253). Empty (the default) matches every
    // request, as before. Part of the frontend's identity: two frontends
    // that differ only by their predicates coexist, and a removal must name
    // the same predicates. For one hostname, a rule whose predicates all
    // hold outranks every rule without predicates; see `doc/configure.md`.
    repeated HeaderPredicate header_predicates = 17;
}

message RequestTcpFrontend {
    required string cluster_id = 1;
    // the socket address on which to listen for incoming traffic
    required SocketAddress address = 2;
    // custom tags to identify the frontend in the access logs
    map<string, string> tags = 3;
    // SNI hostname to match against the TLS ClientHello, read via preread on
    // the listener before any bytes are relayed to a backend. Either an
    // exact hostname (e.g. "example.com") or a single leading `*.` wildcard
    // label (e.g. "*.example.com"); no other wildcard shape is accepted.
    // Absent means this frontend matches regardless of SNI (a raw-TCP
    // fallback), and a listener cannot mix SNI and no-SNI frontends.
    optional string sni = 4;
    // ALPN protocol names this frontend matches, read from the TLS
    // ClientHello during the same preread as `sni`. Empty means this
    // frontend is the catch-all for its `sni` on this listener; at most one
    // frontend per `(address, sni)` may leave this empty, and no two
    // frontends on the same `(address, sni)` may share a protocol name.
    repeated string alpn = 5;
}

message RequestUdpFrontend {
    required string cluster_id = 1;
    // the socket address on which to listen for incoming datagrams
    required SocketAddress address = 2;
    // custom tags to identify the frontend in the access logs
    map<string, string> tags = 3;
}

// list the frontends, filtered by protocol, domain and/or cluster id
message FrontendFilters {
    required bool http = 1;
    required bool https = 2;
    required bool tcp = 3;
    optional string domain = 4;
    // only list frontends routing to this cluster id. A frontend with no
    // cluster (a `Deny` rule) never matches.
    optional string cluster_id = 5;
}

// A filter for the path of incoming requests
message PathRule {
    // The kind of filter used for path rules
    required PathRuleKind kind = 1;
    // the value of the given prefix, regex, equal or path-only regex pathrule
    required string value = 2;
}

// The kind of filter used for path rules
enum PathRuleKind {
    // filters paths that start with a pattern, typically "/api"
    PREFIX = 0;
    // filters paths that match a regex pattern
    REGEX = 1;
    // filters paths that exactly match a pattern, no more, no less
    EQUALS = 2;
    // filters paths that match a regex pattern, anchored at both ends like
    // `REGEX`, but tested against the path ALONE: the request-target up to
    // its first `?` (sozu-proxy/sozu#1909, Gateway API `RegularExpression`
    // path match). `REGEX` keeps matching the path together with its query
    // string. Its `$PATH[n]` rewrite captures come from that path-only
    // match, and the request's original `?query` is appended to a rewritten
    // path that carries no `?` of its own.
    REGEX_PATH = 3;
}

// TODO: find a proper definition for this
enum RulePosition {
    PRE = 0;
    POST = 1;
    TREE = 2;
}

// Add a new TLS certificate to an HTTPs listener
message AddCertificate {
    required SocketAddress address = 1;
    required CertificateAndKey certificate = 2;
    // A unix timestamp. Overrides certificate expiration.
    optional int64 expired_at = 3;
}

message RemoveCertificate {
    required SocketAddress address = 1;
    // a hex-encoded TLS fingerprint to identify the certificate to remove
    required string fingerprint = 2;
}

message ReplaceCertificate {
    required SocketAddress address = 1;
    required CertificateAndKey new_certificate = 2;
    // a hex-encoded TLS fingerprint to identify the old certificate
    required string old_fingerprint = 3;
    // A unix timestamp. Overrides certificate expiration.
    optional int64 new_expired_at = 4;
}

message CertificateAndKey {
    required string certificate = 1;
    repeated string certificate_chain = 2;
    required string key = 3;
    repeated TlsVersion versions = 4;
    // a list of domain names. Override certificate names
    // if empty, the names of the certificate will be used
    repeated string names = 5;
}

// Should be either a domain name or a fingerprint.
// These filter do not compound, use either one but not both.
// If none of them is specified, all certificates will be returned.
message QueryCertificatesFilters {
    // a host name. Answers with the certificate Sōzu would present for that
    // host, resolved through the same SNI trie a handshake uses, so a wildcard
    // certificate answers for the hosts it serves. This is NOT an exact-SAN
    // filter, and it resolves to at most one certificate per HTTPS listener.
    // See sozu#1383 and doc/configure_cli.md.
    optional string domain = 1;
    // a hex-encoded fingerprint of the TLS certificate to find
    optional string fingerprint = 2;
}

// domain name and fingerprint of a certificate
message CertificateSummary {
    required string domain = 1;
    // a hex-encoded TLS fingerprint
    required string fingerprint = 2;
}

// Used by workers to reply to some certificate queries
message ListOfCertificatesByAddress {
    repeated CertificatesByAddress certificates = 1;
}

// Summaries of certificates for a given address
message CertificatesByAddress {
    required SocketAddress address = 1;
    repeated CertificateSummary certificate_summaries = 2;
}

// to reply to several certificate queries
message CertificatesWithFingerprints {
    // a map of fingerprint -> certificate_and_key
    map<string, CertificateAndKey> certs = 1;
}

enum TlsVersion {
    SSL_V2 = 0;
    SSL_V3 = 1;
    TLS_V1_0 = 2;
    TLS_V1_1 = 3;
    TLS_V1_2 = 4;
    TLS_V1_3 = 5;
}

// Mutual TLS client-certificate authentication policy for an HTTPS listener.
// NONE is field 0 so an absent `client_auth` decodes to the current
// no-client-auth behavior, keeping legacy state files byte-compatible.
enum ClientAuthMode {
    // No CertificateRequest; client certificates are neither requested nor
    // verified. The historical default.
    CLIENT_AUTH_NONE = 0;
    // Request a client certificate but accept connections that present none.
    // Presented certificates must still chain to a trusted CA.
    CLIENT_AUTH_OPTIONAL = 1;
    // Require a client certificate chaining to a trusted CA; abort the
    // handshake otherwise.
    CLIENT_AUTH_REQUIRED = 2;
}

// How a UDP flow is keyed for backend affinity. SOURCE_IP keys on the
// client source IP only (all ports from one client pin to one backend);
// SOURCE_IP_PORT keys on the full 2-tuple (per-socket affinity). It only
// selects the backend: a flow is always one client source IP and port.
enum UdpAffinityKey {
    SOURCE_IP = 0;
    SOURCE_IP_PORT = 1;
}

// UDP backend health probe mode. HEALTH_OFF disables health checking;
// TCP_PROBE opens a non-blocking TCP connection to a companion port;
// UDP_PROBE sends an application datagram and waits for any reply.
enum UdpHealthMode {
    HEALTH_OFF = 0;
    TCP_PROBE = 1;
    UDP_PROBE = 2;
}

// Optional health-check configuration for a UDP cluster's backends.
message UdpHealthConfig {
    // probe mode; defaults to TCP_PROBE when a udp block is present
    optional UdpHealthMode mode = 1;
    // companion TCP probe port; unset = the backend data port
    optional uint32 tcp_port = 2;
    // consecutive successes before a backend is marked up
    optional uint32 rise = 3 [default = 2];
    // consecutive failures before a backend is marked down
    optional uint32 fall = 4 [default = 3];
    // when all backends are down, still forward (don't drop the flow)
    optional bool fail_open = 5 [default = true];
    // payload sent for a UDP_PROBE
    optional bytes udp_probe_payload = 6;
    // delay between probes, in seconds
    optional uint32 probe_interval_seconds = 7 [default = 5];
    // per-probe response timeout, in seconds
    optional uint32 probe_timeout_seconds = 8 [default = 2];
}

// UDP-specific cluster knobs. Attached to a `Cluster` via the `udp` field.
message UdpClusterConfig {
    // flow affinity key; defaults to SOURCE_IP
    optional UdpAffinityKey affinity_key = 1;
    // expected replies per flow; 0 = unlimited
    optional uint32 responses = 2;
    // max client datagrams per flow; 0 = unlimited
    optional uint32 requests = 3;
    // send a PROXY protocol v2 header to the backend
    optional bool send_proxy_protocol = 4;
    // prepend PPv2 to every datagram; false = first-datagram only
    optional bool proxy_protocol_every_datagram = 5;
    // optional backend health-check configuration
    optional UdpHealthConfig health = 6;
}

// A cluster is what binds a frontend to backends with routing rules
message Cluster {
    required string cluster_id = 1;
    // wether a connection from a client shall be always redirected to the same backend
    required bool sticky_session = 2;
    required bool https_redirect = 3;
    optional ProxyProtocolConfig proxy_protocol = 4;
    required LoadBalancingAlgorithms load_balancing = 5 [default = ROUND_ROBIN];
    optional string answer_503 = 6;
    optional LoadMetric load_metric = 7;
    // Backend-capability hint: set to true when THE BACKEND speaks HTTP/2 (h2c or h2+TLS).
    // This does NOT gate H2 acceptance at the frontend — frontend H2 is negotiated via
    // TLS ALPN independently of per-cluster configuration (see alpn_protocols on the listener).
    optional bool http2 = 8;
    // Per-cluster HTTP answer template overrides keyed by HTTP status code
    // (e.g. "503"). Override a listener-level answer for this cluster only.
    map<string, string> answers = 9;
    // Optional explicit port to use when building the `Location` header for
    // an `https_redirect`. When unset, the listener's effective HTTPS port is
    // used. Lets operators front a non-standard HTTPS port (e.g. 8443) on
    // the redirect target while keeping `https_redirect = true`.
    optional uint32 https_redirect_port = 10;
    // Authorized credentials for HTTP basic authentication. Each entry is
    // formatted as `username:hex(sha256(password))` (lower-case hex). The
    // mux compares the supplied `Authorization: Basic` header in
    // constant-time against the full list. Empty list disables auth even
    // when a frontend sets `required_auth = true` — those requests are
    // rejected with a 401.
    repeated string authorized_hashes = 11;
    // Realm string emitted in `WWW-Authenticate: Basic realm="…"` when an
    // unauthenticated request is rejected. Treated as an opaque value (no
    // template substitution). Defaults to a generic realm if unset.
    optional string www_authenticate = 12;
    // Per-cluster override for the global `max_connections_per_ip`.
    // `None` (field absent) inherits the global default. `Some(0)` is
    // explicit "unlimited for this cluster". `Some(n > 0)` overrides with
    // the cluster-specific limit. Counts are kept per
    // `(cluster_id, source_ip)` pair, so two clusters never share a
    // counter even from the same IP. On a UDP cluster it limits concurrent
    // flows per datagram source address, per listener; UDP never inherits
    // the global default.
    optional uint64 max_connections_per_ip = 13;
    // Per-cluster override for the global `retry_after` header value
    // (seconds, HTTP 429 only). `None` inherits the global default.
    // `Some(0)` omits the header.
    optional uint32 retry_after = 14;
    // Optional HTTP health check configuration for backends in this cluster.
    // Tag 8 in this message is the `http2` backend-capability hint and
    // tags 9-14 cover answers/redirect/auth/limits, so health-check
    // configuration occupies tag 15.
    optional HealthCheckConfig health_check = 15;
    // Optional UDP-specific cluster configuration. Present only for clusters
    // that front UDP backends; absent for HTTP/HTTPS/TCP clusters.
    optional UdpClusterConfig udp = 16;
    // Per-cluster override for the global `max_connections_per_subnet`.
    // Same three-state semantics as `max_connections_per_ip` above:
    // `None` (field absent) inherits the global default, `Some(0)` is
    // explicit "unlimited for this cluster", `Some(n > 0)` overrides.
    // This is an INDEPENDENT counter from tag 13, not a replacement:
    // a connection must satisfy BOTH the per-IP and the per-subnet cap
    // to be admitted, which is what lets an operator express "10 per IP
    // AND 100 per /64". Counts are kept per `(cluster_id, masked_ip)`,
    // so two clusters never share a counter. The mask itself comes from
    // the boot-time `ServerConfig.subnet_ipv4_prefix` /
    // `subnet_ipv6_prefix` and is NOT overridable per cluster. A UDP
    // listener counts flows, as for tag 13.
    optional uint64 max_connections_per_subnet = 17;
    // Client affinity key of an HTTP/HTTPS cluster whose `load_balancing` is
    // HRW or MAGLEV: the value of this request header, matched
    // case-insensitively, first occurrence. A request that does not carry it
    // is keyed on its source IP (the PROXY-protocol source when the listener
    // expects one). Ignored by every other policy and by TCP clusters, which
    // always key on the source IP: the main state refuses a cluster that
    // names a key and serves a TCP frontend. `Host` and `Cookie` are refused
    // (never kept as headers). Mutually exclusive with `affinity_cookie`. The
    // key is read only when a new backend connection is dialled; a request
    // reusing one follows it.
    optional string affinity_header = 18;
    // Same as `affinity_header`, keyed on the raw value of this request
    // cookie, matched case-sensitively. Mutually exclusive with
    // `affinity_header`.
    optional string affinity_cookie = 19;
    // Shuffle sharding (sozu-proxy/sozu#524): restrict each client's
    // selection to a shard of k backends, the top k of the rendezvous (HRW)
    // ranking of its affinity key over the cluster's primary backends, where
    // k = max(2, ceil(shard_percent * N / 100)), capped at N. Off when unset.
    // 1..=100. The cluster's `load_balancing` policy picks inside the shard.
    optional uint32 shard_percent = 20;
    // Sharding applies only while the cluster has at least this many primary
    // backends; below it the cluster selects over all of them. At least 2;
    // defaults to 8. Requires `shard_percent`.
    optional uint32 shard_min_backends = 21;
    // What happens when no backend of a client's shard can take a
    // connection. Requires `shard_percent`.
    optional ShardMode shard_mode = 22;
    // Per-cluster override for the global `max_connection_attempts`: how
    // many backend connections a request routed to this cluster may try,
    // the first included, before it is answered `503` (HTTP) or closed
    // (TCP). Every failed connection counts: refused, timed out on
    // `connect_timeout`, or reporting a socket error. Between 1 and 255.
    // `None` (field absent) inherits the global value.
    optional uint32 max_connection_attempts = 23;
}

// See `Cluster.shard_mode`.
enum ShardMode {
    // Spill over to the rest of the cluster (counted in
    // `backend.shard.spillover`).
    FALLBACK = 0;
    // Refuse: no backend is selected, HTTP answers 503 and TCP closes
    // (counted in `backend.shard.exhausted`).
    STRICT = 1;
}

// How a health-check probe decides that a backend is healthy.
enum HealthCheckMode {
    // Send an HTTP `GET <uri>` and judge the response status against
    // `accepted_statuses` (or `expected_status` when that list is empty).
    HEALTH_CHECK_MODE_HTTP = 0;
    // Healthy iff a TCP connection to the backend is established within
    // `timeout`. No byte is sent; the connection is closed as soon as it
    // is established. `uri` is ignored; a non-zero `expected_status` or a
    // non-empty `accepted_statuses` is refused. A peer that predates this
    // field ignores it and runs the HTTP probe instead.
    HEALTH_CHECK_MODE_TCP = 1;
}

// An inclusive range of HTTP status codes, `start <= end`, both within
// 100..=599 (RFC 9110 §15). A single code is `start == end`.
message HttpStatusRange {
    required uint32 start = 1;
    required uint32 end = 2;
}

// Public metadata of one custom request header field of a health-check probe:
// its name and the keyed fingerprint of its value. The value itself is never
// part of the configuration, the state, a query or a log: it travels once in a
// `HealthCheckHeaderValue` and lives in memory only.
message HealthCheckHeader {
    required string name = 1;
    // Value 2 carried the clear value in an unreleased draft. Never reuse it.
    reserved 2;
    // `sozu-hc-hmac-sha256:v1:<epoch>:<tag>` under the main process key; empty
    // in an operator order, which the main process fills in.
    required string fingerprint = 3;
}

// Protected ingress/IPC carrier of one health-check header value: the clear
// bytes travel in `SetProtectedHealthCheck` from the operator to the main
// process, and are moved out into a memory-only secret at once. It is never
// part of the state, a query response or a generic worker order, and neither
// its `Debug` nor its serde output ever shows the value.
message HealthCheckHeaderValue {
    required string name = 1;
    required bytes value = 2;
}

message HealthCheckConfig {
    // Request target of the HTTP probe; must start with `/`. Ignored in
    // `TCP` mode. Kept `required` on the wire for compatibility with
    // peers that predate `mode`.
    required string uri = 1;
    required uint32 interval = 2 [default = 10];
    required uint32 timeout = 3 [default = 5];
    required uint32 healthy_threshold = 4 [default = 3];
    required uint32 unhealthy_threshold = 5 [default = 3];
    // `0` accepts any 2xx, any other value exactly that status. Applies
    // only while `accepted_statuses` is empty; setting both is rejected.
    required uint32 expected_status = 6 [default = 0];
    // Probe mode. Absent decodes as `HTTP`, the behaviour of peers that
    // predate this field.
    required HealthCheckMode mode = 7 [default = HEALTH_CHECK_MODE_HTTP];
    // HTTP mode: the response statuses that count as healthy. When
    // non-empty it replaces `expected_status`, which must then be `0`.
    repeated HttpStatusRange accepted_statuses = 8;
    // Port the probe dials, in `1..=65535`; unset = the backend's data
    // port. When set, both HTTP and TCP probes connect to the backend's IP
    // address with this port, and the HTTP probe's `Host` names that
    // address. A peer that predates this field ignores it and probes the
    // data port.
    optional uint32 port = 9;
    // Extra request header fields of the HTTP probe (typically
    // `Authorization`), in the order they are sent. Refused in `TCP` mode, with
    // more than 32 entries, with a duplicate name (compared case-insensitively),
    // with a name that is not an RFC 9110 `token` or that begins with `:` or is
    // one of `host`, `connection`, `keep-alive`, `proxy-connection`,
    // `transfer-encoding`, `content-length`, `te`, `trailer`, `upgrade`,
    // `expect`, with a value holding a control byte other than HTAB or beginning or ending
    // with SP or HTAB (RFC 9113 section 8.2.1; protobuf
    // and TOML keep exact bytes and are refused), or when
    // the sum of `name + value + 4` bytes exceeds 8192 or the HTTP/2 probe's
    // HPACK block (four pseudo-headers included) may exceed 16384 bytes.
    // Only names and fingerprints live here; the values travel in
    // `SetProtectedHealthCheck`. A configuration that names headers whose
    // values the process does not hold (restored from a saved state, or set
    // through `SetHealthCheck`) sends no probe until they are provided again.
    // A peer that predates this field ignores it, probes without the headers,
    // and drops them when it re-emits the state.
    repeated HealthCheckHeader headers = 10;
    // The probe wire format is derived from `Cluster.http2` (the same
    // backend-capability hint the mux router reads). When the cluster
    // sets `http2 = true`, the probe sends the HTTP/2 connection
    // preface + empty SETTINGS + HEADERS frame on stream 1; otherwise
    // HTTP/1.1. There is no per-`HealthCheckConfig` h2c flag — the
    // probe wire follows the data-plane wire so an h2c-only backend
    // is never probed with HTTP/1.1 (and vice versa).
}

enum LoadBalancingAlgorithms {
    ROUND_ROBIN = 0;
    RANDOM = 1;
    LEAST_LOADED = 2;
    POWER_OF_TWO = 3;
    // Highest-Random-Weight / rendezvous hashing — client-affine backend
    // selection. Maps a client key (on UDP the source IP, or source IP and
    // port per `UdpAffinityKey`; the source IP, or the
    // cluster's `affinity_header` / `affinity_cookie`, on HTTP, HTTPS and
    // TCP) to a backend that survives minimal disruption on backend
    // add/remove.
    HRW = 4;
    // Maglev consistent hashing — precomputed lookup table for even, stable
    // backend distribution across the same client keyspace as HRW.
    MAGLEV = 5;
}

enum ProxyProtocolConfig {
    EXPECT_HEADER = 0;
    SEND_HEADER = 1;
    RELAY_HEADER = 2;
}

// how sozu measures which backend is less loaded
enum LoadMetric {
    // number of TCP connections
    CONNECTIONS = 0;
    // number of active HTTP requests
    REQUESTS = 1;
    // time to connect to the backend, weighted by the number of active connections (peak EWMA)
    CONNECTION_TIME = 2;
}

// add a backend to the cluster `cluster_id` names, which must exist: the
// backend belongs to it and is removed with it
message AddBackend {
    required string cluster_id = 1;
    required string backend_id = 2;
    // the socket address of the backend
    required SocketAddress address = 3;
    optional string sticky_id = 4;
    optional LoadBalancingParams load_balancing_parameters = 5;
    optional bool backup = 6;
    // when set, sozu dials this UNIX domain stream socket instead of `address`:
    // a filesystem path, or `@name` for a Linux abstract-namespace socket.
    // `address` stays the backend's identity within its cluster (removal,
    // retry exclusion, sticky and hash routing, events) and is never dialed,
    // so it must be unique among the cluster's backends.
    // Applies to HTTP, HTTPS and TCP clusters. A UDP cluster refuses it, in
    // the configuration file and in the main process's state alike: datagrams
    // cannot travel over a stream socket.
    // A backend with `unix_path` is carried by `Request.add_unix_backend`,
    // never by `Request.add_backend` (see there).
    optional string unix_path = 7;
}

// remove an existing backend
message RemoveBackend {
    required string cluster_id = 1;
    required string backend_id = 2;
    // the socket address of the backend
    required SocketAddress address = 3 ;
}

message LoadBalancingParams {
    required int32 weight = 1;
}

message QueryClusterByDomain {
    required string hostname = 1;
    optional string path = 2;
}

// Options when querying metrics
message QueryMetricsOptions {
    // query a list of available metrics
    required bool list = 1;
    // query metrics for these clusters
    repeated string cluster_ids = 2;
    // query metrics for these backends
    repeated string backend_ids = 3;
    // query only these metrics
    repeated string metric_names = 4;
    // query only worker and main process metrics (no cluster metrics)
    required bool no_clusters = 5;
    // display metrics of each worker, without flattening (takes more space)
    required bool workers = 6;
}

// options to configure metrics collection
enum MetricsConfiguration {
    // enable metrics collection
    ENABLED = 0;
    // disable metrics collection
    DISABLED = 1;
    // wipe the metrics memory
    CLEAR = 2;
}

// Response to a request
message Response {
    // wether the request was a success, a failure, or is processing
    required ResponseStatus status = 1 [default = FAILURE];
    // a success or error message
    required string message = 2;
    // response data, if any
    optional ResponseContent content = 3;
}


// content of a response
message ResponseContent {
    oneof content_type {
        // a list of workers, with ids, pids, statuses
        WorkerInfos workers = 1;
        // aggregated metrics of main process and workers
        AggregatedMetrics metrics = 2;
        // a collection of worker responses to the same request
        WorkerResponses worker_responses = 3;
        // a proxy event
        Event event = 4;
        // a filtered list of frontend
        ListedFrontends frontend_list = 5;
        // all listeners
        ListenersList listeners_list = 6;
        // contains proxy & cluster metrics
        WorkerMetrics worker_metrics = 7;
        // Lists of metrics that are available
        AvailableMetrics available_metrics = 8;
        // a list of cluster informations
        ClusterInformations clusters = 9;
        // collection of hashes of cluster information, 
        ClusterHashes cluster_hashes = 10;
        // a list of certificates summaries, grouped by socket address
        ListOfCertificatesByAddress certificates_by_address = 11;
        // a map of complete certificates using fingerprints as key
        CertificatesWithFingerprints certificates_with_fingerprints = 12;
        // a census of the types of requests received since startup,
        RequestCounts request_counts = 13;
        // current global per-(cluster, source-IP) connection limit
        MaxConnectionsPerIpLimit max_connections_per_ip_limit = 14;
        // health check configurations by cluster (renumbered from PR #1191's
        // original `14` since post-1209 occupies that tag).
        HealthChecksList health_checks_list = 15;
        // Aggregated outcome of a `SetMetricDetail` fan-out: per-worker
        // configured/effective/previous_effective levels plus the list of
        // workers that could not decode the verb (mixed-version safety).
        MetricDetailStatus metric_detail_status = 16;
        // Per-worker status payload returned by a single worker in
        // response to `SetMetricDetail`. The master collects these
        // across the fan-out and assembles them into
        // `MetricDetailStatus.workers[<worker_id>]`. Carries the
        // worker's own `(configured, effective, previous_effective,
        // active_lease_count)` quartet — distinct from the master-side
        // view rendered in `MetricDetailStatus.{configured,effective,
        // previous_effective}` because each worker holds its own
        // `Aggregator` with an independent lease table.
        WorkerMetricDetailStatus worker_metric_detail_status = 17;
        // current global per-(cluster, source-SUBNET) connection limit,
        // together with the two prefix lengths that define "subnet".
        // The prefixes travel with the limit because they are boot-time
        // only: without them in the reply an operator could read the
        // live cap but had no way to learn what it is a cap ON.
        MaxConnectionsPerSubnetLimit max_connections_per_subnet_limit = 18;
        // one worker's outcome of `Request.close_sessions`
        ClosedSessions closed_sessions = 19;
        // a worker's positive answer to a protected health check order
        ProtectedHealthCheckReply protected_health_check_reply = 20;
    }
}

// The sessions one worker matched for `Request.close_sessions`, counted at
// the moment it answered.
message ClosedSessions {
    // sessions closed right away: idle ones, TCP and WebSocket ones
    required uint64 closed = 1;
    // sessions finishing their in-flight HTTP work before they close: an
    // HTTP/1.1 response gets `Connection: close` while its backend headers
    // are not parsed yet, an HTTP/2 session receives a GOAWAY and is closed
    // by its graceful-shutdown deadline when that is nonzero (`0` drains
    // without bound)
    required uint64 draining = 2;
}

message HealthChecksList {
    map<string, HealthCheckConfig> map = 1;
}

// a map of worker_id -> ResponseContent
message WorkerResponses {
    map<string, ResponseContent> map = 1;
}

// lists of frontends present in the state
message ListedFrontends {
    repeated RequestHttpFrontend http_frontends = 1;
    repeated RequestHttpFrontend https_frontends = 2;
    repeated RequestTcpFrontend tcp_frontends = 3;
    repeated RequestUdpFrontend udp_frontends = 4;
}

message ClusterInformations {
    repeated ClusterInformation vec = 1;
}

// Information about a given cluster
// Contains types usually used in requests, because they are readily available in protobuf
message ClusterInformation {
    optional Cluster configuration = 1;
    repeated RequestHttpFrontend http_frontends = 2;
    repeated RequestHttpFrontend https_frontends = 3;
    repeated RequestTcpFrontend tcp_frontends = 4;
    repeated AddBackend backends = 5;
    repeated RequestUdpFrontend udp_frontends = 6;
}

// an event produced by a worker to notify about backends status
message Event {
    required EventKind kind = 1;
    optional string cluster_id = 2;
    optional string backend_id = 3;
    optional SocketAddress address = 4;
    // Set only when `kind == METRIC_DETAIL_CHANGED` and the worker is
    // surfacing a worker-local lease transition (apply, clear, or polled
    // expiry). Operator-initiated transitions are audited at the master
    // dispatch site and DO emit this event for the SubscribeEvents bus,
    // but the audit-log line for those is generated master-side and
    // duplicates of `metric_detail` should be ignored by SOC tooling.
    // See the `EventKind::METRIC_DETAIL_CHANGED` doc and the
    // `MetricDetailTransition` message below for the trust model.
    optional MetricDetailTransition metric_detail = 5;
}

// Worker-emitted cardinality-lease transition. Populates the
// `Event.metric_detail` field when a worker's `effective` level changes
// because a lease was applied, renewed, expired (TTL janitor), or
// cleared. The master folds these into the audit log alongside the
// operator-initiated transitions emitted from
// `bin/src/command/requests.rs::worker_request`, closing the gap where
// worker-local expiries previously left no audit trail.
message MetricDetailTransition {
    // The worker's effective cardinality level BEFORE the transition.
    required MetricDetail previous_effective = 1;
    // The worker's effective cardinality level AFTER the transition.
    required MetricDetail effective = 2;
    // What caused the transition. Stable strings: "lease_tick_expired"
    // (janitor retired one or more leases), "lease_apply" (worker arm
    // applied a lease), "lease_clear" (worker arm cleared a lease).
    // Operator-initiated apply/clear emit master-side; the worker still
    // emits this Event so the SubscribeEvents bus has one canonical
    // signal for cardinality changes regardless of origin.
    required string transition_kind = 3;
    // Operator-supplied lease key (`SetMetricDetail.client_id`) when the
    // transition was triggered by an explicit apply/clear. Empty for
    // janitor expiries, which clear many leases at once.
    optional string client_id = 4;
}

enum EventKind {
    BACKEND_DOWN = 0;
    BACKEND_UP = 1;
    NO_AVAILABLE_BACKENDS = 2;
    REMOVED_BACKEND_HAS_NO_CONNECTIONS = 3;
    // Control-plane mutation events (audit trail).
    // Emitted by the main process to clients subscribed via SubscribeEvents.
    // The Event.cluster_id / backend_id / address fields are populated when
    // they are meaningful for the verb (e.g. address for listener verbs,
    // cluster_id for cluster/frontend verbs). Backend events keep their
    // historical numeric tags 0..3.
    CLUSTER_ADDED = 4;
    CLUSTER_REMOVED = 5;
    FRONTEND_ADDED = 6;
    FRONTEND_REMOVED = 7;
    CERTIFICATE_ADDED = 8;
    CERTIFICATE_REMOVED = 9;
    CERTIFICATE_REPLACED = 10;
    LISTENER_ACTIVATED = 11;
    LISTENER_DEACTIVATED = 12;
    CONFIGURATION_RELOADED = 13;
    WORKER_KILLED = 14;
    WORKER_RELAUNCHED = 15;
    LOGGING_LEVEL_CHANGED = 16;
    METRICS_CONFIGURED = 17;
    // A listener's configuration was patched in place via UpdateHttp/Https/TcpListenerConfig
    LISTENER_UPDATED = 18;
    // A saved state file was loaded (batch state replay via LoadState request).
    // Emitted once at task completion; `target=file:<path>` and `result=ok|err`
    // with the ok/err request counts encoded in `target`.
    STATE_LOADED = 19;
    // A snapshot of the current state was written to disk via SaveState.
    STATE_SAVED = 20;
    // A new listener was added to the config (AddHttp/Https/TcpListener).
    // Distinct from LISTENER_ACTIVATED (binds the socket) — ADDED just
    // creates the listener's in-memory definition.
    LISTENER_ADDED = 21;
    // A listener's in-memory definition was removed (RemoveListener).
    // Distinct from LISTENER_DEACTIVATED (unbinds the socket) — REMOVED
    // drops the whole listener from the state.
    LISTENER_REMOVED = 22;
    // A stop request was accepted (SoftStop / HardStop).
    // `target=stop:soft` or `stop:hard` — distinguishes drain-then-stop from
    // immediate-abort on the audit trail.
    SOZU_STOP_REQUESTED = 23;
    // The main process started a re-exec upgrade (UpgradeMain).
    MAIN_UPGRADED = 24;
    // A worker was re-launched (UpgradeWorker).
    WORKER_UPGRADED = 25;
    // A client subscribed to the SubscribeEvents bus — privileged because
    // subscribers observe every control-plane mutation.
    EVENTS_SUBSCRIBED = 26;
    // Backend health-check transitioned to healthy after consecutive successes.
    // Tags 0..3 are the historical backend-state events; 4..26 carry the
    // control-plane mutation events (cluster, frontend, certificate,
    // listener, worker, configuration, metrics, state, stop, upgrade,
    // events). Backend health-check transitions therefore start at 27.
    HEALTH_CHECK_HEALTHY = 27;
    // Backend health-check transitioned to unhealthy after consecutive failures.
    HEALTH_CHECK_UNHEALTHY = 28;
    // Cluster transitioned from "all backends down" back to "at least one
    // backend available". Pairs with `NoAvailableBackends` (tag 2) so
    // dashboards can plot per-cluster recovery.
    CLUSTER_RECOVERED = 29;
    // The worker's effective `MetricDetail` changed because a runtime
    // lease was applied, renewed, expired, or cleared. Pairs with
    // `MetricsConfigured` (tag 17) but distinct: that one fires for
    // `MetricsConfiguration` (Enabled/Disabled/Clear), this one fires
    // for cardinality changes.
    //
    // Emitter scope: operator-initiated transitions emit
    // `METRIC_DETAIL_CHANGED` via the master-side audit log (see
    // `bin/src/command/requests.rs` around the `SetMetricDetail`
    // success path). Worker-local transitions — the polled janitor
    // expiring a lease, or a worker-local clear/apply after a master
    // fan-out — are not yet surfaced because the worker has no direct
    // IPC path to the master's audit sink; follow-up tracked separately.
    METRIC_DETAIL_CHANGED = 30;
}

message ClusterHashes {
    // cluster id -> hash of cluster information
    map<string, uint64> map = 1;
}

enum ResponseStatus {
    OK = 0;
    PROCESSING = 1;
    FAILURE = 2;
}

// A list of worker infos
message WorkerInfos {
    repeated WorkerInfo vec = 1;
}

// Information about a worker with id, pid, runstate
message WorkerInfo {
    required uint32 id = 1;
    required int32 pid = 2;
    required RunState run_state = 3;
    reserved 4;
    reserved "proto_version";
}

// Runstate of a worker
enum RunState {
    RUNNING = 0;
    STOPPING = 1;
    STOPPED = 2;
    NOT_ANSWERING = 3;
}

// lists of available metrics in a worker, or in the main process (in which case there are no cluster metrics)
message AvailableMetrics {
    repeated string proxy_metrics = 1;
    repeated string cluster_metrics = 2;
}

// Aggregated metrics of main process & workers
message AggregatedMetrics {
    // metrics about the main process.
    // metric_name -> metric_value
    map<string, FilteredMetrics> main = 1;
    // details of worker metrics, with clusters and backends.
    // worker_id -> worker_metrics
    map<string, WorkerMetrics> workers = 2;
    // if present, contains metrics of clusters and their backends, merged across all workers.
    // cluster_id -> cluster_metrics
    map<string, ClusterMetrics> clusters = 3;
    // if present, proxying metrics, merged accross all workers.
    // metric_name -> metric_value
    map<string, FilteredMetrics> proxying = 4;
}

// All metrics of a worker: proxy and clusters
// Populated by Options so partial results can be sent
message WorkerMetrics {
   // Metrics of the worker process, key -> value
    map<string, FilteredMetrics> proxy = 1;
    // cluster_id -> cluster_metrics
    map<string, ClusterMetrics> clusters = 2;
}

// the metrics of a given cluster, with several backends
message ClusterMetrics {
    // metric name -> metric value
    map<string, FilteredMetrics> cluster = 1;
    // list of backends with their metrics
    repeated BackendMetrics backends = 2;
}

message BackendMetrics {
    required string backend_id = 1;
    map<string, FilteredMetrics> metrics = 2;
}

// A metric, in a "filtered" format, which means: sendable to outside programs.
message FilteredMetrics {
    oneof inner {
        // increases or decrease depending on the state
        uint64 gauge = 1;
        // increases only
        int64 count = 2;
        // milliseconds
        uint64 time = 3;
        Percentiles percentiles = 4;
        FilteredTimeSerie time_serie = 5;
        FilteredHistogram histogram = 6;
    }
}

message FilteredTimeSerie {
    required uint32 last_second = 1;
    repeated uint32 last_minute = 2;
    repeated uint32 last_hour = 3;
}

message Percentiles {
    required uint64 samples = 1;
    required uint64 p_50 = 2;
    required uint64 p_90 = 3;
    required uint64 p_99 = 4;
    required uint64 p_99_9 = 5;
    required uint64 p_99_99 = 6;
    required uint64 p_99_999 = 7;
    required uint64 p_100 = 8;
    required uint64 sum = 9;
}

// a histogram meant to be translated to prometheus
message FilteredHistogram {
    required uint64 sum = 1;
    required uint64 count = 2;
    repeated Bucket buckets = 3;
}

// a prometheus histogram bucket
message Bucket {
    required uint64 count = 1;
    // upper range of the bucket (le = less or equal)
    required uint64 le = 2;
}

message RequestCounts {
    map<string, int32> map = 1;
}

// `0` means unlimited (the feature is disabled). Returned by workers in
// response to `Request.query_max_connections_per_ip`.
message MaxConnectionsPerIpLimit {
    required uint64 limit = 1;
}

// `0` means unlimited (the subnet limiter is disabled), which is the
// default. Returned by workers in response to
// `Request.query_max_connections_per_subnet`. Carries the two prefix
// lengths alongside the cap: they are set once at worker boot from
// `ServerConfig`, so this reply is the only runtime surface that can
// tell an operator which mask the live counters are keyed on.
message MaxConnectionsPerSubnetLimit {
    required uint64 limit = 1;
    // IPv4 prefix length in bits, 0-32. 32 (the default) makes an IPv4
    // "subnet" the single address, i.e. inert.
    required uint32 ipv4_prefix = 2;
    // IPv6 prefix length in bits, 0-128. 128 (the default) makes an
    // IPv6 "subnet" the single address, i.e. inert.
    required uint32 ipv6_prefix = 3;
}

// matches std::net::SocketAddr in the Rust library
// beware that the ports are expressed with uint32 here,
// but they should NOT exceed uint16 value
message SocketAddress {
    required IpAddress ip = 1;
    required uint32 port = 2;
}

message IpAddress {
    oneof inner {
        fixed32 v4 = 1;
        Uint128 v6 = 2;
    }
}

// used to represent the 128 bits of an IPv6 address
message Uint128 {
    // higher value, first 8 bytes of the ip
    required uint64 low = 1;
    // lower value, last 8 bytes of the ip
    required uint64 high = 2;
}

// This is sent only from Sōzu to Sōzu
message WorkerRequest {
    required string id = 1;
    required Request content = 2;
}

// A response as sent by a worker
message WorkerResponse {
    required string id = 1;
    required ResponseStatus status = 2;
    // an associated message to detail failure, success or processing
    required string message = 3;
    optional ResponseContent content = 4;
}

// label-cardinality knob for the metrics drain.
// Mirrors HAProxy's `process|frontend|backend|server` extra-counters opt-in:
// a higher level enables more granular labels (and thus more keys), letting
// operators bound the StatsD keyspace explicitly.
//
// Each level is a SUPERSET of the previous one.
enum MetricDetail {
    // proxy-only counters (legacy default before opt-in landed)
    DETAIL_PROCESS = 0;
    // adds per-listener (frontend) breakdown for accept/connection counters
    DETAIL_FRONTEND = 1;
    // adds per-cluster aggregation (current default)
    DETAIL_CLUSTER = 2;
    // adds per-backend aggregation (cluster + backend, highest cardinality)
    DETAIL_BACKEND = 3;
}

// Apply, renew, or release a runtime cardinality lease on the metrics drain.
//
// Leasing model: `sozu top` (and any future TUI client) leases a higher
// `MetricDetail` for the duration of an interactive session. The worker's
// effective detail is `max(configured, max(active leases))`, where
// `configured` is `MetricsConfig.detail` from the static configuration.
// Multiple clients can lease independently; the worker keeps a `client_id`-
// keyed table and uses the maximum across active entries.
//
// Lifecycle:
// 1. Apply: send `SetMetricDetail{ client_id, detail, ttl_seconds, reason }`.
//   The worker stores `(client_id) -> (detail, expires_at = now + ttl)`. If
//   a lease for `client_id` already exists, it is REPLACED (acts as a
//   renewal). The renewer client is expected to re-send every `ttl/2`.
// 2. Expire: leases self-expire server-side at `expires_at`. The worker's
//   janitor (5s polled tick on the worker event loop, which wakes at least
//   once per second without traffic or commands) prunes expired leases
//   and recomputes effective. Crash safety: a dead client is forgotten.
// 3. Clear: send `SetMetricDetail{ client_id, clear: true }` for explicit
//   revocation. `client_id` must match the leased entry; mismatched IDs
//   are silently ignored (other clients' leases are not affected).
//
// Audit
// =====
// Every operator-initiated effective-level transition emits an
// `EventKind::METRIC_DETAIL_CHANGED` event on `SubscribeEvents` with the
// previous and new effective levels and the requesting `client_id` plus
// optional `reason` text. Renewal-no-op (same effective level) is NOT
// emitted.
//
// Emitter scope: operator-initiated transitions emit
// `METRIC_DETAIL_CHANGED` via the master-side audit log. Worker-local
// transitions — the polled janitor expiring a lease, or a worker-local
// clear/apply after a master fan-out — are not yet surfaced; follow-up
// tracked separately.
//
// Backwards compatibility
// =======================
// Workers that pre-date this verb cannot decode `SetMetricDetail` and return
// `WorkerResponse::error("unknown request type")` which folds into the standard
// fan-out error tally (`extras.fanout.workers_err`); operators see "succeeded
// with errors" rather than a dedicated capability-skip list. Production
// deployments keep master + workers in sync via the `UpgradeMain` hot-upgrade
// flow, so this mixed-version state is transient. The master has no runtime
// lease table: its response contribution is the configured floor initialized
// by `setup_metrics`, while every worker owns and reports its leases.
message SetMetricDetail {
    // Stable identifier for the leasing client (`sozu top` uses
    // `top:<pid>:<random>`). Required so multiple TUIs / scrapers / other
    // tooling can lease independently.
    required string client_id = 1;
    // Target detail for the lease. Required when `clear` is false/absent.
    optional MetricDetail detail = 2;
    // Time-to-live for the lease in seconds. The worker rejects (FAILURE)
    // values larger than 300s to bound the worst-case effect of a stuck
    // renewer. Defaults server-side to 60s when absent (the master treats
    // 0 as "use default" and emits a warning).
    optional uint32 ttl_seconds = 3;
    // When true, releases the lease for `client_id` instead of applying.
    // `detail` and `ttl_seconds` are ignored when `clear` is true.
    optional bool clear = 4;
    // Optional human-readable provenance for the audit log
    // (e.g. `"sozu top --detail backend"`, `"prometheus-scraper:sozu-1"`).
    optional string reason = 5;
    // Master-populated peer binding. These fields are NOT set by clients —
    // the master fills them in `bin/src/command/requests.rs::worker_request`
    // from the connecting `ClientSession` (`actor_pid` + `session_ulid`)
    // before forwarding to workers. The worker stores the binding
    // alongside the lease and rejects subsequent `clear` requests whose
    // binding does not match the apply-time binding. Prevents one same-UID
    // operator from accidentally (or deliberately) clearing another
    // operator's lease by guessing the `client_id` format. A `None` value
    // means "binding not available" — the worker accepts any matching
    // `client_id` clear, preserving compat with pre-binding callers and
    // with platforms whose unix socket peer credentials are unavailable.
    optional int32 peer_pid = 6;
    optional string peer_session_ulid = 7;
}

// Per-worker outcome of a `SetMetricDetail` fan-out. Reported back to the
// requesting client so it can decide whether the elevation actually took
// effect (e.g. all workers acknowledged) or whether degraded operation
// (some workers too old) is in play.
message WorkerMetricDetailStatus {
    // The worker's static `MetricsConfig.detail` (or DETAIL_CLUSTER if
    // unset). Independent of leases.
    required MetricDetail configured = 1;
    // Effective level AFTER processing this verb: `max(configured, leases)`.
    required MetricDetail effective = 2;
    // Effective level BEFORE the verb. Equal to `effective` for a no-op.
    required MetricDetail previous_effective = 3;
    // Number of active leases on this worker (post-prune). Useful to
    // surface "another client is still leasing this level" in the TUI.
    required uint32 active_lease_count = 4;
}

// Aggregated `SetMetricDetail` outcome across the fleet. Returned by the
// master to the requesting client (no `WorkerResponses` indirection needed
// because the schema is symmetric per-worker).
message MetricDetailStatus {
    // The master's own `configured` view (mirrors a worker's view since the
    // master also runs the metrics aggregator).
    required MetricDetail configured = 1;
    // Master's effective level AFTER the verb.
    required MetricDetail effective = 2;
    // Master's effective level BEFORE the verb.
    required MetricDetail previous_effective = 3;
    // Per-worker status. Map keyed by worker_id (string form for parity
    // with `WorkerResponses`).
    map<string, WorkerMetricDetailStatus> workers = 4;
    reserved 5;
    reserved "unsupported_workers";
}

// intended to workers
message ServerMetricsConfig {
    required string address = 1;
    required bool tagged_metrics = 2;
    optional string prefix = 3;
    // optional in proto: workers built before this field default to
    // DETAIL_CLUSTER on the lib side to preserve historical behaviour.
    optional MetricDetail detail = 4;
}

// Used by a worker to start its server loop.
// The defaults should match those of the config module
message ServerConfig {
    required uint64 max_connections = 1 [default = 10000];
    required uint32 front_timeout = 2 [default = 60];
    required uint32 back_timeout = 3 [default = 30];
    required uint32 connect_timeout = 4 [default = 3];
    required uint32 zombie_check_interval = 5 [default = 1800];
    required uint32 accept_queue_timeout = 6 [default = 60];
    required uint64 min_buffers = 7 [default = 1];
    required uint64 max_buffers = 8 [default = 1000];
    required uint64 buffer_size = 9 [default = 16393];
    required string log_level = 10 [default = "info"];
    required string log_target = 11 [default = "stdout"];
    optional string access_logs_target = 12;
    required uint64 command_buffer_size = 13 [default = 1000000];
    required uint64 max_command_buffer_size = 14 [default = 2000000];
    optional ServerMetricsConfig metrics = 15;
    required ProtobufAccessLogFormat access_log_format = 16;
    required bool log_colored = 17;
    // Dedicated file path for the control-plane audit trail. When set on the
    // main process, every audit line is also appended to this file opened
    // `O_APPEND | O_CREAT` with mode `0o640`. Workers currently ignore this
    // field (audit only lives on the main), but the field is propagated on
    // the proto wire so a future worker-side audit path can pick it up.
    optional string audit_logs_target = 18;
    // Dedicated JSON mirror of the audit log. One JSON object per line for
    // SIEM ingest. Same lifecycle as `audit_logs_target`.
    optional string audit_logs_json_target = 19;
    // Slab capacity multiplier per connection. Defaults to 4 to accommodate
    // H2 multiplexing (1 frontend + up to 3 backend connections per
    // frontend). Operators with topologies that fan out across more clusters
    // per session can raise this; the slab capacity is computed as
    // `10 + slab_entries_per_connection * max_connections`. Clamped to
    // [2, 32] at config-load time. The previous compile-time constant was
    // 4 and remains the default.
    optional uint64 slab_entries_per_connection = 20;
    // Maximum length, in bytes, of a base64-decoded `Authorization: Basic`
    // payload accepted by `mux::auth`. Caps the per-failed-auth allocation
    // so a hostile peer cannot force the worker to decode arbitrarily
    // large tokens. RFC 7617 imposes no upper bound; the default is 4096
    // (well above the realistic shape `username:password`). Operators on
    // tight memory budgets can lower this to 256-512; values that approach
    // the per-frontend `buffer_size` raise a warning at config-load time
    // (see config.rs validation). Set once at worker boot via
    // `mux::auth::set_max_decoded_credential_bytes`.
    optional uint64 basic_auth_max_credential_bytes = 21;
    // when the accept queue is full (max_connections reached), evict the
    // least recently active sessions to make room for new connections.
    // Defaults to false: during DDoS, existing connections are likely real clients.
    optional bool evict_on_queue_full = 22 [default = false];
    // Default per-(cluster, source-IP) connection limit. `0` means unlimited
    // (the default). When a request resolves to a cluster whose
    // `(cluster_id, client_ip)` already holds this many concurrent
    // connections, the proxy answers HTTP 429 (H1 + H2) or closes the TCP
    // socket gracefully. Each cluster may override with its own
    // `max_connections_per_ip`. The source IP is the proxy-protocol
    // address when present, else `peer_addr`. UDP listeners ignore this
    // default: only a cluster's own `max_connections_per_ip` limits UDP
    // flows.
    optional uint64 max_connections_per_ip = 23 [default = 0];
    // Default `Retry-After` header value (seconds) sent on HTTP 429
    // responses. `0` omits the header (rendering `Retry-After: 0` invites
    // an immediate retry that defeats the limit). Per-cluster overrides
    // are available on the `Cluster` message. TCP rejections do not emit
    // this value (no HTTP envelope), but it is still accepted in the
    // proto/config shape for symmetry.
    optional uint32 retry_after = 24 [default = 60];
    // Default per-(cluster, source-SUBNET) connection limit. `0` means
    // unlimited and IS THE DEFAULT, so this limiter is inert until an
    // operator turns it on and the pre-existing per-IP behaviour is
    // strictly unchanged out of the box.
    //
    // This is a SECOND, independent counter standing beside
    // `max_connections_per_ip` (tag 23), not a replacement for it. The
    // per-IP cap serves the API-gateway case (a single abusive client);
    // the per-subnet cap serves the denial-of-service case, where an
    // attacker holding a routed prefix — an ordinary residential IPv6
    // `/64` — defeats a per-address counter entirely by taking a fresh
    // address per connection (sozu-proxy/sozu#1270). Both gates are
    // consulted and BOTH must admit, so "10 per IP AND 100 per /64" is
    // expressible. UDP listeners ignore this default, as for tag 23.
    optional uint64 max_connections_per_subnet = 26 [default = 0];
    // IPv4 prefix length, in bits, used to derive the subnet key from an
    // IPv4 source address. Valid range 0-32; rejected at config-load
    // time outside it. The default of 32 masks nothing, so an operator
    // who sets only `max_connections_per_subnet` gets a per-address
    // counter rather than a surprising aggregation. `/24` is the
    // recommended starting point (see doc/configure.md).
    optional uint32 subnet_ipv4_prefix = 27 [default = 32];
    // IPv6 prefix length, in bits, used to derive the subnet key from an
    // IPv6 source address. Valid range 0-128; rejected at config-load
    // time outside it. The default of 128 masks nothing. `/56` is the
    // recommended starting point (see doc/configure.md). An
    // IPv4-mapped IPv6 source (`::ffff:a.b.c.d`, what a dual-stack
    // `[::]` listener hands back for a v4 client) is canonicalised to
    // its IPv4 form FIRST and then masked with `subnet_ipv4_prefix`, so
    // v4 clients are not all collapsed into a single `::/56` bucket.
    optional uint32 subnet_ipv6_prefix = 28 [default = 128];
    // Requested kernel-pipe capacity, in bytes, for each `splice(2)`
    // zero-copy direction in the `Pipe` protocol. Applied via
    // `fcntl(F_SETPIPE_SZ)` per pipe at `SplicePipe::new`; the kernel
    // rounds up to a page boundary and caps the value at
    // `/proc/sys/fs/pipe-max-size` (default 1 MiB for unprivileged
    // processes; CAP_SYS_RESOURCE goes higher). The realised capacity
    // is read back via `fcntl(F_GETPIPE_SZ)` and used as the per-call
    // `len` for `splice_in`. `None` keeps the kernel default of 64 KiB.
    // Larger values amortise syscalls and reduce wakeups for bulk-
    // transfer workloads at the cost of per-session pinned memory.
    // Linux-only; ignored on builds without the `splice` feature.
    optional uint64 splice_pipe_capacity_bytes = 25;
    // Backend connection attempt budget of every request: how many backend
    // connections a request may try, the first included, before it is
    // answered `503` (HTTP) or closed (TCP). A failed connection — refused,
    // timed out on `connect_timeout`, or reporting a socket error — is
    // retried on another backend while the budget lasts. Between 1 and 255.
    // Each cluster may override it with `Cluster.max_connection_attempts`,
    // and `Request.set_max_connection_attempts` changes it at runtime.
    // Replaces the library constant `CONN_RETRIES = 3`.
    optional uint32 max_connection_attempts = 29 [default = 5];
}

enum ProtobufAccessLogFormat {
    Ascii = 1;
    Protobuf = 2;
}

// Addresses of listeners, passed to new workers. Each entry is a listener
// key: the socket address, followed by `%<interface>` when the listener is
// bound to a network interface (see `ListenerKey` in
// `command/src/listener_key.rs`).
message ListenersCount {
    // socket addresses of HTTP listeners
    repeated string http = 1;
    // socket addresses of HTTPS listeners
    repeated string tls = 2;
    // socket addresses of TCP listeners
    repeated string tcp = 3;
    // socket addresses of UDP listeners
    repeated string udp = 4;
}

// the Sōzu state, passed to a new worker.
// Consists in a collection of worker requests
message InitialState {
    repeated WorkerRequest requests = 1;
}

message OpenTelemetry {
    required string trace_id = 1;
    required string span_id = 2;
    optional string parent_span_id = 3;
}

// An access log, meant to be passed to another agent
message ProtobufAccessLog {
    // error message if any
    optional string message = 1;
    // LogContext = request_id + cluster_id + backend_id
    required Uint128 request_id = 2;
    // id of the cluster (set of frontend, backend, routing rules)
    optional string cluster_id = 3;
    // id of the backend (the server to which the traffic is redirected)
    optional string backend_id = 4;
    // ip and port of the client
    optional SocketAddress session_address = 5;
    // socket address of the backend server
    optional SocketAddress backend_address = 6;
    // the protocol, with SSL/TLS version, for instance "HTTPS-TLS1.1"
    required string protocol = 7;
    // TCP or HTTP endpoint (method, path, context...)
    required ProtobufEndpoint endpoint = 8;
    // round trip time for the client (microseconds)
    optional uint64 client_rtt = 9;
    // round trip time for the backend (microseconds)
    optional uint64 server_rtt = 10;
    // time spent on a session (microseconds)
    required uint64 service_time = 13;
    // number of bytes received from the client
    required uint64 bytes_in = 14;
    // number of bytes written to the client
    required uint64 bytes_out = 15;
    // value of the User-Agent header, if any
    optional string user_agent = 16;
    // custom tags as key-values, for instance owner_id: MyOrganisation
    map<string, string> tags = 17;
    // short description of which process sends the log, for instance: "WRK-02"
    required string tag = 18;
    // POSIX timestamp, nanoseconds
    required Uint128 time = 19;
    // Entire time between first byte received and last byte of the response.
    // If a request ends abruptly before the last byte is transmitted,
    // the `request_time` produced is the time elapsed since the first byte received.
    optional uint64 request_time = 20;
    // time for the backend to respond (microseconds)
    optional uint64 response_time = 21;
    // OpenTelemetry tracing information
    optional OpenTelemetry otel = 22;
    // connection/session ULID — stable across all requests multiplexed on the
    // same TCP or TLS connection. Distinct from `request_id`, which is set
    // per-request (one per H2 stream, one per H1 keep-alive exchange).
    optional Uint128 session_id = 23;
    // Value of the `x-request-id` header as forwarded to the backend —
    // either preserved verbatim from the client/upstream LB, or derived from
    // the request ULID when the client did not supply one. Universal
    // correlation key for end-to-end tracing across Envoy/HAProxy/Sōzu hops.
    optional string x_request_id = 24;
    // Negotiated TLS protocol version, short-form (e.g. "TLSv1.3"). Captured
    // once at handshake completion. `None` for plaintext listeners or when
    // the rustls version label is unknown to Sōzu.
    optional string tls_version = 25;
    // Negotiated TLS cipher suite, short-form (e.g.
    // "TLS_AES_128_GCM_SHA256"). Captured once at handshake completion.
    // `None` for plaintext listeners or when the rustls cipher label is
    // unknown to Sōzu.
    optional string tls_cipher = 26;
    // TLS Server Name Indication (SNI) sent by the client at handshake.
    // Stored pre-lowercased without a port. `None` for plaintext listeners
    // or when the client omitted the SNI extension.
    optional string tls_sni = 27;
    // Negotiated ALPN protocol, short-form (e.g. "h2", "http/1.1"). `None`
    // for plaintext listeners or when no ALPN was negotiated.
    optional string tls_alpn = 28;
    // Verbatim value of the client-supplied `X-Forwarded-For` header as
    // observed before Sōzu appended its own hop. Comma-separated chain of
    // proxy hops (e.g. `"203.0.113.5, 198.51.100.10"`). `None` if no
    // upstream proxy supplied the header.
    optional string xff_chain = 29;
    // Wall-clock timestamp (POSIX nanoseconds since epoch) captured at the
    // start of the request. Enables accurate OTel span reconstruction
    // without subtracting a monotonic `request_time` duration from the
    // wall-clock `time` field — a computation that mixes two unsynchronised
    // clock sources (CLOCK_MONOTONIC vs CLOCK_REALTIME) and produces
    // unreliable start timestamps, especially for short-lived requests or
    // across NTP adjustments. Optional for backwards compatibility.
    optional Uint128 start_time = 30;
}

message ProtobufEndpoint {
    oneof inner {
        HttpEndpoint http = 1;
        TcpEndpoint tcp = 2;
    }
}

message HttpEndpoint {
    optional string method = 1;
    optional string authority = 2;
    optional string path = 3;
    // warning: this should be a u16 but protobuf only has uint32.
    // Make sure the value never exceeds u16 bounds.
    optional uint32 status = 4;
    optional string reason = 5;
}

message TcpEndpoint {}