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
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
// src/commands/cluster.rs
//
// CLUSTER subcommands. Step 2 implements the read-only surface plus
// CLUSTER MYID. Mutating subcommands (ADDSLOTS, MEET, FORGET, SETSLOT,
// etc.) come in Step 4 and beyond.

use crate::cluster::{
    CLUSTER_SLOTS, ClusterState, MigrationState, NodeFlags, NodeId, key_hash_slot, node_id_str,
};
use crate::commands::ctx::Ctx;
use crate::resp::write::*;
use std::sync::Arc;

pub fn handle(ctx: &mut Ctx, name: &str) -> Option<Vec<u8>> {
    let cmd = &ctx.cmd;

    match name {
        "CLUSTER" => {
            if cmd.len() < 2 {
                return Some(resp_error(
                    "ERR wrong number of arguments for 'cluster' command",
                ));
            }
            let sub = String::from_utf8_lossy(cmd[1]).to_ascii_uppercase();
            Some(handle_cluster(ctx, &sub))
        }
        "ASKING" => Some(cmd_asking(ctx)),
        "READONLY" => Some(cmd_readonly(ctx)),
        "READWRITE" => Some(cmd_readwrite(ctx)),
        _ => None,
    }
}

fn handle_cluster(ctx: &mut Ctx, sub: &str) -> Vec<u8> {
    let state: &Arc<ClusterState> = ctx.cluster;

    // Subcommands that work even when cluster is disabled.
    match sub {
        // Read-only — work in both standalone and cluster modes
        "INFO" => return cmd_info(state),
        "KEYSLOT" => return cmd_keyslot(&ctx.cmd),
        "NODES" => return cmd_nodes(state),
        "SLOTS" => return cmd_slots(state),
        "SHARDS" => return cmd_shards(state),

        // Mutating — require cluster mode (each handler checks via state.enabled)
        "ADDSLOTS" => return cmd_addslots(ctx),
        "DELSLOTS" => return cmd_delslots(state, &ctx.cmd),
        "ADDSLOTSRANGE" => return cmd_addslotsrange(ctx),
        "DELSLOTSRANGE" => return cmd_delslotsrange(state, &ctx.cmd),
        "FLUSHSLOTS" => return cmd_flushslots(ctx),
        "BUMPEPOCH" => return cmd_bumpepoch(state),
        "SET-CONFIG-EPOCH" => return cmd_set_config_epoch(state, &ctx.cmd),
        "SAVECONFIG" => return cmd_saveconfig(state),

        _ => {}
    }

    // Anything past this point requires cluster mode for now.
    // (ADDSLOTS / SETSLOT / MEET come in later steps; until they exist we
    // return the same error redis-cli expects, instead of "unknown".) A
    // subcommand there is no such thing as is unknown either way, as in
    // Redis.
    if !state.enabled {
        if crate::commands::arity::of(&format!("CLUSTER|{sub}")).is_none()
            && !matches!(sub, "MIGRATION" | "SYNCSLOTS")
        {
            return unknown_cluster_subcommand(ctx);
        }
        return resp_error("ERR This instance has cluster support disabled");
    }

    match sub {
        // As in Redis, these refuse on a node with cluster support disabled
        // (#563): there is no node id, and a slot means nothing.
        "MYID" => cmd_myid(state),
        "COUNTKEYSINSLOT" => cmd_countkeysinslot(ctx),
        "GETKEYSINSLOT" => cmd_getkeysinslot(ctx),
        "MEET" => cmd_meet(ctx),
        "FORGET" => cmd_forget(ctx),
        "COUNT-FAILURE-REPORTS" => cmd_count_failure_reports(ctx),
        "LINKS" => cmd_links(ctx),
        "REPLICAS" | "SLAVES" => cmd_replicas(ctx),

        "REPLICATE" => cmd_replicate(ctx),
        "FAILOVER" => cmd_failover(ctx),
        "SETSLOT" => cmd_setslot(ctx),

        "RESET" => cmd_reset(ctx),
        "MYSHARDID" => cmd_myshardid(ctx),
        "SLOT-STATS" => cmd_slot_stats(ctx),

        "MIGRATION" => cmd_migration(ctx),
        // Node-to-node half of CLUSTER MIGRATION; not for clients.
        "SYNCSLOTS" => cmd_syncslots(ctx),
        "HELP" if ctx.cmd.len() == 2 => cluster_help(),
        _ => unknown_cluster_subcommand(ctx),
    }
}

/// Redis's reply to a `CLUSTER` subcommand there is no such thing as.
fn unknown_cluster_subcommand(ctx: &Ctx) -> Vec<u8> {
    resp_error(&format!(
        "ERR unknown subcommand '{}'. Try CLUSTER HELP.",
        String::from_utf8_lossy(ctx.cmd[1])
    ))
}

/// `CLUSTER HELP`, Redis 8.10's lines (#562).
fn cluster_help() -> Vec<u8> {
    const LINES: &[&str] = &[
        "CLUSTER <subcommand> [<arg> [value] [opt] ...]. Subcommands are:",
        "COUNTKEYSINSLOT <slot>",
        "    Return the number of keys in <slot>.",
        "GETKEYSINSLOT <slot> <count>",
        "    Return key names stored by current node in a slot.",
        "INFO",
        "    Return information about the cluster.",
        "KEYSLOT <key>",
        "    Return the hash slot for <key>.",
        "MYID",
        "    Return the node id.",
        "MYSHARDID",
        "    Return the node's shard id.",
        "NODES",
        "    Return cluster configuration seen by node. Output format:",
        "    <id> <ip:port@bus-port[,hostname]> <flags> <master> <pings> <pongs> <epoch> <link> <slot> ...",
        "REPLICAS <node-id>",
        "    Return <node-id> replicas.",
        "SLOTS",
        "    Return information about slots range mappings. Each range is made of:",
        "    start, end, master and replicas IP addresses, ports and ids",
        "SLOT-STATS",
        "    Return an array of slot usage statistics for slots assigned to the current node.",
        "SHARDS",
        "    Return information about slot range mappings and the nodes associated with them.",
        "ADDSLOTS <slot> [<slot> ...]",
        "    Assign slots to current node.",
        "ADDSLOTSRANGE <start slot> <end slot> [<start slot> <end slot> ...]",
        "    Assign slots which are between <start-slot> and <end-slot> to current node.",
        "BUMPEPOCH",
        "    Advance the cluster config epoch.",
        "COUNT-FAILURE-REPORTS <node-id>",
        "    Return number of failure reports for <node-id>.",
        "DELSLOTS <slot> [<slot> ...]",
        "    Delete slots information from current node.",
        "DELSLOTSRANGE <start slot> <end slot> [<start slot> <end slot> ...]",
        "    Delete slots information which are between <start-slot> and <end-slot> from current node.",
        "FAILOVER [FORCE|TAKEOVER]",
        "    Promote current replica node to being a master.",
        "FORGET <node-id>",
        "    Remove a node from the cluster.",
        "FLUSHSLOTS",
        "    Delete current node own slots information.",
        "MEET <ip> <port> [<bus-port>]",
        "    Connect nodes into a working cluster.",
        "REPLICATE <node-id>",
        "    Configure current node as replica to <node-id>.",
        "RESET [HARD|SOFT]",
        "    Reset current node (default: soft).",
        "SET-CONFIG-EPOCH <epoch>",
        "    Set config epoch of current node.",
        "SETSLOT <slot> (IMPORTING <node-id>|MIGRATING <node-id>|STABLE|NODE <node-id>)",
        "    Set slot state.",
        "SAVECONFIG",
        "    Force saving cluster configuration on disk.",
        "LINKS",
        "    Return information about all network links between this node and its peers.",
        "    Output format is an array where each array element is a map containing attributes of a link",
        "MIGRATION IMPORT <start-slot end-slot [start-slot end-slot ...]> |",
        "          STATUS [ID <task-id> | ALL] | CANCEL [ID <task-id> | ALL]",
        "    Start, monitor and cancel slot migration.",
        "HELP",
        "    Print this help.",
    ];
    resp_array(LINES.iter().map(|line| resp_simple(line)).collect())
}

// ── CLUSTER MYID ─────────────────────────────────────────────────────────────

fn cmd_myid(state: &ClusterState) -> Vec<u8> {
    resp_bulk_str(node_id_str(&state.myself()))
}

// ── CLUSTER INFO ─────────────────────────────────────────────────────────────
//
// Returns a bulk string with key:value lines, separated by \r\n.
// Same format Redis uses, so redis-cli prints it cleanly.

fn cmd_info(state: &ClusterState) -> Vec<u8> {
    // Refresh first: this is what operators and orchestration poll, and it
    // should never trail a change they just made.
    state.refresh_state();
    let cluster_enabled = if state.enabled { 1 } else { 0 };
    let cluster_state = state.cluster_state_str();
    // Slot counts by the health of each slot's owner, and the cluster's size
    // as Redis defines it: masters that own at least one slot. These used to
    // report every assigned slot as ok and every master as part of the size.
    let (slots_assigned, slots_ok, slots_pfail, slots_fail) = state.slot_health();
    let size = state.voting_master_count();
    let current_epoch = state.current_epoch();
    let nodes = state.nodes.read();
    let known_nodes = nodes.len();

    let mut out = String::with_capacity(512);
    out.push_str(&format!("cluster_enabled:{cluster_enabled}\r\n"));
    out.push_str(&format!("cluster_state:{cluster_state}\r\n"));
    out.push_str(&format!("cluster_slots_assigned:{slots_assigned}\r\n"));
    out.push_str(&format!("cluster_slots_ok:{slots_ok}\r\n"));
    out.push_str(&format!("cluster_slots_pfail:{slots_pfail}\r\n"));
    out.push_str(&format!("cluster_slots_fail:{slots_fail}\r\n"));
    out.push_str(&format!("cluster_known_nodes:{known_nodes}\r\n"));
    out.push_str(&format!("cluster_size:{size}\r\n"));
    out.push_str(&format!("cluster_current_epoch:{current_epoch}\r\n"));
    out.push_str(&format!(
        "cluster_my_epoch:{}\r\n",
        nodes
            .get(&state.myself())
            .map(|n| n.config_epoch)
            .unwrap_or(0)
    ));
    out.push_str(&format!(
        "cluster_stats_messages_sent:{}\r\n",
        state
            .stats_messages_sent
            .load(std::sync::atomic::Ordering::Relaxed)
    ));
    out.push_str(&format!(
        "cluster_stats_messages_received:{}\r\n",
        state
            .stats_messages_received
            .load(std::sync::atomic::Ordering::Relaxed)
    ));
    out.push_str(&format!(
        "cluster_stats_bus_connects:{}\r\n",
        state
            .stats_bus_connects
            .load(std::sync::atomic::Ordering::Relaxed)
    ));
    out.push_str("total_cluster_links_buffer_limit_exceeded:0\r\n");

    resp_bulk_str(&out)
}

// ── CLUSTER KEYSLOT ──────────────────────────────────────────────────────────

fn cmd_keyslot(cmd: &[&[u8]]) -> Vec<u8> {
    if cmd.len() != 3 {
        return resp_error("ERR wrong number of arguments for 'cluster|keyslot' command");
    }
    let slot = key_hash_slot(cmd[2]);
    resp_integer(slot as i64)
}

// ── CLUSTER COUNTKEYSINSLOT ──────────────────────────────────────────────────
//
// Walk the keyspace of the currently selected DB and count keys hashing to
// the given slot. O(N) over the DB. Cluster mode normally restricts the
// keyspace to the slots we own, but in standalone mode this still works
// and returns a count for any slot — useful for testing.

fn cmd_countkeysinslot(ctx: &Ctx) -> Vec<u8> {
    if ctx.cmd.len() != 3 {
        return resp_error("ERR wrong number of arguments for 'cluster|countkeysinslot' command");
    }
    let slot: u16 = match parse_slot_arg(ctx.cmd[2]) {
        Ok(s) => s,
        Err(e) => return e,
    };

    let db = &ctx.store[*ctx.selected_db];
    let mut count: i64 = 0;
    for shard in db.iter() {
        let map = crate::read_lock!(shard);
        for k in map.keys() {
            if key_hash_slot(k) == slot {
                count += 1;
            }
        }
    }
    resp_integer(count)
}

// ── CLUSTER GETKEYSINSLOT ────────────────────────────────────────────────────

fn cmd_getkeysinslot(ctx: &Ctx) -> Vec<u8> {
    if ctx.cmd.len() != 4 {
        return resp_error("ERR wrong number of arguments for 'cluster|getkeysinslot' command");
    }
    let slot: u16 = match parse_slot_arg(ctx.cmd[2]) {
        Ok(s) => s,
        Err(e) => return e,
    };
    let count: i64 = match std::str::from_utf8(ctx.cmd[3])
        .ok()
        .and_then(|s| s.parse().ok())
    {
        Some(n) => n,
        None => return resp_error("ERR value is not an integer or out of range"),
    };
    if count < 0 {
        return resp_error("ERR Invalid slot or number of keys");
    }
    let count = count as usize;

    let db = &ctx.store[*ctx.selected_db];
    let mut out: Vec<Vec<u8>> = Vec::with_capacity(count.min(64));
    // A count of 0 is an empty array, as in Redis: the loop below pushes
    // a key before it compares (#563).
    if count == 0 {
        return resp_array(out);
    }
    'outer: for shard in db.iter() {
        let map = crate::read_lock!(shard);
        for k in map.keys() {
            if key_hash_slot(k) == slot {
                out.push(resp_bulk(k));
                if out.len() >= count {
                    break 'outer;
                }
            }
        }
    }
    resp_array(out)
}

