kividb 1.2.2

A fast RedisĀ®-compatible in-memory store written in Rust
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
use clap::Parser;

/// The values `tls-auth-clients` accepts.
pub const TLS_AUTH_CLIENTS: [&str; 3] = ["yes", "no", "optional"];

/// `tls-auth-clients-allowed-names` as a list of names, lower case: words
/// separated by spaces or commas, each a DNS name, or `*.` and one, where
/// `*` stands for exactly one label, as it does in a certificate. Empty:
/// any name. `Err` says which word is neither.
pub fn allowed_names(value: &str) -> Result<Vec<String>, String> {
    value
        .split(|c: char| c.is_whitespace() || c == ',')
        .filter(|name| !name.is_empty())
        .map(|name| {
            let name = name.trim_end_matches('.').to_ascii_lowercase();
            let label = |label: &str| {
                !label.is_empty()
                    && label
                        .bytes()
                        .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
            };
            if name
                .strip_prefix("*.")
                .unwrap_or(&name)
                .split('.')
                .all(label)
            {
                Ok(name)
            } else {
                Err(format!(
                    "'{name}' is not a DNS name, nor '*.' and one: '*' may only be the whole \
                     first label"
                ))
            }
        })
        .collect()
}

/// Whether `name`, as a certificate gives it, matches `pattern`, one of
/// [`allowed_names`]: the same name, in any case, or for `*.parent` one label
/// more than `parent`.
#[cfg_attr(not(feature = "tls"), allow(dead_code))]
pub fn allowed_name_matches(pattern: &str, name: &str) -> bool {
    let name = name.trim_end_matches('.').to_ascii_lowercase();
    match pattern.strip_prefix("*.") {
        Some(parent) => name
            .strip_suffix(parent)
            .and_then(|head| head.strip_suffix('.'))
            .is_some_and(|label| !label.is_empty() && !label.contains('.')),
        None => name == pattern,
    }
}

#[derive(clap::ValueEnum, Debug, Clone, Default, PartialEq)]
pub enum IoModel {
    #[default]
    Auto, // io_uring if available, tokio fallback
    Uring, // force io_uring, fail if unavailable
    Tokio, // always use tokio
}

#[derive(Parser, Debug, Clone)]
#[command(
    name = "kividb",
    about = "Fast Redis-compatible store",
    version = env!("CARGO_PKG_VERSION"),
    author = env!("CARGO_PKG_AUTHORS")
)]
pub struct Config {
    /// Port to listen
    #[arg(long, default_value_t = 6380)]
    pub port: u16,

    /// Address to listen
    #[arg(long, default_value = "0.0.0.0")]
    pub bind: String,

    /// While the default user has no password, accept clients from this
    /// machine only (Redis `protected-mode`). See `src/protected_mode.rs`.
    #[arg(long, default_value = "yes", value_parser = parse_yes_no, num_args = 1)]
    pub protected_mode: bool,

    /// Whether `bind` was set (on the command line or in the configuration
    /// file). Protected mode applies only while it was not, as in Redis
    /// before 7: listening on every address by choice is a choice.
    #[arg(skip)]
    pub bind_explicit: bool,

    /// Number of worker threads (0 = auto)
    #[arg(long, default_value_t = 0)]
    pub threads: usize,

    /// Enable append-only file persistence
    #[arg(long, default_value_t = false)]
    pub aof: bool,

    /// When the append-only file is synced to disk: `always`, before the
    /// reply to each write, as in Redis; `everysec`, once a second. `no` is
    /// taken as `everysec`.
    #[arg(long, default_value = "everysec")]
    pub appendfsync: String,

    /// Start a rewritten AOF with a KDB image of the dataset, so recovery loads
    /// the bulk at snapshot speed and replays only what came after it.
    /// Disable to emit the plain command log older builds produce.
    #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
    pub aof_preamble: bool,

    /// Run scripts whose KEYS share a hash tag beside each other, each under
    /// its tag's lock, instead of one at a time for the whole server. A
    /// script run that way may not touch a key outside the tag. On unless
    /// switched off; it means something only in a build with Lua. See
    /// docs/SCRIPTS.md.
    #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
    pub lua_parallel_scripts: bool,

    /// Rewrite the AOF once it has grown this much past its post-rewrite size,
    /// as a percentage (0 = never rewrite automatically).
    #[arg(long, default_value_t = 100)]
    pub aof_rewrite_percentage: u64,

    /// Never rewrite automatically below this size, in bytes. Keeps a small
    /// log from rewriting constantly just because it doubled.
    #[arg(long, default_value_t = 64 * 1024 * 1024)]
    pub aof_rewrite_min_size: u64,

    /// Number of databases
    #[arg(long, default_value_t = 16)]
    pub databases: usize,

    /// Max memory (0 = unlimited): bytes, or with a unit as in Redis (`3gb`,
    /// `512mb`). Once the process uses more, writes are refused with an OOM
    /// error.
    #[arg(long, default_value_t = 0, value_parser = parse_memory_flag)]
    pub maxmemory: usize,

    /// Idle time before a private client query buffer is released. Hidden so
    /// integration tests can shorten the maintenance interval deterministically.
    #[arg(long, default_value_t = 2000, hide = true)]
    pub query_buffer_idle_resize_after_ms: u64,

    /// What to do when `maxmemory` is reached (Redis `maxmemory-policy`):
    ///   noeviction — refuse the write
    ///   allkeys-lru | allkeys-lfu | allkeys-lrm | allkeys-random — delete
    ///            keys to make room: the least recently used, least
    ///            frequently used, least recently modified, or any
    ///   volatile-lru | volatile-lfu | volatile-lrm | volatile-random |
    ///   volatile-ttl — the same, among keys with a TTL only; or the one
    ///            nearest to expiring
    #[arg(long, default_value = "noeviction")]
    pub maxmemory_policy: String,

    /// How many keys are looked at to choose the one to evict (Redis
    /// `maxmemory-samples`).
    #[arg(long, default_value_t = 5)]
    pub maxmemory_samples: usize,

    /// How slowly a key's use count grows, for the LFU policies (Redis
    /// `lfu-log-factor`).
    #[arg(long, default_value_t = 10)]
    pub lfu_log_factor: u32,

    /// Record every key's use whatever the eviction policy, so that `OBJECT
    /// IDLETIME` and `OBJECT FREQ` report it under `noeviction` too. Costs
    /// every command a little: see `eviction::key_access_tracking`.
    #[arg(long, default_value = "no", value_parser = parse_yes_no, num_args = 1)]
    pub key_access_tracking: bool,

    /// Minutes for a key's use count to fall by one, for the LFU policies
    /// (Redis `lfu-decay-time`). 0 = it never falls.
    #[arg(long, default_value_t = 1)]
    pub lfu_decay_time: u32,

    /// Move string values off the slabs deletes have left sparse, so that
    /// their memory goes back to the system (Redis `activedefrag`; see
    /// `src/compaction.rs`). On unless switched off.
    #[arg(long, default_value = "yes", value_parser = parse_yes_no, num_args = 1)]
    pub activedefrag: bool,

    /// Waste in the slabs under which active defrag does not start (Redis
    /// `active-defrag-ignore-bytes`).
    #[arg(long, default_value_t = 64 << 20)]
    pub active_defrag_ignore_bytes: u64,

    /// Waste, as a percentage of what is in the slabs, over which active
    /// defrag starts (Redis `active-defrag-threshold-lower`).
    #[arg(long, default_value_t = 20)]
    pub active_defrag_threshold_lower: u32,

    /// The most of one core active defrag uses, a percentage (Redis
    /// `active-defrag-cycle-max`).
    #[arg(long, default_value_t = 10)]
    pub active_defrag_cycle_max: u32,

    /// Working directory: where `dump.kdb`, `appendonly.aof`, backups and
    /// `nodes.conf` live (Redis `dir`). Empty = the directory the server was
    /// started in.
    #[arg(long, default_value = "")]
    pub dir: String,

    /// Log level: debug, verbose, notice (or info), warning, nothing.
    /// docs/LOGGING.md says what each shows.
    #[arg(long, default_value = "info")]
    pub loglevel: String,

    /// Write the log to this file, appending, instead of standard error.
    #[arg(long, default_value = "")]
    pub logfile: String,

    /// Log line format: `text`, or `json` — one object per line, for log
    /// pipelines.
    #[arg(long, default_value = "text", value_parser = ["text", "json"])]
    pub log_format: String,

    /// I/O model: auto, uring, tokio
    #[arg(long, default_value = "auto", value_enum)]
    pub io_model: IoModel,

    /// Replicate from master: "host port" (e.g. "127.0.0.1 6379")
    /// Pass as two args: --replicaof 127.0.0.1 6379
    #[arg(long, num_args = 2, value_names = ["HOST", "PORT"])]
    pub replicaof: Option<Vec<String>>,

    /// This replica's announced port (for REPLCONF listening-port)
    /// Defaults to the server's own port.
    #[arg(long, default_value_t = 0)]
    pub replica_announced_port: u16,