// ── CLUSTER NODES ────────────────────────────────────────────────────────────
//
// Bulk string with one line per node. Format must match Redis byte-for-byte
// or clients (redis-cli, redis-py cluster client, jedis) will misparse it.
// Reuse the same line format as nodes.conf — that's by design in Redis too.

fn cmd_nodes(state: &ClusterState) -> Vec<u8> {
    use std::fmt::Write;

    let nodes = state.nodes.read();
    let slots = state.slots.read();
    let migrations = state.migrations.read();
    let myself = state.myself();

    let mut out = String::with_capacity(256 * nodes.len().max(1));

    let mut sorted: Vec<&crate::cluster::ClusterNode> = nodes.values().collect();
    sorted.sort_by_key(|n| n.id);

    for node in sorted {
        let _ = write!(
            out,
            "{} {}:{}@{}{}",
            node_id_str(&node.id),
            node.ip,
            node.client_facing_port(),
            node.cluster_port,
            crate::cluster::persist::hostname_suffix(&node.hostname)
        );
        out.push(' ');
        out.push_str(&format_flags_for_nodes(node.flags));
        out.push(' ');
        match node.master_id {
            Some(m) => out.push_str(node_id_str(&m)),
            None => out.push('-'),
        }
        let _ = write!(
            out,
            " {} {} {} {}",
            node.ping_sent_ms,
            node.pong_received_ms,
            node.config_epoch,
            link_state(node)
        );

        if node.flags.contains(NodeFlags::MASTER) {
            for (a, b) in compute_slot_ranges(&slots, node.id) {
                if a == b {
                    let _ = write!(out, " {a}");
                } else {
                    let _ = write!(out, " {a}-{b}");
                }
            }
        }
        // As Redis, on this node's own line: the slots it is moving out
        // (`[slot->-dest]`) or in (`[slot-<-src]`). redis-cli --cluster check
        // and fix find open slots by them.
        if node.id == myself {
            let mut open: Vec<(u16, MigrationState)> =
                migrations.iter().map(|(slot, m)| (*slot, *m)).collect();
            open.sort_by_key(|(slot, _)| *slot);
            for (slot, migration) in open {
                let _ = match migration {
                    MigrationState::Migrating { dest_id } => {
                        write!(out, " [{slot}->-{}]", node_id_str(&dest_id))
                    }
                    MigrationState::Importing { src_id } => {
                        write!(out, " [{slot}-<-{}]", node_id_str(&src_id))
                    }
                };
            }
        }
        out.push('\n');
    }

    resp_bulk_str(&out)
}

// ── CLUSTER SLOTS ────────────────────────────────────────────────────────────
//
// Returns an array of [start, end, [master_ip, master_port, master_id], ...].
// One element per contiguous range of slots owned by a single master.

fn cmd_slots(state: &ClusterState) -> Vec<u8> {
    let nodes = state.nodes.read();
    let slots = state.slots.read();

    // Build one (start, end, owner_id) entry per contiguous range.
    let mut ranges: Vec<(usize, usize, NodeId)> = Vec::new();
    let mut start: Option<(usize, NodeId)> = None;
    for i in 0..CLUSTER_SLOTS {
        match (slots[i], start) {
            (Some(owner), None) => start = Some((i, owner)),
            (Some(owner), Some((s, prev_owner))) if owner != prev_owner => {
                ranges.push((s, i - 1, prev_owner));
                start = Some((i, owner));
            }
            (None, Some((s, prev_owner))) => {
                ranges.push((s, i - 1, prev_owner));
                start = None;
            }
            _ => {}
        }
    }
    if let Some((s, owner)) = start {
        ranges.push((s, CLUSTER_SLOTS - 1, owner));
    }

    let mut entries: Vec<Vec<u8>> = Vec::with_capacity(ranges.len());
    for (a, b, owner_id) in ranges {
        let owner = match nodes.get(&owner_id) {
            Some(n) => n,
            None => continue,
        };
        let mut entry = vec![
            resp_integer(a as i64),
            resp_integer(b as i64),
            slots_node_entry(state, owner),
        ];
        // Append replicas of this master.
        for replica in nodes
            .values()
            .filter(|n| n.flags.contains(NodeFlags::REPLICA) && n.master_id == Some(owner_id))
        {
            entry.push(slots_node_entry(state, replica));
        }
        entries.push(resp_array(entry));
    }

    resp_array(entries)
}

/// One node in a CLUSTER SLOTS range, as Redis 7 gives it: the endpoint
/// `cluster-preferred-endpoint-type` asks for (null for `unknown-endpoint`),
/// port, id, and then what the endpoint does not already say — the address
/// in place of a hostname, the hostname in place of an address. That last
/// part is left out when there is nothing in it, which is the reply before
/// Redis 7 and what every client reads.
fn slots_node_entry(state: &ClusterState, node: &crate::cluster::ClusterNode) -> Vec<u8> {
    use crate::cluster::Endpoint;
    let preferred = state.preferred_endpoint();
    let mut fields = vec![
        match preferred {
            Endpoint::Unknown => resp_null_bulk(),
            _ => resp_bulk_str(&state.endpoint_of(node)),
        },
        resp_integer(node.client_facing_port() as i64),
        resp_bulk_str(node_id_str(&node.id)),
    ];
    let mut metadata: Vec<Vec<u8>> = Vec::new();
    if preferred != Endpoint::Ip {
        metadata.push(resp_bulk_str("ip"));
        metadata.push(resp_bulk_str(&node.ip));
    }
    if preferred != Endpoint::Hostname && !node.hostname.is_empty() {
        metadata.push(resp_bulk_str("hostname"));
        metadata.push(resp_bulk_str(&node.hostname));
    }
    if !metadata.is_empty() {
        fields.push(resp_array(metadata));
    }
    resp_array(fields)
}

// ── CLUSTER SHARDS ───────────────────────────────────────────────────────────
//
// Redis 7+. Groups nodes by shard (master + its replicas) and returns the
// slot ranges they cover. Each shard is a map: { slots: [...], nodes: [...] }.

fn cmd_shards(state: &ClusterState) -> Vec<u8> {
    let nodes = state.nodes.read();
    let slots = state.slots.read();

    let mut shards: Vec<Vec<u8>> = Vec::new();
    for master in nodes
        .values()
        .filter(|n| n.flags.contains(NodeFlags::MASTER))
    {
        let mut slot_pairs: Vec<Vec<u8>> = Vec::new();
        for (a, b) in compute_slot_ranges(&slots, master.id) {
            slot_pairs.push(resp_integer(a as i64));
            slot_pairs.push(resp_integer(b as i64));
        }

        let mut node_descs: Vec<Vec<u8>> = Vec::new();
        node_descs.push(node_description(state, master));
        for replica in nodes
            .values()
            .filter(|n| n.flags.contains(NodeFlags::REPLICA) && n.master_id == Some(master.id))
        {
            node_descs.push(node_description(state, replica));
        }

        shards.push(resp_array(vec![
            resp_bulk_str("slots"),
            resp_array(slot_pairs),
            resp_bulk_str("nodes"),
            resp_array(node_descs),
        ]));
    }

    resp_array(shards)
}

/// The link-state column of `CLUSTER NODES`: whether we can currently reach
/// the node. Our own row is always `connected`.
fn link_state(node: &crate::cluster::ClusterNode) -> &'static str {
    if !node.flags.contains(NodeFlags::MYSELF)
        && node
            .flags
            .intersects(NodeFlags::PFAIL | NodeFlags::FAIL | NodeFlags::HANDSHAKE)
    {
        "disconnected"
    } else {
        "connected"
    }
}

fn node_description(state: &ClusterState, node: &crate::cluster::ClusterNode) -> Vec<u8> {
    let role = if node.flags.contains(NodeFlags::MASTER) {
        "master"
    } else if node.flags.contains(NodeFlags::REPLICA) {
        "replica"
    } else {
        "unknown"
    };
    // `loading` means a node that is still syncing its dataset, which is not
    // something a suspected-unreachable node is known to be doing.
    let health = if node.flags.contains(NodeFlags::FAIL) {
        "fail"
    } else {
        "online"
    };
    let mut fields = vec![
        resp_bulk_str("id"),
        resp_bulk_str(node_id_str(&node.id)),
        resp_bulk_str("port"),
        resp_integer(node.client_facing_port() as i64),
        resp_bulk_str("ip"),
        resp_bulk_str(&node.ip),
        resp_bulk_str("endpoint"),
        resp_bulk_str(&state.endpoint_of(node)),
    ];
    if !node.hostname.is_empty() {
        fields.push(resp_bulk_str("hostname"));
        fields.push(resp_bulk_str(&node.hostname));
    }
    fields.extend([
        resp_bulk_str("role"),
        resp_bulk_str(role),
        resp_bulk_str("replication-offset"),
        resp_integer(0),
        resp_bulk_str("health"),
        resp_bulk_str(health),
    ]);
    resp_array(fields)
}

// ── Shared helpers ───────────────────────────────────────────────────────────

fn parse_slot_arg(arg: &[u8]) -> Result<u16, Vec<u8>> {
    let s = std::str::from_utf8(arg).map_err(|_| resp_error("ERR invalid slot"))?;
    let n: i64 = s
        .parse()
        .map_err(|_| resp_error("ERR value is not an integer or out of range"))?;
    if !(0..CLUSTER_SLOTS as i64).contains(&n) {
        return Err(resp_error(&format!(
            "ERR Invalid slot {n}, must be between 0 and {}",
            CLUSTER_SLOTS - 1
        )));
    }
    Ok(n as u16)
}

fn format_flags_for_nodes(f: NodeFlags) -> String {
    let mut parts: Vec<&str> = Vec::new();
    if f.contains(NodeFlags::MYSELF) {
        parts.push("myself");
    }
    if f.contains(NodeFlags::MASTER) {
        parts.push("master");
    }
    if f.contains(NodeFlags::REPLICA) {
        parts.push("slave");
    }
    if f.contains(NodeFlags::PFAIL) {
        parts.push("fail?");
    }
    if f.contains(NodeFlags::FAIL) {
        parts.push("fail");
    }
    if f.contains(NodeFlags::HANDSHAKE) {
        parts.push("handshake");
    }
    if f.contains(NodeFlags::NOADDR) {
        parts.push("noaddr");
    }
    if parts.is_empty() {
        return "noflags".into();
    }
    parts.join(",")
}

fn compute_slot_ranges(
    slots: &[Option<NodeId>; CLUSTER_SLOTS],
    owner: NodeId,
) -> Vec<(usize, usize)> {
    let mut ranges = Vec::new();
    let mut start: Option<usize> = None;
    for (i, slot) in slots.iter().enumerate().take(CLUSTER_SLOTS) {
        let owned = matches!(*slot, Some(o) if o == owner);
        match (start, owned) {
            (None, true) => start = Some(i),
            (Some(s), false) => {
                ranges.push((s, i - 1));
                start = None;
            }
            _ => {}
        }
    }
    if let Some(s) = start {
        ranges.push((s, CLUSTER_SLOTS - 1));
    }
    ranges
}

// ── Mutating subcommands (Step 3) ─────────────────────────────────────────────
//
// All of these:
//   1. Require cluster mode (state.enabled). The release_/claim_ helpers
//      check this themselves; we still need an explicit check for the
//      argument-only commands (FLUSHSLOTS, BUMPEPOCH, SAVECONFIG).
//   2. Persist to nodes.conf on success. A failed mutation does not
//      trigger a save.
//   3. Return Redis-compatible error strings. The format matters because
//      cluster orchestrators (redis-cli --cluster, redis-trib) parse them.

fn require_cluster_mode(state: &ClusterState) -> Option<Vec<u8>> {
    if !state.enabled {
        Some(resp_error("ERR This instance has cluster support disabled"))
    } else {
        None
    }
}

/// CLUSTER ADDSLOTS slot [slot ...]
fn cmd_addslots(ctx: &mut Ctx) -> Vec<u8> {
    let (state, cmd): (&ClusterState, &[&[u8]]) = (ctx.cluster, &ctx.cmd);
    if let Some(err) = require_cluster_mode(state) {
        return err;
    }
    if cmd.len() < 3 {
        return resp_error("ERR wrong number of arguments for 'cluster|addslots' command");
    }

    // Parse all slots first, before mutating anything. Same pattern as the
    // range mutators: validate-then-apply so we don't leave half-claimed
    // state on a parse error.
    let mut slots: Vec<u16> = Vec::with_capacity(cmd.len() - 2);
    for arg in &cmd[2..] {
        match parse_slot_arg(arg) {
            Ok(s) => slots.push(s),
            Err(e) => return e,
        }
    }
    // Every slot is checked (free, and named once) before any is claimed,
    // as in Redis: one busy slot claims none of them. The earlier ones used
    // to stay claimed, unsaved and with `cluster_state` stale (#553).
    if let Err(e) = state.check_slots_claimable(&slots) {
        return resp_error(&format!("ERR {e}"));
    }
    if let Some(refused) = before_slots_come(ctx, &slots, "ADDSLOTS") {
        return refused;
    }
    let state: &ClusterState = ctx.cluster;
    if let Err(e) = state.claim_slots(&slots) {
        return resp_error(&format!("ERR {e}"));
    }
    if let Err(e) = state.save_to_disk() {
        return resp_error(&format!(
            "ERR ADDSLOTS persisted in memory but disk save failed: {e}"
        ));
    }
    resp_simple("OK")
}