    /// Where this replica stands when Sentinel picks one to promote (Redis
    /// `replica-priority`, reported as `slave_priority` by `INFO
    /// replication`): a lower one goes first, and 0 is never promoted.
    #[arg(long, alias = "slave-priority", default_value_t = 100,
          value_parser = clap::value_parser!(u32).range(0..=i32::MAX as i64))]
    pub replica_priority: u32,

    /// Whether Sentinel lists this replica (Redis `replica-announced`,
    /// reported as `replica_announced` by `INFO replication`).
    #[arg(long, default_value = "yes", value_parser = parse_yes_no, num_args = 1)]
    pub replica_announced: bool,

    /// Password required for AUTH (empty = no authentication required)
    #[arg(long, default_value = "")]
    pub requirepass: String,

    /// Path to ACL file (empty = no ACL file, use inline SETUSER rules only)
    #[arg(long, default_value = "")]
    pub aclfile: String,

    /// Slowlog threshold in microseconds (0 = log everything)
    #[arg(long, default_value_t = u64::MAX)]
    pub slowlog_log_slower_than: u64,

    /// Maximum number of slowlog entries to keep
    #[arg(long, default_value_t = 128)]
    pub slowlog_max_len: usize,

    /// Maximum number of ACL LOG entries to keep (`acllog-max-len`); 0
    /// keeps none
    #[arg(long, default_value_t = 128)]
    pub acllog_max_len: usize,

    /// True iff the server should run as a cluster node.
    /// Activated by `--cluster-enabled yes`. Defaults to false (standalone).
    #[arg(long, default_value = "no", value_parser = parse_yes_no, num_args=1)]
    pub cluster_enabled: bool,

    /// Milliseconds without a PONG before a peer is marked PFAIL.
    /// Default 15000 matches Redis. Lower values detect failures faster
    /// but increase false positives under network jitter.
    #[arg(long, default_value_t = 15000)]
    pub cluster_node_timeout: u64,

    /// Path to a config file to load settings from.
    /// Equivalent to passing redis-server /etc/redis.conf.
    #[arg(long, default_value = "/etc/kividb/kividb.conf")]
    pub configfile: String,

    /// Whether the server was started from `configfile`: it was there, and
    /// was read. Only then may `CONFIG REWRITE` write it, as in Redis. A
    /// server started without one used to create the file, and the next
    /// server started with the same path (the default one, shared by every
    /// server on the host) loaded it, `replicaof` and all (#442).
    #[arg(skip)]
    pub configfile_loaded: bool,

    /// Port to accept TLS connections on. 0 = TLS disabled.
    /// Separate from `port` so the uring hot-path on `port` is untouched.
    #[arg(long, default_value_t = 0)]
    pub tls_port: u16,

    /// Path to the TLS certificate file (PEM format).
    #[arg(long, default_value_t = String::new())]
    pub tls_cert_file: String,

    /// Path to the TLS private key file (PEM format).
    #[arg(long, default_value_t = String::new())]
    pub tls_key_file: String,

    /// Path to the CA certificate file (PEM) that client certificates are
    /// verified against; see `tls-auth-clients`. Leave empty to not ask
    /// clients for a certificate.
    #[arg(long, default_value_t = String::new())]
    pub tls_ca_cert_file: String,

    /// Whether TLS clients must present a certificate signed by
    /// `tls-ca-cert-file` (Redis `tls-auth-clients`):
    ///   yes      — required; a client without a valid one is refused
    ///   optional — not required, but one that is presented must be valid
    ///   no       — not asked for
    /// Has no effect while `tls-ca-cert-file` is empty.
    #[arg(long, default_value = "yes")]
    pub tls_auth_clients: String,

    /// The names a client certificate must carry to be accepted, separated
    /// by spaces or commas: a client (or replica, or node on the cluster
    /// bus) that presents a certificate is refused unless its subject CN or
    /// one of its DNS names matches one of them. A name is exact, or starts
    /// with `*.`, where `*` stands for exactly one label: `*.db.example`
    /// takes `node-0.db.example`, not `a.b.db.example`. Case does not
    /// matter. Empty (the default): any certificate the CA signed.
    #[arg(long, default_value = "")]
    pub tls_auth_clients_allowed_names: String,

    /// The cluster bus over TLS, and the TLS port announced as this node's
    /// port, so that what nodes open to each other is TLS (Redis
    /// `tls-cluster`). Needs `tls-port`, the certificate, key and CA files.
    #[arg(long, default_value = "no", value_parser = parse_yes_no, num_args = 1)]
    pub tls_cluster: bool,

    /// A replica connects to its master over TLS (Redis `tls-replication`).
    /// Implied by `tls-cluster` in a cluster.
    #[arg(long, default_value = "no", value_parser = parse_yes_no, num_args = 1)]
    pub tls_replication: bool,

    /// Certificate this node presents when it connects to another node
    /// (Redis `tls-client-cert-file`); `tls-cert-file` when empty.
    #[arg(long, default_value = "")]
    pub tls_client_cert_file: String,

    /// Key for `tls-client-cert-file`.
    #[arg(long, default_value = "")]
    pub tls_client_key_file: String,

    /// Whether to ask GitHub at startup for the latest release, and say so
    /// when it is newer than this build (see docs/UPDATE_CHECK.md).
    /// `--update-check no` turns it off, as does KIVIDB_NO_UPDATE_CHECK=1.
    #[arg(long, default_value = "yes", value_parser = parse_yes_no, num_args = 1)]
    pub update_check: bool,

    /// Where the update check asks: a releases/latest page that redirects to
    /// the newest release's tag (https:// only).
    #[arg(long, default_value = crate::update_check::DEFAULT_URL)]
    pub update_check_url: String,

    /// Keyspace notification events to publish (empty = disabled).
    #[arg(long, default_value = "")]
    pub notify_keyspace_events: String,

    /// Max bytes a master will queue for a single replica that isn't keeping up
    /// (analogous to Redis's `client-output-buffer-limit slave <hard-limit>`).
    /// Once exceeded the replica is disconnected — it must full-resync to catch
    /// back up — rather than letting the queue grow without bound. Settable at
    /// runtime.
    #[arg(long, default_value_t = 268_435_456)]
    pub repl_replica_max_backlog_bytes: u64,

    /// Max bytes a master will queue for a replica during its full sync, from
    /// the cut until the replica has loaded the dataset and drained its queue
    /// to a quarter of `repl-replica-max-backlog-bytes`. The replica reads nothing of the
    /// stream while it loads, so everything written meanwhile waits in the
    /// queue (#305). The larger of the two applies. Settable at runtime.
    #[arg(long, default_value_t = 1_073_741_824)]
    pub repl_replica_sync_max_backlog_bytes: u64,

    /// Bytes of the write stream a master keeps for replicas that reconnect
    /// (Redis `repl-backlog-size`). A replica that was away for less than
    /// this much writing is brought up to date without a full resync.
    ///
    /// 64 MB, a few seconds of heavy writing; Redis's default is 1 MB, a
    /// fraction of a second at 100,000 writes a second, less than a replica
    /// takes to reconnect after its master restarts. Kept only from a
    /// replica's first sync (or a promotion) until `repl-backlog-ttl` after
    /// the last replica has gone: a server that never had one keeps none.
    #[arg(long, default_value_t = 64 * 1024 * 1024)]
    pub repl_backlog_size: u64,

    /// Seconds a master with no replicas keeps that backlog before releasing
    /// it (Redis `repl-backlog-ttl`). 0 = never release it.
    #[arg(long, default_value_t = 3600)]
    pub repl_backlog_ttl: u64,

    /// How a replica loads a full resync (Redis `repl-diskless-load`):
    ///   disabled | flushdb | on-empty-db — drop the local dataset first, then
    ///            load: memory for one dataset
    ///   swapdb — keep serving the local dataset until the new one is loaded,
    ///            then swap: memory for two
    #[arg(long, default_value = "disabled")]
    pub repl_diskless_load: String,

    /// Password this node presents when connecting to its master as a
    /// replica (Redis `masterauth`). Required when the master has
    /// `requirepass` or ACLs; without it the handshake is refused.
    #[arg(long, default_value = "")]
    pub masterauth: String,

    /// ACL user to authenticate as on the master (Redis `masteruser`).
    /// Empty = the `default` user.
    #[arg(long, default_value = "")]
    pub masteruser: String,

    /// Seconds without a byte from the master before a replica declares the
    /// link dead and reconnects (Redis `repl-timeout`). Also bounds each step
    /// of the handshake. This is what notices a master that was powered off or
    /// partitioned away: such a peer never refuses or resets the connection,
    /// so without a deadline the replica waits on the kernel's own TCP
    /// retransmission limit (~15 minutes) while reporting a healthy link.
    #[arg(long, default_value_t = 60)]
    pub repl_timeout: u64,

    /// Seconds a master that is shutting down waits for its replicas to
    /// acknowledge the end of its write stream before it saves and exits
    /// (Redis `shutdown-timeout`). A replica that has it all is continued
    /// after the restart instead of being sent the whole dataset. 0 does not
    /// wait; nor does `SHUTDOWN NOW` or `NOSAVE`.
    #[arg(long, default_value_t = 10)]
    pub shutdown_timeout: u64,

    /// Refuse writes while fewer than this many replicas are good: online,
    /// and heard from within `min-replicas-max-lag` seconds (Redis
    /// `min-replicas-to-write`). 0 is off. A master cut off from its
    /// replicas then refuses writes with NOREPLICAS instead of accepting
    /// ones that are lost when the partition heals.
    #[arg(long, default_value_t = 0)]
    pub min_replicas_to_write: u32,

    /// How recently, in seconds, a replica must have acknowledged to count
    /// as good for `min-replicas-to-write` (Redis `min-replicas-max-lag`).
    /// 0 turns `min-replicas-to-write` off.
    #[arg(long, default_value_t = 10)]
    pub min_replicas_max_lag: u64,

    /// Seconds between the PINGs a master writes into the replication stream
    /// (Redis `repl-ping-replica-period`). They give an idle link traffic, so
    /// a replica can tell "nothing to replicate" apart from "master is gone".
    #[arg(long, default_value_t = 10)]
    pub repl_ping_replica_period: u64,

    /// What a replica does when a full resync would replace its dataset with a
    /// smaller one:
    ///   off    — always accept (Redis behaviour)
    ///   empty  — refuse a master that has no keys while we hold some
    ///   shrink — additionally refuse a master holding fewer than
    ///            `replica-full-sync-guard-ratio` percent of our key count
    /// A refused sync keeps the local dataset, leaves the link down, and is
    /// retried; the operator overrides with `CONFIG SET replica-full-sync-guard off`.
    #[arg(long, default_value = "empty")]
    pub replica_full_sync_guard: String,

    /// Percentage used by `replica-full-sync-guard shrink`.
    #[arg(long, default_value_t = 50)]
    pub replica_full_sync_guard_ratio: u64,

    /// Address this node tells the rest of the cluster to reach it on (Redis
    /// `cluster-announce-ip`). Empty = let peers use the address they observe.
    #[arg(long, default_value = "")]
    pub cluster_announce_ip: String,

    /// Hostname this node announces to the cluster (Redis
    /// `cluster-announce-hostname`): letters, digits, `-` and `.`. Shown in
    /// CLUSTER NODES, SLOTS and SHARDS, and given to clients in place of the
    /// address when `cluster-preferred-endpoint-type` is `hostname`.
    #[arg(long, default_value = "")]
    pub cluster_announce_hostname: String,

    /// What clients are told to connect to, in MOVED, ASK and the topology
    /// replies: `ip`, `hostname` or `unknown-endpoint` (Redis
    /// `cluster-preferred-endpoint-type`).
    #[arg(long, default_value = "ip")]
    pub cluster_preferred_endpoint_type: String,

    /// Client port announced to the cluster. 0 = `port`.
    #[arg(long, default_value_t = 0)]
    pub cluster_announce_port: u16,

    /// The port clients are told to reach this node on (redirects, `CLUSTER
    /// SLOTS`, `SHARDS`, `NODES`), where it is not the client port nodes use
    /// between themselves: a NodePort, a load balancer that maps ports. 0 =
    /// the client port. Settable at runtime.
    #[arg(long, default_value_t = 0)]
    pub cluster_announce_client_port: u16,

    /// Bus port announced to the cluster. 0 = `port` + 10000.
    #[arg(long, default_value_t = 0)]
    pub cluster_announce_bus_port: u16,

    /// A secret every node of the cluster shares. A node connecting to
    /// another's bus port must prove it knows it (a challenge and an
    /// HMAC-SHA256 answer; the secret itself is never sent) before anything
    /// it says is read. Empty: the bus is open to anything that can reach
    /// it. Set it on every node or none.
    #[arg(long, default_value = "")]
    pub cluster_bus_secret: String,

    /// Refuse to run as a cluster node while the bus port is unauthenticated
    /// (Redis `cluster-bus-port-protected-mode`): with this `yes`, a cluster
    /// node needs `cluster-bus-secret`. The default `no` starts without one
    /// and logs a warning.
    #[arg(long, default_value = "no", value_parser = parse_yes_no, num_args = 1)]
    pub cluster_bus_port_protected_mode: bool,

    /// Where cluster topology is persisted (Redis `cluster-config-file`).
    #[arg(long, default_value = "nodes.conf")]
    pub cluster_config_file: String,

    /// Stop serving keyed commands while any hash slot is unassigned or owned
    /// by a failed node (Redis `cluster-require-full-coverage`).
    #[arg(long, default_value = "yes", value_parser = parse_yes_no, num_args = 1)]
    pub cluster_require_full_coverage: bool,

    /// A replica whose link to its master has been down longer than this
    /// many node timeouts (plus `repl-ping-replica-period`) does not stand
    /// for election when the master fails; 0 = always stand (Redis
    /// `cluster-replica-validity-factor`).
    #[arg(long, default_value_t = 10)]
    pub cluster_replica_validity_factor: u64,

    /// Arguments kept per slowlog entry (Redis 8.8 `slowlog-entry-max-argc`).
    #[arg(long, default_value_t = 32)]
    pub slowlog_entry_max_argc: usize,

    /// Bytes kept per argument in a slowlog entry (Redis 8.8
    /// `slowlog-entry-max-string-len`).
    #[arg(long, default_value_t = 128)]
    pub slowlog_entry_max_string_len: usize,

    /// Default seconds an `XADD ... IDMP` producer/id pair is remembered
    /// (Redis 8.6 `stream-idmp-duration`).
    #[arg(long, default_value_t = 100)]
    pub stream_idmp_duration: u64,

    /// Default idempotency ids remembered per producer (Redis 8.6
    /// `stream-idmp-maxsize`).
    #[arg(long, default_value_t = 100)]
    pub stream_idmp_maxsize: u64,

    /// Directory `BACKUP START` writes a backup into, under the working
    /// directory (Redis 8.10 `backupdirname`). Startup-only.
    #[arg(long, default_value = "backupdir")]
    pub backupdirname: String,

    /// Seconds a sealed backup is kept before it is cleaned up automatically;
    /// `0` keeps it until `BACKUP CLEANUP` (Redis 8.10 `backup-sealed-ttl`).
    #[arg(long, default_value_t = 0)]
    pub backup_sealed_ttl: u64,

    /// Load this file at startup instead of the usual `dump.kdb` and
    /// `appendonly.aof`: `aof:<manifest>` restores a sealed backup,
    /// `rdb:<file>` a single snapshot (Redis 8.10 `preload-file`).
    /// Startup-only; startup fails if the target cannot be loaded.
    #[arg(long, default_value = "")]
    pub preload_file: String,

    /// Atomic slot migration: once the source has less than this many bytes
    /// of the write stream left to send, it pauses writes and hands the slots
    /// over (Redis 8.4 `cluster-slot-migration-handoff-max-lag-bytes`).
    #[arg(long, default_value_t = 1024 * 1024)]
    pub cluster_slot_migration_handoff_max_lag_bytes: u64,

    /// Atomic slot migration: how long the source waits, writes paused, for
    /// the destination's answer to the takeover, in milliseconds, before it
    /// asks the destination whether it took the slots; writes stay paused
    /// until it knows (Redis 8.4 `cluster-slot-migration-write-pause-timeout`).
    #[arg(long, default_value_t = 10_000)]
    pub cluster_slot_migration_write_pause_timeout: u64,
    /// HLL write format during rolling upgrade: "legacy" or "redis".
    #[arg(long, default_value = "legacy")]
    pub hll_write_format: String,
}