/// CLUSTER DELSLOTS slot [slot ...]
fn cmd_delslots(state: &ClusterState, cmd: &[&[u8]]) -> Vec<u8> {
    if let Some(err) = require_cluster_mode(state) {
        return err;
    }
    if cmd.len() < 3 {
        return resp_error("ERR wrong number of arguments for 'cluster|delslots' command");
    }
    let mut slots: Vec<u16> = Vec::with_capacity(cmd.len() - 2);
    for arg in &cmd[2..] {
        match parse_slot_arg(arg) {
            Ok(s) => slots.push(s),
            Err(e) => return e,
        }
    }
    {
        let mut seen = std::collections::HashSet::with_capacity(slots.len());
        for &s in &slots {
            if !seen.insert(s) {
                return resp_error(&format!("ERR Slot {s} specified multiple times"));
            }
        }
    }
    // All or nothing, as in Redis.
    if let Err(e) = state.release_slots(&slots) {
        return resp_error(&format!("ERR {e}"));
    }
    if let Err(e) = state.save_to_disk() {
        return resp_error(&format!(
            "ERR DELSLOTS persisted in memory but disk save failed: {e}"
        ));
    }
    resp_simple("OK")
}

/// CLUSTER ADDSLOTSRANGE start-slot end-slot [start-slot end-slot ...]
fn cmd_addslotsrange(ctx: &mut Ctx) -> Vec<u8> {
    let (state, cmd): (&ClusterState, &[&[u8]]) = (ctx.cluster, &ctx.cmd);
    if let Some(err) = require_cluster_mode(state) {
        return err;
    }
    // Need at least: CLUSTER ADDSLOTSRANGE start end -> 4 args
    if cmd.len() < 4 || !(cmd.len() - 2).is_multiple_of(2) {
        return resp_error("ERR wrong number of arguments for 'cluster|addslotsrange' command");
    }
    // Parse all (start, end) pairs first.
    let mut ranges: Vec<(u16, u16)> = Vec::new();
    let mut i = 2;
    while i + 1 < cmd.len() {
        let start = match parse_slot_arg(cmd[i]) {
            Ok(s) => s,
            Err(e) => return e,
        };
        let end = match parse_slot_arg(cmd[i + 1]) {
            Ok(s) => s,
            Err(e) => return e,
        };
        if start > end {
            return resp_error(&format!(
                "ERR start slot number {start} is greater than end slot number {end}"
            ));
        }
        ranges.push((start, end));
        i += 2;
    }

    let slots: Vec<u16> = ranges
        .iter()
        .flat_map(|&(start, end)| start..=end)
        .collect();
    // All the ranges or none, as in Redis. A busy slot in a later range
    // used to leave the earlier ranges claimed, unsaved (#553).
    if let Err(e) = state.check_slots_claimable(&slots) {
        return resp_error(&format!("ERR {e}"));
    }
    if let Some(refused) = before_slots_come(ctx, &slots, "ADDSLOTSRANGE") {
        return refused;
    }
    let state: &ClusterState = ctx.cluster;
    if let Err(e) = state.claim_slots(&slots) {
        return resp_error(&format!("ERR {e}"));
    }
    if let Err(e) = state.save_to_disk() {
        return resp_error(&format!(
            "ERR ADDSLOTSRANGE persisted in memory but disk save failed: {e}"
        ));
    }
    resp_simple("OK")
}

/// CLUSTER DELSLOTSRANGE start-slot end-slot [start-slot end-slot ...]
fn cmd_delslotsrange(state: &ClusterState, cmd: &[&[u8]]) -> Vec<u8> {
    if let Some(err) = require_cluster_mode(state) {
        return err;
    }
    if cmd.len() < 4 || !(cmd.len() - 2).is_multiple_of(2) {
        return resp_error("ERR wrong number of arguments for 'cluster|delslotsrange' command");
    }
    let mut ranges: Vec<(u16, u16)> = Vec::new();
    let mut i = 2;
    while i + 1 < cmd.len() {
        let start = match parse_slot_arg(cmd[i]) {
            Ok(s) => s,
            Err(e) => return e,
        };
        let end = match parse_slot_arg(cmd[i + 1]) {
            Ok(s) => s,
            Err(e) => return e,
        };
        if start > end {
            return resp_error(&format!("ERR Invalid range {start}-{end}"));
        }
        ranges.push((start, end));
        i += 2;
    }
    // Every range is checked before any slot is released, as in Redis.
    let mut slots: Vec<u16> = Vec::new();
    let mut seen = vec![false; crate::cluster::CLUSTER_SLOTS];
    for (start, end) in ranges {
        for s in start..=end {
            if std::mem::replace(&mut seen[s as usize], true) {
                return resp_error(&format!("ERR Slot {s} specified multiple times"));
            }
            slots.push(s);
        }
    }
    if let Err(e) = state.release_slots(&slots) {
        return resp_error(&format!("ERR {e}"));
    }
    if let Err(e) = state.save_to_disk() {
        return resp_error(&format!(
            "ERR DELSLOTSRANGE persisted in memory but disk save failed: {e}"
        ));
    }
    resp_simple("OK")
}

/// CLUSTER FLUSHSLOTS — give up every slot this node owns, as Redis's
/// `clusterDelNodeSlots(myself)`. Refused while the node holds keys, as in
/// Redis. It used to unassign every slot in this node's view, the other
/// masters' too, keys or not, and the node went to `cluster_state:fail`
/// (#552).
fn cmd_flushslots(ctx: &Ctx) -> Vec<u8> {
    let state: &ClusterState = ctx.cluster;
    if let Some(err) = require_cluster_mode(state) {
        return err;
    }
    {
        // No write lands between the check and the flush: the writes in
        // the gate are waited for, and the next ones held back, until the
        // slots are gone. Those find them gone, and are refused. (Not
        // inside a transaction or a script: nothing runs beside them.)
        let _cut = (!crate::command_gate::alone_on_this_thread()).then(crate::write_gate::cut);
        let has_keys = ctx
            .store
            .iter()
            .any(|db| db.iter().any(|shard| !crate::read_lock!(shard).is_empty()));
        if has_keys {
            return resp_error("ERR DB must be empty to perform CLUSTER FLUSHSLOTS.");
        }
        state.flush_slots();
    }
    if let Err(e) = state.save_to_disk() {
        return resp_error(&format!(
            "ERR FLUSHSLOTS persisted in memory but disk save failed: {e}"
        ));
    }
    resp_simple("OK")
}

/// CLUSTER BUMPEPOCH — give this node a config epoch of its own, above
/// every other one, unless it has one already: `BUMPED <n>` or `STILL <n>`,
/// with this node's config epoch, as Redis's
/// `clusterBumpConfigEpochWithoutConsensus`. It used to raise only the
/// current epoch, and always said `BUMPED` (#563).
fn cmd_bumpepoch(state: &ClusterState) -> Vec<u8> {
    if let Some(err) = require_cluster_mode(state) {
        return err;
    }
    let (bumped, epoch) = state.bump_config_epoch_without_consensus();
    if !bumped {
        return resp_simple(&format!("STILL {epoch}"));
    }
    // Save to disk so the bump survives restart.
    if let Err(e) = state.save_to_disk() {
        return resp_error(&format!(
            "ERR BUMPEPOCH persisted in memory but disk save failed: {e}"
        ));
    }
    resp_simple(&format!("BUMPED {epoch}"))
}

/// CLUSTER SET-CONFIG-EPOCH <epoch>
/// Only on a fresh node: one that knows no other node and has no config
/// epoch yet, as in Redis.
fn cmd_set_config_epoch(state: &ClusterState, cmd: &[&[u8]]) -> Vec<u8> {
    if let Some(err) = require_cluster_mode(state) {
        return err;
    }
    if cmd.len() != 3 {
        return resp_error("ERR wrong number of arguments for 'cluster|set-config-epoch' command");
    }
    let new_epoch: i64 = match std::str::from_utf8(cmd[2])
        .ok()
        .and_then(|s| s.parse().ok())
    {
        Some(n) => n,
        None => return resp_error("ERR value is not an integer or out of range"),
    };
    if new_epoch < 0 {
        return resp_error(&format!("ERR Invalid config epoch specified: {new_epoch}"));
    }
    if let Err(e) = state.set_my_config_epoch(new_epoch as u64) {
        return resp_error(&format!("ERR {e}"));
    }
    if let Err(e) = state.save_to_disk() {
        return resp_error(&format!(
            "ERR SET-CONFIG-EPOCH persisted in memory but disk save failed: {e}"
        ));
    }
    resp_simple("OK")
}

/// CLUSTER SAVECONFIG — force a write of nodes.conf.
fn cmd_saveconfig(state: &ClusterState) -> Vec<u8> {
    if let Some(err) = require_cluster_mode(state) {
        return err;
    }
    match state.save_to_disk() {
        Ok(()) => resp_simple("OK"),
        Err(e) => resp_error(&format!("ERR {e}")),
    }
}

// ── CLUSTER MEET ip port [cluster-bus-port] ───────────────────────────────────

fn cmd_meet(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if let Some(err) = require_cluster_mode(ctx.cluster) {
        return err;
    }
    if cmd.len() < 4 || cmd.len() > 5 {
        return resp_error("ERR wrong number of arguments for 'cluster|meet' command");
    }
    let ip = match std::str::from_utf8(cmd[2]) {
        Ok(s) => s.to_string(),
        Err(_) => return resp_error("ERR invalid IP"),
    };
    let client_port: u16 = match std::str::from_utf8(cmd[3])
        .ok()
        .and_then(|s| s.parse().ok())
    {
        Some(p) => p,
        None => return resp_error("ERR invalid port"),
    };
    let bus_port: u16 = if cmd.len() == 5 {
        match std::str::from_utf8(cmd[4])
            .ok()
            .and_then(|s| s.parse().ok())
        {
            Some(p) => p,
            None => return resp_error("ERR invalid cluster bus port"),
        }
    } else {
        client_port + crate::cluster::bus::BUS_PORT_OFFSET
    };

    let Some(bus) = ctx.cluster.bus_runtime.get() else {
        return resp_error("ERR the cluster bus is not running");
    };

    // Insert a HANDSHAKE placeholder so CLUSTER NODES immediately reflects
    // the in-flight handshake even before the PONG comes back.
    let placed =
        crate::cluster::bus::dialer::insert_handshake_placeholder(ctx.cluster, &ip, client_port);

    // Fire off the actual handshake. We don't await it from the command
    // handler — the command returns OK as soon as the request is queued,
    // matching Redis's behavior.
    let state = std::sync::Arc::clone(ctx.cluster);
    bus.spawn(async move {
        if let Err(e) =
            crate::cluster::bus::dialer::send_meet(Arc::clone(&state), ip.clone(), bus_port).await
        {
            log_warn!("Cluster: MEET {ip}:{client_port} failed: {e}");
            // Nobody answered; do not leave a handshake row behind.
            if placed {
                crate::cluster::bus::dialer::remove_handshake_placeholder(&state, &ip, client_port);
            }
        }
    });

    resp_simple("OK")
}

// ── CLUSTER FORGET node-id ────────────────────────────────────────────────────

fn cmd_forget(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if let Some(err) = require_cluster_mode(ctx.cluster) {
        return err;
    }
    if cmd.len() != 3 {
        return resp_error("ERR wrong number of arguments for 'cluster|forget' command");
    }
    let id = match crate::cluster::node::parse_node_id(cmd[2]) {
        Some(id) => id,
        None => return resp_error("ERR Invalid node id"),
    };
    if id == ctx.cluster.myself() {
        return resp_error("ERR I tried hard but I can't forget myself...");
    }
    if ctx.cluster.my_master_id() == Some(id) {
        return resp_error("ERR Can't forget my master!");
    }

    // Removes the node, releases its slots, and bans it from being re-added
    // by gossip for a minute — long enough to send FORGET to every node.
    if !ctx.cluster.forget_node(id) {
        return resp_error("ERR Unknown node");
    }
    if let Err(e) = ctx.cluster.save_to_disk() {
        return resp_error(&format!(
            "ERR FORGET applied in memory but disk save failed: {e}"
        ));
    }
    resp_simple("OK")
}

// ── CLUSTER COUNT-FAILURE-REPORTS node-id ─────────────────────────────────────

fn cmd_count_failure_reports(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if let Some(err) = require_cluster_mode(ctx.cluster) {
        return err;
    }
    if cmd.len() != 3 {
        return resp_error(
            "ERR wrong number of arguments for 'cluster|count-failure-reports' command",
        );
    }
    // A node this one does not know is an error, as in Redis; it used to
    // count 0 failure reports for it (#563).
    let id = crate::cluster::node::parse_node_id(cmd[2])
        .filter(|id| ctx.cluster.nodes.read().contains_key(id));
    let Some(id) = id else {
        return resp_error(&format!(
            "ERR Unknown node {}",
            String::from_utf8_lossy(cmd[2])
        ));
    };
    let count = ctx.cluster.failure_report_count(id);
    resp_integer(count as i64)
}

// ── CLUSTER LINKS ─────────────────────────────────────────────────────────────
//
// Returns one entry per peer connection. We don't yet track real bus link
// state (each PING is a fresh TCP connect — we'd need a connection cache to
// expose link uptime properly), so we report what we know: peer id, address,
// last ping/pong timestamps. This is enough for cluster monitoring tools.

fn cmd_links(ctx: &mut Ctx) -> Vec<u8> {
    if let Some(err) = require_cluster_mode(ctx.cluster) {
        return err;
    }
    let nodes = ctx.cluster.nodes.read();
    let mut out: Vec<Vec<u8>> = Vec::new();

    for n in nodes.values() {
        if n.id == ctx.cluster.myself() || n.flags.contains(crate::cluster::NodeFlags::HANDSHAKE) {
            continue;
        }
        // We expose two "links" per peer (Redis convention: one for-receiving,
        // one for-sending) but ours are the same — each PING uses a fresh
        // connection. Report a single direction.
        let entry = resp_array(vec![
            resp_bulk_str("direction"),
            resp_bulk_str("to"),
            resp_bulk_str("node"),
            resp_bulk_str(crate::cluster::node_id_str(&n.id)),
            resp_bulk_str("create-time"),
            resp_integer(n.ping_sent_ms as i64),
            resp_bulk_str("events"),
            resp_bulk_str("rw"),
            resp_bulk_str("send-buffer-allocated"),
            resp_integer(0),
            resp_bulk_str("send-buffer-used"),
            resp_integer(0),
        ]);
        out.push(entry);
    }
    resp_array(out)
}

// ── CLUSTER REPLICAS / SLAVES node-id ─────────────────────────────────────────

fn cmd_replicas(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if let Some(err) = require_cluster_mode(ctx.cluster) {
        return err;
    }
    if cmd.len() != 3 {
        return resp_error("ERR wrong number of arguments");
    }
    let master_id = match crate::cluster::node::parse_node_id(cmd[2]) {
        Some(id) => id,
        None => return resp_error("ERR Invalid node id"),
    };

    let nodes = ctx.cluster.nodes.read();
    if !nodes.contains_key(&master_id) {
        return resp_error("ERR Unknown node");
    }

    // An array, as Redis replies: one bulk string per replica, in the format
    // of a `CLUSTER NODES` line. It was one string of the lines (#138).
    let mut out = Vec::new();
    for n in nodes.values() {
        if n.flags.contains(crate::cluster::NodeFlags::REPLICA) && n.master_id == Some(master_id) {
            out.push(resp_bulk_str(&format!(
                "{} {}:{}@{}{} {} {} {} {} {} connected",
                crate::cluster::node_id_str(&n.id),
                n.ip,
                n.client_facing_port(),
                n.cluster_port,
                crate::cluster::persist::hostname_suffix(&n.hostname),
                format_flags_for_nodes(n.flags),
                crate::cluster::node_id_str(&master_id),
                n.ping_sent_ms,
                n.pong_received_ms,
                n.config_epoch,
            )));
        }
    }
    resp_array(out)
}

// ── CLUSTER REPLICATE node-id ────────────────────────────────────────────────
//
// Configure this node as a replica of the given master. Internally this is
// equivalent to REPLICAOF <master_ip> <master_port>, plus updating our own
// cluster node entry to set the REPLICA flag and master_id field.
//
// We reuse the existing replication client machinery — kicking it off via
// the same code path REPLICAOF uses ensures the handshake/RDB-sync/stream
// flow is identical between standalone and cluster replication.

fn cmd_replicate(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if let Some(err) = require_cluster_mode(ctx.cluster) {
        return err;
    }
    if cmd.len() != 3 {
        return resp_error("ERR wrong number of arguments for 'cluster|replicate' command");
    }
    let master_id = match crate::cluster::node::parse_node_id(cmd[2]) {
        Some(id) => id,
        None => return resp_error("ERR Invalid node id"),
    };

    // Update cluster topology — returns the master's address so we can
    // hand it to the replication client.
    let (master_ip, master_port) = match ctx.cluster.set_replica_of(master_id) {
        Ok(v) => v,
        Err(e) => return resp_error(&format!("ERR {e}")),
    };

    // Persist nodes.conf with the new replica state.
    if let Err(e) = ctx.cluster.save_to_disk() {
        return resp_error(&format!(
            "ERR REPLICATE applied in memory but disk save failed: {e}"
        ));
    }

    // Start (or restart) the replication client — same path REPLICAOF uses.
    // It flips the ReplState role synchronously, so INFO replication agrees
    // with the cluster view before this command returns.
    crate::replication::replica_client::ReplicaStarter::from_ctx(ctx).start(master_ip, master_port);

    resp_simple("OK")
}

// ── CLUSTER FAILOVER [FORCE | TAKEOVER] ──────────────────────────────────────
//
// Manually trigger a failover from a replica. Three modes:
//   default   — ask the master to pause writes, catch up to it, then win
//               an election; nothing acknowledged is lost
//   FORCE     — skip the handshake (the master may be unreachable) but still
//               win an election
//   TAKEOVER  — skip the election too (dangerous; bypasses quorum)
//
// This must run on a REPLICA; master receiving it returns an error.

fn cmd_failover(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if let Some(err) = require_cluster_mode(ctx.cluster) {
        return err;
    }
    let mode = if cmd.len() == 2 {
        "default"
    } else if cmd.len() == 3 {
        match std::str::from_utf8(cmd[2]) {
            Ok(s) => match s.to_ascii_uppercase().as_str() {
                "FORCE" => "force",
                "TAKEOVER" => "takeover",
                _ => return resp_error("ERR syntax: CLUSTER FAILOVER [FORCE | TAKEOVER]"),
            },
            Err(_) => return resp_error("ERR invalid argument"),
        }
    } else {
        return resp_error("ERR wrong number of arguments for 'cluster|failover' command");
    };

    // Must be a replica with a known master.
    let master_id = match ctx.cluster.my_master_id() {
        Some(id) => id,
        None => return resp_error("ERR You should send CLUSTER FAILOVER to a replica"),
    };
    if !ctx.cluster.nodes.read().contains_key(&master_id) {
        return resp_error("ERR Master is unknown. Please use CLUSTER FAILOVER FORCE.");
    }
    let Some(bus) = ctx.cluster.bus_runtime.get() else {
        return resp_error("ERR the cluster bus is not running");
    };

    match mode {
        "takeover" => {
            // Bypass quorum entirely: bump epoch, claim slots, broadcast.
            let epoch = ctx.cluster.bump_epoch();
            let claimed = ctx.cluster.promote_self(master_id, epoch);
            ctx.repl_state.become_master();
            ctx.cluster.drop_slots_lost_while_promoting(&claimed);
            log_info!("Cluster: Manual TAKEOVER promoted us to master at epoch {epoch}");
            // Announce it now, not on the next heartbeat.
            let state = Arc::clone(ctx.cluster);
            bus.spawn(async move {
                crate::cluster::bus::heartbeat::send_one_round(&state).await;
            });
            resp_simple("OK")
        }
        "force" => {
            // No handshake with the master — it may be unreachable — but still
            // a real election: the other masters have to agree.
            let state = Arc::clone(ctx.cluster);
            bus.spawn(async move {
                crate::cluster::bus::heartbeat::start_forced_election(&state, master_id, None)
                    .await;
            });
            resp_simple("OK")
        }
        _ => {
            // The safe form. The master is asked to stop taking writes and
            // tell us where its stream ends; we take over only once we have
            // read up to that point, so nothing acknowledged is lost. That
            // needs the master to be there to ask.
            if !ctx
                .repl_state
                .slave_link_up
                .load(std::sync::atomic::Ordering::Acquire)
            {
                return resp_error(
                    "ERR Master is down or failed, please use CLUSTER FAILOVER FORCE",
                );
            }
            let state = Arc::clone(ctx.cluster);
            bus.spawn(async move {
                if let Err(e) =
                    crate::cluster::bus::heartbeat::run_manual_failover(state, master_id).await
                {
                    log_warn!("Cluster: Manual failover aborted: {e}");
                }
            });
            resp_simple("OK")
        }
    }
}

// ── ASKING ───────────────────────────────────────────────────────────────────
//
// Set a per-connection single-shot flag: the next command bypasses normal
// slot-ownership and migration-state checks. Cleared automatically after
// the next command runs, whether it succeeded or not.

fn cmd_asking(ctx: &mut Ctx) -> Vec<u8> {
    if let Some(err) = require_cluster_mode(ctx.cluster) {
        return err;
    }
    ctx.client_registry.update(ctx.client_id, |info| {
        info.asking = true;
    });
    resp_simple("OK")
}

// ── READONLY / READWRITE ─────────────────────────────────────────────────────
//
// READONLY enables reads against a replica's slots (slots owned by our master).
// READWRITE flips it back. The flag persists until explicitly toggled.
//
// We don't *currently* serve replica reads — Step 7c-followup if you want
// that. The flag is plumbed; the routing layer can grow conditional logic
// later: "if asking_flag OR (readonly_flag AND slot owned by my master),
// accept the read."

//
// All three refuse on a node with cluster support disabled, as in Redis
// (#563).

fn cmd_readonly(ctx: &mut Ctx) -> Vec<u8> {
    if let Some(err) = require_cluster_mode(ctx.cluster) {
        return err;
    }
    ctx.client_registry.update(ctx.client_id, |info| {
        info.readonly = true;
    });
    resp_simple("OK")
}

fn cmd_readwrite(ctx: &mut Ctx) -> Vec<u8> {
    if let Some(err) = require_cluster_mode(ctx.cluster) {
        return err;
    }
    ctx.client_registry.update(ctx.client_id, |info| {
        info.readonly = false;
    });
    resp_simple("OK")
}

// ── CLUSTER SETSLOT slot <IMPORTING node-id | MIGRATING node-id | NODE node-id | STABLE> ──

/// A slot here has changed state (`SETSLOT`): a write routed before, and not
/// yet in the write gate, is routed again there (#331).
fn slot_changed_state() {
    crate::pause::routes_moved();
}

/// Before `slots` come to this node by `what`: the keys it still had of
/// them, if a deletion of them is under way, are deleted first
/// (`migration::delete_before_coming`, #353). These commands do not hold
/// the command gate for it (`command_gate::skips`). The refusal, inside a
/// transaction, if any.
fn before_slots_come(ctx: &Ctx, slots: &[u16], what: &str) -> Option<Vec<u8>> {
    let env = crate::cluster::migration::Env::from_ctx(ctx);
    crate::cluster::migration::delete_before_coming(&env, slots, what, None)
        .err()
        .map(|e| resp_error(&e))
}

fn cmd_setslot(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if let Some(err) = require_cluster_mode(ctx.cluster) {
        return err;
    }
    if cmd.len() < 4 {
        return resp_error("ERR wrong number of arguments for 'cluster|setslot' command");
    }
    let slot: u16 = match parse_slot_arg(cmd[2]) {
        Ok(s) => s,
        Err(e) => return e,
    };
    let action = match std::str::from_utf8(cmd[3]) {
        Ok(s) => s.to_ascii_uppercase(),
        Err(_) => return resp_error("ERR invalid action"),
    };

    match action.as_str() {
        "MIGRATING" => {
            if cmd.len() != 5 {
                return resp_error(
                    "ERR wrong number of arguments for 'cluster|setslot|migrating' command",
                );
            }
            let dest = match crate::cluster::node::parse_node_id(cmd[4]) {
                Some(id) => id,
                None => return resp_error("ERR Invalid node id"),
            };
            if let Err(e) = ctx.cluster.set_migrating(slot, dest) {
                return resp_error(&format!("ERR {e}"));
            }
            slot_changed_state();
            // And the writes already in the gate are waited for. A write
            // that found its key missing from the slot before it was
            // migrating, and makes it here, is done before this answers: the
            // `CLUSTER GETKEYSINSLOT` that comes next finds the key. One that
            // had not reached the gate is sent on with `-ASK`.
            drop(crate::write_gate::cut());
            let _ = ctx.cluster.save_to_disk();
            resp_simple("OK")
        }
        "IMPORTING" => {
            if cmd.len() != 5 {
                return resp_error(
                    "ERR wrong number of arguments for 'cluster|setslot|importing' command",
                );
            }
            let src = match crate::cluster::node::parse_node_id(cmd[4]) {
                Some(id) => id,
                None => return resp_error("ERR Invalid node id"),
            };
            if let Some(refused) = before_slots_come(ctx, &[slot], "SETSLOT IMPORTING") {
                return refused;
            }
            if let Err(e) = ctx.cluster.set_importing(slot, src) {
                return resp_error(&format!("ERR {e}"));
            }
            slot_changed_state();
            let _ = ctx.cluster.save_to_disk();
            resp_simple("OK")
        }
        "STABLE" => {
            if cmd.len() != 4 {
                return resp_error(
                    "ERR wrong number of arguments for 'cluster|setslot|stable' command",
                );
            }
            ctx.cluster.clear_migration(slot);
            slot_changed_state();
            let _ = ctx.cluster.save_to_disk();
            resp_simple("OK")
        }
        "NODE" => {
            if cmd.len() != 5 {
                return resp_error(
                    "ERR wrong number of arguments for 'cluster|setslot|node' command",
                );
            }
            let new_owner = match crate::cluster::node::parse_node_id(cmd[4]) {
                Some(id) => id,
                None => return resp_error("ERR Invalid node id"),
            };
            // `command_gate::skips` lets `SETSLOT ... NODE` past the gate,
            // for the keys `NODE` to this node may delete first. To another
            // node it takes the gate here, as every command does, and is
            // turned away as they are by a script past its time limit: the
            // look below for keys of the slot is then not beside a
            // transaction or a script that writes one.
            let _gate = if new_owner != ctx.cluster.myself() {
                #[cfg(feature = "lua")]
                let overrun = crate::commands::lua::running_script_is_over_its_time_limit;
                #[cfg(not(feature = "lua"))]
                let overrun = || false;
                match crate::command_gate::enter_unless(
                    std::time::Duration::from_millis(10),
                    overrun,
                ) {
                    Some(gate) => Some(gate),
                    None => {
                        return resp_error(
                            "BUSY Redis is busy running a script. You can only call SCRIPT KILL \
                             or SHUTDOWN NOSAVE.",
                        );
                    }
                }
            } else {
                None
            };
            // Handing a slot to another node while keys from it are still here
            // strands them: clients are redirected away, and the keys sit
            // unreachable until the slot comes back. Finish the migration.
            if new_owner != ctx.cluster.myself()
                && ctx.cluster.owns_slot(slot)
                && slot_has_keys(ctx, slot)
            {
                return resp_error(&format!(
                    "ERR Can't assign hashslot {slot} to a different node while I still hold \
                     keys for this hash slot."
                ));
            }
            if new_owner == ctx.cluster.myself()
                && let Some(refused) = before_slots_come(ctx, &[slot], "SETSLOT NODE")
            {
                return refused;
            }
            if let Err(e) = ctx.cluster.finalize_slot(slot, new_owner) {
                return resp_error(&format!("ERR {e}"));
            }
            slot_changed_state();
            let _ = ctx.cluster.save_to_disk();
            resp_simple("OK")
        }
        other => resp_error(&format!("ERR Unknown SETSLOT subcommand '{other}'")),
    }
}