impl Default for Config {
    /// Mirrors `#[arg(default_values)]` — `derive(Default)` would zero numeric fields
    /// (`databases = 0`), breaking integration tests and emptying DB/expiry stores.
    fn default() -> Self {
        Self {
            port: 6380,
            bind: "0.0.0.0".into(),
            threads: 0,
            aof: false,
            aof_preamble: true,
            lua_parallel_scripts: true,
            aof_rewrite_percentage: 100,
            aof_rewrite_min_size: 64 * 1024 * 1024,
            databases: 16,
            maxmemory: 0,
            query_buffer_idle_resize_after_ms: 2000,
            maxmemory_policy: "noeviction".into(),
            maxmemory_samples: 5,
            lfu_log_factor: 10,
            key_access_tracking: false,
            lfu_decay_time: 1,
            activedefrag: true,
            active_defrag_ignore_bytes: 64 << 20,
            active_defrag_threshold_lower: 20,
            active_defrag_cycle_max: 10,
            dir: String::new(),
            loglevel: "info".into(),
            logfile: String::new(),
            log_format: "text".into(),
            io_model: IoModel::default(),
            replicaof: None,
            replica_announced_port: 0,
            replica_priority: 100,
            replica_announced: true,
            requirepass: "".into(),
            aclfile: "".into(),
            slowlog_log_slower_than: u64::MAX,
            slowlog_max_len: 128,
            acllog_max_len: 128,
            cluster_enabled: false,
            cluster_node_timeout: 15000,
            configfile: "/etc/kividb/kividb.conf".into(),
            tls_port: 0,
            tls_cert_file: "".into(),
            tls_key_file: "".into(),
            tls_ca_cert_file: "".into(),
            tls_auth_clients: "yes".into(),
            tls_auth_clients_allowed_names: String::new(),
            tls_cluster: false,
            tls_replication: false,
            tls_client_cert_file: String::new(),
            tls_client_key_file: String::new(),
            update_check: true,
            update_check_url: crate::update_check::DEFAULT_URL.into(),
            notify_keyspace_events: String::new(),
            repl_replica_max_backlog_bytes: 268_435_456,
            repl_replica_sync_max_backlog_bytes: 1_073_741_824,
            repl_backlog_size: 64 * 1024 * 1024,
            repl_backlog_ttl: 3600,
            repl_diskless_load: "disabled".into(),
            masterauth: String::new(),
            masteruser: String::new(),
            repl_timeout: 60,
            shutdown_timeout: 10,
            min_replicas_to_write: 0,
            min_replicas_max_lag: 10,
            repl_ping_replica_period: 10,
            replica_full_sync_guard: "empty".into(),
            replica_full_sync_guard_ratio: 50,
            cluster_announce_ip: String::new(),
            cluster_announce_hostname: String::new(),
            cluster_preferred_endpoint_type: "ip".into(),
            cluster_announce_port: 0,
            cluster_announce_client_port: 0,
            cluster_announce_bus_port: 0,
            cluster_bus_port_protected_mode: false,
            protected_mode: true,
            bind_explicit: false,
            configfile_loaded: false,
            cluster_bus_secret: String::new(),
            cluster_config_file: "nodes.conf".into(),
            cluster_require_full_coverage: true,
            cluster_replica_validity_factor: 10,
            slowlog_entry_max_argc: 32,
            slowlog_entry_max_string_len: 128,
            stream_idmp_duration: 100,
            stream_idmp_maxsize: 100,
            backupdirname: "backupdir".into(),
            backup_sealed_ttl: 0,
            preload_file: String::new(),
            cluster_slot_migration_handoff_max_lag_bytes: 1024 * 1024,
            cluster_slot_migration_write_pause_timeout: 10_000,
            hll_write_format: "legacy".into(),
            appendfsync: "everysec".into(),
        }
    }
}

impl Config {
    pub fn resolve_threads(&self) -> usize {
        if self.threads > 0 {
            return self.threads;
        }
        std::thread::available_parallelism()
            .map(|n| if n.get() < 4 { n.get() } else { n.get() - 2 })
            .unwrap_or(12)
    }

    pub fn addr(&self) -> String {
        format!("{}:{}", self.bind, self.port)
    }

    /// Returns (host, port) if this instance should run as a replica.
    pub fn replicaof_addr(&self) -> Option<(String, u16)> {
        self.replicaof.as_ref().and_then(|parts| {
            if parts.len() == 2 {
                parts[1]
                    .parse::<u16>()
                    .ok()
                    .map(|port| (parts[0].clone(), port))
            } else {
                None
            }
        })
    }

    /// Returns a minimal Config suitable for use inside the replica
    /// command applier — only the fields that execute_command reads.
    pub fn default_replica() -> Self {
        Self {
            port: 0,
            bind: String::new(),
            threads: 1,
            aof: false,
            aof_preamble: true,
            lua_parallel_scripts: true,
            aof_rewrite_percentage: 100,
            aof_rewrite_min_size: 64 * 1024 * 1024,
            databases: 16,
            maxmemory: 0,
            query_buffer_idle_resize_after_ms: 2000,
            maxmemory_policy: "noeviction".into(),
            maxmemory_samples: 5,
            lfu_log_factor: 10,
            key_access_tracking: false,
            lfu_decay_time: 1,
            activedefrag: true,
            active_defrag_ignore_bytes: 64 << 20,
            active_defrag_threshold_lower: 20,
            active_defrag_cycle_max: 10,
            dir: String::new(),
            loglevel: "warn".into(),
            logfile: String::new(),
            log_format: "text".into(),
            io_model: IoModel::Tokio,
            replicaof: None,
            replica_announced_port: 0,
            replica_priority: 100,
            replica_announced: true,
            requirepass: "".to_string(),
            aclfile: "".to_string(),
            slowlog_log_slower_than: 10_000,
            slowlog_max_len: 128,
            acllog_max_len: 128,
            cluster_enabled: false,
            cluster_node_timeout: 15000,
            configfile: "./kividb.conf".to_string(),
            tls_port: 0,
            tls_cert_file: String::new(),
            tls_key_file: String::new(),
            tls_ca_cert_file: String::new(),
            tls_auth_clients: "yes".into(),
            tls_auth_clients_allowed_names: String::new(),
            tls_cluster: false,
            tls_replication: false,
            tls_client_cert_file: String::new(),
            tls_client_key_file: String::new(),
            update_check: false,
            update_check_url: crate::update_check::DEFAULT_URL.into(),
            notify_keyspace_events: String::new(),
            repl_replica_max_backlog_bytes: 268_435_456,
            repl_replica_sync_max_backlog_bytes: 1_073_741_824,
            repl_backlog_size: 64 * 1024 * 1024,
            repl_backlog_ttl: 3600,
            repl_diskless_load: "disabled".into(),
            masterauth: String::new(),
            masteruser: String::new(),
            repl_timeout: 60,
            shutdown_timeout: 10,
            min_replicas_to_write: 0,
            min_replicas_max_lag: 10,
            repl_ping_replica_period: 10,
            replica_full_sync_guard: "empty".into(),
            replica_full_sync_guard_ratio: 50,
            cluster_announce_ip: String::new(),
            cluster_announce_hostname: String::new(),
            cluster_preferred_endpoint_type: "ip".into(),
            cluster_announce_port: 0,
            cluster_announce_client_port: 0,
            cluster_announce_bus_port: 0,
            cluster_bus_port_protected_mode: false,
            protected_mode: true,
            bind_explicit: false,
            configfile_loaded: false,
            cluster_bus_secret: String::new(),
            cluster_config_file: "nodes.conf".into(),
            cluster_require_full_coverage: true,
            cluster_replica_validity_factor: 10,
            slowlog_entry_max_argc: 32,
            slowlog_entry_max_string_len: 128,
            stream_idmp_duration: 100,
            stream_idmp_maxsize: 100,
            backupdirname: "backupdir".into(),
            backup_sealed_ttl: 0,
            preload_file: String::new(),
            cluster_slot_migration_handoff_max_lag_bytes: 1024 * 1024,
            cluster_slot_migration_write_pause_timeout: 10_000,
            hll_write_format: "legacy".into(),
            appendfsync: "everysec".into(),
        }
    }

    /// Reject configurations that would start a server doing something other
    /// than what was asked for. `Err` is the message to print before exiting;
    /// `Ok` carries warnings to log.
    ///
    /// `tls_compiled` is whether this binary was built with the `tls` feature;
    /// it is a parameter so both outcomes are testable from one build.
    pub fn validate(&self, tls_compiled: bool) -> Result<Vec<String>, String> {
        let mut warnings = Vec::new();

        // Checked here too for `--databases 0`: the config file's directive
        // is checked as it is read, the command line's was not.
        if self.databases == 0 {
            return Err("'databases' must be at least 1".into());
        }

        if !self.update_check_url.starts_with("https://") {
            return Err(format!(
                "--update-check-url must be an https:// URL, not '{}'",
                self.update_check_url
            ));
        }

        // A build without the `tls` feature has no TLS listener at all. It used
        // to accept these flags and ignore them, so a node configured for TLS
        // came up serving plaintext with nothing in its log. `--tls-port` is
        // the flag that asks for a listener, so that one is fatal; a cert or
        // key on its own configures nothing and only earns a warning.
        if !tls_compiled {
            if self.tls_port > 0 {
                return Err(format!(
                    "--tls-port {} was given, but this binary was built without TLS support \
                     (the `tls` feature). It would serve plaintext only. Use a `-tls` build, \
                     or remove --tls-port to run without TLS.",
                    self.tls_port
                ));
            }
            if !self.tls_cert_file.is_empty()
                || !self.tls_key_file.is_empty()
                || !self.tls_ca_cert_file.is_empty()
            {
                warnings.push(
                    "TLS certificate/key options were given, but this binary was built \
                     without TLS support (the `tls` feature) — they are ignored"
                        .to_string(),
                );
            }
        } else if self.tls_port > 0 && !self.tls_enabled() {
            return Err(format!(
                "--tls-port {} requires both --tls-cert-file and --tls-key-file",
                self.tls_port
            ));
        }

        if !TLS_AUTH_CLIENTS.contains(&self.tls_auth_clients.as_str()) {
            return Err(format!(
                "invalid tls-auth-clients '{}' (expected yes, no or optional)",
                self.tls_auth_clients
            ));
        }

        if let Err(e) = allowed_names(&self.tls_auth_clients_allowed_names) {
            return Err(format!("invalid tls-auth-clients-allowed-names: {e}"));
        }
        if !self.tls_auth_clients_allowed_names.trim().is_empty()
            && (self.tls_ca_cert_file.is_empty() || self.tls_auth_clients == "no")
        {
            warnings.push(
                "tls-auth-clients-allowed-names has no effect: clients are asked for a \
                 certificate only with tls-ca-cert-file and tls-auth-clients yes or optional"
                    .to_string(),
            );
        }

        if self.tls_cluster || self.tls_replication {
            if !tls_compiled {
                return Err(
                    "tls-cluster and tls-replication need a build with TLS (the \
                            `tls` feature)"
                        .into(),
                );
            }
            if self.tls_cert_file.is_empty()
                || self.tls_key_file.is_empty()
                || self.tls_ca_cert_file.is_empty()
            {
                return Err("tls-cluster and tls-replication need tls-cert-file, \
                            tls-key-file and tls-ca-cert-file: nodes present their \
                            certificates to each other and check them against the CA"
                    .into());
            }
            if self.tls_client_cert_file.is_empty() != self.tls_client_key_file.is_empty() {
                return Err("tls-client-cert-file and tls-client-key-file go together".into());
            }
        }
        if self.tls_cluster && (!self.cluster_enabled || self.tls_port == 0) {
            return Err("tls-cluster needs cluster-enabled yes and a tls-port".into());
        }
        // Port 0 is no plaintext port, as in Redis; with no Unix socket here,
        // the TLS port is then the only one to reach the server on.
        if self.port == 0 {
            if self.tls_port == 0 {
                return Err(
                    "port 0 turns the plaintext port off, which leaves no port to \
                            reach this server on: set tls-port (with tls-cert-file and \
                            tls-key-file) to serve TLS only, or give port a number"
                        .into(),
                );
            }
            if self.cluster_enabled && !self.tls_cluster {
                return Err(
                    "port 0 on a cluster node needs tls-cluster yes: the node is \
                            then known to the cluster and its clients by its TLS port"
                        .into(),
                );
            }
        }

        match self.replica_full_sync_guard.as_str() {
            "off" | "empty" | "shrink" => {}
            other => {
                return Err(format!(
                    "invalid replica-full-sync-guard '{other}' (expected off, empty or shrink)"
                ));
            }
        }
        if self.replica_full_sync_guard_ratio > 100 {
            return Err("replica-full-sync-guard-ratio must be between 0 and 100".into());
        }
        if self.repl_timeout == 0 {
            return Err("repl-timeout must be at least 1 second".into());
        }
        if crate::eviction::Policy::parse(&self.maxmemory_policy).is_none() {
            return Err(format!(
                "invalid maxmemory-policy '{}' (expected one of: {})",
                self.maxmemory_policy,
                crate::eviction::POLICY_NAMES
            ));
        }
        if !(1..=64).contains(&self.maxmemory_samples) {
            return Err("maxmemory-samples must be between 1 and 64".into());
        }
        if crate::replication::flush_before_load(&self.repl_diskless_load).is_none() {
            return Err(format!(
                "invalid repl-diskless-load '{}' (expected disabled, on-empty-db, swapdb or \
                 flushdb)",
                self.repl_diskless_load
            ));
        }
        if !self.hll_write_format.eq_ignore_ascii_case("legacy")
            && !self.hll_write_format.eq_ignore_ascii_case("redis")
        {
            return Err(format!(
                "invalid hll-write-format '{}' (expected legacy or redis)",
                self.hll_write_format
            ));
        }
        if !matches!(
            self.appendfsync.to_ascii_lowercase().as_str(),
            "always" | "everysec" | "no"
        ) {
            return Err(format!(
                "invalid appendfsync '{}' (expected always, everysec or no)",
                self.appendfsync
            ));
        }

        if self.cluster_enabled {
            if self.replicaof.is_some() {
                return Err(
                    "replicaof directive not allowed in cluster mode — use CLUSTER REPLICATE"
                        .into(),
                );
            }
            if self.client_port() > u16::MAX - 10000 {
                return Err(format!(
                    "port {} leaves no room for the cluster bus port (port + 10000)",
                    self.client_port()
                ));
            }
            if self.cluster_bus_secret.is_empty() {
                if self.cluster_bus_port_protected_mode {
                    return Err(
                        "cluster-bus-port-protected-mode is yes, but the cluster bus is not \
                         authenticated: set cluster-bus-secret, the same on every node. \
                         Refusing to start a cluster node with an open bus port."
                            .into(),
                    );
                }
                warnings.push(format!(
                    "cluster bus port {} is not authenticated: any host that can reach it can \
                     join this cluster. Set cluster-bus-secret, or restrict the port to cluster \
                     members at the network layer.",
                    self.cluster_bus_port()
                ));
            }
        }
        Ok(warnings)
    }

    /// The port the cluster bus listens on: 10000 above the client port.
    pub fn cluster_bus_port(&self) -> u16 {
        self.client_port().saturating_add(10000)
    }

    /// The port the server started with for clients: `port`, or with port 0
    /// (no plaintext port) `tls-port`. Redis derives the bus port from the
    /// TLS port the same way when the node is reached over TLS.
    pub fn client_port(&self) -> u16 {
        if self.port == 0 {
            self.tls_port
        } else {
            self.port
        }
    }

    /// Returns true if TLS should be enabled.
    /// Requires tls_port > 0 AND both cert + key files configured.
    pub fn tls_enabled(&self) -> bool {
        self.tls_port > 0 && !self.tls_cert_file.is_empty() && !self.tls_key_file.is_empty()
    }

    /// This configuration with `values` applied over it: CONFIG GET's names
    /// and values, which are what is in effect now. CONFIG REWRITE writes
    /// that; it used to write the configuration the server started with,
    /// and lose whatever CONFIG SET had changed since. A value that does not
    /// read back as a directive leaves its setting as it was.
    pub fn with_values(&self, values: &[(String, String)]) -> Config {
        let mut config = self.clone();
        for (name, value) in values {
            if value == "**redacted**" {
                continue;
            }
            let args: Vec<String> = value.split_whitespace().map(String::from).collect();
            if args.is_empty() {
                continue;
            }
            let _ = config.apply_directive(&name.to_ascii_lowercase(), &args, &|_| false);
        }
        config
    }

    /// Write the current runtime config to `config_path`.
    ///
    /// Emits one `key value` pair per line in a format KiviDB can parse
    /// with `--key value` on restart. Comments are not preserved (that
    /// is a known limitation documented in COMMANDS.md).
    ///
    /// Refused, with nothing written, when the server was not started from
    /// a config file (see [`Config::configfile_loaded`]); an io::Error if
    /// the write fails.
    pub fn rewrite_to_disk(&self) -> Result<(), RewriteError> {
        if !self.configfile_loaded {
            return Err(RewriteError::NoConfigFile);
        }
        let path = std::path::Path::new(&self.configfile);

        let mut out = String::new();
        out.push_str(&format!("port {}\n", self.port));
        out.push_str(&format!("bind {}\n", self.bind));
        out.push_str(&format!(
            "protected-mode {}\n",
            if self.protected_mode { "yes" } else { "no" }
        ));
        out.push_str(&format!("threads {}\n", self.threads));
        out.push_str(&format!("aof {}\n", if self.aof { "yes" } else { "no" }));
        out.push_str(&format!(
            "aof-preamble {}\n",
            if self.aof_preamble { "yes" } else { "no" }
        ));
        out.push_str(&format!(
            "aof-rewrite-percentage {}\n",
            self.aof_rewrite_percentage
        ));
        out.push_str(&format!(
            "lua-parallel-scripts {}\n",
            if self.lua_parallel_scripts {
                "yes"
            } else {
                "no"
            }
        ));
        out.push_str(&format!(
            "aof-rewrite-min-size {}\n",
            self.aof_rewrite_min_size
        ));
        out.push_str(&format!("databases {}\n", self.databases));
        out.push_str(&format!("maxmemory {}\n", self.maxmemory));
        out.push_str(&format!("maxmemory-policy {}\n", self.maxmemory_policy));
        out.push_str(&format!("maxmemory-samples {}\n", self.maxmemory_samples));
        out.push_str(&format!("lfu-log-factor {}\n", self.lfu_log_factor));
        out.push_str(&format!("lfu-decay-time {}\n", self.lfu_decay_time));
        out.push_str(&format!(
            "activedefrag {}\n",
            if self.activedefrag { "yes" } else { "no" }
        ));
        out.push_str(&format!(
            "active-defrag-ignore-bytes {}\n",
            self.active_defrag_ignore_bytes
        ));
        out.push_str(&format!(
            "active-defrag-threshold-lower {}\n",
            self.active_defrag_threshold_lower
        ));
        out.push_str(&format!(
            "active-defrag-cycle-max {}\n",
            self.active_defrag_cycle_max
        ));
        out.push_str(&format!(
            "key-access-tracking {}\n",
            if self.key_access_tracking {
                "yes"
            } else {
                "no"
            }
        ));
        out.push_str(&format!("loglevel {}\n", self.loglevel));
        if !self.logfile.is_empty() {
            out.push_str(&format!("logfile {}\n", quote(&self.logfile)));
        }
        if self.log_format != "text" {
            out.push_str(&format!("log-format {}\n", self.log_format));
        }
        // A directive with nothing after it is an error when the file is
        // read back, so an unset option is left out.
        if !self.requirepass.is_empty() {
            out.push_str(&format!("requirepass {}\n", quote(&self.requirepass)));
        }
        if !self.aclfile.is_empty() {
            out.push_str(&format!("aclfile {}\n", quote(&self.aclfile)));
        }
        // Off is written -1, as it is set.
        match self.slowlog_log_slower_than {
            u64::MAX => out.push_str("slowlog-log-slower-than -1\n"),
            us => out.push_str(&format!("slowlog-log-slower-than {us}\n")),
        }
        out.push_str(&format!("slowlog-max-len {}\n", self.slowlog_max_len));
        out.push_str(&format!("acllog-max-len {}\n", self.acllog_max_len));
        out.push_str(&format!(
            "cluster-enabled {}\n",
            if self.cluster_enabled { "yes" } else { "no" }
        ));
        out.push_str(&format!(
            "cluster-node-timeout {}\n",
            self.cluster_node_timeout
        ));
        out.push_str(&format!(
            "repl-replica-max-backlog-bytes {}\n",
            self.repl_replica_max_backlog_bytes
        ));
        out.push_str(&format!(
            "repl-replica-sync-max-backlog-bytes {}\n",
            self.repl_replica_sync_max_backlog_bytes
        ));
        if !self.masterauth.is_empty() {
            out.push_str(&format!("masterauth {}\n", quote(&self.masterauth)));
        }
        if !self.masteruser.is_empty() {
            out.push_str(&format!("masteruser {}\n", self.masteruser));
        }
        if !self.update_check {
            out.push_str("update-check no\n");
        }
        if self.update_check_url != crate::update_check::DEFAULT_URL {
            out.push_str(&format!("update-check-url {}\n", self.update_check_url));
        }
        out.push_str(&format!("repl-backlog-size {}\n", self.repl_backlog_size));
        out.push_str(&format!("repl-backlog-ttl {}\n", self.repl_backlog_ttl));
        out.push_str(&format!("repl-diskless-load {}\n", self.repl_diskless_load));
        out.push_str(&format!("hll-write-format {}\n", self.hll_write_format));
        out.push_str(&format!("appendfsync {}\n", self.appendfsync));
        out.push_str(&format!("repl-timeout {}\n", self.repl_timeout));
        out.push_str(&format!("shutdown-timeout {}\n", self.shutdown_timeout));
        out.push_str(&format!("replica-priority {}\n", self.replica_priority));
        out.push_str(&format!(
            "replica-announced {}\n",
            if self.replica_announced { "yes" } else { "no" }
        ));
        out.push_str(&format!(
            "min-replicas-to-write {}\n",
            self.min_replicas_to_write
        ));
        out.push_str(&format!(
            "min-replicas-max-lag {}\n",
            self.min_replicas_max_lag
        ));
        out.push_str(&format!(
            "repl-ping-replica-period {}\n",
            self.repl_ping_replica_period
        ));
        out.push_str(&format!(
            "replica-full-sync-guard {}\n",
            self.replica_full_sync_guard
        ));
        out.push_str(&format!(
            "replica-full-sync-guard-ratio {}\n",
            self.replica_full_sync_guard_ratio
        ));
        if !self.cluster_announce_ip.is_empty() {
            out.push_str(&format!(
                "cluster-announce-ip {}\n",
                self.cluster_announce_ip
            ));
        }
        if !self.cluster_announce_hostname.is_empty() {
            out.push_str(&format!(
                "cluster-announce-hostname {}\n",
                self.cluster_announce_hostname
            ));
        }
        out.push_str(&format!(
            "cluster-preferred-endpoint-type {}\n",
            self.cluster_preferred_endpoint_type
        ));
        if self.cluster_announce_port != 0 {
            out.push_str(&format!(
                "cluster-announce-port {}\n",
                self.cluster_announce_port
            ));
        }
        if self.cluster_announce_client_port != 0 {
            out.push_str(&format!(
                "cluster-announce-client-port {}\n",
                self.cluster_announce_client_port
            ));
        }
        if self.cluster_announce_bus_port != 0 {
            out.push_str(&format!(
                "cluster-announce-bus-port {}\n",
                self.cluster_announce_bus_port
            ));
        }
        if !self.cluster_bus_secret.is_empty() {
            out.push_str(&format!("cluster-bus-secret {}\n", self.cluster_bus_secret));
        }
        out.push_str(&format!(
            "cluster-bus-port-protected-mode {}\n",
            if self.cluster_bus_port_protected_mode {
                "yes"
            } else {
                "no"
            }
        ));
        out.push_str(&format!(
            "cluster-config-file {}\n",
            self.cluster_config_file
        ));
        out.push_str(&format!(
            "cluster-replica-validity-factor {}\n",
            self.cluster_replica_validity_factor
        ));
        out.push_str(&format!(
            "cluster-require-full-coverage {}\n",
            if self.cluster_require_full_coverage {
                "yes"
            } else {
                "no"
            }
        ));
        out.push_str(&format!(
            "slowlog-entry-max-argc {}\n",
            self.slowlog_entry_max_argc
        ));
        out.push_str(&format!(
            "slowlog-entry-max-string-len {}\n",
            self.slowlog_entry_max_string_len
        ));
        out.push_str(&format!(
            "stream-idmp-duration {}\n",
            self.stream_idmp_duration
        ));
        out.push_str(&format!(
            "stream-idmp-maxsize {}\n",
            self.stream_idmp_maxsize
        ));
        out.push_str(&format!("backupdirname {}\n", self.backupdirname));
        out.push_str(&format!("backup-sealed-ttl {}\n", self.backup_sealed_ttl));
        out.push_str(&format!(
            "cluster-slot-migration-handoff-max-lag-bytes {}\n",
            self.cluster_slot_migration_handoff_max_lag_bytes
        ));
        out.push_str(&format!(
            "cluster-slot-migration-write-pause-timeout {}\n",
            self.cluster_slot_migration_write_pause_timeout
        ));
        out.push_str(&format!(
            "notify-keyspace-events {}\n",
            quote(&crate::keyspace_events::flags_to_string(
                crate::keyspace_events::KS_FLAGS.load(std::sync::atomic::Ordering::Relaxed)
            ))
        ));
        if let Some(parts) = &self.replicaof
            && parts.len() == 2
        {
            out.push_str(&format!("replicaof {} {}\n", parts[0], parts[1]));
        }

        // The new file keeps the old one's mode, and its owner where the
        // process may set it: a config kept private because it holds
        // `requirepass` must not become readable by every user (#51). With
        // no old file it is 0600. KiviDB differs from Redis on purpose here:
        // Redis 7.4 to 8.10 set every rewritten file to 0644 less the umask.
        let tmp = path.with_extension("tmp");
        // Whatever is at the temporary path already, a file left by a
        // rewrite that failed or a symlink another user put there, is
        // removed, not written through. Created anew (O_EXCL), the file
        // cannot be one that is already there: if another appears in
        // between, the rewrite fails rather than write into it.
        match std::fs::remove_file(&tmp) {
            Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
                return Err(RewriteError::Io(e));
            }
            _ => {}
        }
        let mut options = std::fs::OpenOptions::new();
        options.write(true).create_new(true);
        // Private from the start, so the contents are never readable by
        // others while they are written.
        #[cfg(unix)]
        std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
        let mut file = options.open(&tmp).map_err(RewriteError::Io)?;
        // Set, not just created with: the umask narrows the mode a file is
        // created with.
        #[cfg(unix)]
        {
            use std::os::unix::fs::{MetadataExt, PermissionsExt};
            match std::fs::metadata(path) {
                Ok(old) => {
                    file.set_permissions(old.permissions())
                        .map_err(RewriteError::Io)?;
                    // Only root may give a file away; for anyone else this
                    // fails, and the file stays the process's.
                    let _ = std::os::unix::fs::fchown(&file, Some(old.uid()), Some(old.gid()));
                }
                Err(_) => file
                    .set_permissions(std::fs::Permissions::from_mode(0o600))
                    .map_err(RewriteError::Io)?,
            }
        }
        std::io::Write::write_all(&mut file, out.as_bytes()).map_err(RewriteError::Io)?;
        drop(file);
        std::fs::rename(&tmp, path).map_err(RewriteError::Io)?;