// ── CLUSTER MIGRATION (Redis 8.4) ────────────────────────────────────────────
//
// CLUSTER MIGRATION IMPORT start-slot end-slot [start-slot end-slot ...]
// CLUSTER MIGRATION CANCEL <ID task-id | ALL>
// CLUSTER MIGRATION STATUS [ID task-id | ALL]
//
// Atomic slot migration: see `cluster::migration`.

fn cmd_migration(ctx: &mut Ctx) -> Vec<u8> {
    use crate::cluster::migration;
    let cmd = &ctx.cmd;
    if cmd.len() < 3 {
        return resp_error("ERR wrong number of arguments for 'cluster|migration' command");
    }
    let registry = &ctx.cluster.slot_migrations;
    let action = String::from_utf8_lossy(cmd[2]).to_ascii_uppercase();
    // `ID <task-id>` or `ALL`, for CANCEL and STATUS.
    let selector = |args: &[&[u8]]| -> Result<Option<String>, Vec<u8>> {
        match args {
            [all] if all.eq_ignore_ascii_case(b"ALL") => Ok(None),
            [id, task] if id.eq_ignore_ascii_case(b"ID") => {
                Ok(Some(String::from_utf8_lossy(task).into_owned()))
            }
            _ => Err(resp_error("ERR syntax error")),
        }
    };

    match action.as_str() {
        "IMPORT" => {
            let ranges = match migration::parse_ranges(&cmd[3..]) {
                Ok(r) => r,
                Err(e) => return resp_error(&format!("ERR {e}")),
            };
            match migration::start_import(migration::Env::from_ctx(ctx), ranges) {
                Ok(id) => resp_bulk_str(&id),
                Err(e) => resp_error(&format!("ERR {e}")),
            }
        }
        "CANCEL" => match selector(&cmd[3..]) {
            Ok(id) => resp_integer(registry.cancel(id.as_deref()) as i64),
            Err(e) => e,
        },
        "STATUS" => {
            // With no argument, the same as ALL.
            let id = if cmd.len() == 3 {
                None
            } else {
                match selector(&cmd[3..]) {
                    Ok(id) => id,
                    Err(e) => return e,
                }
            };
            let resp = crate::commands::handler::effective_resp_for_reply(ctx);
            let text = |s: &str| resp_bulk_str(s);
            let number = |n: u64| resp_integer(n.min(i64::MAX as u64) as i64);
            let tasks: Vec<Vec<u8>> = registry
                .all()
                .iter()
                .filter(|task| id.as_deref().is_none_or(|id| task.id == id))
                .map(|task| {
                    resp_map_for(
                        resp,
                        vec![
                            text("id"),
                            text(&task.id),
                            text("slots"),
                            text(&migration::ranges_text(&task.ranges)),
                            text("source"),
                            text(node_id_str(&task.source)),
                            text("dest"),
                            text(node_id_str(&task.dest)),
                            text("operation"),
                            text(match task.operation {
                                migration::Operation::Import => "import",
                                migration::Operation::Migrate => "migrate",
                            }),
                            text("state"),
                            text(task.state.name()),
                            text("last_error"),
                            text(&task.last_error),
                            text("retries"),
                            number(task.retries),
                            text("create_time"),
                            number(task.create_time_ms),
                            text("start_time"),
                            number(task.start_time_ms),
                            text("end_time"),
                            number(task.end_time_ms),
                            text("write_pause_ms"),
                            number(task.write_pause_ms),
                            text("capture_pause_ms"),
                            number(task.capture_pause_ms),
                        ],
                    )
                })
                .collect();
            resp_array(tasks)
        }
        other => resp_error(&format!(
            "ERR unknown CLUSTER MIGRATION subcommand '{other}'"
        )),
    }
}

// CLUSTER SYNCSLOTS START <task-id> <dest-node-id> start end [start end ...]
//     destination → source: begin sending these slots to me
// CLUSTER SYNCSLOTS CANCEL <task-id>
//     destination → source: stop
// CLUSTER SYNCSLOTS APPLY <task-id> <command> [arg ...]
//     source → destination: a key, or a write, belonging to the slots
// CLUSTER SYNCSLOTS TAKEOVER <task-id>
//     source → destination: that was everything; the slots are yours
// CLUSTER SYNCSLOTS FAIL <task-id> <reason> [start end ...] [FROM <node-id>]
//     source → destination: I have given up on this attempt. OK promises the
//     slots were not taken and will not be in this attempt; an error says
//     they have been, or are being, taken over
//     (`migration::source_failed`)

fn cmd_syncslots(ctx: &mut Ctx) -> Vec<u8> {
    use crate::cluster::migration;
    if ctx.cmd.len() < 4 {
        return resp_error("ERR wrong number of arguments for 'cluster|syncslots' command");
    }
    let action = String::from_utf8_lossy(ctx.cmd[2]).to_ascii_uppercase();
    let task_id = String::from_utf8_lossy(ctx.cmd[3]).into_owned();
    let done = |result: Result<(), String>| match result {
        Ok(()) => resp_simple("OK"),
        Err(e) => resp_error(&format!("ERR {e}")),
    };

    match action.as_str() {
        "START" => {
            if ctx.cmd.len() < 7 {
                return resp_error("ERR syntax error");
            }
            let Some(dest) = crate::cluster::node::parse_node_id(ctx.cmd[4]) else {
                return resp_error("ERR Invalid node id");
            };
            let ranges = match migration::parse_ranges(&ctx.cmd[5..]) {
                Ok(r) => r,
                Err(e) => return resp_error(&format!("ERR {e}")),
            };
            done(migration::start_source(
                migration::Env::from_ctx(ctx),
                &task_id,
                dest,
                ranges,
            ))
        }
        "CANCEL" => {
            ctx.cluster.slot_migrations.cancel(Some(&task_id));
            resp_simple("OK")
        }
        "TAKEOVER" => done(migration::take_over(ctx.cluster, &task_id, ctx.client_id)),
        "FAIL" => {
            let reason = ctx
                .cmd
                .get(4)
                .map(|r| String::from_utf8_lossy(r).into_owned())
                .unwrap_or_default();
            let mut rest: &[&[u8]] = ctx.cmd.get(5..).unwrap_or_default();
            // Who asks, from a source that says (#516).
            let mut from = None;
            if let [head @ .., word, id] = rest
                && word.eq_ignore_ascii_case(b"FROM")
            {
                let Some(id) = crate::cluster::node::parse_node_id(id) else {
                    return resp_error("ERR Invalid node id");
                };
                from = Some(id);
                rest = head;
            }
            // The slots, from a source that sends them (#278).
            let ranges = if rest.is_empty() {
                Vec::new()
            } else {
                match migration::parse_ranges(rest) {
                    Ok(r) => r,
                    Err(e) => return resp_error(&format!("ERR {e}")),
                }
            };
            done(migration::source_failed(
                ctx.cluster,
                &task_id,
                &reason,
                &ranges,
                from,
            ))
        }
        "APPLY" => syncslots_apply(ctx, &task_id),
        other => resp_error(&format!(
            "ERR unknown CLUSTER SYNCSLOTS subcommand '{other}'"
        )),
    }
}

/// Run the command a migration's source sent, as a write of this node's own:
/// it goes to this node's replicas and AOF like any other. The slot does not
/// belong to this node yet, so the ownership check is bypassed — for this
/// command only, and only for keys inside the task's slots.
fn syncslots_apply(ctx: &mut Ctx, task_id: &str) -> Vec<u8> {
    use crate::cluster::migration;
    if ctx.cmd.len() < 5 {
        return resp_error("ERR syntax error");
    }
    if let Err(e) = migration::accept_apply(ctx.cluster, task_id, ctx.client_id) {
        return resp_error(&format!("ERR {e}"));
    }
    let inner: Vec<&[u8]> = ctx.cmd[4..].to_vec();
    let name = String::from_utf8_lossy(inner[0]).to_ascii_uppercase();
    if !crate::replication::command_mutates_for_replication(&name, &inner) {
        return resp_error("ERR only writes can be applied to an importing slot");
    }
    let Some(task) = ctx.cluster.slot_migrations.get(task_id) else {
        return resp_error("ERR no such import in progress");
    };
    let keys = crate::keyspec::key_positions(&name, &inner);
    let inside = !keys.is_empty()
        && keys
            .iter()
            .all(|pos| migration::in_ranges(&task.ranges, key_hash_slot(inner[pos])));
    if !inside {
        return resp_error("ERR the command's keys are not in the importing slots");
    }

    let saved_cmd = std::mem::replace(&mut ctx.cmd, inner);
    let saved_bypass = std::mem::replace(&mut ctx.bypass_cluster_check, true);
    let result = {
        // A write like any other: whole, as far as a cut is concerned, and
        // in order with the other writes to its keys.
        let _command = crate::command_gate::enter();
        let _gate = crate::write_gate::enter();
        let _order = crate::write_order::lock_keys(
            *ctx.selected_db,
            crate::keyspec::key_positions(&name, &ctx.cmd)
                .iter()
                .map(|pos| ctx.cmd[pos]),
        );
        let result = crate::commands::handler::dispatch_command_handlers(ctx, &name)
            .unwrap_or_else(|| resp_error("ERR unknown command"));
        crate::commands::handler::apply_write_side_effects(ctx, &name, &result);
        result
    };
    ctx.cmd = saved_cmd;
    ctx.bypass_cluster_check = saved_bypass;

    if result.starts_with(b"-") {
        result
    } else {
        resp_simple("OK")
    }
}

/// Whether any key in the selected database hashes to `slot`.
fn slot_has_keys(ctx: &Ctx, slot: u16) -> bool {
    ctx.store[*ctx.selected_db].iter().any(|shard| {
        crate::read_lock!(shard)
            .keys()
            .any(|k| key_hash_slot(k) == slot)
    })
}

// ── MIGRATE host port key|"" db timeout [COPY] [REPLACE]
//            [AUTH password | AUTH2 username password] [KEYS key [key ...]] ──
//
// Move keys to another node: serialise each, RESTORE it there, and delete it
// here once the destination has acknowledged it. This is what a cluster
// resharding is made of — `redis-cli --cluster reshard` and `rebalance` drive
// it with the `KEYS` form, a batch of keys from one slot at a time.
//
// It used to handle one key, of type string only, sent as a plain `SET`: the
// TTL was dropped in transit, every other type was refused, and the `KEYS`
// form the resharding tools rely on was rejected outright.

pub fn handle_migrate(ctx: &mut Ctx, name: &str) -> Option<Vec<u8>> {
    if name != "MIGRATE" {
        return None;
    }
    Some(off_the_runtime(|| migrate(ctx)))
}

/// Run `f`, which blocks this thread on the network for up to `MIGRATE`'s
/// timeout, without keeping a tokio worker from the rest of the server.
///
/// With `--io-model tokio`, commands run on the runtime's worker threads, and
/// one of the idle workers at a time polls the sockets and the timers for all
/// of them. A worker that the poll itself woke, with one task to run, wakes no
/// other: if that task is a `MIGRATE`, which then waits on the destination,
/// nothing polls the sockets until it is done. No other client is accepted or
/// read from, no timer fires, a replica's link is not served — for as long as
/// the `MIGRATE` waits. A write to a key it is moving must reach the server
/// and wait for it (#274, see [`hold_while_moving`]), not go unread.
/// `block_in_place` hands this worker's place, the polling with it, to
/// another thread first.
///
/// Only on a multi-threaded runtime. An io_uring worker runs a current-thread
/// runtime of its own (tokio-uring), which has no other thread to hand its
/// place to (`block_in_place` panics there): `f` just runs, as before, and
/// waits with that worker's connections only.
fn off_the_runtime<R>(f: impl FnOnce() -> R) -> R {
    match tokio::runtime::Handle::try_current() {
        Ok(handle) if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => {
            tokio::task::block_in_place(f)
        }
        _ => f(),
    }
}

/// One key on its way out: name, serialised value, absolute expiry (0 = none).
struct Outgoing {
    key: crate::store::Key,
    payload: Vec<u8>,
    expires_at_ms: u64,
}

fn migrate(ctx: &mut Ctx) -> Vec<u8> {
    use std::io::Write;
    use std::net::ToSocketAddrs;
    use std::time::Duration;

    let cmd = &ctx.cmd;
    if cmd.len() < 6 {
        return resp_error("ERR wrong number of arguments for 'migrate' command");
    }
    let Ok(host) = std::str::from_utf8(cmd[1]) else {
        return resp_error("ERR invalid host");
    };
    let Some(port) = std::str::from_utf8(cmd[2])
        .ok()
        .and_then(|s| s.parse::<u16>().ok())
    else {
        return resp_error("ERR invalid port");
    };
    let Some(dest_db) = std::str::from_utf8(cmd[4])
        .ok()
        .and_then(|s| s.parse::<usize>().ok())
    else {
        return resp_error("ERR value is not an integer or out of range");
    };
    let timeout = match std::str::from_utf8(cmd[5])
        .ok()
        .and_then(|s| s.parse::<i64>().ok())
    {
        // Redis treats a non-positive timeout as one second.
        Some(ms) if ms > 0 => Duration::from_millis(ms as u64),
        Some(_) => Duration::from_secs(1),
        None => return resp_error("ERR value is not an integer or out of range"),
    };

    // ── Options ──────────────────────────────────────────────────────────
    let mut copy = false;
    let mut replace = false;
    let mut auth: Option<Vec<Vec<u8>>> = None;
    let mut keys: Vec<&[u8]> = Vec::new();
    let mut i = 6;
    while i < cmd.len() {
        let option = cmd[i].to_ascii_uppercase();
        match option.as_slice() {
            b"COPY" => copy = true,
            b"REPLACE" => replace = true,
            b"AUTH" => {
                let Some(password) = cmd.get(i + 1) else {
                    return resp_error("ERR syntax error");
                };
                auth = Some(vec![b"AUTH".to_vec(), password.to_vec()]);
                i += 1;
            }
            b"AUTH2" => {
                let (Some(user), Some(password)) = (cmd.get(i + 1), cmd.get(i + 2)) else {
                    return resp_error("ERR syntax error");
                };
                auth = Some(vec![b"AUTH".to_vec(), user.to_vec(), password.to_vec()]);
                i += 2;
            }
            b"KEYS" => {
                if !cmd[3].is_empty() {
                    return resp_error(
                        "ERR When using MIGRATE KEYS option, the key argument must be set to \
                         the empty string",
                    );
                }
                // KEYS is the last option: everything after it is a key.
                keys = cmd[i + 1..].to_vec();
                break;
            }
            _ => return resp_error("ERR syntax error"),
        }
        i += 1;
    }
    if keys.is_empty() {
        if cmd[3].is_empty() {
            return resp_error("ERR syntax error");
        }
        keys.push(cmd[3]);
    }

    let db = *ctx.selected_db;
    // From before the keys are read until they are deleted here, writes to
    // them wait (#295). Not for `COPY`, which deletes nothing.
    let _holding = if copy {
        None
    } else {
        hold_while_moving(db, &keys)
    };
    // A node that has become a replica since this was routed: its keys are
    // its master's, and deleting them once they are sent would leave it
    // without keys its master has (#348). In the write gate, held from here
    // until they are deleted (`hold_while_moving`, or the transaction or
    // script this runs in), this is exact: a master becomes a replica with
    // the gate cut.
    if !copy && !ctx.apply_replication && ctx.repl_state.is_slave() {
        return resp_error("READONLY You can't write against a read only replica.");
    }

    // ── Serialise what exists ────────────────────────────────────────────
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0);
    let mut outgoing: Vec<Outgoing> = Vec::with_capacity(keys.len());
    for &key in &keys {
        // Any bytes: a key that is not text was skipped here, and the
        // command answered OK without moving it.
        if crate::commands::helpers::lazy_expire_key(ctx.store, db, key) {
            continue;
        }
        // The value and its time to live, read together.
        let (value, expires_at_ms) = {
            let shard = crate::store::get_shard(&ctx.store[db], key);
            match crate::read_lock!(shard).get_expiring(key) {
                Some((v, expires)) => (v.to_value(), expires.unwrap_or(0)),
                None => continue,
            }
        };
        if expires_at_ms != 0 && expires_at_ms <= now_ms {
            continue;
        }
        let payload = match crate::snapshot::dump_payload(&value) {
            Ok(p) => p,
            Err(e) => {
                let key = String::from_utf8_lossy(key);
                return resp_error(&format!("ERR could not serialise '{key}': {e}"));
            }
        };
        outgoing.push(Outgoing {
            key: crate::store::Key::new(key),
            payload,
            expires_at_ms,
        });
    }
    if outgoing.is_empty() {
        return resp_simple("NOKEY");
    }

    // ── Send ─────────────────────────────────────────────────────────────
    let addr = format!("{host}:{port}");
    let Some(socket_addr) = addr.to_socket_addrs().ok().and_then(|mut it| it.next()) else {
        return resp_error(&format!("IOERR could not resolve {addr}"));
    };
    // TLS with `tls-cluster`, as every connection between nodes.
    let mut sock = match crate::node_tls::connect_node(host, &socket_addr, timeout) {
        Ok((stream, _)) => stream,
        Err(e) => {
            return resp_error(&format!(
                "IOERR error or timeout connecting to the client: {e}"
            ));
        }
    };

    let mut pipeline = Vec::new();
    // Replies that precede the per-key ones and must each be +OK.
    let mut preamble: Vec<&str> = Vec::new();
    if let Some(auth) = &auth {
        pipeline.extend_from_slice(&crate::resp::write::encode_resp_command(auth));
        preamble.push("AUTH");
    }
    pipeline.extend_from_slice(&crate::resp::write::encode_resp_command(&[
        b"SELECT".to_vec(),
        dest_db.to_string().into_bytes(),
    ]));
    preamble.push("SELECT");
    for item in &outgoing {
        // ASKING is single-shot and must immediately precede the RESTORE: the
        // destination is still only *importing* the slot, and would answer a
        // bare RESTORE with a redirect back to us.
        pipeline.extend_from_slice(&crate::resp::write::encode_resp_command(&[
            b"ASKING".to_vec()
        ]));
        let mut restore = vec![
            b"RESTORE".to_vec(),
            item.key.as_bytes().to_vec(),
            item.expires_at_ms.to_string().into_bytes(),
            item.payload.clone(),
        ];
        if replace {
            restore.push(b"REPLACE".to_vec());
        }
        if item.expires_at_ms != 0 {
            // Absolute, so the key expires when it would have here however
            // long the transfer takes.
            restore.push(b"ABSTTL".to_vec());
        }
        pipeline.extend_from_slice(&crate::resp::write::encode_resp_command(&restore));
    }
    if let Err(e) = sock.write_all(&pipeline).and_then(|()| sock.flush()) {
        return resp_error(&format!(
            "IOERR error or timeout writing to target instance: {e}"
        ));
    }

    // ── Read the replies ─────────────────────────────────────────────────
    let mut reader = std::io::BufReader::new(sock);
    for what in preamble {
        match read_status_reply(&mut reader) {
            Ok(Ok(())) => {}
            Ok(Err(reply)) => {
                return resp_error(&format!(
                    "ERR Target instance replied with error to {what}: {reply}"
                ));
            }
            Err(e) => {
                return resp_error(&format!(
                    "IOERR error or timeout reading to target instance: {e}"
                ));
            }
        }
    }
    let mut moved: Vec<&Outgoing> = Vec::with_capacity(outgoing.len());
    let mut failure: Option<String> = None;
    for item in &outgoing {
        // ASKING's reply does not matter; RESTORE's does. A destination that
        // is not in cluster mode answers ASKING with an error and still
        // performs the RESTORE.
        let asking = read_status_reply(&mut reader);
        let restore = match asking {
            Err(e) => Err(e),
            Ok(_) => read_status_reply(&mut reader),
        };
        match restore {
            Ok(Ok(())) => moved.push(item),
            Ok(Err(reply)) => {
                failure.get_or_insert(format!("ERR Target instance replied with error: {reply}"));
            }
            Err(e) => {
                // The connection is gone; nothing after this can be confirmed.
                failure.get_or_insert(format!(
                    "IOERR error or timeout reading to target instance: {e}"
                ));
                break;
            }
        }
    }

    if copy || moved.is_empty() {
        return match failure {
            None => resp_simple("OK"),
            Some(error) => resp_error(&error),
        };
    }

    // ── Delete what the destination confirmed ────────────────────────────
    crate::aof::failpoint("migrate-before-delete");
    let not_deleted = delete_moved(ctx, db, &moved, _holding.is_some());
    // The copies sent of the keys kept here are older than they are: they
    // are taken back, so that the newest, here, is the only one (#295).
    let taken_back = !not_deleted.kept.is_empty()
        && only_here(ctx, &not_deleted.kept)
        && take_back_copies(&mut reader, &not_deleted.kept);
    let written: Vec<&[u8]> = not_deleted
        .kept
        .iter()
        .chain(&not_deleted.gone)
        .copied()
        .collect();
    // Their order, held until the copies are gone, is let go of.
    drop(not_deleted);
    if failure.is_none() && !written.is_empty() {
        failure = Some(written_while_moving(&written, &addr, taken_back));
    }
    match failure {
        None => resp_simple("OK"),
        Some(error) => resp_error(&error),
    }
}

/// What [`migrate`] holds from before it reads its keys until it has
/// deleted them here, so that nothing writes them meanwhile (#295). Let go
/// of in this order: the keys' write order and the write gate, then the
/// keys' mark (the writes that waited for them go on, and find them gone).
struct MoveHold {
    _order: crate::write_order::OrderGuard,
    _gate: crate::write_gate::WriteGuard,
    _marked: crate::key_moves::Marked,
}

/// Hold `keys`, of database `db`, for a `MIGRATE` that will delete them:
/// - **the keys' mark** (`key_moves`): a write that enters the write gate
///   after this, to one of them, steps out and waits (`run_command`); a
///   transaction that does is refused with `TRYAGAIN` (its commands run
///   alone, and cannot wait);
/// - then a wait for every write already in the gate (`write_gate::cut`,
///   let go of at once), the ones that looked before the mark among them;
/// - **the write gate and the keys' write order, whole**: an expiry, an
///   eviction or the field-expiry sweep waits for the move too.
///
/// Not the command gate: a transaction or a script waiting to run alone
/// holds back every command that comes after it, and with one in the
/// queue at each round trip a node being resharded did little else.
///
/// Writes to other keys go on, but for the instant of the cut and a key
/// that shares a stripe of the write order. A cut (a checkpoint, a full
/// sync, a handoff) waits for the move: for as long as the destination
/// takes to answer, each step at most `MIGRATE`'s timeout. A real handoff
/// under way is waited out first, as a write waits it out.
///
/// What a script writes to a key it did not declare is not held back: the
/// keys are deleted only if they still hold what was sent, and kept with
/// `TRYAGAIN` otherwise, as before. Nothing is held, and `None` returned,
/// from inside a transaction or a script (nothing runs beside them), or
/// when this thread is in the write gate already (the lock of a key's hash
/// tag, with `lua-parallel-scripts`).
fn hold_while_moving(db: usize, keys: &[&[u8]]) -> Option<MoveHold> {
    if crate::command_gate::alone_on_this_thread() || crate::write_gate::held_by_this_thread() {
        return None;
    }
    while crate::pause::handoff() {
        crate::pause::wait_out_handoff();
    }
    let marked = crate::key_moves::mark(db, keys.iter().map(|key| key.to_vec()).collect());
    drop(crate::write_gate::cut());
    let gate = crate::write_gate::enter();
    let order = crate::write_order::lock_keys(db, keys.iter().copied());
    Some(MoveHold {
        _order: order,
        _gate: gate,
        _marked: marked,
    })
}

/// How near its time a hash's field may be and still be on one side only of
/// [`same_hash_but_for_expired_fields`]: the two sides are read a moment
/// apart, and a read between them may have dropped a field that ran out.
/// Its time, kept as the Unix milliseconds the payload carries, is the
/// same on both sides to the millisecond (#594).
const FIELD_TIME_SLACK_MS: u64 = 5;