        Ok(())
    }

    /// Load the config file and apply its directives.
    ///
    /// The precedence chain is: defaults < config file < CLI args.
    /// `from_cli` says whether an option (named as its field is) was given on
    /// the command line; a directive for such an option is still checked, and
    /// then left alone.
    ///
    /// `Ok` carries warnings to log. `Err` is the message to print before
    /// exiting: the file is read strictly. A directive that is not known, or a
    /// value that cannot be understood, used to be dropped without a word —
    /// `appendonly yes` did nothing, and the server ran without the
    /// durability its config file asked for.
    pub fn apply_config_file(
        &mut self,
        from_cli: &dyn Fn(&str) -> bool,
    ) -> Result<Vec<String>, String> {
        if self.configfile.is_empty() {
            return Ok(Vec::new());
        }
        let contents = match std::fs::read_to_string(&self.configfile) {
            Ok(s) => s,
            // No file: the server runs on its defaults and the command line,
            // and `CONFIG REWRITE` is refused.
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(e) => {
                return Err(format!("can't open config file '{}': {e}", self.configfile));
            }
        };
        self.configfile_loaded = true;
        let file = self.configfile.clone();
        self.apply_config_text(&contents, from_cli)
            .map(|warnings| {
                warnings
                    .into_iter()
                    .map(|w| format!("{file}: {w}"))
                    .collect()
            })
            .map_err(|e| format!("{file}: {e}"))
    }

    /// [`Config::apply_config_file`], given the text of the file.
    pub fn apply_config_text(
        &mut self,
        contents: &str,
        from_cli: &dyn Fn(&str) -> bool,
    ) -> Result<Vec<String>, String> {
        let mut warnings = Vec::new();
        for (index, line) in contents.lines().enumerate() {
            let number = index + 1;
            let words = split_config_line(line).map_err(|e| format!("line {number}: {e}"))?;
            let Some((key, args)) = words.split_first() else {
                continue;
            };
            let key = key.to_ascii_lowercase();
            match self.apply_directive(&key, args, from_cli) {
                Ok(Some(warning)) => warnings.push(format!("line {number}: {warning}")),
                Ok(None) => {}
                Err(e) => return Err(format!("line {number}: {e} (in: {})", line.trim())),
            }
        }
        Ok(warnings)
    }

    /// Apply one directive. `Ok(Some(_))` is a warning about it.
    fn apply_directive(
        &mut self,
        key: &str,
        args: &[String],
        from_cli: &dyn Fn(&str) -> bool,
    ) -> Result<Option<String>, String> {
        // The single value of a directive that takes one.
        let one = || -> Result<&str, String> {
            match args {
                [value] => Ok(value.as_str()),
                [] => Err(format!("'{key}' needs a value")),
                _ => Err(format!(
                    "'{key}' takes one value, {} were given",
                    args.len()
                )),
            }
        };
        fn number<T: std::str::FromStr>(key: &str, value: &str) -> Result<T, String> {
            value
                .parse()
                .map_err(|_| format!("invalid value '{value}' for '{key}': not a number in range"))
        }
        fn yes_no(key: &str, value: &str) -> Result<bool, String> {
            parse_yes_no(value).map_err(|_| {
                format!("invalid value '{value}' for '{key}': argument must be 'yes' or 'no'")
            })
        }
        // Checked and, unless the command line already said otherwise, stored.
        macro_rules! set {
            ($field:ident, $value:expr) => {{
                let value = $value;
                if !from_cli(stringify!($field)) {
                    self.$field = value;
                }
            }};
        }
        let no_effect = |why: &str| {
            Ok(Some(format!(
                "'{key}' is accepted but has no effect: {why}"
            )))
        };

        match key {
            "port" => set!(port, number(key, one()?)?),
            "bind" => {
                let Some(first) = args.first() else {
                    return Err("'bind' needs an address".into());
                };
                self.bind_explicit = true;
                set!(bind, first.trim_start_matches('-').to_string());
                if args.len() > 1 {
                    return Ok(Some(format!(
                        "'bind' lists {} addresses; KiviDB listens on one, and uses '{}'",
                        args.len(),
                        self.bind
                    )));
                }
            }
            "threads" => set!(threads, number(key, one()?)?),
            "dir" => set!(dir, one()?.to_string()),
            "aof" | "appendonly" => set!(aof, yes_no(key, one()?)?),
            "aof-preamble" | "aof-use-rdb-preamble" => set!(aof_preamble, yes_no(key, one()?)?),
            "hll-write-format" => {
                let value = match one()?.to_ascii_lowercase().as_str() {
                    value @ ("legacy" | "redis") => value.to_string(),
                    other => {
                        return Err(format!(
                            "invalid value '{other}' for 'hll-write-format': expected legacy or redis"
                        ));
                    }
                };
                set!(hll_write_format, value)
            }
            "lua-parallel-scripts" => set!(lua_parallel_scripts, yes_no(key, one()?)?),
            "aof-rewrite-percentage" | "auto-aof-rewrite-percentage" => {
                set!(aof_rewrite_percentage, number(key, one()?)?)
            }
            "aof-rewrite-min-size" | "auto-aof-rewrite-min-size" => {
                set!(aof_rewrite_min_size, parse_memory(key, one()?)?)
            }
            "databases" => {
                let n: usize = number(key, one()?)?;
                if n == 0 {
                    return Err("'databases' must be at least 1".into());
                }
                set!(databases, n)
            }
            "maxmemory" => set!(maxmemory, parse_memory(key, one()?)? as usize),
            "loglevel" => {
                let level = match one()?.to_ascii_lowercase().as_str() {
                    level @ ("debug" | "verbose" | "notice" | "info" | "warn" | "warning"
                    | "nothing" | "error") => level.to_string(),
                    other => {
                        return Err(format!(
                            "invalid value '{other}' for 'loglevel': expected debug, verbose, \
                             notice, warning or nothing"
                        ));
                    }
                };
                set!(loglevel, level)
            }
            "io-model" => {
                let model = match one()?.to_ascii_lowercase().as_str() {
                    "auto" => IoModel::Auto,
                    "uring" => IoModel::Uring,
                    "tokio" => IoModel::Tokio,
                    other => {
                        return Err(format!(
                            "invalid value '{other}' for 'io-model': expected auto, uring or tokio"
                        ));
                    }
                };
                set!(io_model, model)
            }
            "requirepass" => set!(requirepass, one()?.to_string()),
            "aclfile" => set!(aclfile, one()?.to_string()),
            "slowlog-log-slower-than" => {
                // A negative value turns the slow log off.
                let us: i64 = number(key, one()?)?;
                set!(
                    slowlog_log_slower_than,
                    u64::try_from(us).unwrap_or(u64::MAX)
                )
            }
            "slowlog-max-len" => set!(slowlog_max_len, number(key, one()?)?),
            "acllog-max-len" => set!(acllog_max_len, number(key, one()?)?),
            "slowlog-entry-max-argc" => set!(slowlog_entry_max_argc, number(key, one()?)?),
            "slowlog-entry-max-string-len" => {
                set!(slowlog_entry_max_string_len, number(key, one()?)?)
            }
            "cluster-enabled" => set!(cluster_enabled, yes_no(key, one()?)?),
            "update-check" => set!(update_check, yes_no(key, one()?)?),
            "update-check-url" => {
                let url = one()?;
                if !url.starts_with("https://") {
                    return Err(format!(
                        "'update-check-url' must be an https:// URL, not '{url}'"
                    ));
                }
                set!(update_check_url, url.to_string())
            }
            "cluster-node-timeout" => set!(cluster_node_timeout, number(key, one()?)?),
            "cluster-announce-ip" => set!(cluster_announce_ip, one()?.to_string()),
            "cluster-announce-hostname" => {
                let name = one()?;
                if !crate::cluster::valid_hostname(name) {
                    return Err(format!(
                        "'cluster-announce-hostname' may only have letters, digits, '-' and \
                         '.', not '{name}'"
                    ));
                }
                set!(cluster_announce_hostname, name.to_string())
            }
            "cluster-preferred-endpoint-type" => {
                let kind = one()?;
                if crate::cluster::Endpoint::parse(kind).is_none() {
                    return Err(format!(
                        "'cluster-preferred-endpoint-type' must be ip, hostname or \
                         unknown-endpoint, not '{kind}'"
                    ));
                }
                set!(cluster_preferred_endpoint_type, kind.to_ascii_lowercase())
            }
            "cluster-announce-port" => set!(cluster_announce_port, number(key, one()?)?),
            "cluster-announce-client-port" => {
                set!(cluster_announce_client_port, number(key, one()?)?)
            }
            "cluster-announce-bus-port" => set!(cluster_announce_bus_port, number(key, one()?)?),
            "cluster-bus-secret" => set!(cluster_bus_secret, one()?.to_string()),
            "cluster-bus-port-protected-mode" => {
                set!(cluster_bus_port_protected_mode, yes_no(key, one()?)?)
            }
            "cluster-config-file" => set!(cluster_config_file, one()?.to_string()),
            "cluster-require-full-coverage" => {
                set!(cluster_require_full_coverage, yes_no(key, one()?)?)
            }
            "cluster-replica-validity-factor" => {
                set!(cluster_replica_validity_factor, number(key, one()?)?)
            }
            "cluster-slot-migration-handoff-max-lag-bytes" => set!(
                cluster_slot_migration_handoff_max_lag_bytes,
                parse_memory(key, one()?)?
            ),
            "cluster-slot-migration-write-pause-timeout" => set!(
                cluster_slot_migration_write_pause_timeout,
                number(key, one()?)?
            ),
            "repl-replica-max-backlog-bytes" => {
                set!(repl_replica_max_backlog_bytes, parse_memory(key, one()?)?)
            }
            "repl-replica-sync-max-backlog-bytes" => {
                set!(
                    repl_replica_sync_max_backlog_bytes,
                    parse_memory(key, one()?)?
                )
            }
            "repl-backlog-size" => set!(repl_backlog_size, parse_memory(key, one()?)?),
            "repl-backlog-ttl" => set!(repl_backlog_ttl, number(key, one()?)?),
            "repl-diskless-load" => {
                let value = one()?.to_ascii_lowercase();
                if crate::replication::flush_before_load(&value).is_none() {
                    return Err(format!(
                        "invalid value '{value}' for 'repl-diskless-load': expected disabled, \
                         on-empty-db, swapdb or flushdb"
                    ));
                }
                set!(repl_diskless_load, value)
            }
            "masterauth" | "primaryauth" => set!(masterauth, one()?.to_string()),
            "masteruser" | "primaryuser" => set!(masteruser, one()?.to_string()),
            "repl-timeout" => set!(repl_timeout, number(key, one()?)?),
            "shutdown-timeout" => set!(shutdown_timeout, number(key, one()?)?),
            "min-replicas-to-write" | "min-slaves-to-write" => {
                set!(min_replicas_to_write, number(key, one()?)?)
            }
            "min-replicas-max-lag" | "min-slaves-max-lag" => {
                set!(min_replicas_max_lag, number(key, one()?)?)
            }
            "repl-ping-replica-period" | "repl-ping-slave-period" => {
                set!(repl_ping_replica_period, number(key, one()?)?)
            }
            "replica-full-sync-guard" => {
                set!(replica_full_sync_guard, one()?.to_ascii_lowercase())
            }
            "replica-full-sync-guard-ratio" => {
                set!(replica_full_sync_guard_ratio, number(key, one()?)?)
            }
            "replica-announced-port" | "replica-announce-port" | "slave-announce-port" => {
                set!(replica_announced_port, number(key, one()?)?)
            }
            "replica-priority" | "slave-priority" => {
                let priority: u32 = number(key, one()?)?;
                if priority > i32::MAX as u32 {
                    return Err(format!(
                        "invalid value '{priority}' for '{key}': argument must be between 0 \
                         and 2147483647 inclusive"
                    ));
                }
                set!(replica_priority, priority)
            }
            "replica-announced" => set!(replica_announced, yes_no(key, one()?)?),
            "replicaof" | "slaveof" => match args {
                [host, port] => {
                    let _: u16 = number(key, port)?;
                    set!(replicaof, Some(vec![host.clone(), port.clone()]))
                }
                _ => return Err(format!("'{key}' takes a host and a port")),
            },
            "stream-idmp-duration" => set!(stream_idmp_duration, number(key, one()?)?),
            "stream-idmp-maxsize" => set!(stream_idmp_maxsize, number(key, one()?)?),
            "backupdirname" => {
                let name = one()?;
                if name.is_empty() {
                    return Err("'backupdirname' cannot be empty".into());
                }
                set!(backupdirname, name.to_string())
            }
            "backup-sealed-ttl" => set!(backup_sealed_ttl, number(key, one()?)?),
            "preload-file" => set!(preload_file, one()?.to_string()),
            "tls-port" => set!(tls_port, number(key, one()?)?),
            "tls-cert-file" => set!(tls_cert_file, one()?.to_string()),
            "tls-key-file" => set!(tls_key_file, one()?.to_string()),
            "tls-ca-cert-file" => set!(tls_ca_cert_file, one()?.to_string()),
            "protected-mode" => set!(protected_mode, yes_no(key, one()?)?),
            "tls-cluster" => set!(tls_cluster, yes_no(key, one()?)?),
            "tls-replication" => set!(tls_replication, yes_no(key, one()?)?),
            "tls-client-cert-file" => set!(tls_client_cert_file, one()?.to_string()),
            "tls-client-key-file" => set!(tls_client_key_file, one()?.to_string()),
            // A list: one word or several, as `bind`.
            "tls-auth-clients-allowed-names" => {
                let names = allowed_names(&args.join(" "))
                    .map_err(|e| format!("invalid value for '{key}': {e}"))?;
                set!(tls_auth_clients_allowed_names, names.join(" "))
            }
            "tls-auth-clients" => {
                let value = one()?.to_ascii_lowercase();
                if !TLS_AUTH_CLIENTS.contains(&value.as_str()) {
                    return Err(format!(
                        "invalid value '{value}' for 'tls-auth-clients': expected yes, no or \
                         optional"
                    ));
                }
                set!(tls_auth_clients, value)
            }
            "notify-keyspace-events" => {
                let flags = one()?;
                if crate::keyspace_events::parse_ks_flags_strict(flags).is_none() {
                    return Err(format!(
                        "invalid value '{flags}' for 'notify-keyspace-events': {}",
                        crate::keyspace_events::BAD_FLAGS
                    ));
                }
                set!(notify_keyspace_events, flags.to_string())
            }

            // ── Redis directives that name something KiviDB has one way of
            // doing. The value KiviDB already behaves as is accepted quietly;
            // any other would be a promise it does not keep.
            "appendfilename" => {
                if one()? != crate::aof::AOF_PATH {
                    return Err(format!(
                        "'appendfilename' cannot be changed: the append-only file is always \
                         '{}'",
                        crate::aof::AOF_PATH
                    ));
                }
            }
            "dbfilename" => {
                if !matches!(one()?, "dump.kdb" | "dump.rdb") {
                    return Err(
                        "'dbfilename' cannot be changed: the snapshot is always 'dump.kdb'".into(),
                    );
                }
            }
            "daemonize" => {
                if yes_no(key, one()?)? {
                    return Err(
                        "'daemonize yes' is not supported: KiviDB runs in the foreground".into(),
                    );
                }
            }
            // When the AOF is synced (#513). It used to be read and warned
            // about, and the file synced once a second whatever it said.
            "appendfsync" => {
                let value = one()?.to_ascii_lowercase();
                if !matches!(value.as_str(), "always" | "everysec" | "no") {
                    return Err(format!(
                        "invalid value '{value}' for 'appendfsync': expected always, everysec \
                         or no"
                    ));
                }
                let no = value == "no";
                set!(appendfsync, value);
                if no {
                    return Ok(Some(
                        "'appendfsync no' syncs the append-only file once a second, as \
                         'everysec' does"
                            .into(),
                    ));
                }
            }
            "save" => {
                if args.iter().any(|a| !a.is_empty()) {
                    return no_effect(
                        "KiviDB does not snapshot on a schedule — use `appendonly yes`, or \
                         BGSAVE",
                    );
                }
            }
            "replica-read-only" | "slave-read-only" => {
                if !yes_no(key, one()?)? {
                    return no_effect("a replica is always read-only");
                }
            }
            "aof-load-truncated" => {
                if !yes_no(key, one()?)? {
                    return no_effect("a truncated append-only file is always loaded");
                }
            }
            "logfile" => set!(logfile, one()?.to_string()),
            "log-format" => {
                let format = one()?.to_ascii_lowercase();
                if format != "text" && format != "json" {
                    return Err(format!(
                        "invalid value '{format}' for 'log-format': expected text or json"
                    ));
                }
                set!(log_format, format)
            }
            "pidfile" | "unixsocket" => {
                if !one()?.is_empty() {
                    return no_effect("not supported");
                }
            }
            "maxmemory-policy" => {
                let value = one()?.to_ascii_lowercase();
                if crate::eviction::Policy::parse(&value).is_none() {
                    return Err(format!(
                        "invalid value '{value}' for 'maxmemory-policy': expected one of {}",
                        crate::eviction::POLICY_NAMES
                    ));
                }
                set!(maxmemory_policy, value)
            }
            "maxmemory-samples" => {
                let n: usize = number(key, one()?)?;
                if !(1..=64).contains(&n) {
                    return Err("'maxmemory-samples' must be between 1 and 64".into());
                }
                set!(maxmemory_samples, n)
            }
            "lfu-log-factor" => set!(lfu_log_factor, number(key, one()?)?),
            "lfu-decay-time" => set!(lfu_decay_time, number(key, one()?)?),
            "activedefrag" => set!(activedefrag, yes_no(key, one()?)?),
            "active-defrag-ignore-bytes" => {
                set!(active_defrag_ignore_bytes, parse_memory(key, one()?)?)
            }
            "active-defrag-threshold-lower" => {
                set!(active_defrag_threshold_lower, number(key, one()?)?)
            }
            "active-defrag-cycle-max" => set!(active_defrag_cycle_max, number(key, one()?)?),
            "key-access-tracking" => set!(key_access_tracking, yes_no(key, one()?)?),
            "tracking-table-max-keys" => crate::tracking::DEFAULT_MAX_KEYS
                .store(number(key, one()?)?, std::sync::atomic::Ordering::Relaxed),
            // Tuning knobs for machinery KiviDB does not have, or does not
            // expose. They change nothing a client could observe.
            "activerehashing"
            | "always-show-logo"
            | "appenddirname"
            | "dynamic-hz"
            | "hz"
            | "io-threads"
            | "io-threads-do-reads"
            | "lazyfree-lazy-eviction"
            | "lazyfree-lazy-server-del"
            | "lazyfree-lazy-user-del"
            | "no-appendfsync-on-rewrite"
            | "proc-title-template"
            | "rdbcompression"
            | "repl-disable-tcp-nodelay"
            | "repl-diskless-sync"
            | "repl-diskless-sync-delay"
            | "replica-serve-stale-data"
            | "set-proc-title"
            | "stop-writes-on-bgsave-error"
            | "supervised"
            | "tcp-backlog"
            | "tcp-keepalive"
            | "timeout" => {
                if args.is_empty() {
                    return Err(format!("'{key}' needs a value"));
                }
                // For `CONFIG GET`, as `CONFIG SET` remembers it, and
                // checked as it checks it.
                let value = args.join(" ");
                if let Some(reply) = crate::commands::server::config_set_global(key, &value)
                    && reply.starts_with(b"-")
                {
                    return Err(refused(key, &value, &reply));
                }
                return no_effect("KiviDB has no such setting");
            }

            // A setting `CONFIG SET` takes that is the server's as a whole
            // (`array-slice-size`, `busy-reply-threshold`, ...): set, and
            // checked, as `CONFIG SET` sets it. One of Redis's that KiviDB has
            // no use for (`hash-max-listpack-entries`, ...) is remembered, as
            // `CONFIG SET` remembers it, so that a redis.conf carried over
            // starts (#142).
            _ => {
                if args.is_empty() {
                    return Err(format!("'{key}' needs a value"));
                }
                let value = args.join(" ");
                match crate::commands::server::config_set_global(key, &value) {
                    Some(reply) if reply.starts_with(b"-") => {
                        return Err(refused(key, &value, &reply));
                    }
                    // Remembered for `CONFIG GET`, and in effect too. These
                    // were in effect from a config file, but it warned that
                    // they had no effect (#232).
                    Some(_)
                        if matches!(
                            key,
                            "latency-monitor-threshold"
                                | "ts-duplicate-policy"
                                | "aof-ack-after-write"
                                | "maxclients"
                                | "lazyfree-lazy-expire"
                                | "latency-tracking"
                                | "latency-tracking-info-percentiles"
                                | "rdbchecksum"
                        ) || crate::commands::server::remembered_config(key).is_none() => {}
                    Some(_) => return no_effect("KiviDB has no such setting"),
                    None if key.starts_with("cluster-")
                        || !crate::redis_settings::is_redis_setting(key) =>
                    {
                        return Err(format!("unknown directive '{key}'"));
                    }
                    None => {
                        crate::commands::server::remember_config(key, &value);
                        return no_effect("KiviDB has no such setting");
                    }
                }
            }
        }
        Ok(None)
    }
}