/// Whether `value`, a hash, holds what `payload` held but for fields whose
/// time has run out since: a read (`HGETALL`) drops those, and that is no
/// write.
///
/// A field that is due, or nearly, may be on either side alone: the decoder
/// drops the payload's fields whose time is up, by a time that is up to 2 ms
/// early, and here a field is due by the monotonic clock. Compared field by
/// field with each side's own rule, an unchanged hash with a field in its
/// last 2 ms looked written, and `MIGRATE` answered `TRYAGAIN` (#332). So
/// the two sides are compared by one clock and one rule: every field that is
/// not within [`FIELD_TIME_SLACK_MS`] of its time, on either side, is on the
/// other side too, with the same value and a time (or none) that agrees.
fn same_hash_but_for_expired_fields(value: &crate::types::KiviDBValue, payload: &[u8]) -> bool {
    use crate::types::{HashInner, KiviDBValue};
    let (KiviDBValue::HashEx(now), Some(KiviDBValue::HashEx(then))) =
        (value, crate::snapshot::restore_payload(payload))
    else {
        return false;
    };
    let (now, then) = (now.read(), then.read());
    let soon = crate::types::field_now().saturating_add(FIELD_TIME_SLACK_MS);
    let same_time = |a: Option<&u64>, b: Option<&u64>| a == b;
    // Every field of `a` not about to go is in `b`, the same.
    let held_by = |a: &HashInner, b: &HashInner| {
        a.fields.iter().all(|(field, val)| {
            let time = a.expiries.get(field);
            time.is_some_and(|time| *time <= soon)
                || (b.fields.get(field.as_str()) == Some(val)
                    && same_time(time, b.expiries.get(field)))
        })
    };
    held_by(&now, &then) && held_by(&then, &now)
}

/// Delete the keys the destination has confirmed, each only if it still
/// holds what was sent: the same value, and the same time to live (#274).
///
/// [`hold_while_moving`] keeps the writes of clients off the keys while
/// they travel (`held`). Where it holds nothing (see there), or a script
/// writes a key it did not declare, a key can be written in the meantime: the write is acknowledged here, and
/// the destination has the value from before it, so deleting the key would
/// lose an acknowledged write. Such a key is kept, and returned, for
/// `MIGRATE` to fail with: the slot then still holds it here, its newest
/// value, and moving it again takes the write along. A key gone meanwhile is
/// returned too, unless it went because its time was up: the destination's
/// copy has the same absolute time, and is gone there as well.
///
/// The deletions are one write, as far as a full sync, a checkpoint and the
/// other writes to these keys are concerned: under the write gate and the
/// keys' write order (held since the keys were read, by [`hold_while_moving`],
/// or else taken here for the deletions only).
/// They are sent to replicas and the AOF as one `DEL` of exactly the keys
/// deleted, before the order is let go of. (`MIGRATE`'s reply used to be
/// propagated as a `DEL` of every key it named, deleted or not: one written
/// meanwhile, or made meanwhile by a write to a key the dump had not found,
/// was deleted on every replica and kept here.)
fn delete_moved<'a>(ctx: &Ctx, db: usize, moved: &[&'a Outgoing], held: bool) -> NotDeleted<'a> {
    let nested = crate::write_gate::held_by_this_thread();
    let mut gate = crate::write_gate::enter();
    while !nested && !ctx.apply_replication && crate::pause::handoff() {
        drop(gate);
        crate::pause::wait_out_handoff();
        gate = crate::write_gate::enter();
    }
    let order = crate::write_order::lock_keys(db, moved.iter().map(|item| item.key.as_bytes()));
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0);
    let mut del: Vec<Vec<u8>> = vec![b"DEL".to_vec()];
    let mut kept: Vec<&'a [u8]> = Vec::new();
    let mut gone: Vec<&'a [u8]> = Vec::new();
    for item in moved {
        let key = item.key.as_bytes();
        let shard = crate::store::get_shard(&ctx.store[db], key);
        let removal = {
            let mut map = crate::write_lock!(shard);
            let expires_at_ms = map.expires(key).unwrap_or(0);
            // Held, it may still not dump as it did: a read (`HGETALL`)
            // drops a hash's fields whose time is up, which the
            // destination's copy drops too, at the same absolute time.
            map.remove_if(key, |value| {
                let value = value.to_value();
                expires_at_ms == item.expires_at_ms
                    && (crate::snapshot::dump_payload(&value).is_ok_and(|now| now == item.payload)
                        || (held && same_hash_but_for_expired_fields(&value, &item.payload)))
            })
        };
        match removal {
            crate::store::Removal::Taken(taken) => {
                // Freed with the shard unlocked.
                drop(taken);
                crate::vector::maybe_unindex(ctx.index_store, db, key);
                del.push(key.to_vec());
            }
            crate::store::Removal::Kept => kept.push(key),
            crate::store::Removal::Absent => {
                let expired = item.expires_at_ms != 0 && item.expires_at_ms <= now_ms;
                if !expired {
                    gone.push(key);
                }
            }
        }
    }
    // A write routed here before these keys left, and not yet in the write
    // gate, is routed again there (#331).
    if del.len() > 1 && ctx.cluster.enabled {
        crate::pause::routes_moved();
    }
    crate::aof::failpoint("migrate-deleted");
    if del.len() > 1 && crate::replication::write_is_observed(ctx) {
        crate::replication::replicate_one_write(ctx, &del);
    }
    drop(gate);
    NotDeleted {
        kept,
        gone,
        _order: order,
    }
}

/// What [`delete_moved`] left here.
struct NotDeleted<'a> {
    /// Keys written while they travelled: here, with their newest value.
    kept: Vec<&'a [u8]>,
    /// Keys that went from here meanwhile, other than by their time running
    /// out.
    gone: Vec<&'a [u8]>,
    /// The order of the keys, still held: nothing writes them here, or
    /// deletes them, until it is let go of (see [`take_back_copies`]).
    _order: crate::write_order::OrderGuard,
}

/// Whether nobody can have written `keys` at the destination since they
/// were read here, so that the copies this `MIGRATE` sent are the only
/// thing there under those names: this node owns their slot, so clients are
/// sent here for them, and they have been here all along, so no client was
/// sent on with `-ASK` (a node migrating a slot sends a client on only for
/// a key it does not hold). Their order, held since, keeps it so: a key
/// deleted here, and then written by a client sent on to the destination,
/// would otherwise be deleted there by [`take_back_copies`].
///
/// Not when this node does not own the slot (a tool moving keys "cold" from
/// a node that is not the owner, which clients do not reach anyway), and
/// not outside cluster mode, where clients may write at the destination
/// directly.
fn only_here(ctx: &Ctx, keys: &[&[u8]]) -> bool {
    ctx.cluster.enabled
        && keys
            .iter()
            .all(|key| ctx.cluster.owns_slot(crate::cluster::key_hash_slot(key)))
}

/// Delete at the destination the copies of `keys` that this `MIGRATE` sent,
/// on the connection it sent them on (authenticated, the database selected).
/// Each `DEL` goes after `ASKING`, as the `RESTORE` did. Whether every reply
/// came back: a copy that could not be deleted stays, older than the key
/// here, as it always did before.
///
/// Without this, a key written while it travelled (#274) was on both nodes:
/// the newest value here and an older one there. `redis-cli --cluster fix`,
/// closing a slot left open, then found it on both, and, when it picked the
/// destination as the slot's owner, the older value was the one served
/// (#295).
fn take_back_copies(
    reader: &mut std::io::BufReader<Box<dyn crate::node_tls::ReadWrite>>,
    keys: &[&[u8]],
) -> bool {
    use std::io::Write;
    let mut pipeline = Vec::new();
    for key in keys {
        pipeline.extend_from_slice(&crate::resp::write::encode_resp_command(&[
            b"ASKING".to_vec()
        ]));
        pipeline.extend_from_slice(&crate::resp::write::encode_resp_command(&[
            b"DEL".to_vec(),
            key.to_vec(),
        ]));
    }
    let sock = reader.get_mut();
    if sock
        .write_all(&pipeline)
        .and_then(|()| sock.flush())
        .is_err()
    {
        return false;
    }
    // ASKING's reply and DEL's count; an error from either is still a reply.
    (0..keys.len() * 2).all(|_| read_status_reply(reader).is_ok())
}

/// The error `MIGRATE` answers with when keys it moved were written while
/// they travelled, and were kept here (see [`delete_moved`]).
///
/// `TRYAGAIN`: the move did not happen for those keys, and can be made
/// again. A tool resharding a cluster (`redis-cli --cluster reshard`,
/// `rebalance`) stops on it and says so, rather than moving on to the next
/// keys as though the slot were empty here; run again (with `REPLACE`, or
/// `--cluster-replace`, as the destination holds a copy) it takes the keys
/// along with their writes.
fn written_while_moving(keys: &[&[u8]], addr: &str, taken_back: bool) -> String {
    const SHOWN: usize = 5;
    let mut names = keys
        .iter()
        .take(SHOWN)
        .map(|k| format!("'{}'", String::from_utf8_lossy(k)))
        .collect::<Vec<_>>()
        .join(", ");
    if keys.len() > SHOWN {
        names.push_str(&format!(" and {} more", keys.len() - SHOWN));
    }
    let copies = if taken_back {
        format!("The copies sent to {addr} were deleted there; MIGRATE them again")
    } else {
        format!("The copy sent to {addr} may be older; MIGRATE them again with REPLACE")
    };
    format!(
        "TRYAGAIN {} written while being migrated, and kept here: {names}. {copies}",
        if keys.len() == 1 {
            "a key was"
        } else {
            "keys were"
        }
    )
}

/// Read one reply that is expected to be a status. `Ok(Ok(()))` for any `+`
/// reply, `Ok(Err(text))` for an error reply (or anything else), `Err` when
/// the connection fails or times out.
fn read_status_reply(
    reader: &mut std::io::BufReader<Box<dyn crate::node_tls::ReadWrite>>,
) -> std::io::Result<Result<(), String>> {
    use std::io::BufRead;
    let mut line = String::new();
    if reader.read_line(&mut line)? == 0 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::UnexpectedEof,
            "connection closed by target instance",
        ));
    }
    let line = line.trim_end_matches(['\r', '\n']);
    Ok(match line.strip_prefix('+') {
        Some(_) => Ok(()),
        None => Err(line.trim_start_matches('-').to_string()),
    })
}

// ── CLUSTER RESET [HARD | SOFT] ──────────────────────────────────────────────

fn cmd_reset(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if let Some(err) = require_cluster_mode(ctx.cluster) {
        return err;
    }
    let hard = if cmd.len() == 2 {
        false // default is SOFT
    } else if cmd.len() == 3 {
        match std::str::from_utf8(cmd[2]) {
            Ok(s) => match s.to_ascii_uppercase().as_str() {
                "HARD" => true,
                "SOFT" => false,
                _ => return resp_error("ERR syntax: CLUSTER RESET [HARD | SOFT]"),
            },
            Err(_) => return resp_error("ERR invalid argument"),
        }
    } else {
        return resp_error("ERR wrong number of arguments for 'cluster|reset' command");
    };

    // As in FLUSHSLOTS: no write lands between the check for keys below
    // and the reset dropping the slots.
    let cut = (!crate::command_gate::alone_on_this_thread()).then(crate::write_gate::cut);

    // Redis refuses to reset a master that holds keys: the reset drops its
    // slots, and the keys would be left belonging to nothing. (A replica's
    // dataset is flushed by the reset instead.)
    if ctx.cluster.my_master_id().is_none() && !hard {
        let has_keys = ctx
            .store
            .iter()
            .any(|db| db.iter().any(|shard| !crate::read_lock!(shard).is_empty()));
        if has_keys {
            return resp_error(
                "ERR CLUSTER RESET can't be called with master nodes containing keys",
            );
        }
    }

    // FLUSHALL the data on hard reset, mirroring Redis behavior.
    if hard {
        let new_id = ctx.cluster.hard_reset();
        let flushed = crate::store::clear_store(ctx.store);
        let indexes = crate::vector::drop_all_indexes(ctx.index_store);
        crate::vector::drop_all_dicts(ctx.dict_store);
        crate::store::clear_ts_label_index(ctx.ts_index);
        if flushed.should_trim() || indexes > 0 {
            crate::commands::memory::purge_allocator();
        }
        log_info!(
            "Cluster: Hard reset performed — new node ID {}",
            node_id_str(&new_id)
        );
    } else {
        ctx.cluster.soft_reset();
        log_info!("Cluster: Soft reset performed");
    }
    drop(cut);

    // Drop our replica relationship if any.
    ctx.repl_state.become_master();

    resp_simple("OK")
}

// ── CLUSTER MYSHARDID ────────────────────────────────────────────────────────
//
// Shard ID = master node's ID. For a master that's our own ID. For a replica
// it's our master_id. Returns the 40-hex node ID as a bulk string.

fn cmd_myshardid(ctx: &mut Ctx) -> Vec<u8> {
    if let Some(err) = require_cluster_mode(ctx.cluster) {
        return err;
    }
    let shard_id = match ctx.cluster.my_master_id() {
        Some(master_id) => master_id, // we're a replica
        None => ctx.cluster.myself(), // we're a master
    };
    resp_bulk_str(crate::cluster::node_id_str(&shard_id))
}

// ── CLUSTER SLOT-STATS ───────────────────────────────────────────────────────
//
// Two forms:
//   CLUSTER SLOT-STATS SLOTSRANGE <start> <end>
//   CLUSTER SLOT-STATS ORDERBY <metric> [LIMIT <n>] [ASC | DESC]
//
// We track `key-count` honestly (computed by walking the keyspace) and report
// 0 for cpu-usec / network-bytes-in / network-bytes-out — these would require
// per-slot instrumentation we don't currently have.
//
// Returns an array of slot stat entries. Each entry is a 2-element array:
//   [slot, [field1, value1, field2, value2, ...]]

fn cmd_slot_stats(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if let Some(err) = require_cluster_mode(ctx.cluster) {
        return err;
    }
    if cmd.len() < 3 {
        return resp_error("ERR wrong number of arguments for 'cluster|slot-stats' command");
    }
    let mode = match std::str::from_utf8(cmd[2]) {
        Ok(s) => s.to_ascii_uppercase(),
        Err(_) => return resp_error("ERR syntax error"),
    };

    // Compute key counts per slot, only for slots we own.
    // Walk every key in the selected DB once.
    let key_counts = key_counts_per_slot(&ctx.store[*ctx.selected_db], ctx.cluster);

    let entries: Vec<(u16, u64)> = match mode.as_str() {
        "SLOTSRANGE" => {
            if cmd.len() != 5 {
                return resp_error("ERR syntax: CLUSTER SLOT-STATS SLOTSRANGE start-slot end-slot");
            }
            let start: u16 = match parse_slot_arg(cmd[3]) {
                Ok(s) => s,
                Err(e) => return e,
            };
            let end: u16 = match parse_slot_arg(cmd[4]) {
                Ok(s) => s,
                Err(e) => return e,
            };
            if start > end {
                return resp_error(&format!("ERR Invalid range {start}-{end}"));
            }
            (start..=end)
                .filter(|s| ctx.cluster.owns_slot(*s))
                .map(|s| (s, key_counts.get(&s).copied().unwrap_or(0)))
                .collect()
        }
        "ORDERBY" => {
            if cmd.len() < 4 {
                return resp_error(
                    "ERR syntax: CLUSTER SLOT-STATS ORDERBY metric [LIMIT n] [ASC | DESC]",
                );
            }
            let metric = match std::str::from_utf8(cmd[3]) {
                Ok(s) => s.to_ascii_lowercase(),
                Err(_) => return resp_error("ERR invalid metric"),
            };
            // Only "key-count" is meaningful for us.
            if metric != "key-count" {
                return resp_error(&format!(
                    "ERR ORDERBY metric '{metric}' not supported (use 'key-count')"
                ));
            }
            let mut limit: usize = 16384;
            // Busiest first unless asked otherwise, as in Redis: the
            // command is for finding the hot slots. It was ascending (#139).
            let mut descending = true;
            let mut i = 4;
            while i < cmd.len() {
                let arg = match std::str::from_utf8(cmd[i]) {
                    Ok(s) => s.to_ascii_uppercase(),
                    Err(_) => return resp_error("ERR syntax error"),
                };
                match arg.as_str() {
                    "LIMIT" => {
                        i += 1;
                        if i >= cmd.len() {
                            return resp_error("ERR LIMIT requires a value");
                        }
                        limit = match std::str::from_utf8(cmd[i])
                            .ok()
                            .and_then(|s| s.parse().ok())
                        {
                            Some(n) => n,
                            None => return resp_error("ERR invalid LIMIT"),
                        };
                    }
                    "ASC" => descending = false,
                    "DESC" => descending = true,
                    other => {
                        return resp_error(&format!("ERR unexpected token '{other}'"));
                    }
                }
                i += 1;
            }
            // Take all our owned slots, sort by count, truncate.
            let mut all: Vec<(u16, u64)> = (0..crate::cluster::CLUSTER_SLOTS as u16)
                .filter(|s| ctx.cluster.owns_slot(*s))
                .map(|s| (s, key_counts.get(&s).copied().unwrap_or(0)))
                .collect();
            if descending {
                all.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
            } else {
                all.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));
            }
            all.truncate(limit);
            all
        }
        other => return resp_error(&format!("ERR Unknown subcommand '{other}'")),
    };

    let resp_entries: Vec<Vec<u8>> = entries
        .into_iter()
        .map(|(slot, key_count)| {
            resp_array(vec![
                resp_integer(slot as i64),
                resp_array(vec![
                    resp_bulk_str("key-count"),
                    resp_integer(key_count as i64),
                    resp_bulk_str("cpu-usec"),
                    resp_integer(0),
                    resp_bulk_str("network-bytes-in"),
                    resp_integer(0),
                    resp_bulk_str("network-bytes-out"),
                    resp_integer(0),
                ]),
            ])
        })
        .collect();
    resp_array(resp_entries)
}

/// Walk the selected DB once and return a map of slot → key-count, but only
/// for slots we own. Used by CLUSTER SLOT-STATS.
///
/// O(N) over all keys in the DB. For a multi-million-key DB this is slow,
/// but SLOT-STATS is an operator command, not a hot-path one — fine for now.
///
/// The slots this node owns are read once, before any shard is locked. It
/// used to look each key's slot up in the slot table with the key's shard
/// locked; with a deletion of a lost slot's keys waiting for that shard,
/// and `ADDSLOTS` waiting for the deletion's batch with the slot table
/// held, the three waited for each other for good, and the node with them
/// (#353; see `ClusterState`).
pub(crate) fn key_counts_per_slot(
    db: &crate::store::Db,
    cluster: &ClusterState,
) -> std::collections::HashMap<u16, u64> {
    let owned = cluster.owned_slots();
    let mut counts: std::collections::HashMap<u16, u64> = std::collections::HashMap::new();
    for shard in db.iter() {
        let map = crate::read_lock!(shard);
        for k in map.keys() {
            let slot = key_hash_slot(k);
            if owned[slot as usize] {
                *counts.entry(slot).or_insert(0) += 1;
            }
        }
    }
    counts
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{HashInner, KiviDBValue};
    use std::time::Instant;

    /// A hash of `(field, value, time)`.
    fn hash(fields: &[(&str, &str, Option<u64>)]) -> KiviDBValue {
        let mut inner = HashInner::new();
        for (field, value, time) in fields {
            inner
                .fields
                .insert(field.to_string(), std::sync::Arc::from(value.as_bytes()));
            if let Some(time) = time {
                inner.expiries.insert(field.to_string(), *time);
            }
        }
        KiviDBValue::HashEx(std::sync::Arc::new(parking_lot::RwLock::new(inner)))
    }

    fn payload(value: &KiviDBValue) -> Vec<u8> {
        crate::snapshot::dump_payload(value).unwrap()
    }

    /// A field a few milliseconds from its time, on one side and not the
    /// other, or with times that differ: a read between the two may have
    /// dropped it. The hash is unchanged (#332).
    #[test]
    fn a_hash_whose_field_is_about_to_expire_is_unchanged() {
        let now = crate::types::field_now();
        let later = now + 3_600_000;
        let sent = payload(&hash(&[
            ("kept", "1", None),
            ("timed", "2", Some(later)),
            ("brief", "3", Some(now - 1)),
        ]));
        let here = hash(&[
            ("kept", "1", None),
            ("timed", "2", Some(later)),
            ("brief", "3", Some(now + 3)),
        ]);
        assert!(same_hash_but_for_expired_fields(&here, &sent));
        // And the other way round: the field is gone here, and still in the
        // payload, a moment from its time.
        let sent = payload(&hash(&[("kept", "1", None), ("brief", "3", Some(now + 3))]));
        let here = hash(&[("kept", "1", None)]);
        assert!(same_hash_but_for_expired_fields(&here, &sent));
    }

    /// A field written, added, deleted or given another time, away from
    /// the edge, is a write.
    #[test]
    fn a_hash_written_while_it_travelled_is_not_the_same() {
        let later = crate::types::field_now() + 3_600_000;
        let sent = payload(&hash(&[("a", "1", None), ("b", "2", Some(later))]));
        for here in [
            hash(&[("a", "9", None), ("b", "2", Some(later))]),
            hash(&[("a", "1", None), ("b", "9", Some(later))]),
            hash(&[("a", "1", None), ("b", "2", Some(later)), ("c", "3", None)]),
            hash(&[("a", "1", None)]),
            hash(&[("a", "1", None), ("b", "2", None)]),
            hash(&[("a", "1", Some(later)), ("b", "2", Some(later))]),
            hash(&[("a", "1", None), ("b", "2", Some(later + 1_000))]),
            // Given another time a millisecond off: a write too, now that
            // both sides keep the very millisecond (#594).
            hash(&[("a", "1", None), ("b", "2", Some(later + 1))]),
        ] {
            assert!(!same_hash_but_for_expired_fields(&here, &sent));
        }
        let here = hash(&[("a", "1", None), ("b", "2", Some(later))]);
        assert!(same_hash_but_for_expired_fields(&here, &sent));
    }

    /// Run `MIGRATE` with `args` as the command is run once it has been
    /// routed, on a node with `store` and `repl_state`.
    fn migrate_after_routing(
        store: &crate::store::Store,
        repl_state: &Arc<crate::replication::ReplState>,
        args: &[&str],
    ) -> Vec<u8> {
        use crate::commands::ctx::NoopAofSender;
        let lastsave = Arc::new(parking_lot::RwLock::new(0i64));
        let (hub_tx, _hub_rx) = tokio::sync::mpsc::unbounded_channel();
        let config = Arc::new(crate::config::Config::default());
        let started_at = Instant::now();
        let index_store = crate::vector::new_index_store();
        let dict_store = crate::vector::new_dict_store();
        let wait_table = Arc::new(crate::wait_table::WaitTable::new());
        let ts_index = crate::store::new_ts_index();
        let pubsub = crate::pubsub::PubSubHub::new();
        let acl_store = crate::acl::new_acl_store("");
        let acl_log = crate::acl::new_acl_log();
        let slowlog = crate::slowlog::new_slowlog(u64::MAX, 0);
        let latency = crate::latency::new_latency_tracker();
        let (compaction_tx, _compaction_rx) = crate::vector::new_compaction_channel();
        let cluster = Arc::new(ClusterState::new_disabled());
        let client_registry = crate::client_registry::new_client_registry();
        let monitor_registry = crate::monitor::new_monitor_registry();
        let tracking_table = crate::tracking::new_tracking_table();
        let mut selected_db = 0usize;
        let mut ctx = Ctx {
            cmd: args.iter().map(|a| a.as_bytes()).collect(),
            store,
            lastsave: &lastsave,
            selected_db: &mut selected_db,
            aof_tx: &NoopAofSender,
            aof_enabled: false,
            config: &config,
            started_at: &started_at,
            index_store: &index_store,
            dict_store: &dict_store,
            wait_table: &wait_table,
            ts_index: &ts_index,
            pubsub: &pubsub,
            hub_tx: &hub_tx,
            repl_state,
            watch_registry: &crate::watch::NoopWatchRegistry,
            client_id: 0,
            client_registry: &client_registry,
            resp: 2,
            acl_store: &acl_store,
            acl_log: &acl_log,
            slowlog: &slowlog,
            latency: &latency,
            compaction_tx: &compaction_tx,
            cluster: &cluster,
            bypass_cluster_check: false,
            apply_replication: false,
            skip_write_side_effects: false,
            peer_addr: "127.0.0.1:1",
            monitor_registry: &monitor_registry,
            authenticated_user: "default",
            tracking_table: &tracking_table,
            blocking: None,
        };
        handle_migrate(&mut ctx, "MIGRATE").unwrap()
    }

    /// `MIGRATE` on a node that has become a replica since the command was
    /// routed is refused with `READONLY`, and sends nothing: it would have
    /// deleted, once sent, keys its master has (#348). Its keys stay. On a
    /// master it goes ahead, and reaches the destination.
    #[test]
    fn migrate_on_a_node_that_became_a_replica_after_routing_is_refused() {
        let _pause = crate::pause::TEST_LOCK.lock();
        crate::pause::clear_pause();
        let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        destination.set_nonblocking(true).unwrap();
        let port = destination.local_addr().unwrap().port().to_string();
        let store = crate::store::new_store(1);
        let _ = crate::store::get_shard(&store[0], "moving")
            .write()
            .insert_str("moving", "v");
        let has_key = || {
            crate::read_lock!(crate::store::get_shard(&store[0], "moving")).contains_key("moving")
        };
        let args = ["MIGRATE", "127.0.0.1", port.as_str(), "moving", "0", "200"];

        let repl_state = Arc::new(crate::replication::ReplState::new_master());
        repl_state.become_slave();
        let reply = migrate_after_routing(&store, &repl_state, &args);
        assert!(
            reply.starts_with(b"-READONLY"),
            "{}",
            String::from_utf8_lossy(&reply)
        );
        assert!(has_key());
        assert!(
            destination.accept().is_err(),
            "a replica's MIGRATE reached the destination"
        );

        // On a master, it goes ahead: the destination does not answer, and
        // the key stays.
        let repl_state = Arc::new(crate::replication::ReplState::new_master());
        let reply = migrate_after_routing(&store, &repl_state, &args);
        assert!(
            !reply.starts_with(b"-READONLY"),
            "{}",
            String::from_utf8_lossy(&reply)
        );
        assert!(destination.accept().is_ok());
        assert!(has_key());
    }
}