/// Split a config line into words. A word may be quoted — `"…"`, with `\"`,
/// `\\`, `\n`, `\r` and `\t` — or `'…'`; a `#` where a word would start
/// begins a comment.
/// What a config file is told of a value `CONFIG SET` refused with `reply`.
fn refused(key: &str, value: &str, reply: &[u8]) -> String {
    let why = String::from_utf8_lossy(&reply[1..]);
    let why = why.trim_end();
    let why = why.strip_prefix("ERR ").unwrap_or(why);
    format!("invalid value '{value}' for '{key}': {why}")
}

fn split_config_line(line: &str) -> Result<Vec<String>, String> {
    let mut words = Vec::new();
    let mut chars = line.chars().peekable();
    loop {
        while chars.next_if(|c| c.is_whitespace()).is_some() {}
        let Some(&first) = chars.peek() else { break };
        if first == '#' {
            break;
        }
        let mut word = String::new();
        if first == '"' || first == '\'' {
            chars.next();
            let mut closed = false;
            while let Some(c) = chars.next() {
                if c == first {
                    closed = true;
                    break;
                }
                if c == '\\' && first == '"' {
                    match chars.next() {
                        Some('n') => word.push('\n'),
                        Some('r') => word.push('\r'),
                        Some('t') => word.push('\t'),
                        Some(other) => word.push(other),
                        None => break,
                    }
                } else {
                    word.push(c);
                }
            }
            if !closed {
                return Err("unbalanced quotes".into());
            }
            if chars.peek().is_some_and(|c| !c.is_whitespace()) {
                return Err("a closing quote must be followed by a space".into());
            }
        } else {
            while let Some(c) = chars.next_if(|c| !c.is_whitespace()) {
                word.push(c);
            }
        }
        words.push(word);
    }
    Ok(words)
}

/// A value as [`split_config_line`] reads it back: quoted if it has to be.
fn quote(value: &str) -> String {
    if !value.is_empty()
        && !value.starts_with(['#', '"', '\''])
        && !value.contains(|c: char| c.is_whitespace() || c == '\\')
    {
        return value.to_string();
    }
    let mut out = String::from("\"");
    for c in value.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            other => out.push(other),
        }
    }
    out.push('"');
    out
}

/// A size as Redis config files write them: `1048576`, `1mb`, `512k`, `2GB`.
/// `k`, `m` and `g` are powers of 1000; `kb`, `mb` and `gb` powers of 1024.
pub(crate) fn parse_memory(key: &str, value: &str) -> Result<u64, String> {
    let lower = value.to_ascii_lowercase();
    let digits = lower.trim_end_matches(|c: char| c.is_ascii_alphabetic());
    let unit: u64 = match &lower[digits.len()..] {
        "" | "b" => 1,
        "k" => 1000,
        "kb" => 1024,
        "m" => 1000 * 1000,
        "mb" => 1024 * 1024,
        "g" => 1000 * 1000 * 1000,
        "gb" => 1024 * 1024 * 1024,
        _ => {
            return Err(format!(
                "invalid value '{value}' for '{key}': not a memory size"
            ));
        }
    };
    digits
        .parse::<u64>()
        .ok()
        .and_then(|n| n.checked_mul(unit))
        .ok_or_else(|| format!("invalid value '{value}' for '{key}': not a memory size"))
}

/// [`parse_memory`] for a command-line flag, which Redis takes with units too
/// (`--maxmemory 3gb`).
fn parse_memory_flag(value: &str) -> Result<usize, String> {
    parse_memory("--maxmemory", value)
        .and_then(|n| usize::try_from(n).map_err(|_| format!("invalid value '{value}': too large")))
}

/// Parse Redis-style `yes` / `no` into a bool. Used by `--cluster-enabled`
/// and any future flags that want to mirror redis.conf phrasing rather than
/// clap's default `true` / `false`.
fn parse_yes_no(s: &str) -> Result<bool, String> {
    match s.to_ascii_lowercase().as_str() {
        "yes" | "true" | "1" => Ok(true),
        "no" | "false" | "0" => Ok(false),
        other => Err(format!("expected 'yes' or 'no', got '{other}'")),
    }
}

/// Error returned by `Config::rewrite_to_disk`.
pub enum RewriteError {
    /// The server was not started from a config file: there is none to
    /// rewrite.
    NoConfigFile,
    Io(std::io::Error),
}

#[cfg(test)]
mod config_file_tests {
    use super::*;

    fn load(text: &str) -> Result<(Config, Vec<String>), String> {
        let mut config = Config::default();
        let warnings = config.apply_config_text(text, &|_| false)?;
        Ok((config, warnings))
    }

    #[test]
    fn tls_auth_clients_takes_yes_no_or_optional() {
        assert_eq!(Config::default().tls_auth_clients, "yes");
        let (c, _) = load("tls-auth-clients OPTIONAL\n").unwrap();
        assert_eq!(c.tls_auth_clients, "optional");
        let err = load("tls-auth-clients maybe\n").unwrap_err();
        assert!(err.contains("tls-auth-clients"), "{err}");
    }

    #[test]
    fn maxmemory_on_the_command_line_takes_units_as_in_redis() {
        use clap::Parser;
        let at =
            |v: &str| Config::try_parse_from(["kividb", "--maxmemory", v]).map(|c| c.maxmemory);
        assert_eq!(at("3gb").unwrap(), 3 * 1024 * 1024 * 1024);
        assert_eq!(at("512mb").unwrap(), 512 * 1024 * 1024);
        assert_eq!(at("1000").unwrap(), 1000);
        assert!(at("lots").is_err());
    }

    #[test]
    fn hll_write_format_cli_option_is_validated() {
        use clap::Parser;
        let config = Config::try_parse_from(["kividb", "--hll-write-format", "redis"]).unwrap();
        assert_eq!(config.hll_write_format, "redis");
        assert!(config.validate(false).is_ok());

        let invalid = Config::try_parse_from(["kividb", "--hll-write-format", "invalid"]).unwrap();
        assert!(
            invalid
                .validate(false)
                .unwrap_err()
                .contains("hll-write-format")
        );
    }

    #[test]
    fn protected_mode_is_on_until_turned_off_or_a_bind_address_is_given() {
        let c = Config::default();
        assert!(c.protected_mode && !c.bind_explicit);
        assert!(!load("protected-mode no\n").unwrap().0.protected_mode);
        assert!(load("protected-mode yes\n").unwrap().0.protected_mode);
        assert!(load("protected-mode maybe\n").is_err());
        assert!(load("bind 0.0.0.0\n").unwrap().0.bind_explicit);
    }

    /// `appendonly`, Redis's spelling of the AOF switch, must work in a config file.
    #[test]
    fn the_redis_spelling_of_the_aof_switch_is_understood() {
        assert!(load("appendonly yes\n").unwrap().0.aof);
        assert!(load("aof yes\n").unwrap().0.aof);
        assert!(!load("appendonly no\n").unwrap().0.aof);
    }

    #[test]
    fn an_unknown_directive_is_an_error_that_names_its_line() {
        let err = load("port 7000\n\n# comment\nthis-directive-does-not-exist 42\n").unwrap_err();
        assert!(err.contains("line 4"), "{err}");
        assert!(
            err.contains("unknown directive 'this-directive-does-not-exist'"),
            "{err}"
        );
    }

    #[test]
    fn a_value_that_cannot_be_understood_is_an_error() {
        for bad in [
            "maxmemory notanumber",
            "port seventy",
            "port 70000",
            "appendonly maybe",
            "databases 0",
            "loglevel shouting",
            "replicaof onlyhost",
            "port",
            "port 1 2",
            "requirepass \"unterminated",
            "maxmemory-policy allkeys-mru",
            "maxmemory-samples 0",
            "daemonize yes",
            "dbfilename other.rdb",
        ] {
            let err = load(bad).unwrap_err();
            assert!(err.starts_with("line 1: "), "{bad}: {err}");
        }
    }

    #[test]
    fn memory_sizes_take_units() {
        assert_eq!(
            load("maxmemory 100mb").unwrap().0.maxmemory,
            100 * 1024 * 1024
        );
        assert_eq!(load("maxmemory 2G").unwrap().0.maxmemory, 2_000_000_000);
        assert_eq!(load("maxmemory 4096").unwrap().0.maxmemory, 4096);
        assert_eq!(
            load("auto-aof-rewrite-min-size 64mb")
                .unwrap()
                .0
                .aof_rewrite_min_size,
            64 * 1024 * 1024
        );
    }

    #[test]
    fn quotes_and_comments() {
        let (config, _) = load("requirepass \"pa ss#word\" # the password\n").unwrap();
        assert_eq!(config.requirepass, "pa ss#word");
        let (config, _) = load("requirepass 'a\"b'\n").unwrap();
        assert_eq!(config.requirepass, "a\"b");
        let (config, _) = load("requirepass p#ss\n").unwrap();
        assert_eq!(config.requirepass, "p#ss");
        for value in ["plain", "has space", "#hash", "quo\"te", "back\\slash", ""] {
            let words = split_config_line(&format!("k {}", quote(value))).unwrap();
            assert_eq!(words, ["k", value]);
        }
    }

    #[test]
    fn the_command_line_wins_over_the_file() {
        let mut config = Config {
            port: 7000,
            ..Config::default()
        };
        config
            .apply_config_text("port 8000\nthreads 3\n", &|id| id == "port")
            .unwrap();
        assert_eq!(config.port, 7000);
        assert_eq!(config.threads, 3);
        // A value the command line overrides is still checked.
        assert!(
            config
                .apply_config_text("port x\n", &|id| id == "port")
                .is_err()
        );
    }

    /// What `CONFIG SET` takes, the file takes too (#142): the settings the
    /// server keeps for itself are set as `CONFIG SET` sets them, Redis's
    /// are accepted with a warning, and a misspelt name still stops the
    /// server. The values are the defaults: the settings are the process's.
    #[test]
    fn config_set_settings_are_directives_too() {
        let (_, warnings) = load(
            "stream-node-max-entries 100\nstream-node-max-bytes 4kb\n\
             tracking-table-max-keys 1000000\nbusy-reply-threshold 5000\n\
             search-timeout 0\nsearch-on-timeout return\n",
        )
        .unwrap();
        #[cfg(feature = "lua")]
        assert!(warnings.is_empty(), "{warnings:?}");
        #[cfg(not(feature = "lua"))]
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        let (_, warnings) = load(
            "maxclients 10000\nlatency-tracking yes\nhash-max-listpack-entries 512\n\
             proto-max-bulk-len 512mb\nlatency-monitor-threshold 0\nacllog-max-len 128\n",
        )
        .unwrap();
        // All but maxclients, latency-tracking and latency-monitor-threshold,
        // which the latency monitor and `INFO latencystats` go by (#158,
        // #232), and acllog-max-len, which the ACL log goes by.
        assert_eq!(warnings.len(), 2, "{warnings:?}");
        assert!(
            warnings[0].contains("'hash-max-listpack-entries'"),
            "{warnings:?}"
        );
        let err = load("maxclients 0\n").unwrap_err();
        assert!(err.contains("maxclients"), "{err}");
        let err = load("array-slice-size 300\n").unwrap_err();
        assert!(err.contains("power of two"), "{err}");
        let err = load("stream-node-max-entries -1\n").unwrap_err();
        assert!(err.contains("stream-node-max-entries"), "{err}");
        for bad in [
            "search-timeout -1\n",
            "search-timeout soon\n",
            "search-on-timeout never\n",
        ] {
            let err = load(bad).unwrap_err();
            assert!(err.contains("search-"), "{bad}: {err}");
        }
        for typo in ["maxclientz 1\n", "cluster-allow-reads-when-down yes\n"] {
            let err = load(typo).unwrap_err();
            assert!(err.contains("unknown directive"), "{typo}: {err}");
        }
    }

    /// `lazyfree-lazy-expire` and `latency-tracking` from a config file are
    /// set, as `CONFIG SET` sets them, and not reported as having no
    /// effect: they have one (#232). A value other than yes or no is
    /// refused, there and in the other `lazyfree-*` directives.
    #[test]
    fn lazyfree_lazy_expire_and_latency_tracking_are_applied_from_the_file() {
        // Only to what they are already: other tests of this process go by
        // them. tests/expired_propagation.rs sets `no` from a file.
        let (_, warnings) = load("lazyfree-lazy-expire YES\nlatency-tracking yes\n").unwrap();
        assert!(warnings.is_empty(), "{warnings:?}");
        for bad in [
            "lazyfree-lazy-expire maybe\n",
            "lazyfree-lazy-user-del 1\n",
            "lazyfree-lazy-user-flush on\n",
            "latency-tracking sometimes\n",
        ] {
            let err = load(bad).unwrap_err();
            assert!(err.contains("'yes' or 'no'"), "{bad}: {err}");
        }
        assert_eq!(
            crate::commands::server::remembered_config("lazyfree-lazy-expire").as_deref(),
            Some("yes")
        );
    }

    /// `latency-tracking-info-percentiles` is read as Redis reads it (#255).
    /// The inputs through "1e1" were each run against Redis 8.10.3, and what
    /// it answered is what is asserted; `0x` and `--5` are not numbers to any
    /// `strtod`.
    #[test]
    fn latency_percentiles_are_read_as_redis_reads_them() {
        use crate::commands::server::parse_latency_percentiles as parse;
        let not_numbers = Err("Invalid latency-tracking-info-percentiles parameters");
        let out_of_range =
            Err("latency-tracking-info-percentiles parameters should sit between [0.0,100.0]");
        assert_eq!(parse(""), Ok(vec![]));
        assert_eq!(parse("50 99 99.9"), Ok(vec![50.0, 99.0, 99.9]));
        assert_eq!(parse("0"), Ok(vec![0.0]));
        assert_eq!(parse("100"), Ok(vec![100.0]));
        assert_eq!(parse("0x10"), Ok(vec![16.0]));
        assert_eq!(parse("1e1"), Ok(vec![10.0]));
        for bad in [
            "abc", "50 abc", " 50", "50 ", "50  99", "nan", "0x", "--5", "1e-400",
        ] {
            assert_eq!(parse(bad), not_numbers, "{bad:?}");
        }
        for bad in ["101", "-1", "inf"] {
            assert_eq!(parse(bad), out_of_range, "{bad:?}");
        }
    }

    /// What `CONFIG GET` gives back is the numbers as Redis writes them: `%f`,
    /// trailing zeros trimmed (#255).
    #[test]
    fn latency_percentiles_read_back_as_redis_writes_them() {
        use crate::commands::server::format_latency_percentiles as text;
        assert_eq!(text(&[]), "");
        assert_eq!(text(&[50.0, 99.0, 99.9]), "50 99 99.9");
        assert_eq!(text(&[16.0, 10.0]), "16 10");
        assert_eq!(text(&[0.0, 100.0]), "0 100");
        assert_eq!(text(&[50.0, 99.9]), "50 99.9");
        // Rounded as `%f` rounds, and a negative zero keeps its sign
        // (what Redis 8.10.3 read back for `99.9999999`, `-0` and `1e-310`).
        assert_eq!(text(&[99.9999999]), "100");
        assert_eq!(text(&[-0.0]), "-0");
        assert_eq!(text(&[1e-310]), "0");
    }

    /// The file refuses what `CONFIG SET` refuses, with the same words (#255).
    /// A value that is valid is only the one it already is: other tests of
    /// this process go by it. (A double space cannot be tried here: the file
    /// splits a line into words.)
    #[test]
    fn latency_tracking_info_percentiles_are_checked_in_the_file() {
        let (_, warnings) = load("latency-tracking-info-percentiles 50 99 99.9\n").unwrap();
        assert!(warnings.is_empty(), "{warnings:?}");
        for bad in ["abc", "50 abc", "nan"] {
            let err = load(&format!("latency-tracking-info-percentiles {bad}\n")).unwrap_err();
            assert!(
                err.contains("Invalid latency-tracking-info-percentiles parameters"),
                "{bad}: {err}"
            );
        }
        for bad in ["101", "-1", "inf"] {
            let err = load(&format!("latency-tracking-info-percentiles {bad}\n")).unwrap_err();
            assert!(
                err.contains("should sit between [0.0,100.0]"),
                "{bad}: {err}"
            );
        }
    }

    #[test]
    fn redis_directives_with_no_effect_are_reported_and_not_fatal() {
        let (_, warnings) = load("save 900 1\ntcp-keepalive 300\nappendfsync no\n").unwrap();
        assert_eq!(warnings.len(), 3, "{warnings:?}");
        assert!(warnings[0].contains("line 1") && warnings[0].contains("'save'"));
        // The values KiviDB already behaves as are not worth a warning.
        let (_, warnings) =
            load("save \"\"\nappendfsync everysec\ndaemonize no\ndbfilename dump.kdb\n").unwrap();
        assert!(warnings.is_empty(), "{warnings:?}");
    }

    /// `appendfsync` is read from the file, not warned about and ignored
    /// (#513).
    #[test]
    fn appendfsync_is_read_from_the_file() {
        let (config, warnings) = load("appendfsync always\n").unwrap();
        assert_eq!(config.appendfsync, "always");
        assert!(warnings.is_empty(), "{warnings:?}");
        let (config, _) = load("appendfsync EVERYSEC\n").unwrap();
        assert_eq!(config.appendfsync, "everysec");
        assert!(load("appendfsync sometimes\n").is_err());
    }

    /// Every option the file can set is asked about by the name clap knows
    /// it under — a wrong name there would panic at startup.
    #[test]
    fn every_directive_asks_about_an_option_that_exists() {
        use clap::CommandFactory;
        let command = Config::command();
        let known: Vec<String> = command
            .get_arguments()
            .map(|a| a.get_id().to_string())
            .collect();
        let everything = "port 1\nbind a\nthreads 1\ndir d\naof yes\naof-preamble yes\n\
            aof-rewrite-percentage 1\naof-rewrite-min-size 1\ndatabases 1\nmaxmemory 1\n\
            loglevel info\nio-model tokio\nrequirepass p\naclfile f\nslowlog-log-slower-than 1\n\
            slowlog-max-len 1\nslowlog-entry-max-argc 1\nslowlog-entry-max-string-len 1\n\
            cluster-enabled yes\ncluster-node-timeout 1\ncluster-announce-ip a\n\
            cluster-announce-hostname h\ncluster-preferred-endpoint-type ip\n\
            cluster-announce-port 1\ncluster-announce-client-port 1\n\
            cluster-announce-bus-port 1\n\
            cluster-bus-port-protected-mode no\ncluster-bus-secret s\n\
            cluster-config-file f\n\
            cluster-require-full-coverage no\ncluster-replica-validity-factor 1\n\
            cluster-slot-migration-handoff-max-lag-bytes 1\n\
            cluster-slot-migration-write-pause-timeout 1\nrepl-replica-max-backlog-bytes 1\n\
            repl-replica-sync-max-backlog-bytes 1\n\
            masterauth a\nmasteruser u\nrepl-timeout 1\nshutdown-timeout 1\n\
            repl-ping-replica-period 1\n\
            min-replicas-to-write 1\nmin-replicas-max-lag 1\n\
            repl-backlog-size 1mb\nrepl-backlog-ttl 1\nrepl-diskless-load swapdb\n\
            hll-write-format redis\n\
            replica-full-sync-guard off\nreplica-full-sync-guard-ratio 1\n\
            replica-announced-port 1\nreplica-priority 1\nreplica-announced no\n\
            replicaof h 1\nstream-idmp-duration 1\n\
            stream-idmp-maxsize 1\nbackupdirname b\nbackup-sealed-ttl 1\npreload-file f\n\
            tls-port 1\ntls-cert-file f\ntls-key-file f\ntls-ca-cert-file f\n\
            tls-cluster no\ntls-replication no\ntls-client-cert-file f\ntls-client-key-file f\n\
            tls-auth-clients optional\n\
            notify-keyspace-events KEA\n";
        let asked = std::cell::Cell::new(0);
        Config::default()
            .apply_config_text(everything, &|id| {
                assert!(known.iter().any(|k| k == id), "no option named {id}");
                asked.set(asked.get() + 1);
                false
            })
            .unwrap();
        assert_eq!(asked.get(), everything.lines().count());
    }
}

#[cfg(test)]
mod validate_tests {
    use super::Config;

    fn cfg() -> Config {
        Config::default()
    }

    /// Rebuilt nodes serving plaintext:
    /// a build with no TLS in it accepted `--tls-port` and silently served
    /// plaintext. It must refuse instead.
    #[test]
    fn tls_port_on_a_build_without_tls_is_fatal() {
        let c = Config {
            tls_port: 6380,
            tls_cert_file: "cert.pem".into(),
            tls_key_file: "key.pem".into(),
            ..cfg()
        };
        let err = c.validate(false).unwrap_err();
        assert!(err.contains("built without TLS support"), "{err}");
        // The same configuration is fine on a build that has TLS.
        assert!(c.validate(true).is_ok());
    }

    #[test]
    fn invalid_tls_auth_clients_is_fatal() {
        let c = Config {
            tls_auth_clients: "maybe".into(),
            ..cfg()
        };
        let err = c.validate(true).unwrap_err();
        assert!(err.contains("tls-auth-clients"), "{err}");
    }

    #[test]
    fn tls_cert_without_port_only_warns_on_a_build_without_tls() {
        let c = Config {
            tls_cert_file: "cert.pem".into(),
            ..cfg()
        };
        let warnings = c.validate(false).unwrap();
        assert!(warnings.iter().any(|w| w.contains("without TLS support")));
    }

    #[test]
    fn tls_port_without_cert_is_fatal_on_a_tls_build() {
        let c = Config {
            tls_port: 6380,
            ..cfg()
        };
        assert!(c.validate(true).is_err());
    }

    /// Port 0 is no plaintext port: only with a TLS port, and in a cluster
    /// only with `tls-cluster`, whose bus is then 10000 above the TLS port.
    #[test]
    fn port_0_needs_a_tls_port() {
        let plain_off = Config { port: 0, ..cfg() };
        let err = plain_off.validate(true).unwrap_err();
        assert!(err.contains("port 0"), "{err}");
        assert!(plain_off.validate(false).is_err());

        let tls_only = Config {
            port: 0,
            tls_port: 6381,
            tls_cert_file: "cert.pem".into(),
            tls_key_file: "key.pem".into(),
            ..cfg()
        };
        assert!(tls_only.validate(true).is_ok());
        assert_eq!(tls_only.client_port(), 6381);
        assert_eq!(tls_only.cluster_bus_port(), 16381);

        let cluster = Config {
            cluster_enabled: true,
            ..tls_only.clone()
        };
        let err = cluster.validate(true).unwrap_err();
        assert!(err.contains("tls-cluster"), "{err}");
        let tls_cluster = Config {
            tls_cluster: true,
            tls_ca_cert_file: "ca.pem".into(),
            ..cluster
        };
        assert!(tls_cluster.validate(true).is_ok());
    }

    /// `*` is one label, case does not matter, and what is not a name is
    /// refused.
    #[test]
    fn allowed_names_match_one_label_for_a_star() {
        use super::{allowed_name_matches, allowed_names};
        let names = allowed_names("*.DB1.nodes.kividb.internal, admin.example ").unwrap();
        assert_eq!(names, ["*.db1.nodes.kividb.internal", "admin.example"]);
        let ok = |name: &str| names.iter().any(|p| allowed_name_matches(p, name));
        assert!(ok("node-0.db1.nodes.kividb.internal"));
        assert!(ok("Node-1.DB1.Nodes.Kividb.Internal."));
        assert!(ok("ADMIN.example"));
        assert!(!ok("db1.nodes.kividb.internal"));
        assert!(!ok("a.b.db1.nodes.kividb.internal"));
        assert!(!ok("x.db2.nodes.kividb.internal"));
        assert!(!ok("x.xdb1.nodes.kividb.internal"));
        assert!(!ok("other.admin.example"));
        for bad in ["*", "a.*.b", "*.*.b", "a*.b", "a..b", "*.", "a b/c"] {
            assert!(allowed_names(bad).is_err(), "{bad} was taken");
        }
        assert_eq!(allowed_names(" , ").unwrap(), Vec::<String>::new());
        let c = Config {
            tls_auth_clients_allowed_names: "a.*".into(),
            ..cfg()
        };
        assert!(c.validate(true).is_err());
    }

    #[test]
    fn default_config_is_valid_and_quiet() {
        assert_eq!(cfg().validate(false).unwrap(), Vec::<String>::new());
        assert_eq!(cfg().validate(true).unwrap(), Vec::<String>::new());
    }

    #[test]
    fn full_sync_guard_value_is_checked() {
        for ok in ["off", "empty", "shrink"] {
            let c = Config {
                replica_full_sync_guard: ok.into(),
                ..cfg()
            };
            assert!(c.validate(true).is_ok(), "{ok} must be accepted");
        }
        let c = Config {
            replica_full_sync_guard: "sometimes".into(),
            ..cfg()
        };
        assert!(c.validate(true).is_err());
    }

    #[test]
    fn cluster_mode_warns_about_the_open_bus_and_can_refuse() {
        let c = Config {
            cluster_enabled: true,
            ..cfg()
        };
        let warnings = c.validate(true).unwrap();
        assert!(warnings.iter().any(|w| w.contains("not authenticated")));

        let c = Config {
            cluster_enabled: true,
            cluster_bus_port_protected_mode: true,
            ..cfg()
        };
        assert!(c.validate(true).is_err());
    }

    #[test]
    fn replicaof_is_rejected_in_cluster_mode() {
        let c = Config {
            cluster_enabled: true,
            replicaof: Some(vec!["127.0.0.1".into(), "6379".into()]),
            ..cfg()
        };
        assert!(c.validate(true).unwrap_err().contains("CLUSTER REPLICATE"));
    }
}